Compare commits

195 Commits
Author SHA1 Message Date
qinghua 7e183ed7a6 feat: 系统账户页改搜索表单布局,新增支持下拉选公司部门职位 2026-10-28 21:31:57 +08:00
qinghua 2f60efb8ef fix: 修复首条短消息左右气泡挤在中间的布局 2026-10-28 20:50:29 +08:00
qinghua fb05b47d46 feat: 发布草稿助手挂载长期记忆工具 2026-10-28 20:43:39 +08:00
qinghua abe75f87aa feat: 快递报价编辑页分区导航支持拖拽排序 2026-10-28 16:07:48 +08:00
qinghua 7781f53d8a fix: 快递报价编辑页体积重开关避免被拉满整栏宽 2026-10-28 11:45:24 +08:00
qinghua 5427b3830c fix: 快递报价编辑页避免分区卡被 max-height 误裁导致露边 2026-10-28 11:42:46 +08:00
qinghua f382ba9bd7 feat: 快递报价详情按需加载并批量查分区重量带以降低延迟 2026-10-28 11:38:01 +08:00
qinghua e47f76c22a feat: 发货物流增加发货仓商品页支持按仓查看与批量分配 SKU 2026-10-28 11:13:12 +08:00
qinghua b45729fa1a chore: 根目录增加部署 TUI 启动脚本 2026-10-28 11:00:29 +08:00
qinghua 16933b38ff sql: 发货仓库与快递报价菜单独立为发货物流目录 2026-10-28 10:55:37 +08:00
qinghua b06cdc0309 chore: 根目录增加前后端 Agent 开发启动脚本 2026-10-28 10:38:48 +08:00
qinghua 9fafe55c4e feat: 快递报价改为独立编辑页并优化分区双栏布局 2026-10-24 10:51:33 +08:00
qinghua ee985e33a9 fix: 消除警告 2026-10-23 15:32:53 +08:00
qinghua 3f8f066a7c feat: 支持快递报价 Excel 导入与标准模板下载 2026-10-22 14:21:11 +08:00
qinghua 49bbaa7362 feat: 支持快递报价 Excel 导入与标准模板下载 2026-10-22 11:12:04 +08:00
qinghua 36884890af feat: 快递报价改为分区×重量带以对齐承运商矩阵计价 2026-10-22 10:54:30 +08:00
qinghua 31cd151b12 feat: 发货仓与快递报价主数据及按仓选价算运费 2026-10-21 17:41:51 +08:00
qinghua 9e4b92bd15 feat: SKU 增加单件实重 weight_g,为按重算快递费预留 2026-10-21 15:33:07 +08:00
qinghua b8005db2dc fix: 发布助手改为首次发消息再建会话,避免空草稿刷会话 2026-10-20 16:00:25 +08:00
qinghua e667871c58 fix: 草稿首次落库前先改绑发布助手会话,避免路由重挂新建空会话 2026-10-20 15:57:49 +08:00
qinghua 9bbb01fdee fix: 拼多多商品标题按汉字2/ASCII1合计60字符限制 2026-10-20 11:39:13 +08:00
qinghua cf08b393b7 sql: 移除已废弃的聚合管理菜单及前端页面 2026-10-19 21:26:55 +08:00
qinghua 213c5e0b91 feat: 发布工作台和编辑页操作按钮改为短文案并悬停说明 2026-10-19 16:00:57 +08:00
qinghua 7043696b29 fix: 发布助手整体编辑时先按商家编码查内部 SKU 再改规格和重量 2026-10-19 15:51:40 +08:00
qinghua 871628bf7c fix: 发布助手收起改为隐藏,展开不再重新挂载消息列表 2026-10-19 15:38:32 +08:00
qinghua d143ebbe09 feat: 发布助手可局部修改基础信息、SKU 价格库存和类目属性 2026-10-19 15:34:34 +08:00
qinghua d47a991116 refactor: 收紧发布助手提示词,小改直接落表且不要求用户刷新核对 2026-10-19 15:22:18 +08:00
qinghua 216a2516b8 feat: 发布页前端工具改为等待浏览器回执后再继续模型 2026-10-19 15:16:08 +08:00
qinghua 26f438eb6a refactor: 拼多多发布编辑页按基础信息/规格库存/服务承诺分区 2026-10-19 14:13:30 +08:00
qinghua f2556c58cc docs: 发布 DTO 图片字段注释与 pdd.goods.add 文档对齐 2026-10-19 10:36:25 +08:00
qinghua 641520eaa8 feat: 发布工作台点击标题模态框展示系统草稿详情 2026-10-19 10:11:04 +08:00
qinghua 4c3b2870a4 fix: 批量发布改为事务提交后再异步,避免草稿永久卡在发布中 2026-10-16 15:24:08 +08:00
qinghua 5dee928321 feat: 发布工作台草稿解绑平台ID,按店累计推送/发布成功次数 2026-10-14 11:41:57 +08:00
qinghua f272122918 chore: 前端默认 pnpm dev/build 指向 web-antd 2026-10-14 09:52:02 +08:00
qinghua 1b06aa6bcc style: 收紧 ColPage 左右栏中缝间距 2026-10-11 01:38:48 +08:00
qinghua 1f4ea2074a feat: 系统账户页接入 CompanyColPage 共用公司侧栏 2026-10-11 01:34:22 +08:00
qinghua 5795eab75c fix: ColPage 解包侧栏 isCollapsed 以修复公司列表布局记忆 2026-10-11 01:30:22 +08:00
qinghua f4de5d8fd0 fix: ColPage 回写侧栏宽度与收起状态以恢复跨页布局记忆 2026-10-11 00:52:24 +08:00
qinghua c24051aa04 fix: ColPage 回写左右栏宽度与收起状态以恢复侧栏记忆 2026-10-11 00:47:54 +08:00
qinghua 59b3ada695 refactor: 发品去掉主内部商品绑定,改由订单同步兜底建品 2026-10-09 14:15:12 +08:00
qinghua 7fa0729722 fix: 移除批量发布任务中未使用的成败计数变量 2026-10-09 13:45:04 +08:00
qinghua aa87168437 refactor: 移除警告代码 2026-10-09 13:37:52 +08:00
qinghua e5050317ec feat: 补齐拼多多类目属性单位与日期控件及发品传参 2026-10-09 13:35:17 +08:00
qinghua 68ef451ab3 refactor: 发布类目属性改用 pdd.goods.cat.rule.get 2026-10-09 11:41:35 +08:00
qinghua 3c16d538e0 feat: 新增pdd文档和清理污染脚本 2026-10-09 11:12:32 +08:00
qinghua 650d3910ba refactor: 移除工作台多维分析、销售额排行与区间对比 2026-10-08 17:25:33 +08:00
qinghua 4c340ce805 feat: 区域销量接店省日汇聚与 overview API 2026-10-08 13:59:28 +08:00
qinghua f11b0b1d2f refactor: 运营团队成员改挂公司成员表以支持退出级联 2026-10-08 10:24:55 +08:00
qinghua 2d1290f726 feat: 落地内部店铺运营团队与成员管理,为后续按团队收口数据范围做准备 2026-10-03 20:19:39 +08:00
qinghua 21efea8334 fix: 工作台窄屏工具区改为横向滚动避免竖排占高 2026-09-28 17:43:28 +08:00
qinghua af0fec790c feat: 新增区域销量前端壳 2026-09-28 17:36:44 +08:00
qinghua a162c5dd9c fix: 发布助手收起图标改为向右以符合右侧栏语义 2026-09-28 12:03:51 +08:00
qinghua 874851a22a fix: 修复运费模板包邮省份末行标签被裁切 2026-09-28 11:58:14 +08:00
qinghua 7c7e271f05 feat: SKU 列表支持批量设置单买价/拼单价/库存 2026-09-28 11:54:54 +08:00
qinghua 4e956eadcd fix: 修复助手输入框长引用标签溢出导致后续文字叠字 2026-09-28 11:11:03 +08:00
qinghua 3e49d6e9c9 feat: 用户消息中的实体引用展示为标签 2026-09-28 11:00:31 +08:00
qinghua 59881dcb68 feat: 助手引用改为行内标签样式并可自由插入 2026-09-28 10:57:14 +08:00
qinghua e136084794 feat: 发布工作台改为保存/推送/发布时再创建系统草稿 2026-09-28 10:11:57 +08:00
qinghua 92b6026b48 fix: 发布编辑器折扣改为正常折扣并由前端换算后提交 2026-09-28 10:01:39 +08:00
qinghua 370ead39a1 style: 优化智能助手sender样式 2026-09-26 17:15:44 +08:00
qinghua 5567b6d281 feat: 发布草稿助手 UI 对齐智能助手页交互 2026-09-26 16:58:04 +08:00
qinghua 85bac4f710 feat: 智能助手支持软删会话并级联隐藏消息 2026-09-26 16:47:01 +08:00
qinghua 13a2bd9274 refactor: 更换对话加载动画 2026-09-26 00:34:28 +08:00
qinghua 883a1d0cfe fix: 优化助手输入区发送/展开与浅色对比,并精简侧栏展开态图标 2026-09-26 00:19:36 +08:00
qinghua 67d01c678a refactor: 智能助手侧栏支持收起图标轨与居中可拖拽会话搜索 2026-09-25 23:56:19 +08:00
qinghua a72a43cffc refactor: 智能助手页对齐 ChatGPT 式侧栏分组与居中空态布局 2026-09-25 23:38:13 +08:00
qinghua 0b460e22b0 refactor: 助手记忆页改用 VXE 表格与 Alert 对齐系统列表风格 2026-09-25 00:35:36 +08:00
qinghua 41f022bd63 fix: store 证伪时优先无状态 Responses,失败再降 Completions 2026-09-25 00:29:51 +08:00
qinghua 71eca63461 fix: 探测 Responses/store 能力并在无状态时用 Completions 带全量历史 2026-09-25 00:23:28 +08:00
qinghua d20c6a1302 feat: 支持 Completions/Responses 双协议,并在同选型下续链加速 2026-09-24 17:10:34 +08:00
qinghua 9c2c1ed061 feat: 个人中心两栏布局整合资料与改密 2026-09-23 17:40:07 +08:00
qinghua e9aeef7607 sql: sys_user.phone 非空并清理无手机号测试账号 2026-09-23 12:14:04 +08:00
qinghua f40788db9a refactor: 重构用户模型 2026-09-23 12:10:43 +08:00
qinghua b0ad57e442 feat: SSE 推送权限变更并自动刷新菜单与权限码 2026-09-23 11:35:56 +08:00
qinghua 1aafccc289 fix: 将 vxe-table 已废弃的 rowConfig.height 迁移为 cellConfig.height 2026-09-23 11:03:18 +08:00
qinghua 8b035ebca5 fix: 混合侧栏一键进入子页并开启路由进度条,消除首次点菜单无反馈 2026-09-23 10:56:57 +08:00
qinghua 5b15c01606 docs: 补充前端 Vben/Ant 组件选用规则供 Agent 参考 2026-09-22 22:06:01 +08:00
qinghua ff3c8bbe4c fix: 将默认主题设为浅色模式 2026-09-22 17:40:23 +08:00
qinghua 802f72cd9e update: 升级vben5.5.9到5.7.0 2026-09-22 17:09:46 +08:00
qinghua 345e4a31f8 fix: agent 连续改标题时强制落盘,避免 abort 后假成功 2026-09-22 14:20:10 +08:00
qinghua 0dc8e383a6 refactor: 整理发布模块目录为 agent 与 editor 分层 2026-09-22 11:37:08 +08:00
qinghua 21cd9778ae refactor: 去掉弹窗发布并将发布编辑器拆为页面壳与 composables 2026-09-22 11:27:37 +08:00
qinghua 60c4d204ae fix: 规格重组按商家编码由 agent 指定对齐 SKU 2026-09-22 10:58:52 +08:00
qinghua 1d4b737717 fix: 发布助手去掉读表单空转并修正工具状态卡住 2026-09-22 10:46:43 +08:00
qinghua fd6efdb9d2 fix: 智能助手与发布面板加载历史消息后滚到底部 2026-09-21 09:56:00 +08:00
qinghua a140cff81a feat: 拼多多发布页接入场景智能体与表单改写工具 2026-09-20 23:18:28 +08:00
qinghua d28b4d45c3 fix: 各环境补齐 Agent 与 Server 对齐的 MCP Bearer 2026-09-20 22:16:49 +08:00
qinghua 67c2d58c32 feat: 将 Agent 接入运行时镜像挂载式部署 2026-09-20 17:34:25 +08:00
qinghua 5393ad3423 refactor: 模型管理改为表格与弹窗交互 2026-09-20 16:53:17 +08:00
qinghua 9350323ff2 feat: 公司支持多模型提供商与会话消歧选型 2026-09-20 16:35:06 +08:00
qinghua d7e4a987c1 feat: 我的记忆独立页并迁出模型管理 2026-09-20 16:15:03 +08:00
qinghua aac3424911 feat: 模型管理独立页与会话级选模型 2026-09-20 15:42:25 +08:00
qinghua ffb8d5f7dc feat: 公司 LLM 改为提供商凭证加多模型勾选并支持探测目录 2026-09-20 15:00:35 +08:00
qinghua 4114b0b4fb feat: 贯通 context_window 配置并按 token 预算裁剪对话历史 2026-09-20 14:22:53 +08:00
qinghua 8251a57010 fix: 收紧回答 harness 减少记忆场景啰嗦转述 2026-09-20 11:57:38 +08:00
qinghua 51737a4868 fix: 记忆工具用回合 ref 并对用户改自然语言转述 2026-09-20 11:49:30 +08:00
qinghua de0bbb1a9c feat: 工具调用改为独立 SSE 事件并以中文状态条展示 2026-09-20 11:45:00 +08:00
qinghua 9b240b35a9 feat: 长期记忆改为摘要检索并由模型按需载入 2026-09-20 11:33:35 +08:00
qinghua 177036cf3d feat: 重构 Agent 目录为 api/agent/infrastructure 分层并更新启动入口 2026-09-20 11:15:10 +08:00
qinghua 02e7c4b881 feat: 智能助手增加引用功能 2026-09-19 23:43:57 +08:00
qinghua 67c661fd46 feat: 智能体按名称编码反查店铺商品,输入框可引用后直接查数 2026-09-19 23:13:26 +08:00
qinghua 457d776f9f feat: 新对话空态展示能力引导,快捷提示只填入输入框 2026-09-19 22:58:18 +08:00
qinghua 609fdaf71f feat: aichat 改用 tdesign chat 2026-09-19 22:48:13 +08:00
qinghua ffb9f2ca90 feat: 引入antdesignxvue 2026-09-19 00:54:06 +08:00
qinghua bc73668737 feat: 新增agent 2026-09-18 17:34:38 +08:00
qinghua 0d9b5a21c2 refactor: 下线废弃的 EC 手动文件导入(ImportTask)能力 2026-09-18 14:21:42 +08:00
qinghua 17397f5347 feat: 接入拼多多商品审核驳回消息并回写系统草稿 commitId 2026-09-18 13:41:38 +08:00
qinghua 2ff2407e05 feat: 部署 TUI 支持多选服务与分层返回 2026-09-17 10:04:23 +08:00
qinghua 8c56cfb0b5 refactor: 适配 apps/web·server·license-server 目录的部署与插件路径 2026-09-16 22:56:24 +08:00
qinghua 2754ed1e45 refacor: 重构目录架构 2026-09-16 22:43:21 +08:00
qinghua b37cdb0d54 feat: 新增拼多多草稿箱推送 2026-09-16 22:21:54 +08:00
qinghua f54c3ee972 feat: 新增意见反馈功能 2026-09-15 11:07:46 +08:00
qinghua 333f8a3031 feat: 发布工作台悬停 SKU 数展示规格明细表 2026-09-14 17:37:31 +08:00
qinghua 618e052807 fix: 内部 SKU 拉入选择器防抖并去掉 focus 重复请求 2026-09-14 16:58:40 +08:00
qinghua 327ecbf7eb fix: 菜单权限查询改用 route_name 对齐 sys_menu 表结构 2026-09-14 11:51:53 +08:00
qinghua 6e12dc62e2 feat: 新增拼多多发布工作台 2026-09-14 11:43:01 +08:00
qinghua 6246bd2233 feat: 发布弹窗支持规格拖拽、SKU规格内联编辑与商家编码校验关联 2026-09-12 10:44:27 +08:00
qinghua f61fa56b29 feat: 发布商品规格值改为 AutoComplete 内联编辑 2026-09-12 09:47:19 +08:00
qinghua d2e887e61a feat: 发布商品选中类目后校验店铺发布权并提示 2026-09-11 22:24:49 +08:00
qinghua 6ac55fe5d4 refactor: 删除菜单 name,标题必填且同级唯一并加库约束 2026-09-11 14:42:19 +08:00
qinghua 00658f00c0 feat: 文件路径改为 app/env/业务分组/年/hash,并收敛 category 2026-09-10 16:41:12 +08:00
qinghua f83a14edc6 feat: owner 权限码改为返回公司已分配权限而非 company:* 通配 2026-09-10 15:14:24 +08:00
qinghua b304181022 refactor: 迁移设计sql位置 2026-09-10 14:44:21 +08:00
qinghua 963a0aa28b remove: 移除过时迁移sql 2026-09-10 14:43:01 +08:00
qinghua fc2ee0bdaf feat: 商品详情拉取由 information.get 迁移到 detail.get 2026-09-10 13:35:50 +08:00
qinghua bd40064755 feat: 完善拼多多商品发布 2026-09-09 14:53:09 +08:00
qinghua f94d9b2db4 feat: 移除 BI Overview 旧趋势字段,统一使用 dealTrend 2026-09-07 17:23:07 +08:00
qinghua 3138e69c30 feat: 加入规格体系 2026-09-06 23:35:54 +08:00
qinghua f6803bcdae feat: 工作台SKU汇总列展示商品名/规格名并悬停显示编码 2026-09-06 10:50:52 +08:00
qinghua 2b5bc02dc8 feat: 新增拼读都类目管理 2026-09-06 01:29:39 +08:00
qinghua dc864ea57c feat: 工作台增加SKU汇总表并支持跳转SKU概览 2026-09-05 22:29:27 +08:00
qinghua ebca4d093a feat: 菜单侧栏标题与标签标题拆分并支持 tab_title 回退 2026-09-05 18:27:53 +08:00
qinghua d99d8352b6 fix: 订单数据流抽屉全量任务表占满剩余高度 2026-09-05 18:14:43 +08:00
qinghua 2194fbe3c3 feat: 渠道店铺页接入订单同步与转换数据流 2026-09-05 15:22:31 +08:00
qinghua 4f2cd9ecef feat: 概览标签统一为种类「名称」格式 2026-09-05 15:00:47 +08:00
qinghua f3b0384334 feat: 概览页标签优先显示实体名称 2026-09-05 14:55:28 +08:00
qinghua f122176369 feat: 新增品类独立概览页并支持工作台下钻 2026-09-05 14:49:11 +08:00
qinghua 5a37e8f230 feat: 店铺与平台独立概览页并对齐经营 KPI 口径 2026-09-05 11:31:03 +08:00
qinghua 5114abc986 feat: 按经营概览风格重做商品概览并补齐 KPI 与趋势 2026-09-05 11:08:30 +08:00
qinghua b2e0ee5da4 refactor: 拆分拼多多限流配置并将 PMC 开关下沉到环境配置 2026-09-05 01:38:09 +08:00
qinghua 4c053702e2 feat: 接入拼多多商品 PMC 消息并软标平台删除 2026-09-05 01:25:06 +08:00
qinghua 717e108685 refactor: 去掉拼多多商品手工增删改接口与删除入口 2026-09-04 22:44:16 +08:00
qinghua 558dfc4a28 refactor: 去掉拼多多商品内部 product_id 并按 SKU 分摊广告费 2026-09-04 22:18:41 +08:00
qinghua ea9d792096 feat: 经营汇总透出退款单量/件数,并将退款指标归入规模维度 2026-09-04 16:17:37 +08:00
qinghua 2cb0bc205a feat: 经营概览四表支持列显隐配置并本地记忆 2026-09-04 15:40:57 +08:00
qinghua f24a2f6ef9 feat: 发布商品弹窗支持最小化并保留编辑草稿 2026-09-04 15:18:36 +08:00
qinghua 37b5610f27 feat: 拼多多商品发布(goods.add)及发布后详情入库绑定主商品 2026-09-03 17:55:48 +08:00
qinghua 0ccc787165 refactor: 工作台 BI 健康度去掉数据新鲜度占位卡 2026-09-03 14:55:01 +08:00
qinghua f104e5882b feat: 工作台接入 BI 增量计算健康度(滞后/暂停/空闲)与按店明细恢复 2026-09-03 14:44:57 +08:00
qinghua fa1e5ac4ad fix: 修复 BI 脏日卡在重算中时补投失效并误报无待重算 2026-09-02 23:18:11 +08:00
qinghua aee9aac41a perf: 优化拼多多订单列表索引与查询,并放宽前端超时 2026-09-02 23:03:01 +08:00
qinghua b0372c132c fix: 编辑商品内调价后同步刷新表单 SKU 成本展示 2026-09-02 22:51:54 +08:00
qinghua 76df7701b2 feat: 经营概览四张汇总表透出成交量与净销量 2026-09-02 22:43:06 +08:00
qinghua acf8e06c86 feat: 有订单明细的商品/SKU禁止删除,订单明细SKU外键改为RESTRICT 2026-09-02 16:24:06 +08:00
qinghua 2b982593c8 remove: 移除遗留代码 2026-09-02 13:55:57 +08:00
qinghua 27a960c2fe refactor: BI 脏日账本与 as-of 成本重算管线落地,退役 COST_SYNC 并重构工作台健康度 UI 2026-09-02 12:03:59 +08:00
qinghua abcf1894db remove: 移除无用mongo字段 2026-09-01 19:50:12 +08:00
qinghua 67ed4d2ffe refactor: 导入映射/任务迁入 ec/imports 并统一 API 前缀为 /ec/import 2026-09-01 11:57:52 +08:00
qinghua 824643aead refactor: 商品 SKU/成本/回刷/迁品迁入 product/sku 并统一 API 前缀 2026-09-01 10:49:33 +08:00
qinghua a3ac5b1e8d feat: SKU 成本支持删除段与历史编辑模态,调价/删除均进入待同步影响面 2026-08-31 23:48:32 +08:00
qinghua d29e23a4f2 feat: 商品/规格删除增加影响确认,并优化列表操作列与编辑 SKU 滚动体验 2026-08-31 23:11:00 +08:00
qinghua c0ca592d8a fix: 工作台类目汇总按商品主数据实时归属,不再使用 BI 日文档类目快照 2026-08-31 22:32:36 +08:00
qinghua c586120861 feat: 删除商品增加友好提示 2026-08-31 22:08:47 +08:00
qinghua e889bc043a feat: 新增迁品重算 2026-08-31 16:02:09 +08:00
qinghua 32c4788176 refactor: 去掉订单明细/SKU成本/影响面冗余 product_id,归属经 sku 关联 2026-08-31 14:29:46 +08:00
qinghua c5de3499c0 feat: 添加浏览器扩展下载功能 2026-08-30 23:32:26 +08:00
qinghua 7fcb9abf69 feat: 完善成本同步 2026-08-29 17:04:14 +08:00
qinghua f42e6aeb44 remove: 移除废弃代码 2026-08-29 09:32:07 +08:00
qinghua 37beae1580 refactor: 公司菜单/权限 API 规范化并细分 read/assign 权限 2026-08-27 23:09:37 +08:00
qinghua 5f184ef560 refactor: 拆分公司/系统账户权限与模块,系统账户迁至 sys/account 并更新菜单 2026-08-27 22:39:08 +08:00
qinghua 65c412d533 feat(前端): 增加按钮级权限控制 2026-08-27 22:20:02 +08:00
qinghua b6ed7d166d feat: 按钮级权限复用 /auth/codes,新增 PermissionGate/v-permission 与操作列无权限整列隐藏 2026-08-27 17:13:21 +08:00
qinghua b04fec1ef3 fix: JwtUtils 显式绑定 Jackson 序列化,部署上传 jar 后强制 restart 容器 2026-08-27 16:32:41 +08:00
qinghua 871871501d refactor: org 公司/职位菜单与权限分配权限码嵌套为 org:*:menu|permission:assign,职位权限页改用组织域权限树接口 2026-08-27 15:47:52 +08:00
qinghua 8152d06a62 refactor: open/openapi 拆为顶级权限域,HTTP 开放接口权限码统一 openapi 前缀 2026-08-27 15:32:53 +08:00
qinghua ddd5f2455a refactor: 开放 HTTP 接口权限码改 openapi 前缀,控制台 API Key 管理保留 open 前缀 2026-08-27 14:56:16 +08:00
qinghua 01fad1b65a feat(部署): 优化部署目录 2026-08-27 14:42:14 +08:00
qinghua 19bc987f36 feat(浏览器扩展): 优化推广费同步浮窗 2026-08-27 14:24:43 +08:00
qinghua b3c77c08b1 feat(浏览器扩展): 改用新店铺名称精确匹配店铺接口 2026-08-27 14:14:19 +08:00
qinghua bf602ed4b2 feat: 开放密钥管理也增加调用地址显示功能 2026-08-27 09:46:59 +08:00
qinghua c768b14912 fix: 广告费转换按内部商品汇总渠道日表金额,避免多 goods 覆盖丢金额 2026-08-26 14:34:41 +08:00
qinghua 928bfb19a3 fix: 浏览器扩展 Open API 改经 Background 代发,修复 HTTPS 页面混合内容拦截 2026-08-26 14:14:18 +08:00
qinghua 216536815c refactor: 经营概览汇总表统一成交/净销售六列规模字段并同步前后端导出与对比 2026-08-26 10:38:56 +08:00
qinghua a329ebdba5 fix: 修复公司菜单批量分配因 sys_menu_permission 脏数据导致权限外键失败 2026-08-26 09:47:11 +08:00
qinghua 425cc8ea28 fix: 修复订单数据流全链路时区问题 2026-08-26 00:26:12 +08:00
qinghua f5e5175a1f feat: 店铺列表推广费管线(导入→转换)、失败明细与重试,并禁用拼多多广告费日表 CRUD 2026-08-25 23:36:16 +08:00
qinghua 67fe700e88 feat: 订单数据流抽屉优化 2026-08-25 22:47:04 +08:00
qinghua 8ba38ab1a5 feat: 修复转换和计算侧时区问题导致的转换和计算滞后 2026-08-25 20:48:30 +08:00
qinghua 093d23d3b1 feat: 优化工作台动画交互 2026-08-25 20:38:02 +08:00
qinghua ea86cab0a9 refactor: 重构bi计算侧口径,移除原有销售口径补齐退款口径 2026-08-25 14:47:47 +08:00
qinghua 53bb8a32fd feat: 调整欢迎页流程描述 2026-08-25 10:11:19 +08:00
qinghua 3d8865beb7 fix: 修复未登录停留在在欢迎页 2026-08-25 09:40:46 +08:00
qinghua 81358e6d7c refactor: 统一文件存储与上传流程,解耦 OSS 客户端、存储类型与前端上传模式 2026-08-25 00:00:19 +08:00
qinghua 78dbc865fd feat: 测试环境开启oss 2026-08-24 16:45:18 +08:00
qinghua e219baeb33 fix: 修复公司成员删除删掉其他公司其他同一成员问题 2026-08-24 16:44:01 +08:00
3294 changed files with 124753 additions and 57225 deletions
@@ -0,0 +1,12 @@
---
description: 每完成一个完整功能后给出一行 commit message
alwaysApply: true
---
# 功能完成后的提交消息
每完成一个**完整、可独立提交**的功能(或一组相关改动收尾)后,主动给出**一行**中文 conventional commit message,供用户直接复制提交。
- 格式:`feat:` / `fix:` / `refactor:` / `sql:` 等前缀 + 简洁说明(侧重 why)
- 不要主动执行 `git commit`,除非用户明确要求提交
- 若同一会话连续完成多个独立功能,每个功能收尾时各给一行,不要攒到最后一起写
@@ -1,8 +1,6 @@
--- ---
description: 通用企业级开发规范:分层、边界、可维护性;动手前先定结构
alwaysApply: true alwaysApply: true
--- ---
# 企业级开发规范 # 企业级开发规范
先想清楚再写代码。优先可维护、可扩展,不为「先跑通」牺牲结构。 先想清楚再写代码。优先可维护、可扩展,不为「先跑通」牺牲结构。
+67
View File
@@ -0,0 +1,67 @@
---
description: 前端 UI 组件选用优先级(Vben → Ant Design → 封装 → 自研)
globs: apps/web/**/*.{vue,ts,tsx}
alwaysApply: false
---
# 前端 UI 组件选用(Vben 5.7 / web-antd)
写 `apps/web` 业务页时按下面顺序选型,**禁止**一上来自研通用控件。
## 优先级
1. **Vben 应用层组件 / hooks**(`@vben/common-ui`、`#/adapter/*`、`@vben/plugins`)
2. **Ant Design Vue**(`ant-design-vue`)——原子控件、反馈、布局碎片
3. **可复用则封装**——抽到 `components/` 或 adapter,不要复制粘贴
4. **最后才自研**——仅当以上都无法满足,且注释说明原因
> web-antd 是 Ant Design 皮肤。业务页优先 `Button`/`Input`/`Select` 等 antd,不要用 shadcn 的 `VbenButton` 等(那些偏框架内部 / 文档演示)。
## 常用 Vben(优先用)
| 能力 | 用法 | 来源 |
|------|------|------|
| 页面壳 | `Page` | `@vben/common-ui` |
| 左右分栏 | `ColPage` | `@vben/common-ui` |
| 弹窗 | `useVbenModal` | `@vben/common-ui` |
| 抽屉 | `useVbenDrawer` | `@vben/common-ui` |
| 确认/提示/输入 | `alert` / `confirm` / `prompt` | `@vben/common-ui` |
| 搜索/编辑表单 | `useVbenForm` + `z` | `#/adapter/form` |
| 表格 | `useVbenVxeGrid` | `#/adapter/vxe-table` |
| 远程选项 | `ApiComponent` / 表单里 `ApiSelect` `ApiTreeSelect` | `@vben/common-ui` / adapter |
| 图标选择 | `IconPicker` | `@vben/common-ui` |
| 省略文案 | `EllipsisText` | `@vben/common-ui` |
| 数字滚动 | `CountTo` | `@vben/common-ui` |
| JSON 展示 | `JsonViewer` | `@vben/common-ui` |
| 加载 | `Loading` / `Spinner` | `@vben/common-ui` |
| 裁剪 | `VCropper` | `@vben/common-ui` |
| 可调宽 | `VResize` | `@vben/common-ui` |
| Tippy | `Tippy` / 指令 | `@vben/common-ui` |
| 树 | `Tree` | `@vben/common-ui` |
| 验证码 | `SliderCaptcha` 等 | `@vben/common-ui` |
| 图表 | `EchartsUI` / `useEcharts` | `@vben/plugins/echarts` |
| 富文本 | `VbenTiptap` | `@vben/plugins/tiptap` |
| 兜底页 | `Fallback` | `@vben/common-ui` |
列表页典型组合:`Page` + `useVbenVxeGrid`(可带 `useVbenForm` 搜索)+ `useVbenModal` 表单。
## 表单 schema 可用组件类型(adapter 已注册)
`Input` `InputNumber` `InputPassword` `Textarea` `Mentions` `Select` `ApiSelect` `TreeSelect` `ApiTreeSelect` `AutoComplete` `Checkbox` `CheckboxGroup` `Radio` `RadioGroup` `Switch` `DatePicker` `RangePicker` `TimePicker` `Rate` `Upload` `Divider` `Space` `IconPicker` `DefaultButton` `PrimaryButton`
## Ant Design(Vben 没有对应能力时用)
常用:`Button` `Input` `Select` `Table`(轻量表) `Tabs` `Tag` `Card` `Space` `Flex` `Row/Col` `Form`(简单场景) `Modal`(临时/极简) `Drawer` `Dropdown` `Menu` `Tooltip` `Popover` `Popconfirm` `message` `notification` `Spin` `Empty` `Pagination` `Cascader` `Transfer` `Tree` `Upload` `DatePicker` `Progress` `Badge` `Avatar` `Descriptions` `Statistic` `Skeleton` `Alert` `Result` `Image` …
注意:可滚动列表**不要**用 `<Spin :spinning>` 整块包裹(见 `antd-spin-scrollable-layout`)。
## 导入约定
```ts
import { Page, useVbenModal } from '@vben/common-ui';
import { useVbenForm, z } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Button, message } from 'ant-design-vue';
```
更完整清单见 `apps/web/docs/agent-ui-components.md`。
+5
View File
@@ -0,0 +1,5 @@
# 根目录仅薄脚本入口;勿提交本地依赖与锁外产物
node_modules/
.DS_Store
*.log
.pnpm-store/
+5 -2
View File
@@ -2,5 +2,8 @@
// MyBatis-Plus 方法引用会触发 Eclipse 空值分析误报;关闭后无需每类加 @SuppressWarnings("null") // MyBatis-Plus 方法引用会触发 Eclipse 空值分析误报;关闭后无需每类加 @SuppressWarnings("null")
"java.compile.nullAnalysis.mode": "disabled", "java.compile.nullAnalysis.mode": "disabled",
// pom 变更(如 Boot 升级)后自动刷新 classpath,避免 Eclipse「class file was not written / project inconsistent」 // pom 变更(如 Boot 升级)后自动刷新 classpath,避免 Eclipse「class file was not written / project inconsistent」
"java.configuration.updateBuildConfiguration": "automatic" "java.configuration.updateBuildConfiguration": "automatic",
} // Agent(唯一 Python 子项目)用本地 venv,避免 Pylance 解析不到 langchain 等依赖
"python.defaultInterpreterPath": "${workspaceFolder}/apps/agent/.venv/bin/python",
"python.analysis.extraPaths": ["${workspaceFolder}/apps/agent"]
}
+53 -18
View File
@@ -1,18 +1,37 @@
# AGENTS.md # AGENTS.md
电商 DMB 系统。根目录**不是工作区**:5 个相互独立的子项目,各自构建、各自装依赖,根目录无 package.json。提交走 git(分支 `dev`),commit message 用中文 conventional 格式(`feat:`/`fix:`/`refactor:`/`sql:` 前缀)。 电商 DMB / ECBI 系统。根目录**不是业务 monorepo**:各 app 各自构建、各自装依赖;根 `package.json` 只做开发启动薄封装(仅 `concurrently`)。`pnpm-workspace.yaml` 的 `packages: []` 用于阻断向上解析到家目录 workspace,**不要**把 `apps/*` 写进去。提交走 git(分支 `dev`),commit message 用中文 conventional 格式(`feat:`/`fix:`/`refactor:`/`sql:` 前缀)。
## 子项目一览 ## 本地一键启动(根目录)
| 目录 | 技术栈 | 说明 | 先各自装好依赖(`apps/web` 的 `pnpm install`、`apps/agent` 的 venv、Server 环境变量等),再在仓库根:
|------|--------|------|
| ecom-dmb-backend | Spring Boot 3.2.3 / Java 17 / Maven wrapper | 主后端 |
| ecom-dmb-frontend | pnpm + turbo monorepo(vben-admin 5.5.9 fork) | 前端,唯一应用 apps/web-antd |
| ecom-license | NestJS server + Node CLI(两个独立 pnpm 项目) | 授权签发平台 |
| order-generator | 独立 Node 脚本(npm) | 刷单/删单测试工具 |
| ecom-deploy | Node TUI(pnpm) | 部署工具,流程见 MANUAL-DEPLOY.md |
## 后端(ecom-dmb-backend) ```bash
pnpm install # 仅安装 concurrently
pnpm dev # 并行:web + server + agent
pnpm dev:web-server # 只要前后端
pnpm dev:web # 仅前端
pnpm dev:server # 仅 Java(./mvnw spring-boot:run)
pnpm dev:agent # 仅 Agent(需 apps/agent/.venv)
pnpm deploy:tui # 部署 TUI(需先 cd deploy && pnpm install;勿用 pnpm deploy,会撞内置命令)
```
Server 仍依赖本机 `DB_*` / Redis / `JWT_SECRET` 等;Agent 读 `apps/agent/.env.dev`。
## 目录一览
```
apps/
web/ # 前端(原 ecom-dmb-frontend,pnpm+turbo,应用 apps/web-antd)
server/ # 主后端(原 ecom-dmb-backend,Spring Boot)
agent/ # 智能助手(FastAPI/LangGraph;会话 Mongo;模型 Key 落 Server MySQL)
license-server/ # 授权(原 ecom-license:server/ + tui/)
browser-extension/ # 浏览器扩展
order-generator/ # 刷单/删单测试工具
deploy/ # 部署 TUI(原 ecom-deploy),流程见 deploy/MANUAL-DEPLOY.md
```
## 后端(apps/server)
- 构建 `./mvnw clean package -DskipTests`,运行 `./mvnw spring-boot:run`(默认 dev profile) - 构建 `./mvnw clean package -DskipTests`,运行 `./mvnw spring-boot:run`(默认 dev profile)
- 运行依赖环境变量:`DB_URL` / `DB_USERNAME` / `DB_PASSWORD` / `REDIS_HOST` / `REDIS_PASSWORD` / `JWT_SECRET`,见 README.md 与 `application-{profile}.yml`;MongoDB / RabbitMQ 连接见各 profile(与 MySQL 同机,账号 `qinghua`) - 运行依赖环境变量:`DB_URL` / `DB_USERNAME` / `DB_PASSWORD` / `REDIS_HOST` / `REDIS_PASSWORD` / `JWT_SECRET`,见 README.md 与 `application-{profile}.yml`;MongoDB / RabbitMQ 连接见各 profile(与 MySQL 同机,账号 `qinghua`)
@@ -21,30 +40,46 @@
- 架构设计文档在 `docs/`(订单统计读模型、权限控制、时间格式等),改动相关模块前先读 - 架构设计文档在 `docs/`(订单统计读模型、权限控制、时间格式等),改动相关模块前先读
- `.vscode/settings.json` 已关闭 Eclipse null analysis(MyBatis-Plus 方法引用误报),不要补 `@SuppressWarnings("null")` - `.vscode/settings.json` 已关闭 Eclipse null analysis(MyBatis-Plus 方法引用误报),不要补 `@SuppressWarnings("null")`
- 接口文档:启动后 http://localhost:8080/doc.html(knife4j) - 接口文档:启动后 http://localhost:8080/doc.html(knife4j)
- Spring profile:dev / test / pre / prod;部署环境端口 8101 / 8102 / 8103(见 ecom-deploy/MANUAL-DEPLOY.md) - Spring profile:dev / test / pre / prod;部署环境端口 8101 / 8102 / 8103(见 deploy/MANUAL-DEPLOY.md)
## 前端(ecom-dmb-frontend) ## 前端(apps/web)
- 只允许 pnpm;先 `pnpm install`(postinstall 会跑 `stub` 构建) - 只允许 pnpm;先 `pnpm install`(postinstall 会跑 `stub` 构建)
- 开发 `pnpm dev:antd`,构建 `pnpm build:antd`;类型检查 `pnpm -F @vben/web-antd typecheck` - 开发 `pnpm dev`(等同原 `dev:antd`),构建 `pnpm build`;类型检查 `pnpm -F @vben/web-antd typecheck`
- lefthook 钩子会对暂存文件自动 prettier/eslint/stylelint `--fix`,commitlint 强制 conventional commit,不要绕过 - lefthook 钩子会对暂存文件跑 `pnpm lint`(oxfmt/oxlint 等)与 `check:type`,commitlint 强制 conventional commit,不要绕过
- 代码内 `#/` 别名 = `src/` - 代码内 `#/` 别名 = `src/`
- **UI 选型**:Vben 应用层 → Ant Design Vue → 可复用封装 → 自研;清单见 `apps/web/docs/agent-ui-components.md`(规则 `.cursor/rules/frontend-ui-priority.mdc`)
- **web-antd 视图里不要用 `<Spin :spinning>` 整块包住可滚动列表**(ant-spin-container 破坏滚动链);滚动依赖 `flex-1 min-h-0 overflow-y-auto`,加载态拆细(详见 `.cursor/rules/antd-spin-scrollable-layout.mdc`) - **web-antd 视图里不要用 `<Spin :spinning>` 整块包住可滚动列表**(ant-spin-container 破坏滚动链);滚动依赖 `flex-1 min-h-0 overflow-y-auto`,加载态拆细(详见 `.cursor/rules/antd-spin-scrollable-layout.mdc`)
- 智能助手页:`views/agent/chat`;开发代理 `/api/agent` → `localhost:8200`(见 `vite.config.mts`)
- 当前应用版本:`@vben/web-antd` **5.7.0**
## 授权(ecom-license) ## Agent(apps/agent)
- Python 3.11+;设计 `apps/agent/DESIGN.md`
- `cd apps/agent && python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt`
- 配置 `.env`(参考 `.env.example`):`JWT_SECRET` 须与 Java `jwt.secret` 一致
- 运行:`uvicorn api.main:app --reload --port 8200`
- 租户自管 OpenAI Compatible 凭证(Mongo 加密 + Redis 缓存);聊天/会话在 Agent Mongo 库
## 授权(apps/license-server)
- 不是 monorepo:`server/` 与 `tui/` 各自 `pnpm install`(tui/README 中写的 `cli/` 已改名) - 不是 monorepo:`server/` 与 `tui/` 各自 `pnpm install`(tui/README 中写的 `cli/` 已改名)
- Server(NestJS + TypeORM,默认端口 3100):`cd server && pnpm start:dev`;建表 `server/sql/schema.sql`;Ed25519 密钥在 `server/keys/` - Server(NestJS + TypeORM,默认端口 3100):`cd server && pnpm start:dev`;建表 `server/sql/schema.sql`;Ed25519 密钥在 `server/keys/`
- CLI:`cd tui && pnpm dev <command>`;设计见根目录 DESIGN.md - CLI:`cd tui && pnpm dev <command>`;设计见根目录 DESIGN.md
## 部署(ecom-deploy) ## 部署(deploy)
- TUI:`cd ecom-deploy && pnpm dev`,可选自动部署 / 仅编译 / 上传并重启 - TUI:根目录 `pnpm deploy:tui`(或 `cd deploy && pnpm dev`),可选自动部署 / 仅编译 / 上传并重启
- **`config.json` 含真实服务器地址与 SSH 私钥路径,切勿提交或打印** - **`config.json` 含真实服务器地址与 SSH 私钥路径,切勿提交或打印**
- 部署模式:运行时镜像 + 挂载 `app/` 目录;更新 = 上传产物 + 重启容器,无需重建镜像 - 部署模式:运行时镜像 + 挂载 `app/` 目录;更新 = 上传产物 + 重启容器,无需重建镜像
- 编译产物统一放 `artifacts/`(已 gitignore):`backend/app.jar`、`frontend/` dist、`license/` 整目录 - 编译产物统一放 `artifacts/`(已 gitignore):`backend/app.jar`、`frontend/` dist、`license/` 整目录
- 源码路径约定:`apps/web`、`apps/server`、`apps/license-server`
## 浏览器扩展(apps/browser-extension)
- `pnpm build` 会把 features / zip 同步到 `apps/server/src/main/resources/static/extension-features` 与 `static/extension`
## 其他 ## 其他
- `order-generator`:`npm start`(交互式),直接 `node main.js` 也可 - `apps/order-generator`:`npm start`(交互式),直接 `node main.js` 也可
- `.opencode/opencode.json` 配置了 jdtls LSP,指向本机 cursor-server 扩展路径(机器相关,未入库) - `.opencode/opencode.json` 配置了 jdtls LSP,指向本机 cursor-server 扩展路径(机器相关,未入库)
+18
View File
@@ -0,0 +1,18 @@
# 本地开发(AGENT_ENV=dev,默认)
# 可另建 gitignore 的 .env 覆盖本文件中的密钥
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
# 与 Server application-dev 同 Redis DB=2
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=deepseek-chat
CORS_ORIGINS=http://localhost:5173,http://localhost:5666
MCP_BASE_URL=http://localhost:8080/mcp
MCP_BEARER_TOKEN=dev-agent-mcp-token
MCP_TOOLS_ENABLED=true
PORT=8200
+27
View File
@@ -0,0 +1,27 @@
# Agent 环境配置说明
#
# 按 AGENT_ENV 加载对应文件(与后端 Spring profile 对齐):
# AGENT_ENV=dev → .env.dev (本地默认)
# AGENT_ENV=test → .env.test
# AGENT_ENV=pre → .env.pre
# AGENT_ENV=prod → .env.prod
#
# 本地也可再建 gitignore 的 .env,会覆盖同名变量(便于放真实 Key)。
# 部署时 compose 注入 AGENT_ENV=test|pre|prod,并挂载对应 .env.{env}。
#
# Redis:与同环境 Server 共用同一 Redis DB,读缓存键 agent:llm:rt:*
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=deepseek-chat
CORS_ORIGINS=http://localhost:5173,http://localhost:5666
# 须与同环境 Server ecom.agent.mcp.bearer-token / AGENT_MCP_TOKEN 一致;空则 MCP 工具整段跳过
MCP_BASE_URL=http://localhost:8080/mcp
MCP_BEARER_TOKEN=dev-agent-mcp-token
MCP_TOOLS_ENABLED=true
+17
View File
@@ -0,0 +1,17 @@
# 预发环境(AGENT_ENV=pre,端口 8202)
# 与 Server application-pre 对齐:Redis DB=0、后端 8102
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent_pre
MONGO_DB=ecom_dmb_agent_pre
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8102
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=
CORS_ORIGINS=https://cd.newloop.top
MCP_BASE_URL=http://192.168.3.101:8102/mcp
MCP_BEARER_TOKEN=pre-agent-mcp-token
MCP_TOOLS_ENABLED=true
PORT=8202
+17
View File
@@ -0,0 +1,17 @@
# 生产环境(AGENT_ENV=prod,端口 8203)
# 与 Server application-prod 对齐:Redis DB=0、后端 8103
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent
MONGO_DB=ecom_dmb_agent
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8103
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=
CORS_ORIGINS=https://cd.newloop.top
MCP_BASE_URL=http://192.168.3.101:8103/mcp
MCP_BEARER_TOKEN=prod-agent-mcp-token
MCP_TOOLS_ENABLED=true
PORT=8203
+17
View File
@@ -0,0 +1,17 @@
# 测试环境(AGENT_ENV=test,端口 8201)
# 与 Server application-test 对齐:Redis DB=3、后端 8101
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_test:ecom_dmb_agent_test@192.168.3.100:27017/?authSource=ecom_dmb_agent_test
MONGO_DB=ecom_dmb_agent_test
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/3
SERVER_BASE_URL=http://192.168.3.101:8101
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=
CORS_ORIGINS=https://cd.newloop.top,http://localhost:5666
MCP_BASE_URL=http://192.168.3.101:8101/mcp
MCP_BEARER_TOKEN=test-agent-mcp-token
MCP_TOOLS_ENABLED=true
PORT=8201
+10
View File
@@ -0,0 +1,10 @@
.venv/
__pycache__/
*.py[cod]
.env
.pytest_cache/
.mypy_cache/
.ruff_cache/
*.egg-info/
dist/
build/
+389
View File
@@ -0,0 +1,389 @@
# Agent 客户端设计方案(v1)
> 状态:**已拍板,按本文落地**(2026-09-18)
> 范围:`apps/agent`(Python LangGraph)+ `apps/web` 独立聊天页 + 现有 `apps/server` MCP 增强
> 非目标:不直连业务库;不替代 Open API;不做公司级共享会话(v1)
---
## 1. 目标与边界
### 1.1 目标
- 多租户、多用户:隔离键 `company_id + user_id`
- 每用户独立长期记忆;多会话;聊天记录持久化(Mongo)
- Agent 通过 MCP 调 Java 后端能力(查数/办事),不直连 MySQL/业务 Mongo
- 前端提供**独立聊天页面**(登录后使用,复用现有鉴权与菜单体系)
- **租户自管模型凭证**:各公司配置 OpenAI Compatible `base_url` + `api_key` + `model`;Agent 调用时自动注入;Redis 缓存
### 1.2 边界
| 层 | 职责 | 不做什么 |
|----|------|----------|
| `apps/web` 聊天页 | UI、会话列表、流式展示、**会话级选模型** | 不编排 LLM、不调 MCP、不持有明文 Key |
| `apps/web` 模型管理页 | 凭证 CRUD、启用模型列表、记忆管理(`agent:llm-settings`) | 不发聊天 |
| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、按会话模型注入凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** |
| `apps/server` | MySQL 存公司模型配置;MCP `@McpTool`;内部 llm-runtime | 不存聊天记录(对话在 Agent Mongo) |
### 1.3 数据流
```text
[ web-antd ]
│ JWT
├─► 模型管理页 → Server /api/company/agent-llm-providers* (多提供商 CRUD)
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,含 providerId)
└─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_provider_id + llm_model)
│
├─ Redis agent:llm:rt:{companyId}:{providerId}:{model}
├─ Server /api/internal/agent/llm-runtime?companyId=&providerId=&model=
├─ ChatOpenAI(base_url, api_key, model) 按会话选型注入
└─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools
```
---
## 2. 已拍板结论
| # | 议题 | 结论 |
|---|------|------|
| **A** | 会话归属 | 严格私有 `(company_id, user_id)` |
| **B** | 记忆范围 | 仅用户级 |
| **C** | 聊天页 | 挂在 `web-antd` 独立路由 |
| **D** | AI Chat UI 库 | 不引入;Ant Design Vue 自建 |
| **E** | Agent 形态 | `apps/agent` 独立 FastAPI 进程 |
| **F** | MCP 租户 | 按请求注入 company |
| **G** | 模型接入 | **OpenAI Compatible API**;租户自管 Key;Redis 缓存;Agent 自动注入 |
### 2.1 关于 D(聊天 UI)——摘要
不引入专门 AI Chat UI 库;用 Ant Design Vue 自建会话列表 + 气泡 + 输入 + SSE。
### 2.2 关于 G(OpenAI Compatible + 租户 Key)——结论
**认同,作为 v1 标准。**
理由:
- 一套 `base_url + api_key + model` 即可兼容 OpenAI / DeepSeek / 月之暗面 / SiliconFlow / 自建 vLLM 等,避免按厂商分支客户端。
- LangChain `ChatOpenAI`(或等价 OpenAI SDK)天然支持 `base_url`,与 LangGraph 无缝。
- Key 归租户:成本与限额由公司自负;平台不垫付模型费。
约束:
1. **真相源**:MySQL `agent_company_llm_provider`(多行/公司)+ `agent_company_llm_model`(挂 `provider_id`);`api_key` **AES-GCM 加密**。
2. **缓存**:Redis `agent:llm:rt:{company_id}:{provider_id}:{model}`;配置变更按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
3. **注入**:Agent 按会话 **`llm_provider_id` + `llm_model`** 解析;跨提供商允许同名 model。
4. **权限**:写配置靠 `agent:llm-settings`;聊天选模靠 `agent:chat`。
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且未指定选型时)。
6. **启用列表写入**:按 `(provider_id, model)` **增量 upsert**(更新已有、插入新增、删除取消勾选),禁止整表删建,以免破坏会话引用。
---
## 3. 总体架构
```text
apps/agent/
api/ # 接口层:HTTP / DTO / 鉴权依赖
application/ # 应用层:用例编排(发消息、列会话、恢复上下文)
domain/ # 领域层:Session / Message / Memory 模型与规则(无框架)
agent/ # 编排层:工具装载、运行态、LangGraph(预留)
infrastructure/ # 基础设施:Mongo/Redis、LLM、MCP、JWT
config/ # 配置
```
依赖方向:**api → application → domain ← infrastructure**;`application` 经 `agent` 装载工具;`agent` 只依赖 domain/config 与 infrastructure 适配器,不写 Mongo。
### 3.1 分层职责
| 层 | 包 | 职责 | 禁止 |
|----|-----|------|------|
| 接口 | `api` | 路由、请求/响应模型、依赖注入、鉴权提取 | 拼 prompt、直连 Mongo、调 MCP SDK |
| 应用 | `application` | 「用户发一条消息」「新建会话」「加载记忆」用例、事务边界(逻辑) | 框架注解泄漏到 domain |
| 领域 | `domain` | 会话状态机、记忆条目规则、隔离键不变量 | HTTP、Motor、LangChain 类型 |
| 编排 | `agent` | 工具装载、Turn State、LangGraph 图(预留) | 写 Mongo 细节、HTTP 路由 |
| 基础设施 | `infrastructure` | Mongo/Redis 仓库、MCP、ChatModel、JWT 校验 | 业务用例 if/else 堆砌 |
---
## 4. 会话 / 聊天 / 记忆(Mongo)
### 4.1 库
- 独立库名建议:`ecom_dmb_agent`(与业务 Mongo 同实例不同库)
- 所有查询强制带 `company_id` + `user_id`
### 4.2 集合
#### `agent_sessions`
| 字段 | 说明 |
|------|------|
| `thread_id` | 会话 ID(UUID),作业务主键 |
| `company_id`, `user_id` | 隔离键 |
| `title` | 可空,首轮后可自动生成 |
| `status` | `active` / `archived` / `deleted` |
| `summary` | 会话滚动摘要(可选) |
| `llm_provider_id` | 会话选用的提供商 id |
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
| `created_at`, `updated_at`, `last_message_at` | |
唯一索引:`(company_id, user_id, thread_id)`
列表索引:`(company_id, user_id, status, updated_at desc)`
#### `agent_messages`
| 字段 | 说明 |
|------|------|
| `company_id`, `user_id`, `thread_id` | |
| `seq` | 会话内单调序号 |
| `role` | `user` / `assistant` / `system` / `tool` |
| `content` | 文本或结构化块 |
| `tool_name` / `tool_call_id` | tool 轨迹(可选) |
| `created_at` | |
索引:`(company_id, user_id, thread_id, seq)`
**产品真相源 = 本表**;组装模型上下文时:Mongo 多拉若干条 → **按 token 预算从旧到新裁剪**(非固定 40 条);更早内容待 `sessions.summary`(未落地)。
上下文窗口来源(多数 OpenAI Compatible **不会**在 API 返回 context 大小):
1. 启用模型上的 `context_window`(设置页可填;probe 若带回扩展字段可预填)
2. 否则按默认模型的 `model` 名启发式
3. 再否则默认 `128000`
预算:system + 本轮 user + 预留输出/tool 后,剩余给历史原文。
#### `agent_user_memory`
| 字段 | 说明 |
|------|------|
| `company_id`, `user_id` | |
| `kind` | `preference` / `fact` / `entity` / `summary` |
| `key` | 可选,同 key 覆盖更新 |
| `summary` | 短摘要(规则生成),供关键词检索与工具列表 |
| `text` / `value` | 完整正文;仅 `memory_load` 返回 |
| `source_thread_id` | 溯源 |
| `status` | `active` / `stale` / `deleted` |
| `confidence` | 0~1 |
| `created_at`, `updated_at`, `expires_at?` | |
索引:`(company_id, user_id, status, kind, updated_at)`;可选唯一 `(company_id, user_id, key)` where key 非空。
记忆策略(现行):
- **不做向量检索**,也不做每轮 Top-K / 全量注入 system。
- 写入时同步生成规则 `summary`;检索对 `summary`/`text` 做租户内关键词匹配。
- 模型经工具按需使用:`memory_search`(摘要,回合内 `ref`)→ `memory_load(refs)`(正文);亦可 `memory_save`。
- 工具结果不对模型暴露 Mongo `_id`;向用户转述须自然语言,禁止表格/字段名。
- 显式「记住…」仍可由后端捕获写入;system 仅提示条数与「本轮已写入」,不塞正文。
- 自动对话抽取为 P2;LLM 润色摘要为后续。
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
见 `apps/server/sql/design/agent/agent_company_llm_provider_models_design.sql` 与迁移 `V20260920b` / `V20260920d`(多提供商)。
| 表 | 说明 |
|----|------|
| `agent_company_llm_provider` | 公司多套 `base_url` + 加密 Key |
| `agent_company_llm_model` | 挂 `provider_id`;`UNIQUE(provider_id, model)`;`enabled` 启停;公司级全局一条 `is_default=1`(须启用) |
浏览器:
- `GET/POST /api/company/agent-llm-providers`;`GET/PUT/DELETE .../providers/{id}`;`PUT .../providers/{id}/models`(增量 upsert)
- `POST /api/company/agent-llm-settings/probe-models`(可带 `providerId` + `useStoredKey`)
- `GET /api/company/agent-llm-models`:`{ items: [{ providerId, providerDisplayName, model, label, contextWindow, isDefault }] }`
Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=`。
### 4.3 与 LangGraph 的关系
| 概念 | 落点 |
|------|------|
| `thread_id` | 与 LangGraph `configurable.thread_id` 对齐 |
| 聊天记录 | Mongo `agent_messages`(产品真相) |
| Checkpointer | 另集合 `agent_graph_checkpoints`(仅运行时恢复,可同库) |
| 长期记忆 | `agent_user_memory`(跨 thread) |
写入时序(发消息用例):
1. 鉴权得到 `company_id`, `user_id`
2. 校验 `thread_id` 归属
3. 显式「记住」可写记忆(含 summary);统计 active 条数
4. 追加 user message → Mongo
5. 加载最近消息;挂载 builtin / memory_* / MCP 工具 → 流式生成(记忆正文不注入 system)
6. 模型按需 `memory_search` → `memory_load`
7. 落库 assistant/tool messages
8. 异步(后续):更新 session.summary;可选抽取记忆条目
---
## 5. Agent HTTP API(给前端)
前缀建议:`/api/agent`(Agent 服务自身端口,如 `8200`;网关可反代)。
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
| GET | `/memories` | 查看自己的记忆条目(可透明) |
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
公司 LLM 配置在 **Server**:按提供商 CRUD + `PUT .../models` 增量 upsert;聊天只读 `GET /api/company/agent-llm-models`。
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
---
## 6. MCP 与多租户(server)
1. Agent 持有服务级 Bearer(`AGENT_MCP_TOKEN` / `ecom.agent.mcp.bearer-token`)
2. 每次请求头:`X-Agent-Company-Id`、`X-Agent-User-Id`(`AgentMcpAuthenticationFilter`)
3. `CurrentUserContext` 从 `AgentMcpAuthentication` 取租户;静态 `company-id` 仅本地 fallback
4. 内部路径 `/api/internal/agent/**` 同样走 Agent Bearer,JWT 过滤器跳过
权限:v1 MCP 按公司维度只读 BI;办事类 tool 二期再收紧到真实用户权限。
---
## 7. 前端(web-antd)
### 7.1 页面
- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`)
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`);多提供商卡片
- 我的记忆:`/agent/memories`,头像下拉入口(有 `agent:chat` 时显示;静态路由)
- 聊天顶栏:按提供商分组 `Select`;切换即 PATCH `llmProviderId`+`llmModel`
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
### 7.2 组件(自建,不引入 AI UI 库)
```text
views/agent/chat/
index.vue # 聊天:会话列表 + 消息 + 顶栏选模型
catalog-cite*.vue/ts # 店铺/商品引用输入
views/agent/llm-settings/
index.vue # 模型管理:多提供商 CRUD + 启用列表增量保存
views/agent/memories/
index.vue # 我的记忆:列表 / 删除(用户中心入口)
api/agent/ # 调 Agent + Server 公司 LLM API
```
### 7.3 配置
- `VITE_AGENT_API_URL`(dev 可代理到 `localhost:8200`)
- 请求头带现有 accessToken
---
## 8. `apps/agent` 工程结构(落地骨架)
```text
apps/agent/
requirements.txt
README.md
DESIGN.md # 本文
api/
main.py
deps.py # 当前用户 / 用例组装
response.py
routers/sessions.py
routers/chat.py
routers/memories.py
application/
session_service.py
chat_service.py
memory_service.py
llm_settings_service.py # LlmRuntimeService:读 Redis/Server
domain/
models.py
ports.py
agent/
runtime.py # 本轮工具装载入口
state.py # Turn State(图扩展点)
tools/builtin.py
tools/memory.py # memory_search / load / save
graphs/ # LangGraph 预留
infrastructure/
auth/jwt.py
llm/factory.py
llm/gateway.py
mcp/client.py
persistence/mongo/
persistence/redis/
config/settings.py
```
技术选型(v1):
- FastAPI + uvicorn
- LangGraph + langchain-openai(OpenAI Compatible)+ langchain-mcp-adapters
- motor / pymongo、redis、httpx
- PyJWT、pydantic-settings
---
## 9. 分期落地
### P0(可演示)— 已完成
1. `apps/agent` 分层骨架 + 配置
2. Mongo 会话/消息;公司 LLM → **MySQL(Server)** + Redis 运行时
3. OpenAI Compatible 注入 + 流式 SSE
4. web-antd 独立聊天页 + LLM 配置入口
5. JWT 验签打通
### P1(接上现网能力)— 已完成
1. MCP client + server 按请求租户头
2. 挂上现有 BI tools(`langchain-mcp-adapters`)
3. 用户记忆:摘要检索 + 模型按需 load(显式「记住」/ memory_save)
4. (摘要压缩长上下文 → 仍 P2)
### P2
1. 记忆抽取异步任务
2. Checkpointer 持久化与失败恢复
3. 工具调用 UI 细化、引用卡片
4. 公司级记忆 / 共享会话(若产品需要)
5. 会话摘要压缩长上下文
---
## 10. 风险与约束
- Agent 与 Java 两套部署:CORS、网关、环境变量(`JWT_SECRET`、`AGENT_MCP_TOKEN`、`AGENT_LLM_SECRET`/`ecom.agent.llm.secret`、Mongo/Redis URI)要对齐;**Redis 须与 Server 同库**才能共享 LLM 缓存
- 切勿让浏览器直连 `/mcp`;切勿把完整 `api_key` 返回前端
- 租户 Key 泄露面:Redis 与进程内存;生产 Redis 需 ACL/独立 DB;日志禁止打印 Key
- 聊天含业务数据:Mongo 权限与备份纳入运维;删除会话应级联软删消息
- License:若需对「智能助手」门禁,二期加 `LicenseFeature`,v1 可用菜单权限控制
---
## 11. Responses API 分期(多提供商)
原则:**Mongo 仍是对话真相源**;Responses 链(`previous_response_id`)只是同提供商同模型下的加速缓存,切换选型即作废并全量 rebuild。
### Responses-P0 / P1(已落地)— 运行时探测,不写死主机
原则:优先新协议;能力靠探测 + Redis 缓存(`agent:llm:cap:*`),按错误回退,不按 OpenAI/DeepSeek 主机写死。
同轮未产出 token 前的阶梯:
1. **Responses + `store=true`**(语义证实后;有会话链则只发增量 + `previous_response_id`)
2. store 未知:Responses + `store=true` + **Mongo 全量历史**,成功后再做语义探测
3. **store 证伪**:先 **无状态 Responses + Mongo 全量**,接口失败再 **Completions + Mongo 全量**
4. Responses 端点不可用 → Completions
成功后写入能力缓存。**`store=true` 认定**:独立语义探测——先让模型记住密钥,再仅用 `previous_response_id`(不带历史)追问;答对才记 true。未证实前禁止只发增量。
---
## 12. 文档维护
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
+51
View File
@@ -0,0 +1,51 @@
# Ecom DMB Agent(Python / FastAPI / LangGraph)
设计见 [DESIGN.md](./DESIGN.md)。
## 本地运行
```bash
cd apps/agent
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
# 默认 AGENT_ENV=dev,加载 .env.dev;也可 cp .env.dev .env 做本地覆盖
uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
```
健康检查:`GET http://localhost:8200/health`
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
**模型 API 配置不在本服务**:浏览器走 Java 提供商 CRUD(含 `apiStyle`);Agent 拉 runtime 后**运行时探测** Responses/store,结果缓存 Redis `agent:llm:cap:*`,失败阶梯为 Responses+store → Responses → Completions(见 DESIGN §11)。
## 分环境配置
与后端 `application-{profile}.yml` 对应,由 `AGENT_ENV` 选择文件:
| AGENT_ENV | 配置文件 | 端口 | Redis DB(对齐 Server) |
|-----------|----------|------|-------------------------|
| `dev`(默认) | `.env.dev` | 8200 | 2 |
| `test` | `.env.test` | 8201 | 3 |
| `pre` | `.env.pre` | 8202 | 0 |
| `prod` | `.env.prod` | 8203 | 0 |
若存在 gitignore 的 `.env`,仅在 `AGENT_ENV=dev` 时覆盖同名变量。部署时 compose 注入 `AGENT_ENV=test|pre|prod`。
## 环境变量要点
| 变量 | 说明 |
|------|------|
| `AGENT_ENV` | 选择 `.env.{env}` |
| `JWT_SECRET` | 与 Java `jwt.secret` 一致 |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory) |
| `REDIS_URL` | **与同环境 Server 同 DB**,读 LLM 运行时缓存 `agent:llm:rt:*` |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime` |
| `MCP_BASE_URL` / `MCP_BEARER_TOKEN` | 调 Server `/mcp`;Bearer 须与 Java `AGENT_MCP_TOKEN` / `ecom.agent.mcp.bearer-token` 一致,空则不加载 MCP 工具 |
| `LLM_FALLBACK_*` | 仅本地:公司未配置时的 OpenAI Compatible fallback |
| `CHAT_HISTORY_FETCH_LIMIT` | 从 Mongo 最多拉多少条再按 token 裁剪(默认 200) |
| `LLM_DEFAULT_CONTEXT_WINDOW` | 无法估计时的默认上下文(默认 128000) |
| `CONTEXT_RESERVE_OUTPUT_TOKENS` / `CONTEXT_RESERVE_TOOL_TOKENS` | 预留给生成与本轮工具 |
## 分层
`api` → `application` → `domain` ← `infrastructure`;编排在 `agent/`(工具装载 / 图预留)
+1
View File
@@ -0,0 +1 @@
"""编排层:工具装载与 LangGraph 扩展点(不写 Mongo)。"""
+1
View File
@@ -0,0 +1 @@
"""LangGraph 图定义预留。"""
+47
View File
@@ -0,0 +1,47 @@
"""Agent 编排:按会话 scene 装载工具。"""
from __future__ import annotations
from typing import Any
from application.memory_service import MemoryService
from config.settings import Settings
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL, Actor
async def load_tools_for_turn(
settings: Settings,
*,
actor: Actor,
memory: MemoryService,
scene: str = SCENE_GENERAL,
client_tools: list[Any] | None = None,
) -> list[Any]:
"""各场景均挂 memory_*;general 全量 MCP,发布场景仅目录/拼多多 + 前端 ui_。"""
from agent.tools.builtin import builtin_tools
from agent.tools.memory import memory_tools
from infrastructure.mcp.client import load_mcp_tools
scene_value = (scene or SCENE_GENERAL).strip() or SCENE_GENERAL
tools: list[Any] = [*builtin_tools(), *memory_tools(memory, actor)]
mcp_tools = await load_mcp_tools(
settings,
company_id=actor.company_id,
user_id=actor.user_id,
)
if scene_value == SCENE_ECOM_GOODS_PUBLISH:
# 发布场景:目录 + 拼多多渠道;不挂经营 BI
mcp_tools = [
t
for t in mcp_tools
if _tool_name(t).startswith(("catalog_", "pdd_")) or _tool_name(t) == "mcp_ping"
]
tools.extend(mcp_tools)
if client_tools:
tools.extend(client_tools)
return tools
def _tool_name(tool: Any) -> str:
return str(getattr(tool, "name", None) or "")
+18
View File
@@ -0,0 +1,18 @@
"""Agent 运行态占位(LangGraph State 后续落此)。"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class AgentTurnState:
"""单轮对话编排状态(v1 尚未被图驱动,仅作扩展点)。"""
company_id: int
user_id: str
thread_id: str
memory_count: int = 0
tool_names: list[str] = field(default_factory=list)
extras: dict[str, Any] = field(default_factory=dict)
+5
View File
@@ -0,0 +1,5 @@
"""Agent 工具面:本地 builtin / 记忆;MCP 传输在 infrastructure.mcp。"""
from agent.tools.builtin import builtin_tools
__all__ = ["builtin_tools"]
+47
View File
@@ -0,0 +1,47 @@
"""本地工具:不依赖 MCP / 业务库,只提供模型无法自行得知的环境信息。"""
from __future__ import annotations
import json
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
from langchain_core.tools import BaseTool, tool
# 与后端业务库、BI 日期口径一致
_TZ = ZoneInfo("Asia/Shanghai")
_WEEKDAYS = ("周一", "周二", "周三", "周四", "周五", "周六", "周日")
def builtin_tools() -> list[BaseTool]:
return [get_current_time]
@tool
def get_current_time() -> str:
"""获取当前业务时间(Asia/Shanghai)。
用户说近 N 天、昨天、本周、本月等相对日期时必须先调用本工具,
用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查经营数据,不要向用户索要日期。
近 N 天含今天,共 N 个自然日。
"""
now = datetime.now(_TZ)
today = now.date()
payload = {
"timezone": "Asia/Shanghai",
"now": now.isoformat(timespec="seconds"),
"today": today.isoformat(),
"weekday": _WEEKDAYS[today.weekday()],
"ranges": {
"yesterday": _span(today - timedelta(days=1), today - timedelta(days=1)),
"last_7_days": _span(today - timedelta(days=6), today),
"last_30_days": _span(today - timedelta(days=29), today),
"this_week": _span(today - timedelta(days=today.weekday()), today),
"this_month": _span(today.replace(day=1), today),
},
}
return json.dumps(payload, ensure_ascii=False)
def _span(start: date, end: date) -> dict[str, str]:
return {"startDate": start.isoformat(), "endDate": end.isoformat()}
+36
View File
@@ -0,0 +1,36 @@
"""工具名 → 用户可见中文状态文案(不暴露内部 name)。"""
from __future__ import annotations
_LABELS: dict[str, str] = {
"memory_search": "检索记忆",
"memory_load": "载入记忆",
"memory_save": "保存记忆",
"get_current_time": "确认业务日期",
"catalog_search": "查找店铺/商品",
"catalog_sku_detail": "查找内部规格",
"pdd_goods_search": "查找拼多多商品",
"pdd_goods_detail": "读取拼多多商品",
"ui_get_publish_snapshot": "读取发布表单",
"ui_patch_basic": "更新基础信息",
"ui_patch_skus": "更新价格库存",
"ui_patch_props": "更新类目属性",
"ui_set_spec_axes": "设置规格轴",
}
def tool_status_label(name: str) -> str:
"""将工具名映射为前端状态条文案。"""
key = (name or "").strip()
if not key:
return "处理中"
if key in _LABELS:
return _LABELS[key]
lower = key.lower()
if lower.startswith("ui_"):
return "编辑发布表单"
if lower.startswith("catalog_") or lower.startswith("pdd_"):
return "查找商品信息"
if "order" in lower or "sales" in lower or "bi_" in lower or "stat" in lower:
return "查询经营数据"
return "处理中"
+124
View File
@@ -0,0 +1,124 @@
"""长期记忆工具:摘要检索 + 按需载入(对模型暴露 ref,不暴露 Mongo id)。"""
from __future__ import annotations
import json
from langchain_core.tools import BaseTool, tool
from application.memory_service import MemoryService
from domain.models import Actor, MemoryKind
_KIND_LABEL = {
MemoryKind.PREFERENCE.value: "偏好",
MemoryKind.FACT.value: "事实",
MemoryKind.ENTITY.value: "实体",
MemoryKind.SUMMARY.value: "摘要",
}
def memory_tools(svc: MemoryService, actor: Actor) -> list[BaseTool]:
"""闭包绑定 company/user;本轮 ref→id 映射仅工具内部使用。"""
# 本轮命中序号 → Mongo id(不对模型展示 id)
ref_to_id: dict[int, str] = {}
next_ref = 1
def _alloc_ref(memory_id: str | None) -> int | None:
nonlocal next_ref
if not memory_id:
return None
for r, mid in ref_to_id.items():
if mid == memory_id:
return r
r = next_ref
next_ref += 1
ref_to_id[r] = memory_id
return r
@tool
async def memory_search(query: str = "", limit: int = 8) -> str:
"""搜索或列出当前用户的长期记忆摘要(结果仅供内部)。
query 可空:空则返回最近若干条。用户问「有哪些记忆」时调用。
返回 items: [{ref, summary, kind}];需要正文时再用 memory_load(refs)。
对用户:只转述命中摘要,结论先行;不汇报未命中、多轮搜索或 ref。
"""
rows = await svc.search(actor, query or "", limit=limit)
items = []
for row in rows:
ref = _alloc_ref(row.get("id"))
if ref is None:
continue
kind = row.get("kind") or MemoryKind.FACT.value
items.append(
{
"ref": ref,
"summary": row.get("summary") or "",
"kind": _KIND_LABEL.get(kind, "事实"),
}
)
return json.dumps(
{"count": len(items), "items": items},
ensure_ascii=False,
)
@tool
async def memory_load(refs: list[int]) -> str:
"""按 memory_search 的 ref 载入正文;单次最多 5 条(仅供内部)。
对用户只叙述正文含义,禁止输出 ref 或检索过程。
"""
ids: list[str] = []
for r in refs or []:
try:
key = int(r)
except (TypeError, ValueError):
continue
mid = ref_to_id.get(key)
if mid:
ids.append(mid)
rows = await svc.load(actor, ids[:5])
items = []
for row in rows:
ref = _alloc_ref(row.get("id"))
kind = row.get("kind") or MemoryKind.FACT.value
items.append(
{
"ref": ref,
"summary": row.get("summary") or "",
"text": row.get("text") or "",
"kind": _KIND_LABEL.get(kind, "事实"),
}
)
return json.dumps({"items": items}, ensure_ascii=False)
@tool
async def memory_save(text: str, kind: str = "fact") -> str:
"""写入长期记忆(跨会话)。kind:preference / fact / entity。
确认时只简短复述内容;不提 ref/id,不主动建议再记别的。
"""
kind_map = {
"preference": MemoryKind.PREFERENCE,
"fact": MemoryKind.FACT,
"entity": MemoryKind.ENTITY,
"summary": MemoryKind.SUMMARY,
}
mk = kind_map.get((kind or "fact").lower(), MemoryKind.FACT)
try:
saved = await svc.save(actor, text, kind=mk)
except ValueError as e:
return json.dumps({"ok": False, "message": str(e)}, ensure_ascii=False)
ref = _alloc_ref(saved.get("id"))
return json.dumps(
{
"ok": True,
"ref": ref,
"summary": saved.get("summary") or "",
"kind": _KIND_LABEL.get(saved.get("kind") or "", "事实"),
},
ensure_ascii=False,
)
return [memory_search, memory_load, memory_save]
+152
View File
@@ -0,0 +1,152 @@
"""发布场景前端写工具。
只向模型注册 schema。真正写入发生在浏览器;streamer 推 client_tool 后等待回执,
不把这里的占位返回值当成 ToolMessage。
"""
from __future__ import annotations
from typing import Any
from langchain_core.tools import StructuredTool
from pydantic import BaseModel, Field
class PatchBasicArgs(BaseModel):
"""只填要改的字段;未出现的字段保持页面原值。"""
goodsName: str | None = Field(
default=None,
description="商品标题:汉字算 2、英文数字算 1,合计最多 60(约 30 汉字)",
)
goodsDesc: str | None = Field(default=None, description="商品描述;空字符串表示清空")
marketPriceYuan: float | None = Field(default=None, description="参考价,元")
twoPiecesDiscount: float | None = Field(
default=None, description="满两件折扣,0–10,9.5 表示 9.5 折,0 表示取消"
)
shipmentLimitSecond: int | None = Field(
default=None, description="承诺发货秒数,只能是快照中的 86400 或 172800"
)
isFolt: bool | None = Field(default=None, description="是否假一赔十")
isRefundable: bool | None = Field(default=None, description="是否 7 天无理由")
isPreSale: bool | None = Field(default=None, description="是否预售")
secondHand: bool | None = Field(default=None, description="是否二手")
costTemplateId: int | None = Field(
default=None, description="运费模板 ID,必须来自快照 costTemplates"
)
class SkuPatch(BaseModel):
outSkuSn: str = Field(description="已有商家编码,勿编造")
priceYuan: float | None = Field(default=None, description="单买价,元")
multiPriceYuan: float | None = Field(default=None, description="拼单价,元")
quantity: int | None = Field(default=None, description="库存")
weight: int | None = Field(default=None, description="重量,克")
class PatchSkusArgs(BaseModel):
skus: list[SkuPatch] = Field(description="按商家编码局部更新,不增删行")
class PropPatch(BaseModel):
refPid: int = Field(description="类目属性 refPid,来自快照 goodsProperties")
value: str = Field(description="枚举传 vid 或选项文案;文本/数值传字面值。多选用英文逗号分隔")
unit: str | None = Field(default=None, description="单位,必须是该属性 units 中的一项")
class PatchPropsArgs(BaseModel):
props: list[PropPatch] = Field(description="只更新列出的类目属性")
class SpecAxis(BaseModel):
name: str = Field(description="规格维名称,如 颜色、尺码")
values: list[str] = Field(description="该维下的规格值列表")
class SkuAssignment(BaseModel):
outSkuSn: str = Field(
description="商家编码(SKU 唯一身份,必须来自当前表单已有编码,勿编造)"
)
values: list[str] = Field(
description="与 axes 同序的规格值文案,如 1 维 ['月光白'] 或 2 维 ['红','S']"
)
class SetSpecAxesArgs(BaseModel):
axes: list[SpecAxis] = Field(
description="完整规格轴(维名+值列表)"
)
skuAssignments: list[SkuAssignment] | None = Field(
default=None,
description=(
"把每个商家编码挂到新的规格组合上。"
"仅改同维文案可省略;2×2↔1×4 等结构调整时必须提供,"
"由你决定哪个编码对应哪组新描述。"
),
)
def build_publish_client_tools(
*,
form_snapshot: dict[str, Any] | None = None,
) -> list[Any]:
"""仅注册写工具;读快照已注入 system,避免再占一轮「读取发布表单」。"""
del form_snapshot # 快照由 system 注入,工具闭包不再依赖
def patch_basic(**_kwargs: Any) -> str:
return "已请求更新基础信息"
def patch_skus(skus: list[Any]) -> str:
return f"已请求更新 {len(skus or [])} 条 SKU"
def patch_props(props: list[Any]) -> str:
return f"已请求更新 {len(props or [])} 个类目属性"
def set_spec_axes(
axes: list[Any],
skuAssignments: list[Any] | None = None,
) -> str:
n = len(axes or [])
m = len(skuAssignments or [])
if m:
return f"已请求写入 {n} 个规格维,并按商家编码绑定 {m} 个 SKU"
return f"已请求写入 {n} 个规格维,页面将重建 SKU 行"
return [
StructuredTool.from_function(
func=patch_basic,
name="ui_patch_basic",
description=(
"局部更新标题、描述、参考价、满两件折扣、发货时限、"
"假一赔十/7天无理由/预售/二手、运费模板。未传的字段不要改。"
),
args_schema=PatchBasicArgs,
),
StructuredTool.from_function(
func=patch_skus,
name="ui_patch_skus",
description="按已有商家编码局部更新单买价、拼单价、库存、重量。不增删 SKU,不改规格文案。",
args_schema=PatchSkusArgs,
),
StructuredTool.from_function(
func=patch_props,
name="ui_patch_props",
description="按 refPid 局部更新类目属性。枚举用快照里的 vid 或文案。",
args_schema=PatchPropsArgs,
),
StructuredTool.from_function(
func=set_spec_axes,
name="ui_set_spec_axes",
description=(
"设置规格轴。商家编码是 SKU 唯一身份;结构调整时用 skuAssignments "
"把已有 outSkuSn 挂到新的 values 组合上,前端按编码对齐。"
),
args_schema=SetSpecAxesArgs,
),
]
def is_client_tool_name(name: str) -> bool:
"""需前端执行的写工具;读类工具不走 client_tool。"""
n = name or ""
return n.startswith("ui_set_") or n.startswith("ui_patch_")
+1
View File
@@ -0,0 +1 @@
"""HTTP 接口层:路由、DTO、依赖注入。"""
+83
View File
@@ -0,0 +1,83 @@
"""FastAPI 依赖组装。"""
from __future__ import annotations
from fastapi import Depends, Header, HTTPException, status
from application.chat_service import ChatService
from application.llm_settings_service import LlmRuntimeService
from application.memory_service import MemoryService
from application.session_service import SessionService
from config.settings import Settings, get_settings
from domain.models import Actor
from infrastructure.auth.jwt import parse_actor
from infrastructure.llm.factory import OpenAICompatibleStreamer
from infrastructure.llm.gateway import ServerLlmRuntimeGateway
from infrastructure.persistence.mongo.client import get_db
from infrastructure.persistence.mongo.repositories import (
MongoMemoryRepository,
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.persistence.redis.cache import (
RedisLlmProtocolCapabilityCache,
RedisLlmRuntimeCache,
get_redis,
)
async def current_actor(
authorization: str | None = Header(default=None),
settings: Settings = Depends(get_settings),
) -> Actor:
if not authorization or not authorization.lower().startswith("bearer "):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 Bearer Token")
token = authorization.split(" ", 1)[1].strip()
if not token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 Bearer Token")
return parse_actor(settings, token)
async def llm_runtime_service(
settings: Settings = Depends(get_settings),
) -> LlmRuntimeService:
cache = RedisLlmRuntimeCache(get_redis(settings))
return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings))
async def session_service(
settings: Settings = Depends(get_settings),
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
) -> SessionService:
db = await get_db(settings)
return SessionService(
MongoSessionRepository(db),
llm_runtime=llm_svc,
messages=MongoMessageRepository(db),
)
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
db = await get_db(settings)
return MemoryService(settings, MongoMemoryRepository(db))
async def chat_service(
settings: Settings = Depends(get_settings),
sessions: SessionService = Depends(session_service),
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
mem_svc: MemoryService = Depends(memory_service),
) -> ChatService:
db = await get_db(settings)
return ChatService(
settings=settings,
sessions=sessions,
session_repo=MongoSessionRepository(db),
messages=MongoMessageRepository(db),
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(
RedisLlmProtocolCapabilityCache(get_redis(settings)),
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
),
)
+57
View File
@@ -0,0 +1,57 @@
"""Agent FastAPI 入口。"""
from __future__ import annotations
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.response import fail
from api.routers import chat, memories, sessions
from config.settings import get_settings
from infrastructure.persistence.mongo.client import close_mongo, ensure_indexes, get_db
from infrastructure.persistence.redis.cache import close_redis
@asynccontextmanager
async def lifespan(_app: FastAPI):
settings = get_settings()
db = await get_db(settings)
await ensure_indexes(db)
yield
await close_mongo()
await close_redis()
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(title=settings.app_name, lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origin_list,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(sessions.router, prefix="/api/agent")
app.include_router(chat.router, prefix="/api/agent")
app.include_router(memories.router, prefix="/api/agent")
@app.exception_handler(HTTPException)
async def http_exception_handler(_request: Request, exc: HTTPException):
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
return JSONResponse(
status_code=exc.status_code,
content=fail(detail, code=exc.status_code),
)
@app.get("/health")
async def health():
return {"ok": True, "service": settings.app_name}
return app
app = create_app()
+14
View File
@@ -0,0 +1,14 @@
"""与 Java ApiResponse 对齐的统一响应。"""
from __future__ import annotations
from typing import Any
def ok(data: Any = None, message: str = "操作成功") -> dict[str, Any]:
return {"code": 0, "message": message, "data": data}
def fail(message: str, code: int = 1) -> dict[str, Any]:
return {"code": code, "message": message, "data": None}
+148
View File
@@ -0,0 +1,148 @@
"""对话与历史消息。"""
from __future__ import annotations
import json
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from api.deps import chat_service, current_actor, session_service
from api.response import ok
from application.chat_service import ChatService
from application.client_tool_gate import get_client_tool_gate
from application.session_service import SessionService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["chat"])
class ChatBody(BaseModel):
content: str = Field(min_length=1, max_length=20000)
# 发布场景:当前表单快照,注入 system(不再走 ui_get_publish_snapshot)
formSnapshot: dict | None = None
class ClientToolResultBody(BaseModel):
"""浏览器执行 ui_set_* 后的真实结果,唤醒挂起的工具轮。"""
toolCallId: str = Field(min_length=1, max_length=200)
ok: bool
message: str = Field(default="", max_length=2000)
@router.get("/{thread_id}/messages")
async def list_messages(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
try:
rows = await svc.list_messages(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(
{
"items": [
{
"id": m.id,
"seq": m.seq,
"role": m.role.value,
"content": m.content,
"createdAt": m.created_at.isoformat() + "Z",
}
for m in rows
]
}
)
@router.post("/{thread_id}/chat")
async def chat_stream(
thread_id: str,
body: ChatBody,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
"""SSE 流式,不走 ApiResponse 包装。"""
async def gen():
try:
async for event in svc.stream_chat(
actor,
thread_id,
body.content,
form_snapshot=body.formSnapshot,
):
if event.kind == "token" and event.text:
yield {
"event": "token",
"data": json.dumps({"text": event.text}, ensure_ascii=False),
}
elif event.kind == "tool":
yield {
"event": "tool",
"data": json.dumps(
{
"phase": event.phase,
"name": event.name,
"label": event.label,
},
ensure_ascii=False,
),
}
elif event.kind == "client_tool":
yield {
"event": "client_tool",
"data": json.dumps(
{
"toolCallId": event.tool_call_id,
"name": event.name,
"args": event.args or {},
"label": event.label,
},
ensure_ascii=False,
),
}
yield {"event": "done", "data": "{}"}
except LookupError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except ValueError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except Exception as e:
yield {
"event": "error",
"data": json.dumps({"message": str(e)}, ensure_ascii=False),
}
return EventSourceResponse(
gen(),
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
ping=15,
)
@router.post("/{thread_id}/client-tool-results")
async def submit_client_tool_result(
thread_id: str,
body: ClientToolResultBody,
actor: Actor = Depends(current_actor),
sessions: SessionService = Depends(session_service),
):
"""前端工具回执。对上当前轮等待则 accepted=true;迟到或未知 id 仍 200,避免打断页面。"""
try:
await sessions.require_owned(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
accepted = get_client_tool_gate().submit(
thread_id,
body.toolCallId.strip(),
body.ok,
body.message,
)
return ok({"accepted": accepted})
+33
View File
@@ -0,0 +1,33 @@
"""用户记忆 API。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from api.deps import current_actor, memory_service
from api.response import ok
from application.memory_service import MemoryService
from domain.models import Actor
router = APIRouter(prefix="/memories", tags=["memories"])
@router.get("")
async def list_memories(
actor: Actor = Depends(current_actor),
svc: MemoryService = Depends(memory_service),
):
items = await svc.list_public(actor)
return ok({"items": items})
@router.delete("/{memory_id}")
async def delete_memory(
memory_id: str,
actor: Actor = Depends(current_actor),
svc: MemoryService = Depends(memory_service),
):
deleted = await svc.delete(actor, memory_id)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="记忆不存在")
return ok({"ok": True})
+150
View File
@@ -0,0 +1,150 @@
"""会话路由。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from api.deps import current_actor, session_service
from api.response import ok
from application.session_service import SessionService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["sessions"])
class CreateSessionBody(BaseModel):
title: str | None = None
llmProviderId: int | None = None
llmModel: str | None = None
scene: str | None = None
sceneRef: str | None = None
# 同 scene+sceneRef 已有活跃会话则复用(发布草稿一会话)
reuseBySceneRef: bool = False
class PatchSessionBody(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
llmProviderId: int | None = None
llmModel: str | None = None
# 未落库会话(local-*)改绑到稳定业务键,如系统草稿 ID
sceneRef: str | None = Field(default=None, min_length=1, max_length=200)
def _session_vo(s) -> dict:
return {
"threadId": s.thread_id,
"title": s.title,
"status": s.status.value,
"scene": s.scene or "general",
"sceneRef": s.scene_ref,
"llmProviderId": s.llm_provider_id,
"llmModel": s.llm_model,
"createdAt": s.created_at.isoformat() + "Z",
"updatedAt": s.updated_at.isoformat() + "Z",
"lastMessageAt": s.last_message_at.isoformat() + "Z" if s.last_message_at else None,
}
@router.get("")
async def list_sessions(
scene: str | None = Query(default="general"),
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
rows = await svc.list_mine(actor, scene=scene)
return ok({"items": [_session_vo(s) for s in rows]})
@router.post("")
async def create_session(
body: CreateSessionBody,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
scene = (body.scene or "general").strip() or "general"
ref = (body.sceneRef or "").strip() or None
if body.reuseBySceneRef and ref:
existing = await svc.find_by_scene_ref(actor, scene=scene, scene_ref=ref)
if existing is not None:
return ok(_session_vo(existing))
s = await svc.create(
actor,
body.title,
llm_provider_id=body.llmProviderId,
llm_model=body.llmModel,
scene=scene,
scene_ref=ref,
)
return ok(_session_vo(s))
@router.patch("/{thread_id}")
async def patch_session(
thread_id: str,
body: PatchSessionBody,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
if (
body.title is None
and body.llmModel is None
and body.llmProviderId is None
and body.sceneRef is None
):
raise HTTPException(status_code=400, detail="无有效更新字段")
try:
s = None
if body.sceneRef is not None:
s = await svc.rebind_scene_ref(
actor,
thread_id,
scene_ref=body.sceneRef,
title=body.title,
)
elif body.title is not None:
s = await svc.rename(actor, thread_id, body.title)
if body.llmModel is not None or body.llmProviderId is not None:
if body.llmModel is None or body.llmProviderId is None:
raise HTTPException(
status_code=400, detail="切换模型须同时提供 llmProviderId 与 llmModel"
)
s = await svc.update_llm_selection(
actor,
thread_id,
llm_provider_id=body.llmProviderId,
llm_model=body.llmModel,
)
assert s is not None
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(_session_vo(s))
@router.post("/{thread_id}/archive")
async def archive_session(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
try:
s = await svc.archive(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(_session_vo(s))
@router.delete("/{thread_id}")
async def delete_session(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
"""软删会话并级联软删消息;列表与聊天不再可见。"""
try:
s = await svc.delete(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(_session_vo(s))
View File
+214
View File
@@ -0,0 +1,214 @@
"""对话用例:落库 + token 窗口裁剪 + 记忆工具 + 流式生成。"""
from __future__ import annotations
from datetime import datetime
from typing import AsyncIterator
from agent.runtime import load_tools_for_turn
from application.client_tool_gate import BoundClientToolTurn, get_client_tool_gate
from application.context_window import resolve_context_window, trim_history_to_budget
from application.llm_settings_service import LlmRuntimeService
from application.memory_service import MemoryService
from application.session_service import SessionService
from application.system_prompt import build_system_prompt
from config.settings import Settings
from domain.models import (
Actor,
ChatMessage,
LlmResponseChain,
MessageRole,
StreamEvent,
)
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
class ChatService:
def __init__(
self,
settings: Settings,
sessions: SessionService,
session_repo: SessionRepository,
messages: MessageRepository,
llm_runtime: LlmRuntimeService,
memory: MemoryService,
streamer: ChatStreamer,
) -> None:
self._settings = settings
self._sessions = sessions
self._session_repo = session_repo
self._messages = messages
self._llm_runtime = llm_runtime
self._memory = memory
self._streamer = streamer
async def list_messages(self, actor: Actor, thread_id: str) -> list[ChatMessage]:
await self._sessions.require_owned(actor, thread_id)
return await self._messages.list_recent(
actor.company_id,
actor.user_id,
thread_id,
self._settings.chat_history_limit,
)
async def stream_chat(
self,
actor: Actor,
thread_id: str,
content: str,
*,
form_snapshot: dict | None = None,
) -> AsyncIterator[StreamEvent]:
text = (content or "").strip()
if not text:
raise ValueError("消息不能为空")
session = await self._sessions.require_owned(actor, thread_id)
scene = session.scene or "general"
llm = await self._llm_runtime.resolve_runtime(
actor.company_id,
provider_id=session.llm_provider_id,
model=session.llm_model,
)
changed = False
if session.llm_model != llm.model:
session.llm_model = llm.model
changed = True
if llm.provider_id is not None and session.llm_provider_id != llm.provider_id:
session.llm_provider_id = llm.provider_id
changed = True
if changed:
session.llm_response_chain = None
await self._session_repo.update(session)
# 链是否可用由 streamer 按 store 能力决定;此处只做选型匹配
chain_id = _usable_chain_id(session.llm_response_chain, llm)
if session.llm_response_chain and not chain_id:
session.llm_response_chain = None
await self._session_repo.update(session)
# 各 scene 均可按需 memory_*;显式「记住」也会 maybe_capture
just_saved = await self._memory.maybe_capture_from_user(
actor, thread_id=thread_id, text=text
)
memory_count = await self._memory.count_active(actor)
system_prompt = build_system_prompt(
memory_count=memory_count,
memory_just_saved=just_saved,
scene=scene,
form_snapshot=form_snapshot,
)
client_tools = None
if scene == "ecom_goods_publish":
from agent.tools.publish_ui import build_publish_client_tools
client_tools = build_publish_client_tools()
tools = await load_tools_for_turn(
self._settings,
actor=actor,
memory=self._memory,
scene=scene,
client_tools=client_tools,
)
raw_history = await self._messages.list_recent(
actor.company_id,
actor.user_id,
thread_id,
self._settings.chat_history_fetch_limit,
)
context_window = resolve_context_window(
llm, fallback=self._settings.llm_default_context_window
)
history = trim_history_to_budget(
raw_history,
system_text=system_prompt,
user_text=text,
context_window=context_window,
reserve_output_tokens=self._settings.context_reserve_output_tokens,
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
)
max_tool_chars = max(
500, self._settings.context_reserve_tool_tokens * 2
)
seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
user_msg = ChatMessage(
company_id=actor.company_id,
user_id=actor.user_id,
thread_id=thread_id,
seq=seq,
role=MessageRole.USER,
content=text,
)
await self._messages.append(user_msg)
if session.title == "新对话":
session.title = text[:40] + ("…" if len(text) > 40 else "")
session.last_message_at = datetime.utcnow()
await self._session_repo.update(session)
parts: list[str] = []
new_response_id: str | None = None
gate = get_client_tool_gate()
epoch = gate.begin(thread_id)
turn = BoundClientToolTurn(gate, thread_id, epoch)
try:
async for event in self._streamer.stream_reply(
llm=llm,
history=history,
user_text=text,
system_prompt=system_prompt,
tools=tools or None,
max_tool_result_chars=max_tool_chars,
previous_response_id=chain_id,
client_tool_turn=turn,
):
if event.kind == "response_chain" and event.response_id:
new_response_id = event.response_id
continue
if event.kind == "token" and event.text:
parts.append(event.text)
yield event
finally:
gate.end(thread_id, epoch)
full = "".join(parts).strip() or "(模型未返回内容)"
a_seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
await self._messages.append(
ChatMessage(
company_id=actor.company_id,
user_id=actor.user_id,
thread_id=thread_id,
seq=a_seq,
role=MessageRole.ASSISTANT,
content=full,
)
)
session.last_message_at = datetime.utcnow()
if new_response_id:
session.llm_response_chain = LlmResponseChain(
provider_id=llm.provider_id,
model=llm.model,
previous_response_id=new_response_id,
)
else:
session.llm_response_chain = None
await self._session_repo.update(session)
def _usable_chain_id(chain: LlmResponseChain | None, llm) -> str | None:
if chain is None:
return None
rid = (chain.previous_response_id or "").strip()
if not rid:
return None
if (chain.model or "") != (llm.model or ""):
return None
if chain.provider_id is not None and llm.provider_id is not None:
if int(chain.provider_id) != int(llm.provider_id):
return None
return rid
+127
View File
@@ -0,0 +1,127 @@
"""前端工具回执门闩:进程内按会话代次等待,供 SSE 挂起后由 POST 唤醒。"""
from __future__ import annotations
import asyncio
from dataclasses import dataclass
# 前端写入应很快返回;超时后模型拿到失败,避免 SSE 一直挂着
_DEFAULT_TIMEOUT_SECONDS = 20.0
def format_client_tool_result(ok: bool, message: str) -> str:
"""写成模型可读的 ToolMessage。失败统一前缀,便于提示词识别。"""
text = (message or "").strip()
if ok:
return text or "已写入"
return f"写入失败:{text or '未知原因'}"
@dataclass
class _Waiter:
epoch: int
future: asyncio.Future[tuple[bool, str]]
class ClientToolGate:
"""单进程等待表。多 worker 时回执可能打到别的进程,当前部署按单进程使用。"""
def __init__(self, timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS) -> None:
self._timeout = timeout_seconds
self._epoch: dict[str, int] = {}
self._waiters: dict[tuple[str, str], _Waiter] = {}
def begin(self, thread_id: str) -> int:
"""新开一轮:抬高代次,并结束该会话上一代尚未完成的等待。"""
epoch = self._epoch.get(thread_id, 0) + 1
self._epoch[thread_id] = epoch
self._settle(thread_id, only_epoch=None, keep_epoch=epoch, message="本轮已取消")
return epoch
def end(self, thread_id: str, epoch: int) -> None:
"""本轮流结束或断开:只结算这一代,避免误伤已开始的下一轮。"""
self._settle(thread_id, only_epoch=epoch, keep_epoch=None, message="本轮已取消")
def arm(self, thread_id: str, epoch: int, tool_call_id: str) -> None:
"""在向浏览器推 client_tool 之前登记,避免回执先到。"""
if self._epoch.get(thread_id) != epoch:
return
key = (thread_id, tool_call_id)
loop = asyncio.get_running_loop()
previous = self._waiters.get(key)
if previous is not None and not previous.future.done():
previous.future.set_result((False, "本轮已取消"))
self._waiters[key] = _Waiter(epoch=epoch, future=loop.create_future())
async def wait(self, thread_id: str, epoch: int, tool_call_id: str) -> tuple[bool, str]:
key = (thread_id, tool_call_id)
waiter = self._waiters.get(key)
if waiter is None or waiter.epoch != epoch:
return False, "本轮已取消"
future = waiter.future
try:
# shield:超时或断流时不把 Future 一起取消,便于区分迟到回执
return await asyncio.wait_for(asyncio.shield(future), self._timeout)
except asyncio.TimeoutError:
if not future.done():
future.set_result((False, "前端未回执"))
return False, "前端未回执"
finally:
current = self._waiters.get(key)
if current is not None and current.future is future:
self._waiters.pop(key, None)
def submit(self, thread_id: str, tool_call_id: str, ok: bool, message: str) -> bool:
"""对上当前代次的等待则唤醒。迟到或未知 id 返回 False。"""
key = (thread_id, tool_call_id)
waiter = self._waiters.get(key)
epoch = self._epoch.get(thread_id)
if waiter is None or epoch is None or waiter.epoch != epoch or waiter.future.done():
return False
waiter.future.set_result((bool(ok), message or ""))
return True
def _settle(
self,
thread_id: str,
*,
only_epoch: int | None,
keep_epoch: int | None,
message: str,
) -> None:
for key, waiter in list(self._waiters.items()):
if key[0] != thread_id:
continue
if only_epoch is not None and waiter.epoch != only_epoch:
continue
if keep_epoch is not None and waiter.epoch == keep_epoch:
continue
self._waiters.pop(key, None)
if not waiter.future.done():
waiter.future.set_result((False, message))
_gate: ClientToolGate | None = None
def get_client_tool_gate() -> ClientToolGate:
global _gate
if _gate is None:
_gate = ClientToolGate()
return _gate
class BoundClientToolTurn:
"""绑定到一次 stream_chat 的代次。"""
def __init__(self, gate: ClientToolGate, thread_id: str, epoch: int) -> None:
self._gate = gate
self._thread_id = thread_id
self._epoch = epoch
def arm(self, tool_call_id: str) -> None:
self._gate.arm(self._thread_id, self._epoch, tool_call_id)
async def wait_result(self, tool_call_id: str) -> str:
ok, message = await self._gate.wait(self._thread_id, self._epoch, tool_call_id)
return format_client_tool_result(ok, message)
+103
View File
@@ -0,0 +1,103 @@
"""上下文窗口解析与粗粒度 token 估算(非精确 tokenizer)。"""
from __future__ import annotations
import re
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole
# 未配置且无法按模型名识别时的保守默认
_DEFAULT_CONTEXT_WINDOW = 128_000
def resolve_context_window(llm: LlmRuntimeConfig, fallback: int | None = None) -> int:
"""生效上下文窗口:租户配置 > 模型名启发式 > 默认。"""
if llm.context_window is not None and llm.context_window > 0:
return int(llm.context_window)
guessed = guess_context_window(llm.model)
if guessed:
return guessed
if fallback is not None and fallback > 0:
return fallback
return _DEFAULT_CONTEXT_WINDOW
def guess_context_window(model: str) -> int | None:
"""按常见模型名估计 context;无法识别返回 None。"""
m = (model or "").lower().strip()
if not m:
return None
# 显式带 k 标记
mk = re.search(r"(\d+)\s*k\b", m)
if mk:
return int(mk.group(1)) * 1024
if "claude" in m:
return 200_000
if "gpt-4o" in m or "gpt-4.1" in m or "o1" in m or "o3" in m:
return 128_000
if "gpt-4-turbo" in m or "gpt-4-1106" in m or "gpt-4-0125" in m:
return 128_000
if "gpt-4-32k" in m:
return 32_768
if "gpt-3.5" in m or "gpt-35" in m:
return 16_385
if "deepseek" in m:
return 128_000
if "qwen" in m or "qwq" in m:
return 131_072
if "glm" in m or "moonshot" in m or "kimi" in m:
return 128_000
if "gemini" in m:
return 128_000
return None
def estimate_tokens(text: str) -> int:
"""粗估 token:偏保守(略高估),避免撑爆真实窗口。"""
if not text:
return 0
# CJK 约 1.5 字/token,其余按 ~4 char/token;整体再乘 1.1
cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
other = max(0, len(text) - cjk)
raw = cjk / 1.5 + other / 4.0
return max(1, int(raw * 1.1) + 1)
def estimate_message_tokens(role: str, content: str) -> int:
"""单条消息开销(含 role 包装余量)。"""
return estimate_tokens(content) + 8
def trim_history_to_budget(
history: list[ChatMessage],
*,
system_text: str,
user_text: str,
context_window: int,
reserve_output_tokens: int,
reserve_tool_tokens: int,
min_history_messages: int = 2,
) -> list[ChatMessage]:
"""从旧到新丢弃历史,直到落入 token 预算;保证至少保留最近若干条。"""
if not history:
return []
fixed = (
estimate_message_tokens("system", system_text)
+ estimate_message_tokens("user", user_text)
+ max(0, reserve_output_tokens)
+ max(0, reserve_tool_tokens)
)
budget = max(512, context_window - fixed)
keep: list[ChatMessage] = []
used = 0
# 从新到旧挑选
for msg in reversed(history):
if msg.role not in (MessageRole.USER, MessageRole.ASSISTANT):
continue
cost = estimate_message_tokens(msg.role.value, msg.content or "")
if keep and used + cost > budget and len(keep) >= min_history_messages:
break
keep.append(msg)
used += cost
keep.reverse()
return keep
@@ -0,0 +1,65 @@
"""租户 LLM 运行时解析:Redis → Server 内部 API → 本地 fallback。"""
from __future__ import annotations
from fastapi import HTTPException, status
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache, LlmRuntimeGateway
class LlmRuntimeService:
def __init__(
self,
settings: Settings,
cache: LlmRuntimeCache,
gateway: LlmRuntimeGateway,
) -> None:
self._settings = settings
self._cache = cache
self._gateway = gateway
async def resolve_runtime(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig:
want_model = (model or "").strip() or None
want_provider = provider_id
cached = await self._cache.get(company_id, want_provider, want_model)
if cached is not None and cached.api_key:
return cached
remote = await self._gateway.fetch(company_id, want_provider, want_model)
if remote is not None and remote.api_key and remote.base_url and remote.model:
await self._cache.set(
company_id,
remote,
self._settings.llm_cache_ttl_seconds,
)
return remote
if (
self._settings.llm_fallback_enabled
and self._settings.llm_fallback_api_key
and not want_model
and want_provider is None
):
return LlmRuntimeConfig(
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
api_key=self._settings.llm_fallback_api_key,
model=self._settings.llm_fallback_model,
provider_id=None,
context_window=None,
api_style="auto",
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
"当前公司尚未配置模型 API,或所选模型未启用;"
"请在「模型管理」中配置提供商并启用模型"
),
)
+137
View File
@@ -0,0 +1,137 @@
"""用户记忆用例:摘要写入、关键词检索、按需载入。"""
from __future__ import annotations
import hashlib
import re
from config.settings import Settings
from domain.models import Actor, MemoryKind, UserMemory
from domain.ports import MemoryRepository
# 消息中出现「记住…」即写入(不必整句以此开头)
_REMEMBER_RE = re.compile(
r"(?:请?帮?我?记住一下?|请?记住)[::\s,,]*(.+)",
re.DOTALL,
)
_SUMMARY_MAX = 80
def build_memory_summary(text: str) -> str:
"""规则摘要:压缩空白并截断,供搜索与列表展示。"""
s = re.sub(r"\s+", " ", (text or "").strip())
if not s:
return ""
if len(s) <= _SUMMARY_MAX:
return s
return s[: _SUMMARY_MAX - 1] + "…"
class MemoryService:
def __init__(self, settings: Settings, repo: MemoryRepository) -> None:
self._settings = settings
self._repo = repo
async def list_public(self, actor: Actor, limit: int = 50) -> list[dict]:
rows = await self._repo.list_active(actor.company_id, actor.user_id, limit)
return [
{
"id": m.id,
"kind": m.kind.value,
"key": m.key,
"summary": m.summary or build_memory_summary(m.text),
"text": m.text,
"updatedAt": m.updated_at.isoformat() + "Z",
}
for m in rows
]
async def delete(self, actor: Actor, memory_id: str) -> bool:
return await self._repo.soft_delete(actor.company_id, actor.user_id, memory_id)
async def count_active(self, actor: Actor) -> int:
return await self._repo.count_active(actor.company_id, actor.user_id)
async def search(
self, actor: Actor, query: str, limit: int = 5
) -> list[dict]:
"""返回摘要命中列表(无正文)。"""
rows = await self._repo.search(
actor.company_id,
actor.user_id,
query,
max(1, min(limit, 20)),
)
return [
{
"id": m.id,
"summary": m.summary or build_memory_summary(m.text),
"kind": m.kind.value,
"updatedAt": m.updated_at.isoformat() + "Z",
}
for m in rows
]
async def load(self, actor: Actor, memory_ids: list[str]) -> list[dict]:
"""按 id 载入正文;单次最多 5 条。"""
ids = [i for i in memory_ids if i][:5]
rows = await self._repo.get_by_ids(actor.company_id, actor.user_id, ids)
return [
{
"id": m.id,
"summary": m.summary or build_memory_summary(m.text),
"text": m.text,
"kind": m.kind.value,
}
for m in rows
]
async def save(
self,
actor: Actor,
text: str,
*,
kind: MemoryKind = MemoryKind.FACT,
thread_id: str | None = None,
key: str | None = None,
) -> dict:
"""写入一条记忆(含规则摘要)。"""
body = (text or "").strip()
if not body:
raise ValueError("记忆内容不能为空")
body = body[:1000]
summary = build_memory_summary(body)
mem_key = key or ("remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16])
saved = await self._repo.upsert(
UserMemory(
company_id=actor.company_id,
user_id=actor.user_id,
kind=kind,
key=mem_key,
text=body,
summary=summary,
source_thread_id=thread_id,
)
)
return {"id": saved.id, "summary": saved.summary or summary, "kind": saved.kind.value}
async def maybe_capture_from_user(
self, actor: Actor, *, thread_id: str, text: str
) -> str | None:
"""显式「记住…」写入跨会话记忆;命中则返回写入正文,否则 None。"""
m = _REMEMBER_RE.search((text or "").strip())
if not m:
return None
body = m.group(1).strip().rstrip("。.!!")
if not body or len(body) > 1000:
return None
if body in ("一下", "下"):
return None
result = await self.save(
actor,
body,
kind=MemoryKind.PREFERENCE,
thread_id=thread_id,
)
return body if result else None
+172
View File
@@ -0,0 +1,172 @@
"""会话用例。"""
from __future__ import annotations
import uuid
from datetime import datetime
from application.llm_settings_service import LlmRuntimeService
from domain.models import Actor, Session, SessionStatus
from domain.ports import MessageRepository, SessionRepository
class SessionService:
def __init__(
self,
sessions: SessionRepository,
llm_runtime: LlmRuntimeService | None = None,
messages: MessageRepository | None = None,
) -> None:
self._sessions = sessions
self._llm_runtime = llm_runtime
self._messages = messages
async def create(
self,
actor: Actor,
title: str | None = None,
llm_provider_id: int | None = None,
llm_model: str | None = None,
*,
scene: str | None = None,
scene_ref: str | None = None,
) -> Session:
now = datetime.utcnow()
model = (llm_model or "").strip() or None
provider_id = llm_provider_id
if (not model or provider_id is None) and self._llm_runtime is not None:
try:
rt = await self._llm_runtime.resolve_runtime(
actor.company_id,
provider_id=provider_id,
model=model,
)
model = rt.model or model
provider_id = rt.provider_id if rt.provider_id is not None else provider_id
except Exception:
pass
scene_value = (scene or "general").strip() or "general"
ref = (scene_ref or "").strip() or None
session = Session(
thread_id=str(uuid.uuid4()),
company_id=actor.company_id,
user_id=actor.user_id,
title=(title or "新对话").strip() or "新对话",
status=SessionStatus.ACTIVE,
scene=scene_value,
scene_ref=ref,
llm_provider_id=provider_id,
llm_model=model,
created_at=now,
updated_at=now,
)
return await self._sessions.create(session)
async def list_mine(
self, actor: Actor, *, scene: str | None = None
) -> list[Session]:
return await self._sessions.list_active(
actor.company_id, actor.user_id, scene=scene
)
async def find_by_scene_ref(
self, actor: Actor, *, scene: str, scene_ref: str
) -> Session | None:
"""同一 scene_ref 复用已有活跃会话(一草稿一会话)。"""
return await self._sessions.find_active_by_scene_ref(
actor.company_id,
actor.user_id,
scene=scene,
scene_ref=scene_ref,
)
async def require_owned(self, actor: Actor, thread_id: str) -> Session:
session = await self._sessions.get(actor.company_id, actor.user_id, thread_id)
if session is None or session.status == SessionStatus.DELETED:
raise LookupError("会话不存在")
return session
async def rename(self, actor: Actor, thread_id: str, title: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def rebind_scene_ref(
self,
actor: Actor,
thread_id: str,
*,
scene_ref: str,
title: str | None = None,
) -> Session:
"""把未落库会话(scene_ref=local-*)改绑到稳定业务键(如系统草稿 ID)。"""
new_ref = (scene_ref or "").strip()
if not new_ref:
raise ValueError("scene_ref 不能为空")
if new_ref.startswith("local-"):
raise ValueError("不能改绑到临时 local 键")
session = await self.require_owned(actor, thread_id)
if session.scene_ref == new_ref:
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
return session
current = (session.scene_ref or "").strip()
if current and not current.startswith("local-"):
raise ValueError("仅未落库会话可改绑 scene_ref")
existing = await self.find_by_scene_ref(
actor, scene=session.scene or "general", scene_ref=new_ref
)
if existing is not None and existing.thread_id != thread_id:
raise ValueError("该业务对象已有关联会话")
session.scene_ref = new_ref
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def update_llm_selection(
self,
actor: Actor,
thread_id: str,
*,
llm_provider_id: int,
llm_model: str,
) -> Session:
model = (llm_model or "").strip()
if not model:
raise ValueError("模型不能为空")
if llm_provider_id is None or int(llm_provider_id) <= 0:
raise ValueError("提供商不能为空")
session = await self.require_owned(actor, thread_id)
switched = (
session.llm_provider_id != int(llm_provider_id)
or (session.llm_model or "") != model
)
session.llm_provider_id = int(llm_provider_id)
session.llm_model = model
if switched:
# 切换选型后厂商侧链不可复用
session.llm_response_chain = None
return await self._sessions.update(session)
async def archive(self, actor: Actor, thread_id: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.status = SessionStatus.ARCHIVED
return await self._sessions.update(session)
async def delete(self, actor: Actor, thread_id: str) -> Session:
"""软删会话,并级联软删该线程消息。"""
session = await self.require_owned(actor, thread_id)
session.status = SessionStatus.DELETED
session.llm_response_chain = None
session.summary = None
saved = await self._sessions.update(session)
if self._messages is not None:
await self._messages.soft_delete_by_thread(
actor.company_id, actor.user_id, thread_id
)
return saved
+106
View File
@@ -0,0 +1,106 @@
"""对话 system 提示组装(应用策略,供裁剪预算与流式共用)。"""
from __future__ import annotations
import json
from typing import Any
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL
_BASE_SYSTEM = (
"你是电商 DMB 系统的经营助手。回答简洁、可执行、结论先行。"
"需要经营数据时优先调用可用工具。"
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
"用户要求记住:可用 memory_save,或系统提示「本轮已写入」时只简短确认内容。"
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
"恰好一条就用返回的 id 继续查数;多条只列名称和编码让用户选。"
"用户消息含 [引用] 且带 id= 时,直接用这些 id,不必再搜索,也不要向用户复述 id。"
"禁止向用户索要店铺 ID、商品 ID 或 SKU ID。"
"若只给了引用、没有具体问题,按近 7 天概览回答该对象。"
"若工具失败或无权限,请说明原因并给出可操作建议。"
)
_PUBLISH_SYSTEM = (
"你是电商 DMB 的拼多多商品发布助手,只在当前系统草稿页改表。"
"能写的工具:ui_patch_basic(标题、描述、参考价、满两件折扣、发货时限、"
"假一赔十/7天无理由/预售/二手、运费模板)、ui_set_spec_axes(规格轴)、"
"ui_patch_skus(按 outSkuSn 改单买价、拼单价、库存、重量)、ui_patch_props(类目属性)。"
"每次只传要改的字段,未传的保持原样。"
"商品标题字数:汉字算 2、英文数字算 1,合计最多 60(约 30 汉字);生成或改写标题时自行压缩到上限内,不要写超再指望页面截断。"
"运费模板 ID 必须来自快照 costTemplates;发货时限只能用快照里的秒数;"
"类目属性枚举用 goodsProperties 里的 vid 或文案,多选英文逗号分隔。"
"不能改店铺、叶子类目、轮播图、详情图、SKU 缩略图;用户要求这些时用一句话说明对话里改不了。"
"【当前发布表单】是本轮开始时的页面内容。改表必须调用上述工具,不要只口头说已修改。"
"工具返回是页面当时的写入结果:不以「写入失败」开头即已显示在编辑器里,无需用户刷新或再核对。"
"以「写入失败」开头时只说明原因,不要声称已经改好。"
"商家编码 outSkuSn 是 SKU 唯一身份,规格文案只是描述。只改同一维的名称或取值时只传 axes;"
"改变组合结构(如 2×2→1×4)时必须带 skuAssignments,把表单里已有的 outSkuSn 挂到新 values 上,勿编造编码。"
"用户指定了标题或规格怎么写,就按用户的写。"
"用户只说改标题、改规格名、改某个规格值时,直接改这一处,不要先搜渠道商品,也不要改别的字段。"
"用户要整体编辑、完善草稿、按 SKU 填写时:表单 skuRows 里已有 outSkuSn 的,先对每个编码调用 catalog_sku_detail,再改表。"
"用返回的 name、attrs、specCombinationKey、productName 写规格文案、类目属性和标题;容量、斤、千克能换算成克的,直接写入重量。"
"重量为 1 克、规格值像「10个」「9」这类占位,视为无效,用查到的资料覆盖,不要保留并向用户求正确值。"
"内部 SKU 没有单买价和拼单价。规格和重量能从资料得出就必须写入,不要和售价一起追问;只有售价确实没有时,才单独问一句。"
"只有用户明确要求参考本店在售、查重或模仿某条时,才用 pdd_goods_search / pdd_goods_detail(本地已同步商品)。"
"不要处理图片。"
"对用户只报结论,一两句:给出改完的标题或规格名即可。"
"不要复述工具名、回执原文、字数统计、查了几条、竞品标题全文或改写策略,除非用户问为什么这样改。"
"不要主动列 SKU 编码表,不要给没问过的下一版备选,不要让用户刷新、核对,或说「如果还是旧的再告诉我」。"
"禁止向用户索要或复述数字 ID。"
"【长期记忆】跨会话用户级记忆不自动注入;标题口径、常用规格写法、用户偏好等需要时:"
"先 memory_search,必要时 memory_load;用户要求记住用 memory_save。"
"改表仍以当前表单与用户本轮指令为准,记忆只作补充,勿用旧记忆覆盖用户刚说的写法。"
)
def _append_memory_status(
system: str,
*,
memory_count: int,
memory_just_saved: str | None,
) -> str:
if memory_count > 0:
system += (
f"\n\n当前用户约有 {memory_count} 条长期记忆,"
"需要时用 memory_search / memory_load。"
)
if memory_just_saved:
system += f"\n\n【本轮已写入长期记忆】{memory_just_saved}"
return system
def build_system_prompt(
*,
memory_count: int = 0,
memory_just_saved: str | None = None,
scene: str = SCENE_GENERAL,
form_snapshot: dict[str, Any] | None = None,
) -> str:
if (scene or SCENE_GENERAL).strip() == SCENE_ECOM_GOODS_PUBLISH:
snap = form_snapshot if isinstance(form_snapshot, dict) else {}
snap_text = json.dumps(snap, ensure_ascii=False, default=str)
# 控制体积,避免拖垮上下文
if len(snap_text) > 12000:
snap_text = snap_text[:12000] + "…(截断)"
system = f"{_PUBLISH_SYSTEM}\n\n【当前发布表单】\n{snap_text}"
return _append_memory_status(
system,
memory_count=memory_count,
memory_just_saved=memory_just_saved,
)
return _append_memory_status(
_BASE_SYSTEM,
memory_count=memory_count,
memory_just_saved=memory_just_saved,
)
View File
+90
View File
@@ -0,0 +1,90 @@
"""应用配置:按 AGENT_ENV 加载 .env.{env},环境变量优先。"""
from __future__ import annotations
import os
from functools import lru_cache
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
# 与后端 Spring profile 对齐:dev | test | pre | prod
_AGENT_ENV = (os.getenv("AGENT_ENV") or "dev").strip().lower() or "dev"
def _resolve_env_files() -> tuple[str, ...]:
"""加载 .env.{AGENT_ENV};仅 dev 额外允许 .env 覆盖(本机密钥)。"""
files: list[str] = []
profile = Path(f".env.{_AGENT_ENV}")
if profile.is_file():
files.append(str(profile))
if _AGENT_ENV == "dev":
local = Path(".env")
if local.is_file():
files.append(str(local))
if not files:
# 兼容:尚无分环境文件时回退 .env
if Path(".env").is_file():
files.append(".env")
else:
files.append(f".env.{_AGENT_ENV}")
return tuple(files)
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=_resolve_env_files(),
env_file_encoding="utf-8",
extra="ignore",
)
app_name: str = "ecom-dmb-agent"
# 当前环境名(只读展示;实际由 AGENT_ENV 决定加载哪个文件)
agent_env: str = _AGENT_ENV
host: str = "0.0.0.0"
port: int = 8200
cors_origins: str = "http://localhost:5173,http://localhost:5666"
# 与 Java server jwt.secret 一致(HS512)
jwt_secret: str = "your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security"
jwt_algorithms: str = "HS512"
mongo_uri: str = "mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev"
mongo_db: str = "ecom_dmb_agent_dev"
# 须与同环境 Server Redis 同库,才能命中 agent:llm:rt:* 缓存
redis_url: str = "redis://:redis_qinghua@192.168.3.100:6379/2"
llm_cache_ttl_seconds: int = 600
# Java Server 根地址(内部拉 LLM 运行时)
server_base_url: str = "http://localhost:8080"
# 仅本地开发:公司未配置时的 fallback(test/pre/prod 应关闭)
llm_fallback_enabled: bool = True
llm_fallback_base_url: str = "https://api.openai.com/v1"
llm_fallback_api_key: str = ""
llm_fallback_model: str = "gpt-4o-mini"
mcp_base_url: str = "http://localhost:8080/mcp"
mcp_bearer_token: str = "dev-agent-mcp-token"
mcp_tools_enabled: bool = True
chat_history_limit: int = 40
# 从 Mongo 最多拉多少条再按 token 裁剪(应 ≥ 条数窗口时代的 limit)
chat_history_fetch_limit: int = 200
# 未配置 context_window 且模型名无法识别时的默认
llm_default_context_window: int = 128000
# 为模型输出与本轮 tool 预留的 token
context_reserve_output_tokens: int = 4096
context_reserve_tool_tokens: int = 8192
# Responses/store 能力缓存 TTL(秒)
llm_capability_ttl_seconds: int = 604800
@property
def cors_origin_list(self) -> list[str]:
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
@lru_cache
def get_settings() -> Settings:
return Settings()
+14
View File
@@ -0,0 +1,14 @@
# 运行时镜像:业务代码与依赖通过 volume 挂载 /app,更新部署无需重建镜像
ARG BASE_IMAGE=docker.m.daocloud.io/library/python:3.12-slim
FROM ${BASE_IMAGE}
WORKDIR /app
RUN groupadd --system app && useradd --system --gid app --home-dir /app app
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
USER app
# 实际端口由环境 PORT 决定(test:8201 / pre:8202 / prod:8203)
EXPOSE 8201 8202 8203
ENTRYPOINT ["/entrypoint.sh"]
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# 使用镜像内 Python 加载挂载的源码与 .deps(避免 venv shebang 路径不可移植)
set -e
export PYTHONPATH="/app:/app/.deps${PYTHONPATH:+:$PYTHONPATH}"
exec python -m uvicorn api.main:app --host 0.0.0.0 --port "${PORT:-8201}"
View File
+189
View File
@@ -0,0 +1,189 @@
"""领域模型(无框架依赖)。"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any
class SessionStatus(str, Enum):
ACTIVE = "active"
ARCHIVED = "archived"
DELETED = "deleted"
class MessageRole(str, Enum):
USER = "user"
ASSISTANT = "assistant"
SYSTEM = "system"
TOOL = "tool"
class MemoryKind(str, Enum):
PREFERENCE = "preference"
FACT = "fact"
ENTITY = "entity"
SUMMARY = "summary"
class MemoryStatus(str, Enum):
ACTIVE = "active"
STALE = "stale"
DELETED = "deleted"
@dataclass(frozen=True)
class Actor:
"""当前请求主体。"""
user_id: str
company_id: int
company_role: str | None = None
is_super: bool = False
def can_manage_llm(self) -> bool:
if self.is_super:
return True
role = (self.company_role or "").lower()
return role in {"owner", "admin"}
@dataclass
class LlmResponseChain:
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
provider_id: int | None
model: str
previous_response_id: str
@dataclass
class Session:
thread_id: str
company_id: int
user_id: str
title: str = "新对话"
status: SessionStatus = SessionStatus.ACTIVE
summary: str | None = None
# general=经营助手;ecom_goods_publish=拼多多商品发布编辑
scene: str = "general"
# 场景业务键,如发布草稿 draftId
scene_ref: str | None = None
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
llm_provider_id: int | None = None
llm_model: str | None = None
# Responses 续链;切换选型或链失效时清空
llm_response_chain: LlmResponseChain | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
last_message_at: datetime | None = None
SCENE_GENERAL = "general"
SCENE_ECOM_GOODS_PUBLISH = "ecom_goods_publish"
@dataclass
class ChatMessage:
company_id: int
user_id: str
thread_id: str
seq: int
role: MessageRole
content: str
tool_name: str | None = None
tool_call_id: str | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
id: str | None = None
@dataclass
class UserMemory:
"""用户级长期记忆条目;summary 供检索,text 仅按需载入。"""
company_id: int
user_id: str
kind: MemoryKind
text: str
summary: str = ""
key: str | None = None
value: dict[str, Any] = field(default_factory=dict)
source_thread_id: str | None = None
status: MemoryStatus = MemoryStatus.ACTIVE
confidence: float = 0.8
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
id: str | None = None
@dataclass(frozen=True)
class LlmRuntimeConfig:
"""注入 LLM 客户端的运行时配置(含明文 key,仅进程内)。"""
base_url: str
api_key: str
model: str
provider_id: int | None = None
extra_headers: dict[str, str] = field(default_factory=dict)
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
context_window: int | None = None
# API 协议:auto | completions | responses
api_style: str = "auto"
@dataclass(frozen=True)
class LlmProtocolCapability:
"""按提供商缓存的协议能力;None 表示尚未验证。"""
responses: bool | None = None
store: bool | None = None
@dataclass(frozen=True)
class StreamEvent:
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
kind: str # token | tool | client_tool | pending_client_tools | response_chain
text: str | None = None
phase: str | None = None # start | end
name: str | None = None
label: str | None = None
tool_call_id: str | None = None
args: dict | None = None
# Responses 本轮最终 response id(仅 kind=response_chain)
response_id: str | None = None
@staticmethod
def token(text: str) -> StreamEvent:
return StreamEvent(kind="token", text=text)
@staticmethod
def tool(*, phase: str, name: str, label: str) -> StreamEvent:
return StreamEvent(kind="tool", phase=phase, name=name, label=label)
@staticmethod
def client_tool(
*,
tool_call_id: str,
name: str,
args: dict | None,
label: str,
) -> StreamEvent:
return StreamEvent(
kind="client_tool",
tool_call_id=tool_call_id,
name=name,
args=args or {},
label=label,
)
@staticmethod
def pending_client_tools() -> StreamEvent:
return StreamEvent(kind="pending_client_tools")
@staticmethod
def response_chain(response_id: str) -> StreamEvent:
"""内部事件:落会话续链;不推给前端 SSE。"""
return StreamEvent(kind="response_chain", response_id=response_id)
+170
View File
@@ -0,0 +1,170 @@
"""领域端口(依赖倒置)。"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, AsyncIterator, Protocol
from domain.models import (
ChatMessage,
LlmProtocolCapability,
LlmRuntimeConfig,
Session,
StreamEvent,
UserMemory,
)
class SessionRepository(ABC):
@abstractmethod
async def create(self, session: Session) -> Session: ...
@abstractmethod
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None: ...
@abstractmethod
async def list_active(
self,
company_id: int,
user_id: str,
limit: int = 50,
*,
scene: str | None = None,
) -> list[Session]: ...
@abstractmethod
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None: ...
@abstractmethod
async def update(self, session: Session) -> Session: ...
class MessageRepository(ABC):
@abstractmethod
async def append(self, message: ChatMessage) -> ChatMessage: ...
@abstractmethod
async def list_recent(
self, company_id: int, user_id: str, thread_id: str, limit: int
) -> list[ChatMessage]: ...
@abstractmethod
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
@abstractmethod
async def soft_delete_by_thread(
self, company_id: int, user_id: str, thread_id: str
) -> int:
"""软删某会话下全部消息,返回影响条数。"""
...
class MemoryRepository(ABC):
@abstractmethod
async def list_active(
self, company_id: int, user_id: str, limit: int
) -> list[UserMemory]: ...
@abstractmethod
async def count_active(self, company_id: int, user_id: str) -> int: ...
@abstractmethod
async def search(
self, company_id: int, user_id: str, query: str, limit: int
) -> list[UserMemory]: ...
@abstractmethod
async def get_by_ids(
self, company_id: int, user_id: str, memory_ids: list[str]
) -> list[UserMemory]: ...
@abstractmethod
async def upsert(self, memory: UserMemory) -> UserMemory: ...
@abstractmethod
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool: ...
class LlmRuntimeCache(ABC):
@abstractmethod
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None: ...
@abstractmethod
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None: ...
@abstractmethod
async def delete(self, company_id: int) -> None: ...
class LlmRuntimeGateway(ABC):
"""从 Server 拉取运行时模型配置(MySQL 真相源)。"""
@abstractmethod
async def fetch(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None: ...
class LlmProtocolCapabilityCache(ABC):
"""缓存某提供商(或 base_url)是否支持 Responses / store。"""
@abstractmethod
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None: ...
@abstractmethod
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None: ...
class ClientToolTurn(Protocol):
"""一轮聊天里前端工具的回执等待:先 arm 再推 SSE,再 wait_result。"""
def arm(self, tool_call_id: str) -> None: ...
async def wait_result(self, tool_call_id: str) -> str: ...
class ChatStreamer(ABC):
"""流式生成助手回复。"""
@abstractmethod
async def stream_reply(
self,
*,
llm: LlmRuntimeConfig,
history: list[ChatMessage],
user_text: str,
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 4000,
previous_response_id: str | None = None,
client_tool_turn: ClientToolTurn | None = None,
) -> AsyncIterator[StreamEvent]: ...
+1
View File
@@ -0,0 +1 @@
"""基础设施:鉴权、LLM、MCP、持久化适配。"""
+35
View File
@@ -0,0 +1,35 @@
"""JWT 校验(对齐 Java JwtUtils:HS512,sub=userId,claim companyId)。"""
from __future__ import annotations
from typing import Any
import jwt
from fastapi import HTTPException, status
from config.settings import Settings
from domain.models import Actor
def parse_actor(settings: Settings, token: str) -> Actor:
try:
payload: dict[str, Any] = jwt.decode(
token,
settings.jwt_secret,
algorithms=[a.strip() for a in settings.jwt_algorithms.split(",") if a.strip()],
options={"require": ["sub", "exp"]},
)
except jwt.PyJWTError as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"无效令牌: {e}") from e
user_id = payload.get("sub")
company_id = payload.get("companyId")
if not user_id or company_id is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌缺少用户或公司信息")
return Actor(
user_id=str(user_id),
company_id=int(company_id),
company_role=payload.get("companyRole"),
is_super=bool(payload.get("super", False)),
)
+128
View File
@@ -0,0 +1,128 @@
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
from __future__ import annotations
from dataclasses import dataclass
from domain.models import LlmProtocolCapability
def normalize_api_style(raw: str | None) -> str:
s = (raw or "auto").strip().lower()
if s in ("auto", "completions", "responses"):
return s
return "auto"
@dataclass(frozen=True)
class ProtocolAttempt:
"""单次调用策略。"""
use_responses: bool
use_store: bool
use_chain: bool # 是否只发增量 + previous_response_id(须 store 已证实)
def plan_protocol_attempts(
api_style: str | None,
cap: LlmProtocolCapability | None,
*,
has_chain_id: bool,
) -> list[ProtocolAttempt]:
"""
同轮探测顺序(未产出 token 前可依次尝试):
- store 已证实:Responses+store,有链则增量续聊
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
- store 证伪:先 **无状态 Responses + Mongo 全量**,失败再 **Completions**
- Responses 不可用:Completions
"""
style = normalize_api_style(api_style)
cap = cap or LlmProtocolCapability()
if style == "completions":
return [ProtocolAttempt(False, False, False)]
attempts: list[ProtocolAttempt] = []
if cap.store is False:
# 无真实 store:无状态 Responses(全量历史)→ Completions
if cap.responses is not False:
attempts.append(ProtocolAttempt(True, False, False))
attempts.append(ProtocolAttempt(False, False, False))
return _dedupe(attempts)
if cap.responses is not False:
if cap.store is True:
attempts.append(
ProtocolAttempt(True, True, use_chain=bool(has_chain_id))
)
# 有链失败时可降到同协议全量
attempts.append(ProtocolAttempt(True, True, use_chain=False))
else:
# store 未知:Responses+store,必须全量历史,禁止 use_chain
attempts.append(ProtocolAttempt(True, True, use_chain=False))
attempts.append(ProtocolAttempt(True, False, False))
# Completions 兜底
if style == "auto" or cap.responses is False:
attempts.append(ProtocolAttempt(False, False, False))
elif style == "responses" and cap.responses is False:
attempts.append(ProtocolAttempt(False, False, False))
return _dedupe(attempts) or [ProtocolAttempt(False, False, False)]
def _dedupe(attempts: list[ProtocolAttempt]) -> list[ProtocolAttempt]:
seen: set[tuple[bool, bool, bool]] = set()
out: list[ProtocolAttempt] = []
for a in attempts:
key = (a.use_responses, a.use_store, a.use_chain)
if key in seen:
continue
seen.add(key)
out.append(a)
return out
def classify_protocol_error(exc: BaseException) -> str:
"""返回: store | responses | chain | other。"""
text = str(exc).lower()
status = getattr(exc, "status_code", None) or getattr(
getattr(exc, "response", None), "status_code", None
)
if "previous_response_id" in text or "previous response" in text:
return "chain"
if status == 400 and "response" in text and "not found" in text:
return "chain"
if "store" in text and any(
n in text
for n in (
"unsupported",
"unknown",
"unrecognized",
"invalid",
"not support",
"not supported",
)
):
return "store"
if status in (404, 405):
return "responses"
responses_needles = (
"/responses",
"responses api",
"unknown endpoint",
"not implemented",
"invalid pathname",
"no route",
)
if any(n in text for n in responses_needles):
return "responses"
if status == 400 and ("responses" in text or "response.create" in text):
return "responses"
return "other"
+503
View File
@@ -0,0 +1,503 @@
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
优先 Responses+store → Responses store=false → Completions;
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
"""
from __future__ import annotations
import json
import logging
from typing import Any, AsyncIterator
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from langchain_openai import ChatOpenAI
from agent.tools.labels import tool_status_label
from agent.tools.publish_ui import is_client_tool_name
from domain.models import (
ChatMessage,
LlmProtocolCapability,
LlmRuntimeConfig,
MessageRole,
StreamEvent,
)
from domain.ports import ChatStreamer, ClientToolTurn, LlmProtocolCapabilityCache
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
logger = logging.getLogger(__name__)
_UNSET = object()
class OpenAICompatibleStreamer(ChatStreamer):
def __init__(
self,
capability_cache: LlmProtocolCapabilityCache | None = None,
*,
capability_ttl_seconds: int = 604800,
) -> None:
self._cap_cache = capability_cache
self._cap_ttl = capability_ttl_seconds
async def stream_reply(
self,
*,
llm: LlmRuntimeConfig,
history: list[ChatMessage],
user_text: str,
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 8000,
previous_response_id: str | None = None,
client_tool_turn: ClientToolTurn | None = None,
) -> AsyncIterator[StreamEvent]:
chain_id = (previous_response_id or "").strip() or None
style = normalize_api_style(llm.api_style)
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
cap = await self._ensure_protocol_capability(llm, style)
attempts = plan_protocol_attempts(
llm.api_style, cap, has_chain_id=bool(chain_id)
)
i = 0
while i < len(attempts):
attempt = attempts[i]
# 仅缓存已证实 store=true 时才丢历史、纯续链
use_chain_id = (
chain_id if (attempt.use_chain and cap and cap.store is True) else None
)
logger.warning(
"LLM attempt model=%s responses=%s store=%s chain=%s hist=%s api_style=%s",
llm.model,
attempt.use_responses,
attempt.use_store,
bool(use_chain_id),
len(history),
style,
)
yielded_any = False
got_chain_id: str | None = None
try:
async for event in self._stream_once(
llm=llm,
history=history,
user_text=user_text,
system_prompt=system_prompt,
tools=tools,
max_tool_result_chars=max_tool_result_chars,
use_responses=attempt.use_responses,
use_store=attempt.use_store,
previous_response_id=use_chain_id,
client_tool_turn=client_tool_turn,
):
if event.kind == "token" and event.text:
yielded_any = True
if event.kind == "response_chain" and event.response_id:
got_chain_id = event.response_id
continue
yield event
if attempt.use_responses:
if use_chain_id:
# 已证实 store 且本轮续链成功
await self._update_cap(llm, responses=True, store=True)
if got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
elif attempt.use_store:
# store 未证实或待刷新:本轮是全量历史;语义探测真伪
need_probe = cap is None or cap.store is not True
if need_probe:
store_ok = await self._probe_store_semantic(llm)
await self._update_cap(
llm, responses=True, store=store_ok
)
cap = LlmProtocolCapability(
responses=True, store=store_ok
)
if store_ok and got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
else:
await self._update_cap(llm, responses=True, store=True)
if got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
else:
# Responses 无 store:能通端点但不持久
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
else:
# Completions:若已知有 Responses 只是无 store,不要把 responses 打成 false
if cap is not None and cap.responses is True and cap.store is False:
await self._update_cap(llm, responses=True, store=False)
elif cap is not None and cap.store is False:
await self._update_cap(llm, responses=cap.responses, store=False)
else:
await self._update_cap(llm, responses=False, store=False)
cap = LlmProtocolCapability(responses=False, store=False)
return
except Exception as e: # noqa: BLE001
if yielded_any:
raise
kind = classify_protocol_error(e)
logger.warning(
"LLM attempt failed kind=%s model=%s err=%s",
kind,
llm.model,
e,
)
if kind == "chain" and use_chain_id:
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
nxt = ProtocolAttempt(True, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if kind == "store" and attempt.use_responses and attempt.use_store:
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
nxt = ProtocolAttempt(True, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if kind == "responses" and attempt.use_responses:
await self._update_cap(llm, responses=False, store=False)
cap = LlmProtocolCapability(responses=False, store=False)
nxt = ProtocolAttempt(False, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if i + 1 < len(attempts):
i += 1
continue
if style == "responses" and attempt.use_responses:
attempts.append(ProtocolAttempt(False, False, False))
i += 1
continue
raise
i += 1 # pragma: no cover
async def _ensure_protocol_capability(
self, llm: LlmRuntimeConfig, style: str
) -> LlmProtocolCapability | None:
"""读取能力缓存;completions 强制走 Completions,不探测。"""
if style == "completions":
return LlmProtocolCapability(responses=False, store=False)
return await self._load_cap(llm)
async def _load_cap(self, llm: LlmRuntimeConfig) -> LlmProtocolCapability | None:
if self._cap_cache is None:
return None
try:
return await self._cap_cache.get(
provider_id=llm.provider_id, base_url=llm.base_url
)
except Exception: # noqa: BLE001
logger.exception("读取协议能力缓存失败")
return None
async def _update_cap(
self,
llm: LlmRuntimeConfig,
*,
responses: bool | None | object = _UNSET,
store: bool | None | object = _UNSET,
) -> None:
"""更新能力缓存;参数为 _UNSET 表示不改该字段,显式 None 表示未知。"""
if self._cap_cache is None:
return
try:
prev = await self._cap_cache.get(
provider_id=llm.provider_id, base_url=llm.base_url
) or LlmProtocolCapability()
new_responses = (
prev.responses if responses is _UNSET else responses # type: ignore[arg-type]
)
new_store = prev.store if store is _UNSET else store # type: ignore[arg-type]
await self._cap_cache.set(
provider_id=llm.provider_id,
base_url=llm.base_url,
capability=LlmProtocolCapability(
responses=new_responses, # type: ignore[arg-type]
store=new_store, # type: ignore[arg-type]
),
ttl_seconds=self._cap_ttl,
)
except Exception: # noqa: BLE001
logger.exception("写入协议能力缓存失败")
async def _probe_store_semantic(self, llm: LlmRuntimeConfig) -> bool:
"""
语义探测:先写入密钥,再用 previous_response_id 且不带历史追问。
能答对密钥 → 真支持 store 续链;否则(报错或静默丢上下文)→ false。
"""
secret = "ALPHA7X"
try:
model = ChatOpenAI(
api_key=llm.api_key,
base_url=llm.base_url,
model=llm.model,
temperature=0,
streaming=False,
default_headers=llm.extra_headers or None,
use_responses_api=True,
output_version="responses/v1",
store=True,
use_previous_response_id=True,
)
first = await model.ainvoke(
[
HumanMessage(
content=(
f"这是接口能力测试。请记住密钥:{secret}。"
"只回复一个词:OK"
)
)
]
)
rid = _response_id_of(first)
if not rid:
logger.info("store 语义探测失败:首轮无 response.id model=%s", llm.model)
return False
second = await model.ainvoke(
[
HumanMessage(
content="接口能力测试续问:刚才的密钥是什么?只回复密钥本身。"
)
],
previous_response_id=rid,
)
text = _chunk_text(getattr(second, "content", None)).upper()
ok = secret in text.replace(" ", "").replace("-", "")
if not ok:
logger.info(
"store 语义探测未通过(静默丢上下文)model=%s reply=%s",
llm.model,
text[:80],
)
return ok
except Exception as e: # noqa: BLE001
logger.info(
"store 语义探测异常 model=%s kind=%s err=%s",
llm.model,
classify_protocol_error(e),
e,
)
return False
async def _stream_once(
self,
*,
llm: LlmRuntimeConfig,
history: list[ChatMessage],
user_text: str,
system_prompt: str,
tools: list[Any] | None,
max_tool_result_chars: int,
use_responses: bool,
use_store: bool,
previous_response_id: str | None,
client_tool_turn: ClientToolTurn | None = None,
) -> AsyncIterator[StreamEvent]:
kwargs: dict[str, Any] = {
"api_key": llm.api_key,
"base_url": llm.base_url,
"model": llm.model,
"temperature": 0.3,
"streaming": True,
"default_headers": llm.extra_headers or None,
"use_responses_api": use_responses,
}
if use_responses:
kwargs["output_version"] = "responses/v1"
kwargs["store"] = use_store
# 仅真正续链时打开;否则 LangChain 可能按 AIMessage.id 截断历史
kwargs["use_previous_response_id"] = bool(
previous_response_id and use_store
)
model = ChatOpenAI(**kwargs)
if previous_response_id and use_store:
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
messages: list[Any] = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_text),
]
first_extra: dict[str, Any] = {
"previous_response_id": previous_response_id
}
else:
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
messages = [SystemMessage(content=system_prompt)]
for m in history:
if m.role == MessageRole.USER:
messages.append(HumanMessage(content=m.content))
elif m.role == MessageRole.ASSISTANT:
messages.append(AIMessage(content=m.content))
messages.append(HumanMessage(content=user_text))
first_extra = {}
logger.warning(
"LLM pack full history lc_messages=%s hist_rows=%s preview=%s",
len(messages),
len(history),
[
(
m.role.value if hasattr(m, "role") else type(m).__name__,
(getattr(m, "content", None) or "")[:40],
)
for m in (
history[-4:] if len(history) > 4 else history
)
],
)
last_response_id: str | None = None
if not tools:
async for chunk in model.astream(messages, **first_extra):
last_response_id = _response_id_of(chunk) or last_response_id
text = _chunk_text(chunk.content)
if text:
yield StreamEvent.token(text)
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
bound = model.bind_tools(tools)
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
tool_cap = max(500, max_tool_result_chars)
for round_idx in range(5):
gathered = None
saw_tool = False
call_extra = first_extra if round_idx == 0 else {}
async for chunk in bound.astream(messages, **call_extra):
gathered = chunk if gathered is None else gathered + chunk
if getattr(chunk, "tool_call_chunks", None) or getattr(
chunk, "tool_calls", None
):
saw_tool = True
continue
if saw_tool:
continue
text = _chunk_text(getattr(chunk, "content", None))
if text:
yield StreamEvent.token(text)
if gathered is None:
yield StreamEvent.token("(模型未返回内容)")
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
last_response_id = _response_id_of(gathered) or last_response_id
messages.append(gathered)
tool_calls = getattr(gathered, "tool_calls", None) or []
if not tool_calls:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
seen: set[str] = set()
for tc in tool_calls:
name = tc.get("name") or ""
if name in seen:
continue
seen.add(name)
yield StreamEvent.tool(
phase="start",
name=name,
label=tool_status_label(name),
)
for tc in tool_calls:
name = tc.get("name") or ""
args = tc.get("args") or {}
call_id = tc.get("id") or name
try:
if is_client_tool_name(name):
# 占位函数不代表页面已写入;先登记等待再推事件,回执到达后才进 ToolMessage
tool_args = args if isinstance(args, dict) else {}
if client_tool_turn is None:
result = "写入失败:前端回执通道未配置"
else:
client_tool_turn.arm(str(call_id))
yield StreamEvent.client_tool(
tool_call_id=str(call_id),
name=name,
args=tool_args,
label=tool_status_label(name),
)
result = await client_tool_turn.wait_result(str(call_id))
else:
tool = tool_map.get(name)
if tool is None:
result = f"未知工具: {name}"
else:
raw = await tool.ainvoke(args)
result = (
raw
if isinstance(raw, str)
else json.dumps(raw, ensure_ascii=False, default=str)
)
except Exception as e: # noqa: BLE001
result = f"工具执行失败: {e}"
messages.append(
ToolMessage(content=str(result)[:tool_cap], tool_call_id=call_id)
)
for name in seen:
yield StreamEvent.tool(
phase="end",
name=name,
label=tool_status_label(name),
)
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
def _response_id_of(msg: Any) -> str | None:
meta = getattr(msg, "response_metadata", None) or {}
if isinstance(meta, dict):
rid = meta.get("id")
if isinstance(rid, str) and rid.strip():
return rid.strip()
mid = getattr(msg, "id", None)
if isinstance(mid, str) and mid.startswith("resp_"):
return mid
return None
def _chunk_text(content: Any) -> str:
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for part in content:
if isinstance(part, str):
parts.append(part)
continue
if not isinstance(part, dict):
text = getattr(part, "text", None)
ptype = getattr(part, "type", None)
if text and ptype in (None, "text", "output_text"):
parts.append(str(text))
continue
ptype = part.get("type")
if ptype in (None, "text", "output_text"):
t = part.get("text")
if t:
parts.append(str(t))
return "".join(parts)
return ""
+78
View File
@@ -0,0 +1,78 @@
"""从 Server 内部接口拉取 LLM 运行时配置。"""
from __future__ import annotations
import logging
import httpx
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeGateway
from infrastructure.llm.api_style import normalize_api_style
logger = logging.getLogger(__name__)
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
def __init__(self, settings: Settings) -> None:
self._settings = settings
async def fetch(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
params: dict[str, str | int] = {"companyId": company_id}
if provider_id is not None:
params["providerId"] = provider_id
if model:
params["model"] = model
try:
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.get(url, params=params, headers=headers)
if resp.status_code == 400:
return None
resp.raise_for_status()
body = resp.json()
data = body.get("data") if isinstance(body, dict) else None
if not isinstance(data, dict):
return None
pid = data.get("providerId")
return LlmRuntimeConfig(
base_url=str(data.get("baseUrl") or "").rstrip("/"),
api_key=str(data.get("apiKey") or ""),
model=str(data.get("model") or ""),
provider_id=int(pid) if pid is not None else provider_id,
extra_headers={
str(k): str(v)
for k, v in (data.get("extraHeaders") or {}).items()
},
context_window=_optional_positive_int(data.get("contextWindow")),
api_style=normalize_api_style(
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
),
)
except Exception:
logger.exception(
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
company_id,
provider_id,
model,
)
return None
def _optional_positive_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None
+45
View File
@@ -0,0 +1,45 @@
"""MCP 工具加载(按请求注入公司/用户头)。"""
from __future__ import annotations
import logging
from typing import Any
from config.settings import Settings
logger = logging.getLogger(__name__)
async def load_mcp_tools(
settings: Settings, *, company_id: int, user_id: str
) -> list[Any]:
if not settings.mcp_tools_enabled or not settings.mcp_bearer_token:
return []
try:
from langchain_mcp_adapters.client import MultiServerMCPClient
except ImportError:
logger.warning("未安装 langchain-mcp-adapters,跳过 MCP tools")
return []
headers = {
"Authorization": f"Bearer {settings.mcp_bearer_token}",
"X-Agent-Company-Id": str(company_id),
"X-Agent-User-Id": str(user_id),
}
try:
client = MultiServerMCPClient(
{
"ecom-dmb": {
"url": settings.mcp_base_url,
"transport": "streamable_http",
"headers": headers,
}
}
)
tools = await client.get_tools()
return list(tools or [])
except Exception:
logger.exception(
"加载 MCP tools 失败 company_id=%s(将降级为无工具对话)", company_id
)
return []
@@ -0,0 +1,46 @@
"""Mongo 连接与索引。"""
from __future__ import annotations
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from config.settings import Settings
_client: AsyncIOMotorClient | None = None
async def get_db(settings: Settings) -> AsyncIOMotorDatabase:
global _client
if _client is None:
_client = AsyncIOMotorClient(settings.mongo_uri)
return _client[settings.mongo_db]
async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
await db.agent_sessions.create_index(
[("company_id", 1), ("user_id", 1), ("thread_id", 1)], unique=True
)
await db.agent_sessions.create_index(
[("company_id", 1), ("user_id", 1), ("status", 1), ("scene", 1), ("updated_at", -1)]
)
await db.agent_sessions.create_index(
[("company_id", 1), ("user_id", 1), ("scene", 1), ("scene_ref", 1), ("status", 1)]
)
await db.agent_messages.create_index(
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
)
await db.agent_user_memory.create_index(
[("company_id", 1), ("user_id", 1), ("status", 1), ("kind", 1), ("updated_at", -1)]
)
await db.agent_user_memory.create_index(
[("company_id", 1), ("user_id", 1), ("key", 1)],
unique=True,
partialFilterExpression={"key": {"$type": "string"}},
)
async def close_mongo() -> None:
global _client
if _client is not None:
_client.close()
_client = None
@@ -0,0 +1,449 @@
"""会话 / 消息 / 用户记忆 Mongo 实现。"""
from __future__ import annotations
from datetime import datetime
from typing import Any
import re
from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorDatabase
from domain.models import (
ChatMessage,
LlmResponseChain,
MemoryKind,
MemoryStatus,
MessageRole,
Session,
SessionStatus,
UserMemory,
)
from domain.ports import MemoryRepository, MessageRepository, SessionRepository
def _dt(v: Any) -> datetime:
if isinstance(v, datetime):
return v
return datetime.utcnow()
def _optional_int(v: Any) -> int | None:
if v is None:
return None
try:
return int(v)
except (TypeError, ValueError):
return None
def _chain_to_doc(chain: LlmResponseChain | None) -> dict[str, Any] | None:
if chain is None or not (chain.previous_response_id or "").strip():
return None
return {
"provider_id": chain.provider_id,
"model": chain.model,
"previous_response_id": chain.previous_response_id.strip(),
}
def _chain_from_doc(raw: Any) -> LlmResponseChain | None:
if not isinstance(raw, dict):
return None
rid = str(raw.get("previous_response_id") or "").strip()
model = str(raw.get("model") or "").strip()
if not rid or not model:
return None
return LlmResponseChain(
provider_id=_optional_int(raw.get("provider_id")),
model=model,
previous_response_id=rid,
)
class MongoSessionRepository(SessionRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_sessions
async def create(self, session: Session) -> Session:
doc = {
"thread_id": session.thread_id,
"company_id": session.company_id,
"user_id": session.user_id,
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"scene": session.scene or "general",
"scene_ref": session.scene_ref,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
"created_at": session.created_at,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
}
await self._col.insert_one(doc)
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
doc = await self._col.find_one(
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
)
return None if doc is None else self._to_session(doc)
async def list_active(
self,
company_id: int,
user_id: str,
limit: int = 50,
*,
scene: str | None = None,
) -> list[Session]:
query: dict[str, Any] = {
"company_id": company_id,
"user_id": user_id,
"status": SessionStatus.ACTIVE.value,
}
# 缺省只列经营助手;旧文档无 scene 字段视为 general
want = (scene or "general").strip() or "general"
if want == "general":
query["$or"] = [
{"scene": "general"},
{"scene": {"$exists": False}},
{"scene": None},
]
else:
query["scene"] = want
cursor = (
self._col.find(query)
.sort("updated_at", -1)
.limit(limit)
)
return [self._to_session(d) async for d in cursor]
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None:
ref = (scene_ref or "").strip()
if not ref:
return None
doc = await self._col.find_one(
{
"company_id": company_id,
"user_id": user_id,
"status": SessionStatus.ACTIVE.value,
"scene": (scene or "").strip() or "general",
"scene_ref": ref,
},
sort=[("updated_at", -1)],
)
return self._to_session(doc) if doc else None
async def update(self, session: Session) -> Session:
session.updated_at = datetime.utcnow()
await self._col.update_one(
{
"company_id": session.company_id,
"user_id": session.user_id,
"thread_id": session.thread_id,
},
{
"$set": {
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"scene": session.scene or "general",
"scene_ref": session.scene_ref,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
}
},
)
return session
@staticmethod
def _to_session(doc: dict[str, Any]) -> Session:
return Session(
thread_id=doc["thread_id"],
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
title=doc.get("title") or "新对话",
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
summary=doc.get("summary"),
scene=(doc.get("scene") or "general"),
scene_ref=doc.get("scene_ref"),
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
llm_model=doc.get("llm_model"),
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
last_message_at=doc.get("last_message_at"),
)
class MongoMessageRepository(MessageRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_messages
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int:
doc = await self._col.find_one(
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id},
sort=[("seq", -1)],
projection={"seq": 1},
)
return 1 if doc is None else int(doc["seq"]) + 1
async def append(self, message: ChatMessage) -> ChatMessage:
doc = {
"company_id": message.company_id,
"user_id": message.user_id,
"thread_id": message.thread_id,
"seq": message.seq,
"role": message.role.value,
"content": message.content,
"tool_name": message.tool_name,
"tool_call_id": message.tool_call_id,
"created_at": message.created_at,
}
result = await self._col.insert_one(doc)
message.id = str(result.inserted_id)
return message
async def list_recent(
self, company_id: int, user_id: str, thread_id: str, limit: int
) -> list[ChatMessage]:
cursor = (
self._col.find(
{
"company_id": company_id,
"user_id": user_id,
"thread_id": thread_id,
# 兼容旧文档无 status;软删后 status=deleted
"$or": [
{"status": {"$exists": False}},
{"status": None},
{"status": {"$ne": "deleted"}},
],
}
)
.sort("seq", -1)
.limit(limit)
)
rows = [self._to_msg(d) async for d in cursor]
rows.reverse()
return rows
async def soft_delete_by_thread(
self, company_id: int, user_id: str, thread_id: str
) -> int:
result = await self._col.update_many(
{
"company_id": company_id,
"user_id": user_id,
"thread_id": thread_id,
"$or": [
{"status": {"$exists": False}},
{"status": None},
{"status": {"$ne": "deleted"}},
],
},
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
)
return int(result.modified_count or 0)
@staticmethod
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
return ChatMessage(
id=str(doc.get("_id")),
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
thread_id=doc["thread_id"],
seq=int(doc["seq"]),
role=MessageRole(doc["role"]),
content=doc.get("content") or "",
tool_name=doc.get("tool_name"),
tool_call_id=doc.get("tool_call_id"),
created_at=_dt(doc.get("created_at")),
)
class MongoMemoryRepository(MemoryRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_user_memory
async def list_active(
self, company_id: int, user_id: str, limit: int
) -> list[UserMemory]:
cursor = (
self._col.find(
{
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
.sort("updated_at", -1)
.limit(limit)
)
return [self._to_mem(d) async for d in cursor]
async def count_active(self, company_id: int, user_id: str) -> int:
return int(
await self._col.count_documents(
{
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
)
async def search(
self, company_id: int, user_id: str, query: str, limit: int
) -> list[UserMemory]:
"""按摘要/正文关键词匹配(非向量);无关键词时退化为最近更新列表。"""
tokens = _keyword_tokens(query)
filt: dict[str, Any] = {
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
if tokens:
token_clauses = []
for t in tokens:
escaped = re.escape(t)
token_clauses.append(
{
"$or": [
{"summary": {"$regex": escaped, "$options": "i"}},
{"text": {"$regex": escaped, "$options": "i"}},
]
}
)
filt["$and"] = token_clauses
cursor = self._col.find(filt).sort("updated_at", -1).limit(max(1, min(limit, 20)))
return [self._to_mem(d) async for d in cursor]
async def get_by_ids(
self, company_id: int, user_id: str, memory_ids: list[str]
) -> list[UserMemory]:
oids: list[ObjectId] = []
for mid in memory_ids:
try:
oids.append(ObjectId(mid))
except Exception:
continue
if not oids:
return []
cursor = self._col.find(
{
"_id": {"$in": oids},
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
by_id: dict[str, UserMemory] = {}
async for d in cursor:
by_id[str(d["_id"])] = self._to_mem(d)
# 保持调用方 id 顺序
return [by_id[mid] for mid in memory_ids if mid in by_id]
async def upsert(self, memory: UserMemory) -> UserMemory:
memory.updated_at = datetime.utcnow()
if not (memory.summary or "").strip():
memory.summary = _fallback_summary(memory.text)
payload = {
"company_id": memory.company_id,
"user_id": memory.user_id,
"kind": memory.kind.value,
"key": memory.key,
"text": memory.text,
"summary": memory.summary,
"value": memory.value,
"source_thread_id": memory.source_thread_id,
"status": memory.status.value,
"confidence": memory.confidence,
"updated_at": memory.updated_at,
}
if memory.key:
existing = await self._col.find_one(
{
"company_id": memory.company_id,
"user_id": memory.user_id,
"key": memory.key,
"status": {"$ne": MemoryStatus.DELETED.value},
}
)
if existing:
await self._col.update_one({"_id": existing["_id"]}, {"$set": payload})
memory.id = str(existing["_id"])
memory.created_at = _dt(existing.get("created_at"))
return memory
payload["created_at"] = memory.created_at
result = await self._col.insert_one(payload)
memory.id = str(result.inserted_id)
return memory
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool:
try:
oid = ObjectId(memory_id)
except Exception:
return False
result = await self._col.update_one(
{"_id": oid, "company_id": company_id, "user_id": user_id},
{
"$set": {
"status": MemoryStatus.DELETED.value,
"updated_at": datetime.utcnow(),
}
},
)
return result.modified_count > 0
@staticmethod
def _to_mem(doc: dict[str, Any]) -> UserMemory:
text = doc.get("text") or ""
summary = (doc.get("summary") or "").strip() or _fallback_summary(text)
return UserMemory(
id=str(doc.get("_id")),
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value),
key=doc.get("key"),
text=text,
summary=summary,
value=doc.get("value") or {},
source_thread_id=doc.get("source_thread_id"),
status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value),
confidence=float(doc.get("confidence") or 0.8),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
)
def _fallback_summary(text: str, max_len: int = 80) -> str:
s = (text or "").strip().replace("\n", " ")
if len(s) <= max_len:
return s
return s[: max_len - 1] + "…"
def _keyword_tokens(query: str) -> list[str]:
"""按空白与常见标点切词;过短 token 丢弃。"""
parts = re.split(r"[\s,,。.!!??;;::、/\\|]+", (query or "").strip())
out: list[str] = []
for p in parts:
t = p.strip()
if len(t) >= 1 and t not in out:
out.append(t)
return out[:8]
@@ -0,0 +1,153 @@
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
from infrastructure.llm.api_style import normalize_api_style
class RedisLlmRuntimeCache(LlmRuntimeCache):
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
if provider_id is not None and model:
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
if model:
return f"agent:llm:rt:{company_id}:{model}"
return f"agent:llm:rt:{company_id}"
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
raw = await self._r.get(self._key(company_id, provider_id, model))
if not raw and provider_id is not None and model:
# 兼容旧键 companyId:model
raw = await self._r.get(self._key(company_id, None, model))
if not raw:
return None
data = json.loads(raw)
cfg = LlmRuntimeConfig(
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
context_window=_optional_int(data.get("context_window")),
api_style=normalize_api_style(data.get("api_style")),
)
if model and cfg.model and cfg.model != model:
return None
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
return None
return cfg
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
"extra_headers": config.extra_headers,
"context_window": config.context_window,
"api_style": normalize_api_style(config.api_style),
}
await self._r.set(
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
async def delete(self, company_id: int) -> None:
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
if keys:
await self._r.delete(*keys)
_redis: redis.Redis | None = None
def _optional_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None
def get_redis(settings: Settings) -> redis.Redis:
global _redis
if _redis is None:
_redis = redis.from_url(settings.redis_url, decode_responses=True)
return _redis
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(*, provider_id: int | None, base_url: str) -> str:
if provider_id is not None and int(provider_id) > 0:
return f"agent:llm:cap:p:{int(provider_id)}"
url = (base_url or "").rstrip("/").lower()
return f"agent:llm:cap:u:{url}"
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
if not raw:
return None
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
return LlmProtocolCapability(
responses=data.get("responses"),
store=data.get("store"),
)
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
payload = {
"responses": capability.responses,
"store": capability.store,
}
await self._r.set(
self._key(provider_id=provider_id, base_url=base_url),
json.dumps(payload),
ex=max(60, ttl_seconds),
)
async def close_redis() -> None:
global _redis
if _redis is not None:
await _redis.aclose()
_redis = None
+9
View File
@@ -0,0 +1,9 @@
{
"include": ["."],
"exclude": [".venv", "**/__pycache__"],
"venvPath": ".",
"venv": ".venv",
"pythonVersion": "3.12",
"pythonPlatform": "Linux",
"extraPaths": ["."]
}
+14
View File
@@ -0,0 +1,14 @@
# Agent 服务依赖(Python 3.11+)
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
pydantic>=2.9.0
pydantic-settings>=2.6.0
PyJWT>=2.9.0
motor>=3.6.0
redis>=5.2.0
httpx>=0.27.0
langchain-core>=0.3.0
langchain-openai>=0.3.26
langchain-mcp-adapters>=0.1.0
langgraph>=0.2.0
sse-starlette>=2.1.0
+68
View File
@@ -0,0 +1,68 @@
"""协议探测规划与错误分类。"""
from domain.models import LlmProtocolCapability
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
def test_normalize_api_style():
assert normalize_api_style(None) == "auto"
assert normalize_api_style("Responses") == "responses"
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, False)
assert ProtocolAttempt(True, False, False) in attempts
assert ProtocolAttempt(False, False, False) in attempts
assert not any(a.use_chain for a in attempts)
def test_plan_store_true_allows_chain():
cap = LlmProtocolCapability(responses=True, store=True)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, True)
assert ProtocolAttempt(True, True, False) in attempts
def test_plan_store_false_prefers_stateless_responses_then_completions():
"""store 证伪:无状态 Responses(全量历史)→ Completions。"""
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts == [
ProtocolAttempt(True, False, False),
ProtocolAttempt(False, False, False),
]
assert not any(a.use_chain or a.use_store for a in attempts)
def test_plan_store_false_forced_responses_same_ladder():
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
assert attempts[0] == ProtocolAttempt(True, False, False)
assert ProtocolAttempt(False, False, False) in attempts
def test_plan_completions_only():
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
ProtocolAttempt(False, False, False)
]
def test_plan_responses_known_unsupported_falls_to_completions():
cap = LlmProtocolCapability(responses=False, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
assert attempts == [ProtocolAttempt(False, False, False)]
def test_classify_protocol_error():
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
assert (
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
)
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
assert classify_protocol_error(Exception("rate limit")) == "other"
+45
View File
@@ -0,0 +1,45 @@
"""前端工具回执门闩:代次隔离、超时与迟到提交。"""
import asyncio
from application.client_tool_gate import (
ClientToolGate,
format_client_tool_result,
)
def test_format_failure_prefix():
assert format_client_tool_result(True, "已写入标题") == "已写入标题"
assert format_client_tool_result(False, "标题为空").startswith("写入失败")
def test_submit_wakes_current_epoch_only():
gate = ClientToolGate(timeout_seconds=1)
async def scenario():
epoch = gate.begin("t1")
gate.arm("t1", epoch, "call-1")
late = gate.begin("t1")
assert late != epoch
assert gate.submit("t1", "call-1", True, "旧轮") is False
gate.arm("t1", late, "call-2")
assert gate.submit("t1", "call-2", True, "已写入标题") is True
ok, message = await gate.wait("t1", late, "call-2")
assert ok is True
assert message == "已写入标题"
assert gate.submit("t1", "call-2", True, "再次") is False
asyncio.run(scenario())
def test_timeout_when_no_submit():
gate = ClientToolGate(timeout_seconds=0.05)
async def scenario():
epoch = gate.begin("t2")
gate.arm("t2", epoch, "call")
ok, message = await gate.wait("t2", epoch, "call")
assert ok is False
assert message == "前端未回执"
asyncio.run(scenario())
+32
View File
@@ -0,0 +1,32 @@
"""会话链选型匹配。"""
from domain.models import LlmResponseChain, LlmRuntimeConfig
from application.chat_service import _usable_chain_id
def test_usable_chain_id_matches():
llm = LlmRuntimeConfig(
base_url="https://api.openai.com/v1",
api_key="k",
model="gpt-4o-mini",
provider_id=3,
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm) == "resp_abc"
def test_usable_chain_id_clears_on_model_switch():
llm = LlmRuntimeConfig(
base_url="https://api.openai.com/v1",
api_key="k",
model="gpt-4o",
provider_id=3,
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm) is None
+119
View File
@@ -0,0 +1,119 @@
"""未落库会话 scene_ref 改绑规则。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any
from application.session_service import SessionService
from domain.models import Actor, Session, SessionStatus
class _MemSessions:
def __init__(self) -> None:
self.rows: dict[str, Session] = {}
async def create(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
s = self.rows.get(thread_id)
if s is None:
return None
if s.company_id != company_id or s.user_id != user_id:
return None
return s
async def list_active(self, *args: Any, **kwargs: Any) -> list[Session]:
return []
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None:
for s in self.rows.values():
if (
s.company_id == company_id
and s.user_id == user_id
and s.status == SessionStatus.ACTIVE
and (s.scene or "general") == scene
and s.scene_ref == scene_ref
):
return s
return None
async def update(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
def _actor() -> Actor:
return Actor(company_id=1, user_id="u1")
def _session(*, thread_id: str, scene_ref: str | None) -> Session:
now = datetime.utcnow()
return Session(
thread_id=thread_id,
company_id=1,
user_id="u1",
title="发布草稿(未保存)",
status=SessionStatus.ACTIVE,
scene="ecom_goods_publish",
scene_ref=scene_ref,
created_at=now,
updated_at=now,
)
def test_rebind_local_to_draft_id():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
local = _session(thread_id="t1", scene_ref="local-abc")
await repo.create(local)
out = await svc.rebind_scene_ref(
_actor(), "t1", scene_ref="42", title="发布草稿 #42"
)
assert out.scene_ref == "42"
assert out.title == "发布草稿 #42"
asyncio.run(scenario())
def test_rebind_rejects_non_local():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t1", scene_ref="7"))
try:
await svc.rebind_scene_ref(_actor(), "t1", scene_ref="8")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "未落库" in str(e)
asyncio.run(scenario())
def test_rebind_rejects_occupied_draft():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t-old", scene_ref="9"))
await repo.create(_session(thread_id="t-local", scene_ref="local-x"))
try:
await svc.rebind_scene_ref(_actor(), "t-local", scene_ref="9")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "已有关联会话" in str(e)
asyncio.run(scenario())
@@ -1,5 +1,6 @@
dist dist
dist-features dist-features
artifacts
node_modules node_modules
*.local *.local
.DS_Store .DS_Store
@@ -12,7 +12,7 @@
## 安装依赖 ## 安装依赖
```bash ```bash
cd browser-extension cd apps/browser-extension
pnpm install pnpm install
``` ```
@@ -28,23 +28,28 @@ pnpm dev
pnpm build pnpm build
``` ```
产物: 产物(统一在 `artifacts/`,已 gitignore):
| 目录 | 说明 | | 路径 | 说明 |
|------|------| |------|------|
| `dist/` | 扩展壳(装到浏览器) | | `artifacts/extension/` | 扩展壳(可解压加载到浏览器) |
| `dist-features/` | 功能清单 `manifest.json` + 各功能 JS(部署到后端静态目录) | | `artifacts/features/` | 功能清单 `manifest.json` + 各功能 JS |
| `artifacts/ecbi-data-sync-extension.zip` | 扩展壳压缩包(内含一层 `ecbi-data-sync-extension/` 目录) |
`pnpm build` 会顺带把 `dist-features/` 同步到 `pnpm build` 会同步到后端静态目录(本地联调 / 打进 jar):
`ecom-dmb-backend/src/main/resources/static/extension-features/`(本地联调)。
生产更新功能时:只拷贝 `dist-features/*` 到服务器对应静态目录并重启/热加载即可,扩展壳不必每次重装(壳内 API 未变时)。 | 本地产物 | 后端静态目录 |
|----------|--------------|
| `artifacts/features/*` | `static/extension-features/` |
| `ecbi-data-sync-extension.zip` | `static/extension/` |
生产更新功能时:只拷贝 `artifacts/features/*` 到服务器 `extension-features/` 即可,扩展壳不必每次重装(壳内 API 未变时)。
## 安装到 Chrome / Edge ## 安装到 Chrome / Edge
1. 打开 `chrome://extensions/` 或 `edge://extensions/` 1. 打开 `chrome://extensions/` 或 `edge://extensions/`
2. 开启「开发者模式」 2. 开启「开发者模式」
3. 「加载已解压的扩展程序」→ 选择本项目的 `dist` 目录 3. 「加载已解压的扩展程序」→ 选择 `artifacts/extension`,或后台「开放密钥」页下载 zip 后解压加载
## 项目架构 ## 项目架构
@@ -72,14 +77,16 @@ Popup 右上角「配置」:
| 项 | 说明 | | 项 | 说明 |
|----|------| |----|------|
| Base URL | 例 `http://localhost:8080/api`(不要末尾 `/`) | | Base URL | 例 `http://localhost:8080/api`(**直连后端**,不要用前端 dev 的 `5666`;不要末尾 `/`) |
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT | | API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
Open API 请求由 **Background Service Worker 代发**(Content Script 在 HTTPS 拼多多页内不能直连 `http://localhost`,会被混合内容/CORS 拦截,Network 里常无 HTTP 状态码)。
Key 建议具备: Key 建议具备:
- `open:extension:feature:read`(功能清单/脚本) - `openapi:extension:feature:read`(功能清单/脚本)
- `open:shop:pdd:read` - `openapi:shop:pdd:read`
- `open:product:adfee` - `openapi:product:adfee`
## 功能清单(静态 JSON)方案 ## 功能清单(静态 JSON)方案
@@ -111,6 +118,7 @@ static/extension-features/
- `GET /open/v1/extension/features` - `GET /open/v1/extension/features`
- `GET /open/v1/extension/features/{id}/script` - `GET /open/v1/extension/features/{id}/script`
- `GET /open/v1/channel/pdd/shop/match-by-name?mallName=`
- `POST /open/v1/channel/pdd/shop/list` - `POST /open/v1/channel/pdd/shop/list`
- `POST /open/v1/channel/pdd/goods/adfee/batch-import` - `POST /open/v1/channel/pdd/goods/adfee/batch-import`
@@ -29,7 +29,7 @@ export default defineManifest({
host_permissions: ['http://*/*', 'https://*/*'], host_permissions: ['http://*/*', 'https://*/*'],
icons: { icons: {
'16': 'public/icons/icon-16.png', '16': 'public/icons/icon-16.png',
'48': 'public/icons/icon-48.png', '64': 'public/icons/icon-64.png',
'128': 'public/icons/icon-128.png', '128': 'public/icons/icon-128.png',
}, },
}); });
@@ -13,7 +13,7 @@ importers:
version: 3.5.41(typescript@5.6.3) version: 3.5.41(typescript@5.6.3)
devDependencies: devDependencies:
'@crxjs/vite-plugin': '@crxjs/vite-plugin':
specifier: ^2.0.0-beta.28 specifier: ^2.7.1
version: 2.7.1(vite@5.4.21(@types/node@22.20.1)) version: 2.7.1(vite@5.4.21(@types/node@22.20.1))
'@types/chrome': '@types/chrome':
specifier: ^0.0.287 specifier: ^0.0.287
@@ -39,6 +39,9 @@ importers:
eslint-plugin-vue: eslint-plugin-vue:
specifier: ^9.32.0 specifier: ^9.32.0
version: 9.33.0(eslint@9.39.5(jiti@1.21.7)) version: 9.33.0(eslint@9.39.5(jiti@1.21.7))
linkedom:
specifier: ^0.18.13
version: 0.18.13
postcss: postcss:
specifier: ^8.4.49 specifier: ^8.4.49
version: 8.5.26 version: 8.5.26
@@ -663,6 +666,10 @@ packages:
boolbase@1.0.0: boolbase@1.0.0:
resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
boolbase@2.0.0:
resolution: {integrity: sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==}
engines: {node: '>=20.19.0'}
brace-expansion@1.1.18: brace-expansion@1.1.18:
resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==} resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==}
@@ -725,15 +732,26 @@ packages:
css-select@5.2.2: css-select@5.2.2:
resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==} resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
css-select@7.0.0:
resolution: {integrity: sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==}
engines: {node: '>=20.19.0'}
css-what@6.2.2: css-what@6.2.2:
resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==} resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
css-what@8.0.0:
resolution: {integrity: sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==}
engines: {node: '>=20.19.0'}
cssesc@3.0.0: cssesc@3.0.0:
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'} engines: {node: '>=4'}
hasBin: true hasBin: true
cssom@0.5.0:
resolution: {integrity: sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==}
csstype@3.2.3: csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
@@ -761,16 +779,32 @@ packages:
dom-serializer@2.0.0: dom-serializer@2.0.0:
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
dom-serializer@3.1.1:
resolution: {integrity: sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==}
engines: {node: '>=20.19.0'}
domelementtype@2.3.0: domelementtype@2.3.0:
resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
domelementtype@3.0.0:
resolution: {integrity: sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==}
engines: {node: '>=20.19.0'}
domhandler@5.0.3: domhandler@5.0.3:
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
engines: {node: '>= 4'} engines: {node: '>= 4'}
domhandler@6.0.1:
resolution: {integrity: sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==}
engines: {node: '>=20.19.0'}
domutils@3.2.2: domutils@3.2.2:
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
domutils@4.0.2:
resolution: {integrity: sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==}
engines: {node: '>=20.19.0'}
electron-to-chromium@1.5.407: electron-to-chromium@1.5.407:
resolution: {integrity: sha512-4R8XgQOdfxexCd/u63lRm6wCHjECwI45MV9wxAs2ggtfWe2hwlo1ql97jKsju2IcJ+jFSTwBssyYoiWhh7mauQ==} resolution: {integrity: sha512-4R8XgQOdfxexCd/u63lRm6wCHjECwI45MV9wxAs2ggtfWe2hwlo1ql97jKsju2IcJ+jFSTwBssyYoiWhh7mauQ==}
@@ -782,6 +816,10 @@ packages:
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
engines: {node: '>=0.12'} engines: {node: '>=0.12'}
entities@8.1.0:
resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==}
engines: {node: '>=20.19.0'}
es-errors@1.3.0: es-errors@1.3.0:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -986,6 +1024,12 @@ packages:
resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}
hasBin: true hasBin: true
html-escaper@3.0.3:
resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==}
htmlparser2@10.1.0:
resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
ignore@5.3.2: ignore@5.3.2:
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
engines: {node: '>= 4'} engines: {node: '>= 4'}
@@ -1064,6 +1108,15 @@ packages:
lines-and-columns@1.2.4: lines-and-columns@1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
linkedom@0.18.13:
resolution: {integrity: sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==}
engines: {node: '>=16'}
peerDependencies:
canvas: '>= 2'
peerDependenciesMeta:
canvas:
optional: true
locate-path@6.0.0: locate-path@6.0.0:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'} engines: {node: '>=10'}
@@ -1127,6 +1180,10 @@ packages:
nth-check@2.1.1: nth-check@2.1.1:
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
nth-check@3.0.1:
resolution: {integrity: sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==}
engines: {node: '>=20.19.0'}
object-assign@4.1.1: object-assign@4.1.1:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -1380,6 +1437,9 @@ packages:
engines: {node: '>=14.17'} engines: {node: '>=14.17'}
hasBin: true hasBin: true
uhyphen@0.2.0:
resolution: {integrity: sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==}
undici-types@6.21.0: undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
@@ -2030,6 +2090,8 @@ snapshots:
boolbase@1.0.0: {} boolbase@1.0.0: {}
boolbase@2.0.0: {}
brace-expansion@1.1.18: brace-expansion@1.1.18:
dependencies: dependencies:
balanced-match: 1.0.2 balanced-match: 1.0.2
@@ -2104,10 +2166,22 @@ snapshots:
domutils: 3.2.2 domutils: 3.2.2
nth-check: 2.1.1 nth-check: 2.1.1
css-select@7.0.0:
dependencies:
boolbase: 2.0.0
css-what: 8.0.0
domhandler: 6.0.1
domutils: 4.0.2
nth-check: 3.0.1
css-what@6.2.2: {} css-what@6.2.2: {}
css-what@8.0.0: {}
cssesc@3.0.0: {} cssesc@3.0.0: {}
cssom@0.5.0: {}
csstype@3.2.3: {} csstype@3.2.3: {}
de-indent@1.0.2: {} de-indent@1.0.2: {}
@@ -2128,24 +2202,44 @@ snapshots:
domhandler: 5.0.3 domhandler: 5.0.3
entities: 4.5.0 entities: 4.5.0
dom-serializer@3.1.1:
dependencies:
domelementtype: 3.0.0
domhandler: 6.0.1
entities: 8.1.0
domelementtype@2.3.0: {} domelementtype@2.3.0: {}
domelementtype@3.0.0: {}
domhandler@5.0.3: domhandler@5.0.3:
dependencies: dependencies:
domelementtype: 2.3.0 domelementtype: 2.3.0
domhandler@6.0.1:
dependencies:
domelementtype: 3.0.0
domutils@3.2.2: domutils@3.2.2:
dependencies: dependencies:
dom-serializer: 2.0.0 dom-serializer: 2.0.0
domelementtype: 2.3.0 domelementtype: 2.3.0
domhandler: 5.0.3 domhandler: 5.0.3
domutils@4.0.2:
dependencies:
dom-serializer: 3.1.1
domelementtype: 3.0.0
domhandler: 6.0.1
electron-to-chromium@1.5.407: {} electron-to-chromium@1.5.407: {}
entities@4.5.0: {} entities@4.5.0: {}
entities@7.0.1: {} entities@7.0.1: {}
entities@8.1.0: {}
es-errors@1.3.0: {} es-errors@1.3.0: {}
es-module-lexer@0.10.5: {} es-module-lexer@0.10.5: {}
@@ -2384,6 +2478,15 @@ snapshots:
he@1.2.0: {} he@1.2.0: {}
html-escaper@3.0.3: {}
htmlparser2@10.1.0:
dependencies:
domelementtype: 2.3.0
domhandler: 5.0.3
domutils: 3.2.2
entities: 7.0.1
ignore@5.3.2: {} ignore@5.3.2: {}
ignore@7.0.6: {} ignore@7.0.6: {}
@@ -2446,6 +2549,14 @@ snapshots:
lines-and-columns@1.2.4: {} lines-and-columns@1.2.4: {}
linkedom@0.18.13:
dependencies:
css-select: 7.0.0
cssom: 0.5.0
html-escaper: 3.0.3
htmlparser2: 10.1.0
uhyphen: 0.2.0
locate-path@6.0.0: locate-path@6.0.0:
dependencies: dependencies:
p-locate: 5.0.0 p-locate: 5.0.0
@@ -2504,6 +2615,10 @@ snapshots:
dependencies: dependencies:
boolbase: 1.0.0 boolbase: 1.0.0
nth-check@3.0.1:
dependencies:
boolbase: 2.0.0
object-assign@4.1.1: {} object-assign@4.1.1: {}
object-hash@3.0.0: {} object-hash@3.0.0: {}
@@ -2765,6 +2880,8 @@ snapshots:
typescript@5.6.3: {} typescript@5.6.3: {}
uhyphen@0.2.0: {}
undici-types@6.21.0: {} undici-types@6.21.0: {}
universalify@2.0.1: {} universalify@2.0.1: {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 433 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

@@ -0,0 +1,132 @@
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
renameSync,
rmSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'vite';
/**
* 构建功能脚本 → artifacts/features,打 zip 壳,并同步到后端 static。
*/
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..');
const artifactsRoot = resolve(root, 'artifacts');
const featuresOutDir = resolve(artifactsRoot, 'features');
const extensionOutDir = resolve(artifactsRoot, 'extension');
const zipName = 'ecbi-data-sync-extension.zip';
const zipLocalPath = resolve(artifactsRoot, zipName);
const backendFeaturesStatic = resolve(
root,
'../server/src/main/resources/static/extension-features',
);
const backendExtensionStatic = resolve(
root,
'../server/src/main/resources/static/extension',
);
function syncDirContents(srcDir, destDir) {
if (existsSync(destDir)) {
rmSync(destDir, { recursive: true, force: true });
}
mkdirSync(destDir, { recursive: true });
for (const name of ['manifest.json', 'pdd-ad-fee.js', 'pdd-ad-fee.js.map']) {
const src = resolve(srcDir, name);
if (existsSync(src)) {
copyFileSync(src, resolve(destDir, name));
}
}
}
function packExtensionZip() {
if (!existsSync(extensionOutDir)) {
throw new Error(
`扩展壳目录不存在: ${extensionOutDir}(请先执行 vite build)`,
);
}
if (existsSync(zipLocalPath)) {
unlinkSync(zipLocalPath);
}
// zip 内一层目录:ecbi-data-sync-extension/…,解压后直接「加载已解压的扩展」
const packageDirName = 'ecbi-data-sync-extension';
const packageDir = resolve(artifactsRoot, packageDirName);
if (existsSync(packageDir)) {
rmSync(packageDir, { recursive: true, force: true });
}
renameSync(extensionOutDir, packageDir);
try {
execFileSync('zip', ['-r', '-q', zipLocalPath, packageDirName], {
cwd: artifactsRoot,
});
} finally {
renameSync(packageDir, extensionOutDir);
}
mkdirSync(backendExtensionStatic, { recursive: true });
copyFileSync(zipLocalPath, resolve(backendExtensionStatic, zipName));
}
async function main() {
mkdirSync(artifactsRoot, { recursive: true });
await build({
configFile: resolve(root, 'vite.features.config.ts'),
});
const entryFile = 'pdd-ad-fee.js';
const jsPath = resolve(featuresOutDir, entryFile);
const code = readFileSync(jsPath, 'utf8');
const sha256 = createHash('sha256').update(code).digest('hex');
const manifest = {
schemaVersion: 1,
updatedAt: new Date().toISOString(),
features: [
{
id: 'pdd-ad-fee',
name: '拼多多商品推广费同步',
version: '0.3.10',
description:
'从推广总览读取推广费并同步到 BI(总花费为 0 不记录)',
matchUrlPatterns: [
'*://yingxiao.pinduoduo.com/*',
'https://yingxiao.pinduoduo.com/',
],
entry: entryFile,
sha256,
executionWorld: 'main',
},
],
};
writeFileSync(
resolve(featuresOutDir, 'manifest.json'),
`${JSON.stringify(manifest, null, 2)}\n`,
'utf8',
);
syncDirContents(featuresOutDir, backendFeaturesStatic);
packExtensionZip();
console.log(`[build-features] wrote ${featuresOutDir}`);
console.log(`[build-features] synced features → ${backendFeaturesStatic}`);
console.log(
`[build-features] packed zip → ${resolve(backendExtensionStatic, zipName)}`,
);
console.log(`[build-features] pdd-ad-fee sha256=${sha256}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+86
View File
@@ -0,0 +1,86 @@
import { ExtensionError } from '@/shared/errors';
import { executeOpenApiFetch } from './openApiFetch';
export type { ApiResponseBody } from './openApiFetch';
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
let openApiOverride: OpenApiRequestFn | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
openApiOverride = fn;
}
type OpenApiBgPayload = {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
type OpenApiBgResponse =
| { ok: true; data: unknown }
| { ok: false; code: string; message: string };
function canUseBackgroundProxy(): boolean {
return typeof chrome !== 'undefined' && Boolean(chrome.runtime?.id);
}
async function requestViaBackground<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const headers: Record<string, string> = {};
if (init.headers) {
new Headers(init.headers).forEach((value, key) => {
headers[key] = value;
});
}
const payload: OpenApiBgPayload = {
path,
method: init.method,
body: typeof init.body === 'string' ? init.body : undefined,
headers,
};
let response: OpenApiBgResponse | undefined;
try {
response = (await chrome.runtime.sendMessage({
type: 'OPEN_API_REQUEST',
payload,
})) as OpenApiBgResponse | undefined;
} catch {
throw new ExtensionError('NETWORK_ERROR', '无法连接扩展后台,请重载扩展后重试');
}
if (!response) {
throw new ExtensionError('NETWORK_ERROR', '扩展后台无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as ExtensionError['code']) || 'API_REQUEST_FAILED',
response.message || '请求失败',
);
}
return response.data as T;
}
/**
* Open API 统一入口。
* Content Script 在 HTTPS 第三方页内不能直连 HTTP 本地 API(混合内容/CORS),
* 默认经 Background 代发。
*/
export async function openApiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
if (openApiOverride) {
return openApiOverride<T>(path, init);
}
if (canUseBackgroundProxy()) {
return requestViaBackground<T>(path, init);
}
return executeOpenApiFetch<T>(path, init);
}
@@ -25,6 +25,18 @@ export interface PddShopFilters {
mallName?: string; mallName?: string;
} }
export async function matchPddChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const qs = new URLSearchParams({ mallName: name });
return openApiRequest<PddChannelShop | null>(
`${OPEN_API_PATHS.pddShopMatchByName}?${qs.toString()}`,
{ method: 'GET' },
);
}
export async function listPddChannelShops( export async function listPddChannelShops(
query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 }, query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 },
): Promise<PageResultVO<PddChannelShop>> { ): Promise<PageResultVO<PddChannelShop>> {
@@ -7,23 +7,11 @@ export interface ApiResponseBody<T> {
data: T; data: T;
} }
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>; /** 在扩展上下文(Background / Popup)内直连 Open API */
export async function executeOpenApiFetch<T>(
let openApiOverride: OpenApiRequestFn | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
openApiOverride = fn;
}
export async function openApiRequest<T>(
path: string, path: string,
init: RequestInit = {}, init: RequestInit = {},
): Promise<T> { ): Promise<T> {
if (openApiOverride) {
return openApiOverride<T>(path, init);
}
const settings = await getSettings(); const settings = await getSettings();
if (!settings.apiBaseUrl) { if (!settings.apiBaseUrl) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL'); throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
@@ -65,7 +53,6 @@ export async function openApiRequest<T>(
); );
} }
// 后端业务码:0 / 200 视为成功(兼容)
if (body.code !== 0 && body.code !== 200) { if (body.code !== 0 && body.code !== 200) {
throw new ExtensionError( throw new ExtensionError(
'API_BUSINESS_ERROR', 'API_BUSINESS_ERROR',
@@ -1,8 +1,12 @@
/** /**
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。 * Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。 * chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
* Open API 亦在此代发,避免 HTTPS 页面直连 HTTP 本地服务被混合内容拦截。
*/ */
import { executeOpenApiFetch } from '@/api/openApiFetch';
import { ExtensionError } from '@/shared/errors';
type InjectMessage = { type InjectMessage = {
type: 'INJECT_MAIN_SCRIPT'; type: 'INJECT_MAIN_SCRIPT';
payload: { code: string }; payload: { code: string };
@@ -13,7 +17,21 @@ type CallMessage = {
payload: { featureId: string; action: 'mount' | 'unmount' }; payload: { featureId: string; action: 'mount' | 'unmount' };
}; };
type BgMessage = InjectMessage | CallMessage | { type: 'BACKGROUND_PING' }; type OpenApiMessage = {
type: 'OPEN_API_REQUEST';
payload: {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
};
type BgMessage =
| InjectMessage
| CallMessage
| OpenApiMessage
| { type: 'BACKGROUND_PING' };
chrome.runtime.onInstalled.addListener(() => { chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed'); console.info('[ecbi-extension] installed');
@@ -25,6 +43,23 @@ chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse)
return true; return true;
} }
if (message?.type === 'OPEN_API_REQUEST') {
const { path, method, body, headers } = message.payload;
void executeOpenApiFetch(path, { method, body, headers })
.then((data) => sendResponse({ ok: true, data }))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : 'Open API 请求失败',
);
sendResponse({ ok: false, code: err.code, message: err.message });
});
return true;
}
const tabId = sender.tab?.id; const tabId = sender.tab?.id;
if (tabId == null) { if (tabId == null) {
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' }); sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
@@ -111,16 +111,23 @@ const autoDaySpanLabel = computed(() => {
} }
}); });
const shopStatusLabel = computed(() => { const shopTagLabel = computed(() => {
if (shopMatching.value) return '匹配中'; if (shopMatching.value) return '匹配中';
if (shopMatched.value && channelShopId.value != null) return '已授权'; if (shopMatched.value && channelShopId.value != null) return '已授权';
if (pageMallName.value.trim()) return '未授权,请到 BI 系统授权同名店铺'; if (pageMallName.value.trim()) return '未授权';
return '未识别店铺'; return '未识别';
}); });
const headerShopLine = computed(() => { const shopTagClass = computed(() => {
if (shopMatching.value) return 'ecbi-shop-tag--loading';
if (shopMatched.value && channelShopId.value != null) return 'ecbi-shop-tag--ok';
if (pageMallName.value.trim()) return 'ecbi-shop-tag--warn';
return 'ecbi-shop-tag--muted';
});
const headerShopTitle = computed(() => {
const name = pageMallName.value.trim() || '未识别店铺'; const name = pageMallName.value.trim() || '未识别店铺';
return `${name} · ${shopStatusLabel.value}`; return `${name} · ${shopTagLabel.value}`;
}); });
function onHeatSelect(date: string | undefined) { function onHeatSelect(date: string | undefined) {
@@ -489,15 +496,10 @@ onUnmounted(() => {
> >
<div class="ecbi-header-main"> <div class="ecbi-header-main">
<h1>{{ EXTENSION_NAME }}</h1> <h1>{{ EXTENSION_NAME }}</h1>
<p <div class="ecbi-header-shop" :title="headerShopTitle">
class="ecbi-header-sub" <span class="ecbi-header-shop-name">{{ pageMallName.trim() || '未识别店铺' }}</span>
:class="{ <span class="ecbi-shop-tag" :class="shopTagClass">{{ shopTagLabel }}</span>
'ecbi-header-sub-warn': !shopMatched && Boolean(pageMallName.trim()) && !shopMatching, </div>
}"
:title="headerShopLine"
>
{{ headerShopLine }}
</p>
<p class="ecbi-header-stats">{{ accumulatedLabel }}</p> <p class="ecbi-header-stats">{{ accumulatedLabel }}</p>
</div> </div>
<div class="ecbi-header-actions"> <div class="ecbi-header-actions">
@@ -521,6 +523,14 @@ onUnmounted(() => {
</header> </header>
<div class="ecbi-body"> <div class="ecbi-body">
<div class="ecbi-status-bar">
<p class="ecbi-status" :class="{ 'ecbi-status-busy': busy || autoRunning }">
{{ statusText }}
</p>
<p v-if="syncResultText" class="ecbi-ok">{{ syncResultText }}</p>
<p v-if="errorText" class="ecbi-error">{{ errorText }}</p>
</div>
<div class="ecbi-meta"> <div class="ecbi-meta">
<span>{{ dateModeLabel }}</span> <span>{{ dateModeLabel }}</span>
<span class="ecbi-meta-sep">·</span> <span class="ecbi-meta-sep">·</span>
@@ -550,13 +560,21 @@ onUnmounted(() => {
> >
读当日 读当日
</button> </button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="clearAccumulated"
>
清空累计
</button>
<button <button
class="ecbi-btn ecbi-btn-primary" class="ecbi-btn ecbi-btn-primary"
type="button" type="button"
:disabled="busy || autoRunning || !batch?.items?.length" :disabled="busy || autoRunning || !batch?.items?.length"
@click="handleSync" @click="handleSync"
> >
传入系统 同步到系统
</button> </button>
</div> </div>
@@ -602,14 +620,6 @@ onUnmounted(() => {
<button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect"> <button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect">
停止 停止
</button> </button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="clearAccumulated"
>
清空累计
</button>
</div> </div>
</div> </div>
</details> </details>
@@ -626,12 +636,6 @@ onUnmounted(() => {
<p v-else class="ecbi-muted" style="margin: 0">暂无数据</p> <p v-else class="ecbi-muted" style="margin: 0">暂无数据</p>
</div> </div>
</details> </details>
<p class="ecbi-status" :class="{ 'ecbi-status-busy': busy || autoRunning }">
{{ statusText }}
</p>
<p v-if="syncResultText" class="ecbi-ok">{{ syncResultText }}</p>
<p v-if="errorText" class="ecbi-error">{{ errorText }}</p>
</div> </div>
</div> </div>
</template> </template>
@@ -130,6 +130,76 @@
opacity: 1; opacity: 1;
} }
.ecbi-header-shop {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
min-width: 0;
}
.ecbi-header-shop-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
opacity: 0.92;
}
.ecbi-shop-tag {
flex-shrink: 0;
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
line-height: 1;
}
.ecbi-shop-tag--ok {
background: #f6ffed;
color: #389e0d;
border: 1px solid #b7eb8f;
box-shadow: 0 0 0 1px rgb(255 255 255 / 0.35);
}
.ecbi-shop-tag--warn {
background: #fffbe6;
color: #ad6800;
border: 1px solid #ffe58f;
}
.ecbi-shop-tag--loading {
background: rgb(255 255 255 / 0.22);
color: #fff;
border: 1px solid rgb(255 255 255 / 0.4);
}
.ecbi-shop-tag--muted {
background: rgb(255 255 255 / 0.16);
color: rgb(255 255 255 / 0.9);
border: 1px solid rgb(255 255 255 / 0.28);
}
.ecbi-status-bar {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px 10px;
border-radius: var(--ecbi-radius);
background: var(--ecbi-fill);
border: 1px solid var(--ecbi-border-secondary);
}
.ecbi-status-bar .ecbi-status,
.ecbi-status-bar .ecbi-ok,
.ecbi-status-bar .ecbi-error {
margin: 0;
}
.ecbi-header-link { .ecbi-header-link {
border: 0; border: 0;
background: rgb(255 255 255 / 0.16); background: rgb(255 255 255 / 0.16);
@@ -1,5 +1,5 @@
/** /**
* 远程功能包入口(IIFE → dist-features/pdd-ad-fee.js)。 * 远程功能包入口(IIFE → artifacts/features/pdd-ad-fee.js)。
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。 * 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
*/ */
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters'; import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';

Some files were not shown because too many files have changed in this diff Show More