mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-23 23:09:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
---
|
||||
description: Ant Design Vue Spin 与可滚动 flex/grid 布局的配合方式,避免列表无法滚动
|
||||
globs: ecom-dmb-frontend/apps/web-antd/**/*.vue
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Spin 与侧栏/向导内滚动
|
||||
|
||||
- **不要用 `<Spin :spinning>` 整块包住「可滚动列表」所在的主内容区**。`Spin` 会渲染 `ant-spin-nested-loading` / `ant-spin-container`,内层常见 `overflow: hidden` 或高度链断裂,导致子元素虽有 `overflow-y: auto` 但**滚轮/触控滚不动**。
|
||||
- **推荐**:加载态拆细——例如字段定义用独立 `ref`(如 `fieldDefsLoading`),只在列表上方或占位区放小号 `Spin`/文案;提交操作用按钮 `:loading` + `message.loading`,避免大 Spin 套滚动容器。
|
||||
- **布局**:侧栏/向导内滚动依赖整条 flex 链上的 **`min-h-0` / `minmax(0,1fr)`**,列表容器用 **`flex-1 min-h-0 overflow-y-auto`**;需要时可加 **`overscroll-behavior-y: contain`**(如 Tailwind `overscroll-y-contain`)减少滚动链冒泡到外层页面。
|
||||
|
||||
参考实现:`ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order-import/components/ImportTaskWizard.vue`(订单导入向导)。
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
description: 每完成一个完整功能后给出一行 commit message
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 功能完成后的提交消息
|
||||
|
||||
每完成一个**完整、可独立提交**的功能(或一组相关改动收尾)后,主动给出**一行**中文 conventional commit message,供用户直接复制提交。
|
||||
|
||||
- 格式:`feat:` / `fix:` / `refactor:` / `sql:` 等前缀 + 简洁说明(侧重 why)
|
||||
- 不要主动执行 `git commit`,除非用户明确要求提交
|
||||
- 若同一会话连续完成多个独立功能,每个功能收尾时各给一行,不要攒到最后一起写
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
# 企业级开发规范
|
||||
|
||||
先想清楚再写代码。优先可维护、可扩展,不为「先跑通」牺牲结构。
|
||||
|
||||
## 动手前(必做)
|
||||
|
||||
用几句话写清:
|
||||
|
||||
1. **边界**:谁负责什么,谁不该知道什么
|
||||
2. **依赖方向**:只允许上层依赖下层,禁止反向与环依赖
|
||||
3. **扩展点**:哪里会变(第三方、策略、渠道),如何替换而不改调用方
|
||||
|
||||
没有包结构/模块边界草案,不直接堆实现。
|
||||
|
||||
## 分层原则
|
||||
|
||||
| 层 | 职责 | 禁止 |
|
||||
|----|------|------|
|
||||
| 接口 | API、DTO/VO、鉴权注解 | 业务规则、外部 SDK |
|
||||
| 应用/编排 | 用例流程、事务、锁、调度 | 细节协议解析、持久实现细节 |
|
||||
| 领域 | 规则、幂等、状态流转 | HTTP、框架配置、第三方 SDK |
|
||||
| 基础设施/防腐 | DB、缓存、消息、外部系统适配 | 业务用例编排 |
|
||||
|
||||
- **跨多个业务都会用的能力**(客户端、限流、鉴权出站、通用中间件)放在公共层,不挂在某一个业务子模块下。
|
||||
- **业务模块**只编排「何时调用、结果如何落本地状态」,不直接散落 SDK/协议细节。
|
||||
- 配置按消费者拆分:通用基础设施配置 ≠ 某一业务配置。
|
||||
|
||||
## 设计原则(精简)
|
||||
|
||||
- **单一职责**:一个类/包只做一类事。
|
||||
- **开闭**:新增能力优先扩展(接口/策略/钩子),少改既有主流程。
|
||||
- **依赖倒置**:业务依赖抽象,基础设施实现抽象。
|
||||
- **显式边界**:模块间通过清晰 API/事件交互,禁止随意穿透调用内部实现。
|
||||
- **模式按需**:Facade、Strategy、Factory、Adapter/防腐层等——用来表达边界,不堆砌。
|
||||
|
||||
## 注释(必有、宜短)
|
||||
|
||||
**默认要有注释**,但只说明用途与职责,不复述代码、不写长文。
|
||||
|
||||
| 该写 | 不写 |
|
||||
|------|------|
|
||||
| 类/接口:一句话说明职责与边界 | 翻译方法名 |
|
||||
| public 方法:做什么、关键入参/返回约定、副作用 | 逐步讲解实现细节 |
|
||||
| 非显而易见的业务规则、状态机、幂等、限流、游标 | 废话、历史吐槽、大段设计文档 |
|
||||
| 临时方案 / TODO:原因 + 回收条件 | 注释掉的大段废代码 |
|
||||
|
||||
- 类注释优先;复杂私有逻辑只在「为什么」处点一句。
|
||||
- 中文即可;控制在 **1~3 行**,宁可短,不要啰嗦。
|
||||
- 改代码时同步改注释;过时注释比没有更糟。
|
||||
|
||||
## 代码与变更
|
||||
|
||||
- 命名反映层级与意图(Client / Service / Facade / Listener),避免万能 `Util`、`Helper` 吞掉领域逻辑。
|
||||
- 改动保持最小且一致:跟随现有模块风格,但发现明显错位分层时应纠正,而不是继续复制。
|
||||
- 临时妥协必须标明:**债务是什么、为何、何时收回**。
|
||||
- 自检:去掉某个业务子模块后,公共能力是否仍可被其他业务复用?
|
||||
|
||||
## 不做
|
||||
|
||||
- 为通过编译把无关逻辑塞进方便的已有类。
|
||||
- 在业务包内复制一份「暂时够用」的公共出站/限流/客户端。
|
||||
- 无边界的大类、跨层直接依赖、隐式全局状态。
|
||||
- 大段无注释的公共类/用例入口;或又臭又长的注释小说。
|
||||
@@ -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`。
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"lsp": {
|
||||
"jdtls": {
|
||||
"command": [
|
||||
"/home/qinghua/.cursor-server/extensions/redhat.java-1.55.0/server/bin/jdtls"
|
||||
],
|
||||
"env": {
|
||||
"JAVA_HOME": "/home/qinghua/.cursor-server/extensions/redhat.java-1.55.0/jre/21.0.11-linux-x86_64"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
// MyBatis-Plus 方法引用会触发 Eclipse 空值分析误报;关闭后无需每类加 @SuppressWarnings("null")
|
||||
"java.compile.nullAnalysis.mode": "disabled",
|
||||
// pom 变更(如 Boot 升级)后自动刷新 classpath,避免 Eclipse「class file was not written / project inconsistent」
|
||||
"java.configuration.updateBuildConfiguration": "automatic",
|
||||
// Agent(唯一 Python 子项目)用本地 venv,避免 Pylance 解析不到 langchain 等依赖
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/apps/agent/.venv/bin/python",
|
||||
"python.analysis.extraPaths": ["${workspaceFolder}/apps/agent"]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
# AGENTS.md
|
||||
|
||||
电商 DMB / ECBI 系统。根目录**不是统一工作区**:各 app 各自构建、各自装依赖,根目录无 package.json。提交走 git(分支 `dev`),commit message 用中文 conventional 格式(`feat:`/`fix:`/`refactor:`/`sql:` 前缀)。
|
||||
|
||||
## 目录一览
|
||||
|
||||
```
|
||||
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)
|
||||
- 运行依赖环境变量:`DB_URL` / `DB_USERNAME` / `DB_PASSWORD` / `REDIS_HOST` / `REDIS_PASSWORD` / `JWT_SECRET`,见 README.md 与 `application-{profile}.yml`;MongoDB / RabbitMQ 连接见各 profile(与 MySQL 同机,账号 `qinghua`)
|
||||
- **拼多多 POP SDK 来自本地文件仓库 `libs/repo`(pom.xml 的 project-local repository,未入库)**:不要删除或清理;全新 clone 缺少它无法编译,需从别处恢复
|
||||
- 测试 `./mvnw test`,单个 `./mvnw test -Dtest=RoleAspectTest`
|
||||
- 架构设计文档在 `docs/`(订单统计读模型、权限控制、时间格式等),改动相关模块前先读
|
||||
- `.vscode/settings.json` 已关闭 Eclipse null analysis(MyBatis-Plus 方法引用误报),不要补 `@SuppressWarnings("null")`
|
||||
- 接口文档:启动后 http://localhost:8080/doc.html(knife4j)
|
||||
- Spring profile:dev / test / pre / prod;部署环境端口 8101 / 8102 / 8103(见 deploy/MANUAL-DEPLOY.md)
|
||||
|
||||
## 前端(apps/web)
|
||||
|
||||
- 只允许 pnpm;先 `pnpm install`(postinstall 会跑 `stub` 构建)
|
||||
- 开发 `pnpm dev`(等同原 `dev:antd`),构建 `pnpm build`;类型检查 `pnpm -F @vben/web-antd typecheck`
|
||||
- lefthook 钩子会对暂存文件跑 `pnpm lint`(oxfmt/oxlint 等)与 `check:type`,commitlint 强制 conventional commit,不要绕过
|
||||
- 代码内 `#/` 别名 = `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`)
|
||||
- 智能助手页:`views/agent/chat`;开发代理 `/api/agent` → `localhost:8200`(见 `vite.config.mts`)
|
||||
- 当前应用版本:`@vben/web-antd` **5.7.0**
|
||||
|
||||
## 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/` 已改名)
|
||||
- Server(NestJS + TypeORM,默认端口 3100):`cd server && pnpm start:dev`;建表 `server/sql/schema.sql`;Ed25519 密钥在 `server/keys/`
|
||||
- CLI:`cd tui && pnpm dev <command>`;设计见根目录 DESIGN.md
|
||||
|
||||
## 部署(deploy)
|
||||
|
||||
- TUI:`cd deploy && pnpm dev`,可选自动部署 / 仅编译 / 上传并重启
|
||||
- **`config.json` 含真实服务器地址与 SSH 私钥路径,切勿提交或打印**
|
||||
- 部署模式:运行时镜像 + 挂载 `app/` 目录;更新 = 上传产物 + 重启容器,无需重建镜像
|
||||
- 编译产物统一放 `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`
|
||||
|
||||
## 其他
|
||||
|
||||
- `apps/order-generator`:`npm start`(交互式),直接 `node main.js` 也可
|
||||
- `.opencode/opencode.json` 配置了 jdtls LSP,指向本机 cursor-server 扩展路径(机器相关,未入库)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.env
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
@@ -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 约定。
|
||||
@@ -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/`(工具装载 / 图预留)
|
||||
@@ -0,0 +1 @@
|
||||
"""编排层:工具装载与 LangGraph 扩展点(不写 Mongo)。"""
|
||||
@@ -0,0 +1 @@
|
||||
"""LangGraph 图定义预留。"""
|
||||
@@ -0,0 +1,56 @@
|
||||
"""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]:
|
||||
"""general:builtin + memory + 全部 MCP;发布场景:builtin + 目录/拼多多 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()]
|
||||
|
||||
if scene_value == SCENE_ECOM_GOODS_PUBLISH:
|
||||
mcp_tools = await load_mcp_tools(
|
||||
settings,
|
||||
company_id=actor.company_id,
|
||||
user_id=actor.user_id,
|
||||
)
|
||||
# 发布场景:目录 + 拼多多渠道;不挂经营 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
|
||||
|
||||
tools.extend(memory_tools(memory, actor))
|
||||
mcp_tools = await load_mcp_tools(
|
||||
settings, company_id=actor.company_id, user_id=actor.user_id
|
||||
)
|
||||
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 "")
|
||||
@@ -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)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Agent 工具面:本地 builtin / 记忆;MCP 传输在 infrastructure.mcp。"""
|
||||
|
||||
from agent.tools.builtin import builtin_tools
|
||||
|
||||
__all__ = ["builtin_tools"]
|
||||
@@ -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()}
|
||||
@@ -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 "处理中"
|
||||
@@ -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]
|
||||
@@ -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_")
|
||||
@@ -0,0 +1 @@
|
||||
"""HTTP 接口层:路由、DTO、依赖注入。"""
|
||||
@@ -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,
|
||||
),
|
||||
)
|
||||
@@ -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()
|
||||
@@ -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}
|
||||
|
||||
@@ -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})
|
||||
@@ -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})
|
||||
@@ -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))
|
||||
@@ -0,0 +1,216 @@
|
||||
"""对话用例:落库 + 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)
|
||||
|
||||
just_saved = None
|
||||
memory_count = 0
|
||||
if scene == "general":
|
||||
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
|
||||
@@ -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)
|
||||
@@ -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,或所选模型未启用;"
|
||||
"请在「模型管理」中配置提供商并启用模型"
|
||||
),
|
||||
)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,88 @@
|
||||
"""对话 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。"
|
||||
)
|
||||
|
||||
|
||||
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] + "…(截断)"
|
||||
return (
|
||||
f"{_PUBLISH_SYSTEM}\n\n【当前发布表单】\n{snap_text}"
|
||||
)
|
||||
|
||||
system = _BASE_SYSTEM
|
||||
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
|
||||
@@ -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()
|
||||
@@ -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"]
|
||||
Executable
+5
@@ -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}"
|
||||
@@ -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)
|
||||
@@ -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]: ...
|
||||
@@ -0,0 +1 @@
|
||||
"""基础设施:鉴权、LLM、MCP、持久化适配。"""
|
||||
@@ -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)),
|
||||
)
|
||||
@@ -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"
|
||||
@@ -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 ""
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"include": ["."],
|
||||
"exclude": [".venv", "**/__pycache__"],
|
||||
"venvPath": ".",
|
||||
"venv": ".venv",
|
||||
"pythonVersion": "3.12",
|
||||
"pythonPlatform": "Linux",
|
||||
"extraPaths": ["."]
|
||||
}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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())
|
||||
@@ -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
|
||||
@@ -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())
|
||||
@@ -0,0 +1,7 @@
|
||||
dist
|
||||
dist-features
|
||||
artifacts
|
||||
node_modules
|
||||
*.local
|
||||
.DS_Store
|
||||
temp
|
||||
@@ -0,0 +1 @@
|
||||
ignore-workspace=true
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 100
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
# ECBI 数据同步扩展
|
||||
|
||||
企业内部用 Chromium 扩展(Manifest V3):在电商后台页面由用户主动读取推广费用,经统一模型通过 **Open API** 同步到 BI。
|
||||
|
||||
第一阶段:**工程骨架 + Mock Adapter**,不解析真实平台 DOM。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Node.js >= 18
|
||||
- pnpm >= 9
|
||||
|
||||
## 安装依赖
|
||||
|
||||
```bash
|
||||
cd apps/browser-extension
|
||||
pnpm install
|
||||
```
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 构建
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
产物(统一在 `artifacts/`,已 gitignore):
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `artifacts/extension/` | 扩展壳(可解压加载到浏览器) |
|
||||
| `artifacts/features/` | 功能清单 `manifest.json` + 各功能 JS |
|
||||
| `artifacts/ecbi-data-sync-extension.zip` | 扩展壳压缩包(内含一层 `ecbi-data-sync-extension/` 目录) |
|
||||
|
||||
`pnpm build` 会同步到后端静态目录(本地联调 / 打进 jar):
|
||||
|
||||
| 本地产物 | 后端静态目录 |
|
||||
|----------|--------------|
|
||||
| `artifacts/features/*` | `static/extension-features/` |
|
||||
| `ecbi-data-sync-extension.zip` | `static/extension/` |
|
||||
|
||||
生产更新功能时:只拷贝 `artifacts/features/*` 到服务器 `extension-features/` 即可,扩展壳不必每次重装(壳内 API 未变时)。
|
||||
|
||||
## 安装到 Chrome / Edge
|
||||
|
||||
1. 打开 `chrome://extensions/` 或 `edge://extensions/`
|
||||
2. 开启「开发者模式」
|
||||
3. 「加载已解压的扩展程序」→ 选择 `artifacts/extension`,或后台「开放密钥」页下载 zip 后解压加载
|
||||
|
||||
## 项目架构
|
||||
|
||||
```text
|
||||
Popup(配置 API Key / 默认店铺 / 打开悬浮层)
|
||||
↓ chrome.tabs.sendMessage
|
||||
Content Script
|
||||
├─ 页内悬浮层(选日期、自动读取、同步)
|
||||
└─ Platform Adapter(当前 Mock)
|
||||
↓
|
||||
BI Open API
|
||||
```
|
||||
|
||||
| 环境 | 职责 |
|
||||
|------|------|
|
||||
| Popup | 配置、打开/开关页内悬浮层 |
|
||||
| Content 悬浮层 | 选日期(变更自动读取)、选店、预览、同步到 BI |
|
||||
| Background | 生命周期占位 |
|
||||
|
||||
新增平台:在 `src/platform/<name>/` 实现 `PlatformAdapter`,并注册到 `PlatformDetector`。
|
||||
|
||||
## 配置 BI Open API
|
||||
|
||||
Popup 右上角「配置」:
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| Base URL | 例 `http://localhost:8080/api`(**直连后端**,不要用前端 dev 的 `5666`;不要末尾 `/`) |
|
||||
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
|
||||
|
||||
Open API 请求由 **Background Service Worker 代发**(Content Script 在 HTTPS 拼多多页内不能直连 `http://localhost`,会被混合内容/CORS 拦截,Network 里常无 HTTP 状态码)。
|
||||
|
||||
Key 建议具备:
|
||||
|
||||
- `openapi:extension:feature:read`(功能清单/脚本)
|
||||
- `openapi:shop:pdd:read`
|
||||
- `openapi:product:adfee`
|
||||
|
||||
## 功能清单(静态 JSON)方案
|
||||
|
||||
清单与脚本放在同一静态目录,例如:
|
||||
|
||||
```text
|
||||
static/extension-features/
|
||||
manifest.json
|
||||
pdd-ad-fee.js
|
||||
```
|
||||
|
||||
- **直接读静态文件**:可以,部署简单;但无 API Key 鉴权(取决于网关是否暴露 `/static/**`)。
|
||||
- **推荐(已实现)**:Open API 读同一份 JSON/脚本并鉴权:
|
||||
- `GET /api/open/v1/extension/features`
|
||||
- `GET /api/open/v1/extension/features/{id}/script`
|
||||
|
||||
扩展 Popup 拉清单 → 打开功能时下载脚本并做 sha256 校验 → 当前 UI 仍由壳内嵌入模块挂载(MV3 限制远程 `eval`);远程包用于版本对齐与后续 main-world 执行。
|
||||
|
||||
## 与后端字段对照
|
||||
|
||||
| 插件 | 后端 batch-import |
|
||||
|------|-------------------|
|
||||
| `channelShopId` | `channelShopId`(`channel_pdd_shop.id`) |
|
||||
| `items[].feeDate` | `feeDate`(YYYY-MM-DD,来自页面每条数据) |
|
||||
| `items[].goodsId` | `goodsId` |
|
||||
| `items[].feeAmount` | `feeAmount`(元) |
|
||||
|
||||
相关接口:
|
||||
|
||||
- `GET /open/v1/extension/features`
|
||||
- `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/goods/adfee/batch-import`
|
||||
|
||||
鉴权头:`X-Api-Key: <key>`(或 `Authorization: Bearer <key>`)。
|
||||
|
||||
## 当前能力说明
|
||||
|
||||
- Popup:配置 Base URL / API Key,拉取远程功能清单并打开/关闭功能
|
||||
- **拼多多商品推广费**(`pdd-ad-fee`):页内悬浮读取/累计/同步(逻辑仍在壳内嵌入;远程 JS 同步发布)
|
||||
- 非推广页仍可用 Mock Adapter 联调链路
|
||||
|
||||
## 权限说明
|
||||
|
||||
Manifest 申请:`storage`、`activeTab`、`scripting`;Content Script 匹配 `http(s)://*/*` 以便开发期注入。接入真实平台后应收窄到具体域名。
|
||||
|
||||
## 设计文档
|
||||
|
||||
见同目录 [design.md](./design.md)。
|
||||
@@ -0,0 +1,765 @@
|
||||
可以。你这个项目适合让 Coding Agent **先只搭架构,不要急着实现具体平台的数据解析**。否则 Agent 很容易一上来就把 `content script / popup / background / API` 搞成一坨。
|
||||
|
||||
你可以直接把下面这段给它:
|
||||
|
||||
````text
|
||||
你现在负责创建一个浏览器扩展项目,项目名称暂定为 `ecbi-data-sync-extension`。
|
||||
|
||||
## 一、项目目标
|
||||
|
||||
这是一个用于企业内部使用的浏览器扩展,主要作用是:
|
||||
|
||||
用户登录电商平台后台后,在平台页面中选择指定日期,扩展读取当前页面中用户有权限看到的业务数据,并将数据转换成统一的数据模型,通过 HTTPS Open API 同步到我自己的 BI 系统。
|
||||
|
||||
第一阶段主要用于“推广费用/广告费用”同步。
|
||||
|
||||
目标浏览器:
|
||||
|
||||
- Google Chrome
|
||||
- Microsoft Edge
|
||||
|
||||
要求使用 Chromium Extension 兼容方案,基于 Manifest V3。
|
||||
|
||||
重要:
|
||||
|
||||
- 不需要发布 Chrome Web Store
|
||||
- 不需要实现自动登录
|
||||
- 不需要保存或上传平台 Cookie
|
||||
- 不需要实现后台自动爬取
|
||||
- 不需要实现定时抓取
|
||||
- 必须由用户主动点击“同步”
|
||||
- 第一阶段不要实现任何具体电商平台的解析逻辑
|
||||
- 当前任务重点是搭建一个可长期扩展的工程架构
|
||||
|
||||
---
|
||||
|
||||
# 二、技术栈
|
||||
|
||||
使用:
|
||||
|
||||
- Vue 3
|
||||
- TypeScript
|
||||
- Vite
|
||||
- Manifest V3
|
||||
- pnpm
|
||||
|
||||
UI:
|
||||
|
||||
- 优先使用 Tailwind CSS
|
||||
- 不使用 Element Plus
|
||||
- 不引入重量级 UI 框架
|
||||
|
||||
代码要求:
|
||||
|
||||
- TypeScript strict
|
||||
- ESLint
|
||||
- Prettier
|
||||
- 合理的类型定义
|
||||
- 模块化设计
|
||||
- 避免 any
|
||||
- 避免把业务逻辑全部写进 Vue 组件
|
||||
- 避免平台相关代码污染公共代码
|
||||
|
||||
---
|
||||
|
||||
# 三、先设计架构,再写代码
|
||||
|
||||
在开始创建文件之前,先分析并输出:
|
||||
|
||||
1. 项目整体架构
|
||||
2. Extension 各运行环境之间的职责
|
||||
3. Popup / Content Script / Background Service Worker 的通信方式
|
||||
4. 平台 Adapter 的设计
|
||||
5. BI API Client 的设计
|
||||
6. 数据模型设计
|
||||
7. Token / 配置存储方案
|
||||
8. Manifest 权限设计
|
||||
9. 后续增加多个电商平台时如何扩展
|
||||
|
||||
确认架构合理后再创建代码。
|
||||
|
||||
---
|
||||
|
||||
# 四、运行环境职责
|
||||
|
||||
严格区分以下三个环境:
|
||||
|
||||
## 1. Popup
|
||||
|
||||
负责:
|
||||
|
||||
- 显示当前平台
|
||||
- 显示当前页面状态
|
||||
- 获取用户配置
|
||||
- 获取 BI Open API Key / Base URL
|
||||
- 选择 BI 渠道店铺(channelShopId)
|
||||
- 显示待同步数据
|
||||
- 用户点击“同步”
|
||||
- 显示同步成功/失败
|
||||
- 显示错误信息
|
||||
|
||||
Popup 不负责直接解析平台 DOM。
|
||||
|
||||
---
|
||||
|
||||
## 2. Content Script
|
||||
|
||||
负责:
|
||||
|
||||
- 运行在目标电商平台页面
|
||||
- 读取当前页面已经展示给用户的数据
|
||||
- 获取当前页面 URL
|
||||
- 获取页面上下文信息
|
||||
- 调用对应平台 Adapter
|
||||
- 将平台数据转换为统一业务模型
|
||||
- 将解析结果返回给 Popup / Background
|
||||
|
||||
第一阶段只提供接口和 Mock Adapter,不实现真实平台解析。
|
||||
|
||||
---
|
||||
|
||||
## 3. Background Service Worker
|
||||
|
||||
负责:
|
||||
|
||||
- Extension 全局事件
|
||||
- Popup / Content Script 消息转发
|
||||
- Extension 生命周期相关逻辑
|
||||
- 后续需要跨页面或后台处理的能力
|
||||
|
||||
不要把所有业务逻辑都塞进 background。
|
||||
|
||||
---
|
||||
|
||||
# 五、平台适配器架构
|
||||
|
||||
这是本项目最重要的架构之一。
|
||||
|
||||
必须设计成:
|
||||
|
||||
```text
|
||||
platform/
|
||||
├── core/
|
||||
│ ├── PlatformAdapter.ts
|
||||
│ ├── PlatformDetector.ts
|
||||
│ └── types.ts
|
||||
│
|
||||
├── mock/
|
||||
│ └── MockPlatformAdapter.ts
|
||||
│
|
||||
├── taobao/
|
||||
│ └── ...
|
||||
│
|
||||
├── jd/
|
||||
│ └── ...
|
||||
│
|
||||
└── pdd/
|
||||
└── ...
|
||||
````
|
||||
|
||||
暂时不要实现淘宝、京东、拼多多等真实平台。
|
||||
|
||||
定义统一接口,例如:
|
||||
|
||||
```ts
|
||||
interface PlatformAdapter {
|
||||
platform: PlatformType;
|
||||
|
||||
canHandle(url: string): boolean;
|
||||
|
||||
getPageContext(): Promise<PageContext>;
|
||||
|
||||
parseAdvertisingCost(): Promise<AdvertisingCostBatch>;
|
||||
}
|
||||
```
|
||||
|
||||
具体接口名称可以根据实际架构调整,但必须保持职责清晰。
|
||||
|
||||
---
|
||||
|
||||
# 六、统一业务数据模型
|
||||
|
||||
不要让 BI 后端直接接收某个平台的原始 DOM 数据。
|
||||
|
||||
定义**插件侧统一模型**,再由 API Client **映射**为后端 Open API 入参。
|
||||
|
||||
## 6.1 插件侧统一模型(平台无关)
|
||||
|
||||
```ts
|
||||
/** 单条商品广告费(插件内统一模型) */
|
||||
interface AdvertisingCostItem {
|
||||
/** 统计日期 YYYY-MM-DD(每条各自一份,来自页面数据) */
|
||||
feeDate: string;
|
||||
/** 平台商品 ID,如拼多多 goods_id */
|
||||
goodsId: string;
|
||||
/** 广告费金额(元) */
|
||||
feeAmount: number;
|
||||
/** 可选扩展,不同平台可塞入 metadata,不直接提交后端 */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次读取/同步的批次(插件内)
|
||||
* channelShopId:BI 侧渠道店铺主键;拼多多 = channel_pdd_shop.id(不是 mallId)
|
||||
* 日期在 items[].feeDate,由 Adapter 从页面解析,不用用户手选
|
||||
*/
|
||||
interface AdvertisingCostBatch {
|
||||
platform: 'pdd' | 'taobao' | 'jd' | 'mock';
|
||||
channelShopId: number;
|
||||
items: AdvertisingCostItem[];
|
||||
source: 'browser-extension';
|
||||
importedAt: string; // ISO 时间,仅插件侧审计用,不必提交后端
|
||||
}
|
||||
```
|
||||
|
||||
## 6.2 与现有 BI Open API 对齐(第一阶段:拼多多商品广告费)
|
||||
|
||||
后端已实现(路径均带 `/api` 前缀):
|
||||
|
||||
| 能力 | Method / Path | Scope |
|
||||
|------|---------------|--------|
|
||||
| 渠道店铺列表 | `POST /api/open/v1/channel/pdd/shop/list` | `open:scope:pdd_shop:read` |
|
||||
| 商品广告费批量导入 | `POST /api/open/v1/channel/pdd/goods/adfee/batch-import` | `open:scope:pdd_goods_ad_fee:import` |
|
||||
|
||||
### 店铺列表(取 channelShopId)
|
||||
|
||||
请求体与内部接口一致,分页查询:
|
||||
|
||||
```ts
|
||||
// POST /api/open/v1/channel/pdd/shop/list
|
||||
interface PageQuery<TFilters> {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
filters?: TFilters; // 可选:mallName 等
|
||||
}
|
||||
|
||||
// 响应 records[].id 即为 channelShopId(channel_pdd_shop.id)
|
||||
interface PddChannelShop {
|
||||
id: number; // → AdvertisingCostBatch.channelShopId
|
||||
mallId?: number; // 拼多多 mall_id,仅展示/核对,不要当 BI 店铺主键提交
|
||||
mallName?: string;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 批量导入广告费(提交形态)
|
||||
|
||||
后端入参**仅接受**以下字段,插件必须映射到此结构(不要把 platform / source / importedAt 塞进 body):
|
||||
|
||||
```ts
|
||||
// POST /api/open/v1/channel/pdd/goods/adfee/batch-import
|
||||
interface BatchImportPddGoodsAdFeeRequest {
|
||||
items: Array<{
|
||||
channelShopId: number; // channel_pdd_shop.id
|
||||
feeDate: string; // YYYY-MM-DD
|
||||
goodsId: string; // 拼多多 goods_id
|
||||
feeAmount: number; // 元,>= 0
|
||||
}>;
|
||||
}
|
||||
```
|
||||
|
||||
映射规则:
|
||||
|
||||
```text
|
||||
AdvertisingCostBatch
|
||||
→ items[] = batch.items.map(i => ({
|
||||
channelShopId: batch.channelShopId,
|
||||
feeDate: i.feeDate, // 每条各自日期
|
||||
goodsId: i.goodsId,
|
||||
feeAmount: i.feeAmount,
|
||||
}))
|
||||
```
|
||||
|
||||
后端行为:校验店铺归属 + 该店下存在该 `goods_id`;按 `(channelShopId, goodsId, feeDate)` **upsert**(同日覆盖金额)。
|
||||
|
||||
必须保证:
|
||||
|
||||
平台原始数据 → Platform Adapter → 统一模型 →(映射)→ BI Open API
|
||||
|
||||
而不是:平台 A → 一套 API、平台 B → 另一套 API(多平台仍走统一模型,仅 API Client 按平台选择 endpoint)。
|
||||
|
||||
---
|
||||
|
||||
# 七、BI API Client
|
||||
|
||||
创建独立 API 层,例如:
|
||||
|
||||
```text
|
||||
src/api/
|
||||
├── client.ts # Base URL、Header、超时、错误归一
|
||||
├── open/
|
||||
│ ├── pddShop.ts # POST .../channel/pdd/shop/list
|
||||
│ └── pddGoodsAdFee.ts # POST .../channel/pdd/goods/adfee/batch-import
|
||||
└── types.ts
|
||||
```
|
||||
|
||||
统一处理:
|
||||
|
||||
* Base URL(如 `https://xxx/api` 或含网关前缀,以实际部署为准)
|
||||
* 鉴权 Header(Open API Key,**不是** 系统登录 JWT)
|
||||
* 请求超时
|
||||
* HTTP 错误 / 业务错误(`ApiResponse.code`)/ 网络错误
|
||||
|
||||
鉴权头(二选一,与后端 `ApiKeyAuthenticationFilter` 一致):
|
||||
|
||||
```http
|
||||
X-Api-Key: sk_live_xxxxxxxx
|
||||
```
|
||||
|
||||
或:
|
||||
|
||||
```http
|
||||
Authorization: Bearer sk_live_xxxxxxxx
|
||||
```
|
||||
|
||||
注意:后端会拒绝以 `eyJ` 开头的 JWT 当作 Key。扩展配置里只存 **Open API Key**。
|
||||
|
||||
不要在 Vue 组件中直接到处写 fetch。
|
||||
|
||||
BI API Base URL 与 API Key 必须通过 Extension Storage 配置。
|
||||
|
||||
---
|
||||
|
||||
# 八、配置与 API Key
|
||||
|
||||
使用:
|
||||
|
||||
```ts
|
||||
chrome.storage.local
|
||||
```
|
||||
|
||||
保存:
|
||||
|
||||
```text
|
||||
BI Open API Base URL (例:https://host/api)
|
||||
BI Open API Key (创建 Key 时返回的明文,仅本地保存)
|
||||
默认 channelShopId (可选,用户从店铺列表选过一次后记住)
|
||||
```
|
||||
|
||||
设计独立配置模块:
|
||||
|
||||
```text
|
||||
src/storage/
|
||||
├── settings.ts
|
||||
└── types.ts
|
||||
```
|
||||
|
||||
不要直接在业务代码中到处:
|
||||
|
||||
```ts
|
||||
chrome.storage.local.get(...)
|
||||
```
|
||||
|
||||
统一封装。
|
||||
|
||||
注意:
|
||||
|
||||
* 不保存电商平台 Cookie
|
||||
* 不向 BI 服务上传平台 Cookie
|
||||
* 不实现获取平台 Token 的逻辑
|
||||
* **只保存用户自己的 BI Open API Key**(需具备 `open:scope:pdd_shop:read` 与 `open:scope:pdd_goods_ad_fee:import`)
|
||||
* 不使用系统后台登录 JWT 调 `/api/open/**`
|
||||
|
||||
---
|
||||
|
||||
# 九、权限设计
|
||||
|
||||
Manifest V3 遵循最小权限原则。
|
||||
|
||||
只申请实际需要的权限。
|
||||
|
||||
第一阶段优先考虑:
|
||||
|
||||
```text
|
||||
storage
|
||||
activeTab
|
||||
scripting
|
||||
```
|
||||
|
||||
不要为了方便直接申请:
|
||||
|
||||
```text
|
||||
<all_urls>
|
||||
```
|
||||
|
||||
如果后续确实需要指定平台域名,再针对具体平台增加 host_permissions。
|
||||
|
||||
Manifest 中不要提前加入一堆没有实际用途的权限。
|
||||
|
||||
---
|
||||
|
||||
# 十、Popup UI
|
||||
|
||||
先做一个简洁的内部工具 UI。
|
||||
|
||||
页面结构:
|
||||
|
||||
```text
|
||||
┌──────────────────────────────┐
|
||||
│ BI 数据同步 │
|
||||
├──────────────────────────────┤
|
||||
│ 当前平台 │
|
||||
│ 淘宝 / 京东 / 未识别 │
|
||||
│ │
|
||||
│ 当前页面 │
|
||||
│ xxx │
|
||||
│ │
|
||||
│ 同步日期 │
|
||||
│ 2026-08-15 │
|
||||
│ │
|
||||
│ BI 渠道店铺 │
|
||||
│ [下拉:从 open shop/list 选] │
|
||||
│ channelShopId: 12 │
|
||||
│ │
|
||||
│ 数据状态 │
|
||||
│ 等待读取 │
|
||||
│ │
|
||||
│ [读取数据] │
|
||||
│ │
|
||||
│ 数据预览 │
|
||||
│ ─────────────────────────── │
|
||||
│ 推广费用:¥0 │
|
||||
│ 数据条数:0 │
|
||||
│ │
|
||||
│ [同步到 BI] │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
第一阶段使用 Mock 数据。
|
||||
|
||||
例如点击:
|
||||
|
||||
```text
|
||||
读取数据
|
||||
```
|
||||
|
||||
显示:
|
||||
|
||||
```text
|
||||
平台:Mock
|
||||
BI 渠道店铺:测试店铺(channelShopId=1)
|
||||
日期:2026-08-15
|
||||
推广费用:¥1234.56
|
||||
数据条数:10
|
||||
```
|
||||
|
||||
然后:
|
||||
|
||||
```text
|
||||
同步到 BI
|
||||
```
|
||||
|
||||
调用 Open API:`POST .../channel/pdd/goods/adfee/batch-import`(开发环境可用 Mock Client 或真实 Key)。
|
||||
|
||||
日期约定:**每条推广数据自带 `feeDate`**(由 Adapter 从页面解析);悬浮层 / Popup **不提供手选同步日期**。
|
||||
|
||||
---
|
||||
|
||||
# 十一、消息通信
|
||||
|
||||
设计统一消息协议。
|
||||
|
||||
例如:
|
||||
|
||||
```ts
|
||||
type ExtensionMessage =
|
||||
| {
|
||||
type: 'GET_PAGE_CONTEXT';
|
||||
}
|
||||
| {
|
||||
type: 'PARSE_ADVERTISING_COST';
|
||||
}
|
||||
| {
|
||||
type: 'SYNC_ADVERTISING_COST';
|
||||
payload: AdvertisingCostBatch;
|
||||
};
|
||||
```
|
||||
|
||||
不要直接在各处使用字符串:
|
||||
|
||||
```ts
|
||||
chrome.runtime.sendMessage({
|
||||
type: 'xxx'
|
||||
});
|
||||
```
|
||||
|
||||
应该统一定义消息类型,保证 TypeScript 类型安全。
|
||||
|
||||
---
|
||||
|
||||
# 十二、错误处理
|
||||
|
||||
统一错误模型。
|
||||
|
||||
至少区分:
|
||||
|
||||
```text
|
||||
PLATFORM_NOT_SUPPORTED
|
||||
PAGE_NOT_READY
|
||||
DATA_PARSE_FAILED
|
||||
INVALID_DATA
|
||||
AUTH_FAILED
|
||||
API_REQUEST_FAILED
|
||||
API_BUSINESS_ERROR
|
||||
NETWORK_ERROR
|
||||
CONFIG_MISSING
|
||||
```
|
||||
|
||||
UI 给用户显示友好的错误。
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
当前页面不是支持的推广费用页面
|
||||
|
||||
请先进入平台推广费用页面,然后重新点击“读取数据”。
|
||||
```
|
||||
|
||||
不要直接把底层异常堆栈展示给用户。
|
||||
|
||||
---
|
||||
|
||||
# 十三、目录结构
|
||||
|
||||
最终建议类似:
|
||||
|
||||
```text
|
||||
bi-data-sync-extension/
|
||||
│
|
||||
├── src/
|
||||
│ ├── api/
|
||||
│ │ ├── client.ts
|
||||
│ │ ├── open/
|
||||
│ │ │ ├── pddShop.ts
|
||||
│ │ │ └── pddGoodsAdFee.ts
|
||||
│ │ └── types.ts
|
||||
│ │
|
||||
│ ├── background/
|
||||
│ │ └── index.ts
|
||||
│ │
|
||||
│ ├── content/
|
||||
│ │ └── index.ts
|
||||
│ │
|
||||
│ ├── popup/
|
||||
│ │ ├── App.vue
|
||||
│ │ ├── main.ts
|
||||
│ │ └── components/
|
||||
│ │
|
||||
│ ├── platform/
|
||||
│ │ ├── core/
|
||||
│ │ │ ├── types.ts
|
||||
│ │ │ ├── PlatformAdapter.ts
|
||||
│ │ │ └── PlatformDetector.ts
|
||||
│ │ │
|
||||
│ │ └── mock/
|
||||
│ │ └── MockPlatformAdapter.ts
|
||||
│ │
|
||||
│ ├── storage/
|
||||
│ │ ├── settings.ts
|
||||
│ │ └── types.ts
|
||||
│ │
|
||||
│ ├── shared/
|
||||
│ │ ├── messages.ts
|
||||
│ │ ├── constants.ts
|
||||
│ │ └── errors.ts
|
||||
│ │
|
||||
│ └── types/
|
||||
│ └── advertisingCost.ts
|
||||
│
|
||||
├── public/
|
||||
│ └── icons/
|
||||
│
|
||||
├── manifest.config.ts
|
||||
├── vite.config.ts
|
||||
├── tsconfig.json
|
||||
├── package.json
|
||||
├── .eslintrc...
|
||||
├── .prettierrc...
|
||||
└── README.md
|
||||
```
|
||||
|
||||
可以根据 Vite/Extension 构建方式调整目录,但必须保持职责分离。
|
||||
|
||||
---
|
||||
|
||||
# 十四、构建要求
|
||||
|
||||
需要支持:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
|
||||
pnpm dev
|
||||
|
||||
pnpm build
|
||||
```
|
||||
|
||||
构建后生成:
|
||||
|
||||
```text
|
||||
dist/
|
||||
```
|
||||
|
||||
能够直接通过:
|
||||
|
||||
Chrome:
|
||||
chrome://extensions/
|
||||
|
||||
Edge:
|
||||
edge://extensions/
|
||||
|
||||
开启开发者模式后加载 `dist` 目录运行。
|
||||
|
||||
README 必须写清楚:
|
||||
|
||||
1. 环境要求
|
||||
2. 安装依赖
|
||||
3. 开发
|
||||
4. 构建
|
||||
5. Chrome 安装方式
|
||||
6. Edge 安装方式
|
||||
7. 项目架构
|
||||
8. 如何增加一个新的平台 Adapter
|
||||
9. 如何配置 BI Open API(Base URL + API Key + 所需 scope)
|
||||
10. 当前 Mock 数据说明
|
||||
11. 与后端 open 接口字段对照(channelShopId / feeDate / goodsId / feeAmount)
|
||||
|
||||
---
|
||||
|
||||
# 十五、测试
|
||||
|
||||
至少建立基础测试结构。
|
||||
|
||||
重点测试:
|
||||
|
||||
* PlatformDetector
|
||||
* MockPlatformAdapter
|
||||
* AdvertisingCost 数据转换
|
||||
* API Client 错误处理
|
||||
* Storage 配置读写
|
||||
|
||||
不需要为了测试而过度设计。
|
||||
|
||||
---
|
||||
|
||||
# 十六、重要约束
|
||||
|
||||
不要做以下事情:
|
||||
|
||||
1. 不要实现任何平台爬虫
|
||||
2. 不要逆向任何平台接口
|
||||
3. 不要读取平台 Cookie
|
||||
4. 不要上传平台 Cookie
|
||||
5. 不要自动登录
|
||||
6. 不要后台定时抓取
|
||||
7. 不要自动模拟用户点击
|
||||
8. 不要申请不必要的 Chrome 权限
|
||||
9. 不要使用 `<all_urls>` 作为偷懒方案
|
||||
10. 不要把平台逻辑写死在 Popup
|
||||
11. 不要把 API 请求散落在 Vue 组件
|
||||
12. 不要引入 Element Plus
|
||||
|
||||
第一阶段只需要:
|
||||
|
||||
“插件工程 + Manifest V3 + Vue + TypeScript + Popup + Content Script + Background + Storage + API Client + Platform Adapter + Mock 数据”。
|
||||
|
||||
---
|
||||
|
||||
# 十七、开发原则
|
||||
|
||||
遵循:
|
||||
|
||||
* KISS
|
||||
* SOLID
|
||||
* 单一职责
|
||||
* 依赖倒置
|
||||
* 类型安全
|
||||
* 最小权限
|
||||
* 平台适配器隔离
|
||||
* 基础设施与业务逻辑分离
|
||||
|
||||
不要为了“以后可能用到”创建大量抽象。
|
||||
|
||||
如果一个抽象目前没有真实需求,优先保持简单。
|
||||
|
||||
---
|
||||
|
||||
# 十八、执行方式
|
||||
|
||||
不要一次性生成大量复杂代码。
|
||||
|
||||
按照以下步骤执行:
|
||||
|
||||
Step 1:
|
||||
分析架构并说明关键设计。
|
||||
|
||||
Step 2:
|
||||
创建项目基础结构和 Vite + Vue + TypeScript + Manifest V3。
|
||||
|
||||
Step 3:
|
||||
实现 Popup / Content Script / Background 的最小通信链路。
|
||||
|
||||
Step 4:
|
||||
实现 Storage。
|
||||
|
||||
Step 5:
|
||||
实现 Platform Adapter 和 Mock Adapter。
|
||||
|
||||
Step 6:
|
||||
实现 BI API Client。
|
||||
|
||||
Step 7:
|
||||
实现 Mock 数据同步流程。
|
||||
|
||||
Step 8:
|
||||
完善 UI。
|
||||
|
||||
Step 9:
|
||||
添加测试。
|
||||
|
||||
Step 10:
|
||||
完善 README。
|
||||
|
||||
每完成一个阶段,先检查 TypeScript、ESLint、Build 是否通过,再进入下一阶段。
|
||||
|
||||
如果发现架构问题,先修正架构,不要通过增加临时代码绕过去。
|
||||
|
||||
最终要求:
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
必须成功,并且 `dist` 可以直接加载到 Chrome 和 Edge 中运行。
|
||||
|
||||
````
|
||||
|
||||
### 我建议你再给 Agent 加一句
|
||||
|
||||
如果你用的是 **Cursor / Claude Code / Codex / OpenCode** 这类 Coding Agent,我建议第一轮**不要让它直接开发真实平台**。
|
||||
|
||||
先让它把:
|
||||
|
||||
```text
|
||||
Vue
|
||||
↓
|
||||
Popup
|
||||
↓
|
||||
Content Script
|
||||
↓
|
||||
Mock Adapter
|
||||
↓
|
||||
统一 AdvertisingCostBatch
|
||||
↓
|
||||
映射为 batch-import items
|
||||
↓
|
||||
BI Open API(API Key)
|
||||
````
|
||||
|
||||
注意:提交字段必须是 `channelShopId + feeDate + goodsId + feeAmount`;鉴权用 Open API Key,不要用登录 JWT。
|
||||
|
||||
然后第二轮你再告诉它:
|
||||
|
||||
> “现在接入 XX 平台,只允许读取用户当前页面已经展示的数据,实现 XX 平台 Adapter,先分析页面结构,不要修改公共架构。”
|
||||
|
||||
这样会稳很多。
|
||||
@@ -0,0 +1,35 @@
|
||||
import { defineManifest } from '@crxjs/vite-plugin';
|
||||
|
||||
import packageJson from './package.json';
|
||||
|
||||
const { version } = packageJson;
|
||||
|
||||
export default defineManifest({
|
||||
manifest_version: 3,
|
||||
name: 'ECBI 数据同步',
|
||||
description: '从电商平台后台读取推广费用并同步到 BI(企业内用)',
|
||||
version,
|
||||
action: {
|
||||
default_popup: 'src/popup/index.html',
|
||||
default_title: 'ECBI 数据同步',
|
||||
},
|
||||
background: {
|
||||
service_worker: 'src/background/index.ts',
|
||||
type: 'module',
|
||||
},
|
||||
content_scripts: [
|
||||
{
|
||||
matches: ['http://*/*', 'https://*/*'],
|
||||
js: ['src/content/index.ts'],
|
||||
run_at: 'document_idle',
|
||||
},
|
||||
],
|
||||
permissions: ['storage', 'activeTab', 'scripting'],
|
||||
// 开发期便于任意页注入 Content Script;正式接平台后改为具体域名
|
||||
host_permissions: ['http://*/*', 'https://*/*'],
|
||||
icons: {
|
||||
'16': 'public/icons/icon-16.png',
|
||||
'64': 'public/icons/icon-64.png',
|
||||
'128': 'public/icons/icon-128.png',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "ecbi-data-sync-extension",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "企业内部 BI 数据同步浏览器扩展(Manifest V3)",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build && pnpm build:features",
|
||||
"build:features": "node scripts/build-features.mjs",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint . --ext .ts,.vue",
|
||||
"format": "prettier --write \"src/**/*.{ts,vue,css,json}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crxjs/vite-plugin": "^2.7.1",
|
||||
"@types/chrome": "^0.0.287",
|
||||
"@types/node": "^22.10.2",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vue/eslint-config-prettier": "^10.1.0",
|
||||
"@vue/eslint-config-typescript": "^14.1.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.17.0",
|
||||
"eslint-plugin-vue": "^9.32.0",
|
||||
"linkedom": "^0.18.13",
|
||||
"postcss": "^8.4.49",
|
||||
"prettier": "^3.4.2",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^5.4.11",
|
||||
"vue-tsc": "^2.1.10"
|
||||
},
|
||||
"packageManager": "pnpm@9.15.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
Generated
+2961
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { OPEN_API_PATHS } from '@/shared/constants';
|
||||
import type { ExtensionFeatureItem, ExtensionFeatureManifest } from '@/features/runtime/types';
|
||||
|
||||
export interface FeatureScriptPayload {
|
||||
featureId: string;
|
||||
version?: string;
|
||||
sha256?: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export async function fetchFeatureManifest(): Promise<ExtensionFeatureManifest> {
|
||||
return openApiRequest<ExtensionFeatureManifest>(OPEN_API_PATHS.extensionFeatureList, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchFeatureScript(featureId: string): Promise<FeatureScriptPayload> {
|
||||
return openApiRequest<FeatureScriptPayload>(
|
||||
`${OPEN_API_PATHS.extensionFeatureScript}/${encodeURIComponent(featureId)}/script`,
|
||||
{ method: 'GET' },
|
||||
);
|
||||
}
|
||||
|
||||
/** 下载远程脚本并可选校验 sha256(与静态 manifest 一致) */
|
||||
export async function downloadAndVerifyFeature(
|
||||
item: ExtensionFeatureItem,
|
||||
): Promise<{ code: string; verified: boolean; remoteVersion?: string }> {
|
||||
const payload = await fetchFeatureScript(item.id);
|
||||
const expected = (item.sha256 || payload.sha256 || '').toLowerCase();
|
||||
if (expected) {
|
||||
const hash = await sha256Hex(payload.content);
|
||||
if (hash !== expected) {
|
||||
throw new Error(`功能脚本校验失败:${item.id}(sha256 不匹配)`);
|
||||
}
|
||||
return { code: payload.content, verified: true, remoteVersion: payload.version };
|
||||
}
|
||||
return { code: payload.content, verified: false, remoteVersion: payload.version };
|
||||
}
|
||||
|
||||
async function sha256Hex(text: string): Promise<string> {
|
||||
const data = new TextEncoder().encode(text);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
|
||||
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { OPEN_API_PATHS } from '@/shared/constants';
|
||||
|
||||
export interface BatchImportPddGoodsAdFeeItem {
|
||||
channelShopId: number;
|
||||
feeDate: string;
|
||||
goodsId: string;
|
||||
feeAmount: number;
|
||||
}
|
||||
|
||||
export interface BatchImportPddGoodsAdFeeRequest {
|
||||
items: BatchImportPddGoodsAdFeeItem[];
|
||||
}
|
||||
|
||||
/** 导入任务摘要(创建立即返回 pending,需轮询至终态) */
|
||||
export interface PddGoodsAdFeeImportTask {
|
||||
id: number;
|
||||
companyId?: number;
|
||||
channelShopId: number;
|
||||
status: 'pending' | 'processing' | 'success' | 'partial' | 'failed' | string;
|
||||
totalCount: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
authExpired?: number;
|
||||
message?: string | null;
|
||||
startedAt?: string | null;
|
||||
finishedAt?: string | null;
|
||||
createTime?: string;
|
||||
}
|
||||
|
||||
const TERMINAL_STATUS = new Set(['success', 'partial', 'failed']);
|
||||
const POLL_INTERVAL_MS = 2500;
|
||||
const POLL_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
|
||||
/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item;金额须大于 0) */
|
||||
export function toBatchImportRequest(
|
||||
batch: AdvertisingCostBatch,
|
||||
): BatchImportPddGoodsAdFeeRequest {
|
||||
return {
|
||||
items: batch.items
|
||||
.filter((item) => Number(item.feeAmount) > 0)
|
||||
.map((item) => ({
|
||||
channelShopId: batch.channelShopId,
|
||||
feeDate: item.feeDate,
|
||||
goodsId: item.goodsId,
|
||||
feeAmount: item.feeAmount,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPddGoodsAdFeeImportTask(
|
||||
taskId: number,
|
||||
): Promise<PddGoodsAdFeeImportTask> {
|
||||
return openApiRequest<PddGoodsAdFeeImportTask>(
|
||||
`${OPEN_API_PATHS.pddGoodsAdFeeImportTask}/${taskId}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function waitForPddGoodsAdFeeImportTask(
|
||||
taskId: number,
|
||||
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
|
||||
): Promise<PddGoodsAdFeeImportTask> {
|
||||
const deadline = Date.now() + POLL_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
const task = await getPddGoodsAdFeeImportTask(taskId);
|
||||
onProgress?.(task);
|
||||
if (TERMINAL_STATUS.has(task.status)) {
|
||||
return task;
|
||||
}
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
throw new Error('导入超时,请稍后在后台查看任务进度');
|
||||
}
|
||||
|
||||
/** 提交导入任务并等到处理结束 */
|
||||
export async function batchImportPddGoodsAdFee(
|
||||
batch: AdvertisingCostBatch,
|
||||
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
|
||||
): Promise<PddGoodsAdFeeImportTask> {
|
||||
const body = toBatchImportRequest(batch);
|
||||
if (!body.items.length) {
|
||||
throw new Error('没有可传入的记录(推广费须大于 0)');
|
||||
}
|
||||
const created = await openApiRequest<PddGoodsAdFeeImportTask>(
|
||||
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
onProgress?.(created);
|
||||
return waitForPddGoodsAdFeeImportTask(created.id, onProgress);
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { OPEN_API_PATHS } from '@/shared/constants';
|
||||
|
||||
export interface PageQueryDTO<TFilters> {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
filters?: TFilters;
|
||||
}
|
||||
|
||||
export interface PageResultVO<T> {
|
||||
records: T[];
|
||||
total: number;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface PddChannelShop {
|
||||
id: number;
|
||||
mallId?: number;
|
||||
mallName?: string;
|
||||
logo?: string;
|
||||
}
|
||||
|
||||
export interface PddShopFilters {
|
||||
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(
|
||||
query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 },
|
||||
): Promise<PageResultVO<PddChannelShop>> {
|
||||
return openApiRequest<PageResultVO<PddChannelShop>>(OPEN_API_PATHS.pddShopList, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(query),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { getSettings } from '@/storage/settings';
|
||||
|
||||
export interface ApiResponseBody<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/** 在扩展上下文(Background / Popup)内直连 Open API */
|
||||
export async function executeOpenApiFetch<T>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const settings = await getSettings();
|
||||
if (!settings.apiBaseUrl) {
|
||||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
|
||||
}
|
||||
if (!settings.apiKey) {
|
||||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
|
||||
}
|
||||
|
||||
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set('Content-Type', 'application/json');
|
||||
headers.set('X-Api-Key', settings.apiKey);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
} catch {
|
||||
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
|
||||
}
|
||||
|
||||
let body: ApiResponseBody<T>;
|
||||
try {
|
||||
body = (await response.json()) as ApiResponseBody<T>;
|
||||
} catch {
|
||||
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ExtensionError(
|
||||
'API_REQUEST_FAILED',
|
||||
body.message || `请求失败(HTTP ${response.status})`,
|
||||
);
|
||||
}
|
||||
|
||||
if (body.code !== 0 && body.code !== 200) {
|
||||
throw new ExtensionError(
|
||||
'API_BUSINESS_ERROR',
|
||||
body.message || `业务错误(code=${body.code})`,
|
||||
);
|
||||
}
|
||||
|
||||
return body.data;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type {
|
||||
BatchImportPddGoodsAdFeeItem,
|
||||
BatchImportPddGoodsAdFeeRequest,
|
||||
PddGoodsAdFeeImportTask,
|
||||
} from './open/pddGoodsAdFee';
|
||||
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
|
||||
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
|
||||
* Open API 亦在此代发,避免 HTTPS 页面直连 HTTP 本地服务被混合内容拦截。
|
||||
*/
|
||||
|
||||
import { executeOpenApiFetch } from '@/api/openApiFetch';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
|
||||
type InjectMessage = {
|
||||
type: 'INJECT_MAIN_SCRIPT';
|
||||
payload: { code: string };
|
||||
};
|
||||
|
||||
type CallMessage = {
|
||||
type: 'CALL_MAIN_FEATURE';
|
||||
payload: { featureId: string; action: 'mount' | 'unmount' };
|
||||
};
|
||||
|
||||
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(() => {
|
||||
console.info('[ecbi-extension] installed');
|
||||
});
|
||||
|
||||
chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse) => {
|
||||
if (message?.type === 'BACKGROUND_PING') {
|
||||
sendResponse({ ok: true, data: { pong: 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;
|
||||
if (tabId == null) {
|
||||
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message?.type === 'INJECT_MAIN_SCRIPT') {
|
||||
void chrome.scripting
|
||||
.executeScript({
|
||||
target: { tabId },
|
||||
world: 'MAIN',
|
||||
func: (source: string) => {
|
||||
// 扩展注入的 MAIN world 函数内执行,不受页面 CSP 限制
|
||||
const run = new Function(source);
|
||||
run();
|
||||
},
|
||||
args: [message.payload.code],
|
||||
})
|
||||
.then(() => sendResponse({ ok: true }))
|
||||
.catch((error: unknown) => {
|
||||
sendResponse({
|
||||
ok: false,
|
||||
message: error instanceof Error ? error.message : '注入脚本失败',
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message?.type === 'CALL_MAIN_FEATURE') {
|
||||
const { featureId, action } = message.payload;
|
||||
void chrome.scripting
|
||||
.executeScript({
|
||||
target: { tabId },
|
||||
world: 'MAIN',
|
||||
func: async (id: string, act: 'mount' | 'unmount') => {
|
||||
const bag = (
|
||||
globalThis as typeof globalThis & {
|
||||
__ECBI_FEATURES__?: Record<
|
||||
string,
|
||||
{
|
||||
mount?: () => void | Promise<void>;
|
||||
unmount?: () => void | Promise<void>;
|
||||
}
|
||||
>;
|
||||
}
|
||||
).__ECBI_FEATURES__;
|
||||
const mod = bag?.[id];
|
||||
if (!mod) {
|
||||
throw new Error(`功能未注册:${id}`);
|
||||
}
|
||||
if (act === 'mount') {
|
||||
if (typeof mod.mount !== 'function') {
|
||||
throw new Error(`功能无 mount:${id}`);
|
||||
}
|
||||
await mod.mount();
|
||||
return;
|
||||
}
|
||||
if (typeof mod.unmount !== 'function') {
|
||||
throw new Error(`功能无 unmount:${id}`);
|
||||
}
|
||||
await mod.unmount();
|
||||
},
|
||||
args: [featureId, action],
|
||||
})
|
||||
.then(() => sendResponse({ ok: true }))
|
||||
.catch((error: unknown) => {
|
||||
sendResponse({
|
||||
ok: false,
|
||||
message: error instanceof Error ? error.message : '调用功能失败',
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
import type { AdvertisingCostItem } from '@/types/advertisingCost';
|
||||
import {
|
||||
buildHeatmapWeeks,
|
||||
cellTitle,
|
||||
monthLabelsForWeeks,
|
||||
summarizeByDate,
|
||||
type HeatDayCell,
|
||||
} from '@/shared/dateHeatmap';
|
||||
|
||||
const props = defineProps<{
|
||||
items: AdvertisingCostItem[];
|
||||
pageDate?: string;
|
||||
selectedDate?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [date: string | undefined];
|
||||
}>();
|
||||
|
||||
const WEEKDAY_LABELS = ['', '一', '', '三', '', '五', ''];
|
||||
|
||||
const stats = computed(() => summarizeByDate(props.items));
|
||||
const weeks = computed(() =>
|
||||
buildHeatmapWeeks({
|
||||
weeks: 13,
|
||||
stats: stats.value,
|
||||
pageDate: props.pageDate,
|
||||
}),
|
||||
);
|
||||
const monthLabelMap = computed(() => {
|
||||
const map = new Map<number, string>();
|
||||
for (const item of monthLabelsForWeeks(weeks.value)) {
|
||||
map.set(item.index, item.label);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
function onCellClick(cell: HeatDayCell) {
|
||||
if (!cell.inRange || !cell.stat) return;
|
||||
emit('select', props.selectedDate === cell.date ? undefined : cell.date);
|
||||
}
|
||||
|
||||
function cellClass(cell: HeatDayCell): string[] {
|
||||
const classes = [`ecbi-heat-l${cell.level}`];
|
||||
if (!cell.inRange) classes.push('ecbi-heat-out');
|
||||
if (cell.isToday) classes.push('ecbi-heat-today');
|
||||
if (cell.isPageDate) classes.push('ecbi-heat-page');
|
||||
if (props.selectedDate === cell.date) classes.push('ecbi-heat-selected');
|
||||
if (cell.stat) classes.push('ecbi-heat-lit');
|
||||
return classes;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ecbi-heat">
|
||||
<div class="ecbi-heat-head">
|
||||
<span class="ecbi-heat-title">读取日历</span>
|
||||
<span class="ecbi-muted">点亮=已读 · 点击筛选当日</span>
|
||||
</div>
|
||||
|
||||
<div class="ecbi-heat-body">
|
||||
<div class="ecbi-heat-dows">
|
||||
<span class="ecbi-heat-month-spacer" />
|
||||
<span v-for="(label, i) in WEEKDAY_LABELS" :key="i" class="ecbi-heat-dow">{{ label }}</span>
|
||||
</div>
|
||||
|
||||
<div class="ecbi-heat-weeks">
|
||||
<div v-for="(week, wi) in weeks" :key="wi" class="ecbi-heat-week">
|
||||
<span class="ecbi-heat-month">{{ monthLabelMap.get(wi) || '' }}</span>
|
||||
<button
|
||||
v-for="cell in week"
|
||||
:key="cell.date"
|
||||
type="button"
|
||||
class="ecbi-heat-cell"
|
||||
:class="cellClass(cell)"
|
||||
:title="cellTitle(cell)"
|
||||
:disabled="!cell.inRange || !cell.stat"
|
||||
@click="onCellClick(cell)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ecbi-heat-legend">
|
||||
<span class="ecbi-muted">少</span>
|
||||
<span class="ecbi-heat-cell ecbi-heat-l0" />
|
||||
<span class="ecbi-heat-cell ecbi-heat-l1" />
|
||||
<span class="ecbi-heat-cell ecbi-heat-l2" />
|
||||
<span class="ecbi-heat-cell ecbi-heat-l3" />
|
||||
<span class="ecbi-heat-cell ecbi-heat-l4" />
|
||||
<span class="ecbi-muted">多</span>
|
||||
<span class="ecbi-heat-gap" />
|
||||
<span class="ecbi-heat-cell ecbi-heat-l0 ecbi-heat-page" />
|
||||
<span class="ecbi-muted">当前页日期</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,641 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue';
|
||||
|
||||
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
|
||||
import DateHeatmap from './DateHeatmap.vue';
|
||||
import { resolveAdapter } from '@/platform/core/PlatformDetector';
|
||||
import {
|
||||
MAX_AUTO_COLLECT_DAYS,
|
||||
listDatesInclusive,
|
||||
runAutoCollectByDates,
|
||||
} from '@/platform/pdd/autoCollectDates';
|
||||
import { matchChannelShopByMallName, shopAuthorizeHint } from '@/platform/pdd/matchShop';
|
||||
import { EXTENSION_NAME } from '@/shared/constants';
|
||||
import { toUserMessage } from '@/shared/errors';
|
||||
import { listFeeDates, mergeAdvertisingItems } from '@/shared/mergeItems';
|
||||
import { getSettings, saveSettings } from '@/storage/settings';
|
||||
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
minimize: [];
|
||||
}>();
|
||||
|
||||
const channelShopId = ref<number | undefined>(undefined);
|
||||
const channelShopName = ref('');
|
||||
const pageMallName = ref('');
|
||||
const shopMatching = ref(false);
|
||||
const shopMatched = ref(false);
|
||||
|
||||
const pageContext = ref<PageContext | null>(null);
|
||||
const batch = ref<AdvertisingCostBatch | null>(null);
|
||||
const filterDate = ref<string | undefined>(undefined);
|
||||
const statusText = ref('等待读取');
|
||||
const errorText = ref('');
|
||||
const syncResultText = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
const autoStartDate = ref('');
|
||||
const autoEndDate = ref('');
|
||||
const autoSkipRead = ref(true);
|
||||
const autoRunning = ref(false);
|
||||
let autoAbort: AbortController | null = null;
|
||||
/** 自动切日期期间禁止 URL 轮询触发二次读取 */
|
||||
let suppressUrlAutoRead = false;
|
||||
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const position = ref({ top: 72, left: Math.max(24, window.innerWidth - 400) });
|
||||
let dragOffset = { x: 0, y: 0 };
|
||||
let dragging = false;
|
||||
let readTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let urlPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let lastHref = typeof location !== 'undefined' ? location.href : '';
|
||||
|
||||
function todayIso(): string {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(now.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
function shiftIso(iso: string, deltaDays: number): string {
|
||||
const dt = new Date(`${iso}T00:00:00`);
|
||||
dt.setDate(dt.getDate() + deltaDays);
|
||||
const y = dt.getFullYear();
|
||||
const m = String(dt.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(dt.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
function initAutoDateRange(preferredEnd?: string) {
|
||||
const end = preferredEnd && /^\d{4}-\d{2}-\d{2}$/.test(preferredEnd) ? preferredEnd : todayIso();
|
||||
autoEndDate.value = end;
|
||||
autoStartDate.value = shiftIso(end, -(Math.min(6, MAX_AUTO_COLLECT_DAYS - 1)));
|
||||
}
|
||||
|
||||
const totalFee = computed(() =>
|
||||
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
|
||||
);
|
||||
const itemCount = computed(() => batch.value?.items.length ?? 0);
|
||||
const dateCount = computed(() => listFeeDates(batch.value?.items ?? []).length);
|
||||
const previewItems = computed(() => {
|
||||
const items = batch.value?.items ?? [];
|
||||
if (!filterDate.value) return items;
|
||||
return items.filter((item) => item.feeDate === filterDate.value);
|
||||
});
|
||||
const previewFee = computed(() =>
|
||||
previewItems.value.reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
|
||||
);
|
||||
const dateModeLabel = computed(() => {
|
||||
const mode = pageContext.value?.dateMode;
|
||||
if (mode === 'single') return `单日 ${pageContext.value?.feeDate ?? ''}`;
|
||||
if (mode === 'range') return '范围(本页不追加)';
|
||||
return '未知';
|
||||
});
|
||||
const accumulatedLabel = computed(() => {
|
||||
if (!dateCount.value) return '尚未累计';
|
||||
return `${dateCount.value} 天 · ${itemCount.value} 条`;
|
||||
});
|
||||
const previewLabel = computed(() => {
|
||||
if (!filterDate.value) return '全部已读';
|
||||
return filterDate.value;
|
||||
});
|
||||
const autoDaySpanLabel = computed(() => {
|
||||
try {
|
||||
if (!autoStartDate.value || !autoEndDate.value) return `最多 ${MAX_AUTO_COLLECT_DAYS} 天`;
|
||||
const n = listDatesInclusive(autoStartDate.value, autoEndDate.value).length;
|
||||
return `${n} 天(上限 ${MAX_AUTO_COLLECT_DAYS})`;
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : '日期无效';
|
||||
}
|
||||
});
|
||||
|
||||
const shopTagLabel = computed(() => {
|
||||
if (shopMatching.value) return '匹配中';
|
||||
if (shopMatched.value && channelShopId.value != null) return '已授权';
|
||||
if (pageMallName.value.trim()) return '未授权';
|
||||
return '未识别';
|
||||
});
|
||||
|
||||
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() || '未识别店铺';
|
||||
return `${name} · ${shopTagLabel.value}`;
|
||||
});
|
||||
|
||||
function onHeatSelect(date: string | undefined) {
|
||||
filterDate.value = date;
|
||||
}
|
||||
|
||||
async function refreshContext() {
|
||||
try {
|
||||
pageContext.value = await resolveAdapter(location.href).getPageContext();
|
||||
pageMallName.value = pageContext.value.mallName ?? '';
|
||||
} catch {
|
||||
pageContext.value = null;
|
||||
pageMallName.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLocalSettings() {
|
||||
const settings = await getSettings();
|
||||
channelShopId.value = settings.channelShopId;
|
||||
channelShopName.value = settings.channelShopName ?? '';
|
||||
// 缓存仅作提示;真正读写前会按页面店名再精确校验
|
||||
shopMatched.value =
|
||||
channelShopId.value != null &&
|
||||
Boolean(channelShopName.value) &&
|
||||
channelShopName.value.trim() === (pageMallName.value || channelShopName.value).trim();
|
||||
}
|
||||
|
||||
async function persistShop() {
|
||||
await saveSettings({
|
||||
channelShopId: channelShopId.value,
|
||||
channelShopName: channelShopName.value,
|
||||
});
|
||||
}
|
||||
|
||||
async function clearMatchedShop() {
|
||||
channelShopId.value = undefined;
|
||||
channelShopName.value = '';
|
||||
shopMatched.value = false;
|
||||
await persistShop();
|
||||
}
|
||||
|
||||
/** 仅按页面店铺名完全匹配;失败时提示去系统授权 */
|
||||
async function matchShopFromPage(options: { quiet?: boolean } = {}): Promise<boolean> {
|
||||
await refreshContext();
|
||||
const mallName = pageMallName.value.trim();
|
||||
if (!mallName) {
|
||||
await clearMatchedShop();
|
||||
if (!options.quiet) {
|
||||
errorText.value = '未识别到页面店铺名,请确认已打开推广总览';
|
||||
statusText.value = '无法匹配店铺';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 已与当前页店名精确对应则复用
|
||||
if (
|
||||
channelShopId.value != null &&
|
||||
channelShopName.value.trim() === mallName
|
||||
) {
|
||||
shopMatched.value = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
shopMatching.value = true;
|
||||
if (!options.quiet) errorText.value = '';
|
||||
try {
|
||||
const matched = await matchChannelShopByMallName(mallName);
|
||||
if (!matched) {
|
||||
await clearMatchedShop();
|
||||
const hint = shopAuthorizeHint(mallName);
|
||||
errorText.value = hint;
|
||||
statusText.value = '店铺未授权';
|
||||
return false;
|
||||
}
|
||||
channelShopId.value = matched.id;
|
||||
channelShopName.value = matched.mallName ?? mallName;
|
||||
shopMatched.value = true;
|
||||
await persistShop();
|
||||
statusText.value = `已匹配授权店铺:${channelShopName.value}`;
|
||||
return true;
|
||||
} catch (error) {
|
||||
await clearMatchedShop();
|
||||
errorText.value = toUserMessage(error);
|
||||
statusText.value = '店铺匹配失败';
|
||||
return false;
|
||||
} finally {
|
||||
shopMatching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureChannelShop(): Promise<void> {
|
||||
const ok = await matchShopFromPage();
|
||||
if (!ok || channelShopId.value == null) {
|
||||
const mallName = pageMallName.value.trim();
|
||||
throw new Error(
|
||||
mallName ? shopAuthorizeHint(mallName) : '未识别到页面店铺名,请确认已打开推广总览',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRead(fromAuto = false, allowEmpty = false) {
|
||||
busy.value = true;
|
||||
errorText.value = '';
|
||||
syncResultText.value = '';
|
||||
statusText.value = fromAuto ? '自动读取中…' : '正在读取…';
|
||||
try {
|
||||
await refreshContext();
|
||||
|
||||
if (pageContext.value?.dateMode === 'range') {
|
||||
statusText.value = '范围视图不追加;已累计数据仍保留';
|
||||
errorText.value = pageContext.value.message ?? '请切回单日后再读取';
|
||||
return;
|
||||
}
|
||||
|
||||
await ensureChannelShop();
|
||||
|
||||
statusText.value = '检查分页(每页 100)…';
|
||||
const adapter = resolveAdapter(location.href);
|
||||
const parsed = await adapter.parseAdvertisingCost({ allowEmpty });
|
||||
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
|
||||
const addedOrUpdated = parsed.items.length;
|
||||
|
||||
if (parsed.items.length > 0) {
|
||||
batch.value = {
|
||||
platform: parsed.platform,
|
||||
channelShopId: channelShopId.value!,
|
||||
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
|
||||
source: 'browser-extension',
|
||||
importedAt: new Date().toISOString(),
|
||||
};
|
||||
if (incomingDate) filterDate.value = incomingDate;
|
||||
}
|
||||
|
||||
await refreshContext();
|
||||
const tag = parsed.platform === 'mock' ? 'Mock' : '页面';
|
||||
if (addedOrUpdated === 0) {
|
||||
statusText.value = incomingDate
|
||||
? `${incomingDate} 无推广费数据(已跳过)· 累计 ${dateCount.value} 天`
|
||||
: '当日无推广费数据';
|
||||
return;
|
||||
}
|
||||
statusText.value = incomingDate
|
||||
? `已合并 ${incomingDate}(${addedOrUpdated} 条,${tag})· 累计 ${dateCount.value} 天`
|
||||
: `已读取(${tag})`;
|
||||
} catch (error) {
|
||||
statusText.value = '读取失败';
|
||||
errorText.value = toUserMessage(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function clearAccumulated() {
|
||||
batch.value = null;
|
||||
filterDate.value = undefined;
|
||||
syncResultText.value = '';
|
||||
errorText.value = '';
|
||||
statusText.value = '已清空累计数据';
|
||||
}
|
||||
|
||||
function scheduleAutoRead(delayMs = 450) {
|
||||
if (suppressUrlAutoRead || autoRunning.value) return;
|
||||
if (readTimer) clearTimeout(readTimer);
|
||||
readTimer = setTimeout(() => {
|
||||
void handleRead(true).catch(() => {
|
||||
// 错误已写入 errorText
|
||||
});
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
async function onPageUrlChanged() {
|
||||
if (suppressUrlAutoRead || autoRunning.value) {
|
||||
await refreshContext();
|
||||
return;
|
||||
}
|
||||
await refreshContext();
|
||||
if (pageContext.value?.dateMode === 'single') {
|
||||
errorText.value = '';
|
||||
scheduleAutoRead(1200);
|
||||
return;
|
||||
}
|
||||
if (pageContext.value?.dateMode === 'range') {
|
||||
statusText.value = '范围视图不追加;已累计数据仍保留';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAutoCollect() {
|
||||
if (autoRunning.value) return;
|
||||
errorText.value = '';
|
||||
syncResultText.value = '';
|
||||
try {
|
||||
listDatesInclusive(autoStartDate.value, autoEndDate.value);
|
||||
} catch (error) {
|
||||
errorText.value = toUserMessage(error);
|
||||
return;
|
||||
}
|
||||
|
||||
autoAbort = new AbortController();
|
||||
autoRunning.value = true;
|
||||
suppressUrlAutoRead = true;
|
||||
busy.value = true;
|
||||
if (readTimer) {
|
||||
clearTimeout(readTimer);
|
||||
readTimer = null;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureChannelShop();
|
||||
await runAutoCollectByDates({
|
||||
startDate: autoStartDate.value,
|
||||
endDate: autoEndDate.value,
|
||||
skipDates: autoSkipRead.value ? listFeeDates(batch.value?.items ?? []) : [],
|
||||
signal: autoAbort.signal,
|
||||
onProgress: (p) => {
|
||||
statusText.value = p.message;
|
||||
},
|
||||
readDay: async () => {
|
||||
await refreshContext();
|
||||
await ensureChannelShop();
|
||||
const adapter = resolveAdapter(location.href);
|
||||
const parsed = await adapter.parseAdvertisingCost({ allowEmpty: true });
|
||||
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
|
||||
if (parsed.items.length > 0) {
|
||||
batch.value = {
|
||||
platform: parsed.platform,
|
||||
channelShopId: channelShopId.value!,
|
||||
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
|
||||
source: 'browser-extension',
|
||||
importedAt: new Date().toISOString(),
|
||||
};
|
||||
if (incomingDate) filterDate.value = incomingDate;
|
||||
}
|
||||
await refreshContext();
|
||||
lastHref = location.href;
|
||||
},
|
||||
});
|
||||
statusText.value = `自动读取完成 · 累计 ${dateCount.value} 天 ${itemCount.value} 条`;
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
statusText.value = `已停止自动读取 · 累计 ${dateCount.value} 天`;
|
||||
} else {
|
||||
statusText.value = '自动读取中断';
|
||||
errorText.value = toUserMessage(error);
|
||||
}
|
||||
} finally {
|
||||
autoRunning.value = false;
|
||||
suppressUrlAutoRead = false;
|
||||
busy.value = false;
|
||||
autoAbort = null;
|
||||
lastHref = location.href;
|
||||
}
|
||||
}
|
||||
|
||||
function stopAutoCollect() {
|
||||
autoAbort?.abort();
|
||||
}
|
||||
|
||||
async function handleSync() {
|
||||
if (!batch.value) {
|
||||
errorText.value = '请先读取数据';
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
errorText.value = '';
|
||||
syncResultText.value = '';
|
||||
statusText.value = '正在同步…';
|
||||
try {
|
||||
await ensureChannelShop();
|
||||
const payload: AdvertisingCostBatch = {
|
||||
...batch.value,
|
||||
channelShopId: channelShopId.value!,
|
||||
};
|
||||
const result = await batchImportPddGoodsAdFee(payload, (task) => {
|
||||
const done = (task.successCount ?? 0) + (task.failCount ?? 0);
|
||||
statusText.value = `正在导入… ${done}/${task.totalCount ?? 0}`;
|
||||
});
|
||||
const failed = result.status === 'failed';
|
||||
const partial = result.status === 'partial';
|
||||
statusText.value = failed ? '同步失败' : partial ? '部分成功' : '同步完成';
|
||||
const authHint = result.authExpired
|
||||
? ',授权已失效请重新授权后再导失败商品'
|
||||
: '';
|
||||
syncResultText.value =
|
||||
`成功 ${result.successCount}/${result.totalCount}` +
|
||||
(result.failCount ? `,失败 ${result.failCount}` : '') +
|
||||
authHint;
|
||||
} catch (error) {
|
||||
statusText.value = '同步失败';
|
||||
errorText.value = toUserMessage(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onHeaderPointerDown(event: PointerEvent) {
|
||||
if ((event.target as HTMLElement).closest('button')) return;
|
||||
dragging = true;
|
||||
dragOffset = {
|
||||
x: event.clientX - position.value.left,
|
||||
y: event.clientY - position.value.top,
|
||||
};
|
||||
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||
}
|
||||
|
||||
function onHeaderPointerMove(event: PointerEvent) {
|
||||
if (!dragging) return;
|
||||
const maxLeft = window.innerWidth - 80;
|
||||
const maxTop = window.innerHeight - 80;
|
||||
position.value = {
|
||||
left: Math.min(maxLeft, Math.max(8, event.clientX - dragOffset.x)),
|
||||
top: Math.min(maxTop, Math.max(8, event.clientY - dragOffset.y)),
|
||||
};
|
||||
}
|
||||
|
||||
function onHeaderPointerUp(event: PointerEvent) {
|
||||
dragging = false;
|
||||
try {
|
||||
(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadLocalSettings();
|
||||
await refreshContext();
|
||||
initAutoDateRange(pageContext.value?.feeDate);
|
||||
const matched = await matchShopFromPage({ quiet: true });
|
||||
if (pageContext.value?.dateMode === 'range') {
|
||||
statusText.value = '范围视图不追加;请切到单日逐日读取并累计';
|
||||
errorText.value = pageContext.value.message ?? '';
|
||||
} else if (matched) {
|
||||
scheduleAutoRead();
|
||||
} else if (pageMallName.value.trim()) {
|
||||
errorText.value = shopAuthorizeHint(pageMallName.value);
|
||||
statusText.value = '店铺未授权';
|
||||
}
|
||||
|
||||
lastHref = location.href;
|
||||
urlPollTimer = setInterval(() => {
|
||||
if (location.href === lastHref) return;
|
||||
lastHref = location.href;
|
||||
void onPageUrlChanged();
|
||||
}, 800);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
autoAbort?.abort();
|
||||
if (readTimer) clearTimeout(readTimer);
|
||||
if (urlPollTimer) clearInterval(urlPollTimer);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="panelRef"
|
||||
class="ecbi-panel"
|
||||
:style="{ top: `${position.top}px`, left: `${position.left}px` }"
|
||||
>
|
||||
<header
|
||||
class="ecbi-header"
|
||||
@pointerdown="onHeaderPointerDown"
|
||||
@pointermove="onHeaderPointerMove"
|
||||
@pointerup="onHeaderPointerUp"
|
||||
@pointercancel="onHeaderPointerUp"
|
||||
>
|
||||
<div class="ecbi-header-main">
|
||||
<h1>{{ EXTENSION_NAME }}</h1>
|
||||
<div class="ecbi-header-shop" :title="headerShopTitle">
|
||||
<span class="ecbi-header-shop-name">{{ pageMallName.trim() || '未识别店铺' }}</span>
|
||||
<span class="ecbi-shop-tag" :class="shopTagClass">{{ shopTagLabel }}</span>
|
||||
</div>
|
||||
<p class="ecbi-header-stats">{{ accumulatedLabel }}</p>
|
||||
</div>
|
||||
<div class="ecbi-header-actions">
|
||||
<button
|
||||
class="ecbi-header-link"
|
||||
type="button"
|
||||
title="按页面店名重新精确匹配"
|
||||
:disabled="shopMatching || busy || autoRunning"
|
||||
@pointerdown.stop
|
||||
@click="matchShopFromPage()"
|
||||
>
|
||||
{{ shopMatching ? '…' : '匹配' }}
|
||||
</button>
|
||||
<button class="ecbi-icon-btn" type="button" title="收起" @click="emit('minimize')">
|
||||
–
|
||||
</button>
|
||||
<button class="ecbi-icon-btn" type="button" title="关闭" @click="emit('close')">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<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">
|
||||
<span>{{ dateModeLabel }}</span>
|
||||
<span class="ecbi-meta-sep">·</span>
|
||||
<span class="ecbi-fee">¥{{ totalFee.toFixed(2) }}</span>
|
||||
<span class="ecbi-muted">/ {{ itemCount }} 条</span>
|
||||
</div>
|
||||
|
||||
<section class="ecbi-card ecbi-card-tight">
|
||||
<DateHeatmap
|
||||
:items="batch?.items ?? []"
|
||||
:page-date="pageContext?.feeDate"
|
||||
:selected-date="filterDate"
|
||||
@select="onHeatSelect"
|
||||
/>
|
||||
<div v-if="filterDate" class="ecbi-heat-filter">
|
||||
<span class="ecbi-muted">筛选 {{ filterDate }} · ¥{{ previewFee.toFixed(2) }}</span>
|
||||
<button class="ecbi-link" type="button" @click="filterDate = undefined">全部</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="ecbi-actions">
|
||||
<button
|
||||
class="ecbi-btn ecbi-btn-ghost"
|
||||
type="button"
|
||||
:disabled="busy || autoRunning"
|
||||
@click="handleRead(false)"
|
||||
>
|
||||
读当日
|
||||
</button>
|
||||
<button
|
||||
class="ecbi-btn ecbi-btn-ghost"
|
||||
type="button"
|
||||
:disabled="busy || autoRunning || !batch?.items?.length"
|
||||
@click="clearAccumulated"
|
||||
>
|
||||
清空累计
|
||||
</button>
|
||||
<button
|
||||
class="ecbi-btn ecbi-btn-primary"
|
||||
type="button"
|
||||
:disabled="busy || autoRunning || !batch?.items?.length"
|
||||
@click="handleSync"
|
||||
>
|
||||
同步到系统
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<details class="ecbi-fold">
|
||||
<summary>自动逐日 · {{ autoDaySpanLabel }}</summary>
|
||||
<div class="ecbi-fold-body">
|
||||
<div class="ecbi-date-row">
|
||||
<label class="ecbi-date-field">
|
||||
<span class="ecbi-muted">开始</span>
|
||||
<input
|
||||
v-model="autoStartDate"
|
||||
class="ecbi-date-input"
|
||||
type="date"
|
||||
:disabled="autoRunning"
|
||||
/>
|
||||
</label>
|
||||
<label class="ecbi-date-field">
|
||||
<span class="ecbi-muted">结束</span>
|
||||
<input
|
||||
v-model="autoEndDate"
|
||||
class="ecbi-date-input"
|
||||
type="date"
|
||||
:disabled="autoRunning"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div class="ecbi-row" style="margin-top: 8px">
|
||||
<label class="ecbi-check">
|
||||
<input v-model="autoSkipRead" type="checkbox" :disabled="autoRunning" />
|
||||
跳过已读
|
||||
</label>
|
||||
</div>
|
||||
<div class="ecbi-actions" style="margin-top: 10px">
|
||||
<button
|
||||
v-if="!autoRunning"
|
||||
class="ecbi-btn ecbi-btn-ghost"
|
||||
type="button"
|
||||
:disabled="busy"
|
||||
@click="handleAutoCollect"
|
||||
>
|
||||
开始
|
||||
</button>
|
||||
<button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect">
|
||||
停止
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ecbi-fold">
|
||||
<summary>明细 · {{ previewLabel }}({{ previewItems.length }})</summary>
|
||||
<div class="ecbi-fold-body">
|
||||
<ul v-if="previewItems.length" class="ecbi-list">
|
||||
<li v-for="item in previewItems" :key="`${item.feeDate}-${item.goodsId}`">
|
||||
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
|
||||
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="ecbi-muted" style="margin: 0">暂无数据</p>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,141 @@
|
||||
import { createApp, type App } from 'vue';
|
||||
|
||||
import { emitFeatureEvent } from '@/features/runtime/mainWorldAdapters';
|
||||
|
||||
import FloatingPanel from './FloatingPanel.vue';
|
||||
import styles from './styles.css?inline';
|
||||
|
||||
const HOST_ID = 'ecbi-float-host';
|
||||
const LAUNCHER_ID = 'ecbi-float-launcher';
|
||||
const FEATURE_ID = 'pdd-ad-fee';
|
||||
|
||||
let app: App<Element> | null = null;
|
||||
let visible = false;
|
||||
let minimized = false;
|
||||
|
||||
function ensureHost(): HTMLElement {
|
||||
let host = document.getElementById(HOST_ID);
|
||||
if (!host) {
|
||||
host = document.createElement('div');
|
||||
host.id = HOST_ID;
|
||||
document.documentElement.appendChild(host);
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
function ensureShadow(host: HTMLElement): ShadowRoot {
|
||||
return host.shadowRoot ?? host.attachShadow({ mode: 'open' });
|
||||
}
|
||||
|
||||
function setHostHidden(hidden: boolean) {
|
||||
const host = document.getElementById(HOST_ID);
|
||||
if (host) {
|
||||
host.style.display = hidden ? 'none' : '';
|
||||
}
|
||||
}
|
||||
|
||||
function removeLauncher() {
|
||||
document.getElementById(LAUNCHER_ID)?.remove();
|
||||
}
|
||||
|
||||
function showLauncher() {
|
||||
removeLauncher();
|
||||
const btn = document.createElement('button');
|
||||
btn.id = LAUNCHER_ID;
|
||||
btn.type = 'button';
|
||||
btn.textContent = 'ECBI';
|
||||
btn.title = '展开 ECBI 悬浮面板';
|
||||
Object.assign(btn.style, {
|
||||
position: 'fixed',
|
||||
right: '16px',
|
||||
bottom: '16px',
|
||||
zIndex: '2147483646',
|
||||
border: '0',
|
||||
borderRadius: '999px',
|
||||
padding: '10px 16px',
|
||||
background: '#1677ff',
|
||||
color: '#fff',
|
||||
fontSize: '13px',
|
||||
fontWeight: '500',
|
||||
cursor: 'pointer',
|
||||
boxShadow: '0 6px 16px rgba(22, 119, 255, 0.35)',
|
||||
} as CSSStyleDeclaration);
|
||||
btn.addEventListener('click', () => {
|
||||
minimized = false;
|
||||
setFloatingVisible(true);
|
||||
emitFeatureEvent(FEATURE_ID, 'restored');
|
||||
});
|
||||
document.documentElement.appendChild(btn);
|
||||
}
|
||||
|
||||
function unmountApp() {
|
||||
if (app) {
|
||||
app.unmount();
|
||||
app = null;
|
||||
}
|
||||
const host = document.getElementById(HOST_ID);
|
||||
if (host?.shadowRoot) {
|
||||
host.shadowRoot.innerHTML = '';
|
||||
}
|
||||
if (host) {
|
||||
host.style.display = '';
|
||||
}
|
||||
}
|
||||
|
||||
function mountApp() {
|
||||
const host = ensureHost();
|
||||
const shadow = ensureShadow(host);
|
||||
shadow.innerHTML = '';
|
||||
host.style.display = '';
|
||||
|
||||
const styleEl = document.createElement('style');
|
||||
styleEl.textContent = styles;
|
||||
shadow.appendChild(styleEl);
|
||||
|
||||
const mountEl = document.createElement('div');
|
||||
shadow.appendChild(mountEl);
|
||||
|
||||
app = createApp(FloatingPanel, {
|
||||
onClose: () => setFloatingVisible(false),
|
||||
onMinimize: () => {
|
||||
// 只隐藏,不销毁 Vue,保留已累计的多日数据
|
||||
minimized = true;
|
||||
setHostHidden(true);
|
||||
showLauncher();
|
||||
visible = true;
|
||||
emitFeatureEvent(FEATURE_ID, 'minimized');
|
||||
},
|
||||
});
|
||||
app.mount(mountEl);
|
||||
}
|
||||
|
||||
export function isFloatingVisible(): boolean {
|
||||
return visible;
|
||||
}
|
||||
|
||||
export function setFloatingVisible(next: boolean): boolean {
|
||||
if (!next) {
|
||||
const wasVisible = visible;
|
||||
visible = false;
|
||||
minimized = false;
|
||||
unmountApp();
|
||||
removeLauncher();
|
||||
if (wasVisible) {
|
||||
emitFeatureEvent(FEATURE_ID, 'closed');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
visible = true;
|
||||
minimized = false;
|
||||
removeLauncher();
|
||||
setHostHidden(false);
|
||||
if (!app) {
|
||||
mountApp();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function toggleFloatingPanel(): boolean {
|
||||
return setFloatingVisible(!visible || minimized);
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
#ecbi-float-host {
|
||||
all: initial;
|
||||
}
|
||||
|
||||
/* Ant Design 风格 token(不引入组件库,仅对齐色板与圆角) */
|
||||
.ecbi-panel {
|
||||
--ecbi-primary: #1677ff;
|
||||
--ecbi-primary-hover: #4096ff;
|
||||
--ecbi-primary-active: #0958d9;
|
||||
--ecbi-primary-bg: #e6f4ff;
|
||||
--ecbi-text: rgba(0, 0, 0, 0.88);
|
||||
--ecbi-text-secondary: rgba(0, 0, 0, 0.45);
|
||||
--ecbi-text-tertiary: rgba(0, 0, 0, 0.25);
|
||||
--ecbi-border: #d9d9d9;
|
||||
--ecbi-border-secondary: #f0f0f0;
|
||||
--ecbi-fill: #f5f5f5;
|
||||
--ecbi-bg: #ffffff;
|
||||
--ecbi-success: #52c41a;
|
||||
--ecbi-error: #ff4d4f;
|
||||
--ecbi-radius: 8px;
|
||||
--ecbi-radius-lg: 12px;
|
||||
--ecbi-radius-sm: 6px;
|
||||
|
||||
position: fixed;
|
||||
z-index: 2147483646;
|
||||
width: 380px;
|
||||
max-height: min(640px, calc(100vh - 24px));
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--ecbi-radius-lg);
|
||||
border: 1px solid var(--ecbi-border-secondary);
|
||||
background: var(--ecbi-bg);
|
||||
color: var(--ecbi-text);
|
||||
box-shadow:
|
||||
0 6px 16px 0 rgb(0 0 0 / 0.08),
|
||||
0 3px 6px -4px rgb(0 0 0 / 0.12),
|
||||
0 9px 28px 8px rgb(0 0 0 / 0.05);
|
||||
font-family:
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
'Helvetica Neue',
|
||||
Arial,
|
||||
'Noto Sans',
|
||||
sans-serif;
|
||||
font-size: 13px;
|
||||
line-height: 1.5714;
|
||||
}
|
||||
|
||||
/* 面板内所有滚动条统一细条 */
|
||||
.ecbi-panel,
|
||||
.ecbi-panel * {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
|
||||
}
|
||||
|
||||
.ecbi-panel::-webkit-scrollbar,
|
||||
.ecbi-panel *::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.ecbi-panel::-webkit-scrollbar-thumb,
|
||||
.ecbi-panel *::-webkit-scrollbar-thumb {
|
||||
background: rgb(0 0 0 / 0.28);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.ecbi-panel::-webkit-scrollbar-thumb:hover,
|
||||
.ecbi-panel *::-webkit-scrollbar-thumb:hover {
|
||||
background: rgb(0 0 0 / 0.4);
|
||||
}
|
||||
|
||||
.ecbi-panel::-webkit-scrollbar-track,
|
||||
.ecbi-panel *::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ecbi-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 12px 14px;
|
||||
background: var(--ecbi-primary);
|
||||
color: #fff;
|
||||
cursor: move;
|
||||
user-select: none;
|
||||
border-radius: var(--ecbi-radius-lg) var(--ecbi-radius-lg) 0 0;
|
||||
}
|
||||
|
||||
.ecbi-header h1 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ecbi-header p {
|
||||
margin: 2px 0 0;
|
||||
font-size: 12px;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.ecbi-header-main {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.ecbi-header-sub {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ecbi-header-stats {
|
||||
margin: 2px 0 0;
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ecbi-header-sub-warn {
|
||||
color: #ffe58f;
|
||||
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 {
|
||||
border: 0;
|
||||
background: rgb(255 255 255 / 0.16);
|
||||
color: #fff;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
border-radius: var(--ecbi-radius-sm);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ecbi-header-link:hover:not(:disabled) {
|
||||
background: rgb(255 255 255 / 0.28);
|
||||
}
|
||||
|
||||
.ecbi-header-link:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.ecbi-header-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.ecbi-icon-btn {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--ecbi-radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ecbi-icon-btn:hover {
|
||||
background: rgb(255 255 255 / 0.16);
|
||||
}
|
||||
|
||||
.ecbi-body {
|
||||
padding: 12px 14px 14px;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.ecbi-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.ecbi-meta-sep {
|
||||
color: var(--ecbi-text-tertiary);
|
||||
}
|
||||
|
||||
.ecbi-row-links {
|
||||
display: inline-flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.ecbi-card-tight {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.ecbi-fold {
|
||||
border: 1px solid var(--ecbi-border-secondary);
|
||||
border-radius: var(--ecbi-radius);
|
||||
background: var(--ecbi-bg);
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
.ecbi-fold > summary {
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
padding: 8px 0;
|
||||
font-size: 12px;
|
||||
color: var(--ecbi-text-secondary);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ecbi-fold > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ecbi-fold > summary::before {
|
||||
content: '▸';
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.ecbi-fold[open] > summary::before {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.ecbi-fold-body {
|
||||
padding: 0 0 10px;
|
||||
}
|
||||
|
||||
.ecbi-status {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--ecbi-text-secondary);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.ecbi-status-busy {
|
||||
color: var(--ecbi-primary);
|
||||
}
|
||||
|
||||
.ecbi-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ecbi-label {
|
||||
color: var(--ecbi-text-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ecbi-input,
|
||||
.ecbi-select {
|
||||
width: 100%;
|
||||
border: 1px solid var(--ecbi-border);
|
||||
border-radius: var(--ecbi-radius);
|
||||
padding: 6px 11px;
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
background: var(--ecbi-bg);
|
||||
color: var(--ecbi-text);
|
||||
box-sizing: border-box;
|
||||
transition:
|
||||
border-color 0.2s,
|
||||
box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.ecbi-input:focus,
|
||||
.ecbi-select:focus {
|
||||
border-color: var(--ecbi-primary);
|
||||
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.2);
|
||||
}
|
||||
|
||||
.ecbi-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.ecbi-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ecbi-btn {
|
||||
flex: 1;
|
||||
border-radius: var(--ecbi-radius);
|
||||
border: 1px solid var(--ecbi-border);
|
||||
background: var(--ecbi-bg);
|
||||
color: var(--ecbi-text);
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 1.5714;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 0.2s,
|
||||
border-color 0.2s,
|
||||
background 0.2s;
|
||||
}
|
||||
|
||||
.ecbi-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.ecbi-btn-primary {
|
||||
border-color: var(--ecbi-primary);
|
||||
background: var(--ecbi-primary);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.ecbi-btn-primary:hover:not(:disabled) {
|
||||
border-color: var(--ecbi-primary-hover);
|
||||
background: var(--ecbi-primary-hover);
|
||||
}
|
||||
|
||||
.ecbi-btn-primary:active:not(:disabled) {
|
||||
border-color: var(--ecbi-primary-active);
|
||||
background: var(--ecbi-primary-active);
|
||||
}
|
||||
|
||||
.ecbi-btn-ghost:hover:not(:disabled) {
|
||||
color: var(--ecbi-primary);
|
||||
border-color: var(--ecbi-primary);
|
||||
}
|
||||
|
||||
.ecbi-card {
|
||||
border: 1px solid var(--ecbi-border-secondary);
|
||||
border-radius: var(--ecbi-radius-lg);
|
||||
padding: 12px;
|
||||
background: var(--ecbi-fill);
|
||||
}
|
||||
|
||||
.ecbi-card h2 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--ecbi-text-secondary);
|
||||
}
|
||||
|
||||
.ecbi-fee {
|
||||
font-weight: 600;
|
||||
color: var(--ecbi-error);
|
||||
}
|
||||
|
||||
.ecbi-list {
|
||||
margin: 8px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
max-height: 120px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.ecbi-list li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--ecbi-text-secondary);
|
||||
padding: 3px 0;
|
||||
}
|
||||
|
||||
.ecbi-muted {
|
||||
color: var(--ecbi-text-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.ecbi-error {
|
||||
color: var(--ecbi-error);
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ecbi-ok {
|
||||
color: var(--ecbi-success);
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ecbi-link {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ecbi-primary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.ecbi-link:hover {
|
||||
color: var(--ecbi-primary-hover);
|
||||
}
|
||||
|
||||
/* —— 读取日历(贡献图,蓝色阶) —— */
|
||||
.ecbi-heat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.ecbi-heat-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ecbi-heat-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--ecbi-text-secondary);
|
||||
}
|
||||
|
||||
.ecbi-heat-body {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
|
||||
.ecbi-heat-dows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ecbi-heat-month-spacer {
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.ecbi-heat-dow {
|
||||
height: 11px;
|
||||
width: 14px;
|
||||
font-size: 9px;
|
||||
line-height: 11px;
|
||||
color: var(--ecbi-text-tertiary);
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.ecbi-heat-weeks {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.ecbi-heat-week {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
width: 11px;
|
||||
}
|
||||
|
||||
.ecbi-heat-month {
|
||||
height: 14px;
|
||||
font-size: 9px;
|
||||
line-height: 14px;
|
||||
color: var(--ecbi-text-tertiary);
|
||||
white-space: nowrap;
|
||||
width: max-content;
|
||||
max-width: none;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ecbi-heat-cell {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
border-radius: 3px;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
background: #ebedf0;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
button.ecbi-heat-cell:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.ecbi-heat-cell:disabled {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.ecbi-heat-l0 {
|
||||
background: #ebedf0;
|
||||
}
|
||||
|
||||
.ecbi-heat-l1 {
|
||||
background: #9be9a8;
|
||||
}
|
||||
|
||||
.ecbi-heat-l2 {
|
||||
background: #40c463;
|
||||
}
|
||||
|
||||
.ecbi-heat-l3 {
|
||||
background: #30a14e;
|
||||
}
|
||||
|
||||
.ecbi-heat-l4 {
|
||||
background: #216e39;
|
||||
}
|
||||
|
||||
.ecbi-heat-out {
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.ecbi-heat-page {
|
||||
outline: 1px dashed var(--ecbi-primary);
|
||||
outline-offset: 0;
|
||||
}
|
||||
|
||||
.ecbi-heat-today:not(.ecbi-heat-selected) {
|
||||
box-shadow: inset 0 0 0 1px var(--ecbi-text-secondary);
|
||||
}
|
||||
|
||||
.ecbi-heat-selected {
|
||||
outline: 2px solid var(--ecbi-text);
|
||||
outline-offset: 0;
|
||||
}
|
||||
|
||||
.ecbi-heat-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.ecbi-heat-gap {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.ecbi-heat-filter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.ecbi-date-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.ecbi-date-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ecbi-date-input {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
height: 32px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--ecbi-border);
|
||||
border-radius: var(--ecbi-radius-sm);
|
||||
background: var(--ecbi-bg);
|
||||
color: var(--ecbi-text);
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.ecbi-date-input:focus {
|
||||
border-color: var(--ecbi-primary);
|
||||
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.1);
|
||||
}
|
||||
|
||||
.ecbi-date-input:disabled {
|
||||
background: var(--ecbi-fill);
|
||||
color: var(--ecbi-text-secondary);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.ecbi-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--ecbi-text);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ecbi-check input {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import {
|
||||
getActiveFeatureId,
|
||||
isFeatureUiVisible,
|
||||
mountFeature,
|
||||
unmountActiveFeature,
|
||||
} from '@/features/runtime/registry';
|
||||
import { startBridgeHost } from '@/features/runtime/bridgeHost';
|
||||
import { resolveAdapter } from '@/platform/core/PlatformDetector';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import {
|
||||
isExtensionMessage,
|
||||
type ExtensionMessage,
|
||||
type ExtensionResponse,
|
||||
} from '@/shared/messages';
|
||||
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
|
||||
|
||||
startBridgeHost();
|
||||
|
||||
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
|
||||
const adapter = resolveAdapter(location.href);
|
||||
|
||||
switch (message.type) {
|
||||
case 'PING':
|
||||
return { ok: true, data: { pong: true } };
|
||||
case 'GET_PAGE_CONTEXT': {
|
||||
const data = await adapter.getPageContext();
|
||||
return { ok: true, data };
|
||||
}
|
||||
case 'PARSE_ADVERTISING_COST': {
|
||||
const parsed = await adapter.parseAdvertisingCost();
|
||||
const data: AdvertisingCostBatch = {
|
||||
...parsed,
|
||||
channelShopId: 0,
|
||||
};
|
||||
return { ok: true, data };
|
||||
}
|
||||
case 'TOGGLE_FLOATING_PANEL': {
|
||||
if (isFeatureUiVisible()) {
|
||||
await unmountActiveFeature();
|
||||
return { ok: true, data: { visible: false } };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
code: 'UNKNOWN',
|
||||
message: '请从 Popup 打开功能(需下载远程脚本)',
|
||||
};
|
||||
}
|
||||
case 'SET_FLOATING_PANEL': {
|
||||
if (!message.payload.visible) {
|
||||
await unmountActiveFeature();
|
||||
return { ok: true, data: { visible: false } };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
code: 'UNKNOWN',
|
||||
message: '请从 Popup 打开功能(需下载远程脚本)',
|
||||
};
|
||||
}
|
||||
case 'GET_FLOATING_PANEL_STATE': {
|
||||
return { ok: true, data: { visible: isFeatureUiVisible() } };
|
||||
}
|
||||
case 'MOUNT_FEATURE': {
|
||||
await mountFeature(message.payload.featureId, message.payload.code);
|
||||
return { ok: true, data: { featureId: message.payload.featureId } };
|
||||
}
|
||||
case 'UNMOUNT_FEATURE': {
|
||||
await unmountActiveFeature();
|
||||
return { ok: true, data: { featureId: null } };
|
||||
}
|
||||
case 'GET_ACTIVE_FEATURE': {
|
||||
return { ok: true, data: { featureId: getActiveFeatureId() } };
|
||||
}
|
||||
default:
|
||||
return {
|
||||
ok: false,
|
||||
code: 'UNKNOWN',
|
||||
message: '未知消息类型',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
if (!isExtensionMessage(message)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
void handleMessage(message)
|
||||
.then((result) => sendResponse(result))
|
||||
.catch((error: unknown) => {
|
||||
const err =
|
||||
error instanceof ExtensionError
|
||||
? error
|
||||
: new ExtensionError(
|
||||
'UNKNOWN',
|
||||
error instanceof Error ? error.message : 'Content Script 处理失败',
|
||||
);
|
||||
const response: ExtensionResponse = {
|
||||
ok: false,
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
};
|
||||
sendResponse(response);
|
||||
});
|
||||
|
||||
return true;
|
||||
});
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue';
|
||||
const component: DefineComponent<object, object, unknown>;
|
||||
export default component;
|
||||
}
|
||||
|
||||
declare module '*.css?inline' {
|
||||
const css: string;
|
||||
export default css;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 远程功能包入口(IIFE → artifacts/features/pdd-ad-fee.js)。
|
||||
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
|
||||
*/
|
||||
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
|
||||
import { setFloatingVisible } from '@/content/floating/mount';
|
||||
|
||||
const FEATURE_ID = 'pdd-ad-fee';
|
||||
const FEATURE_VERSION = '0.3.10';
|
||||
|
||||
export interface RemoteFeatureExport {
|
||||
id: string;
|
||||
version: string;
|
||||
executionWorld: 'main';
|
||||
mount: () => Promise<void>;
|
||||
unmount: () => Promise<void>;
|
||||
}
|
||||
|
||||
installMainWorldAdapters();
|
||||
|
||||
const feature: RemoteFeatureExport = {
|
||||
id: FEATURE_ID,
|
||||
version: FEATURE_VERSION,
|
||||
executionWorld: 'main',
|
||||
async mount() {
|
||||
setFloatingVisible(true);
|
||||
},
|
||||
async unmount() {
|
||||
setFloatingVisible(false);
|
||||
},
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
|
||||
}
|
||||
}
|
||||
|
||||
const g = globalThis as typeof globalThis & {
|
||||
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
|
||||
};
|
||||
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
|
||||
g.__ECBI_FEATURES__[FEATURE_ID] = feature;
|
||||
|
||||
export default feature;
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Content Script(isolated)侧桥接主机:代发 Open API、读写 chrome.storage。
|
||||
*/
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { getSettings, saveSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_SHELL_SOURCE,
|
||||
isBridgeFeatureEvent,
|
||||
isBridgeRpcRequest,
|
||||
type BridgeRpcRequest,
|
||||
type BridgeRpcResult,
|
||||
} from './bridgeProtocol';
|
||||
import { clearActiveIfFeature, notifyFeatureEvent } from './registry';
|
||||
|
||||
let started = false;
|
||||
|
||||
function reply(result: BridgeRpcResult): void {
|
||||
window.postMessage(result, '*');
|
||||
}
|
||||
|
||||
async function handleRpc(msg: BridgeRpcRequest): Promise<void> {
|
||||
try {
|
||||
let data: unknown;
|
||||
switch (msg.rpc) {
|
||||
case 'OPEN_API': {
|
||||
if (!msg.path) throw new ExtensionError('UNKNOWN', '缺少 path');
|
||||
data = await openApiRequest(msg.path, {
|
||||
method: msg.method || 'GET',
|
||||
body: msg.body,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'GET_SETTINGS':
|
||||
data = await getSettings();
|
||||
break;
|
||||
case 'SAVE_SETTINGS':
|
||||
data = await saveSettings(msg.patch ?? {});
|
||||
break;
|
||||
default:
|
||||
throw new ExtensionError('UNKNOWN', `未知 RPC:${(msg as { rpc: string }).rpc}`);
|
||||
}
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: true,
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
const err =
|
||||
error instanceof ExtensionError
|
||||
? error
|
||||
: new ExtensionError(
|
||||
'UNKNOWN',
|
||||
error instanceof Error ? error.message : '桥接处理失败',
|
||||
);
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: false,
|
||||
error: { code: err.code, message: err.message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function startBridgeHost(): void {
|
||||
if (started) return;
|
||||
started = true;
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data;
|
||||
|
||||
if (isBridgeRpcRequest(data)) {
|
||||
void handleRpc(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBridgeFeatureEvent(data)) {
|
||||
if (data.event === 'closed') {
|
||||
clearActiveIfFeature(data.featureId);
|
||||
}
|
||||
notifyFeatureEvent(data.featureId, data.event);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/** 壳(isolated)↔ 功能(main world)postMessage 协议 */
|
||||
|
||||
export const ECBI_SHELL_SOURCE = 'ecbi-shell';
|
||||
export const ECBI_FEATURE_SOURCE = 'ecbi-feature';
|
||||
|
||||
export type BridgeRpcType = 'OPEN_API' | 'GET_SETTINGS' | 'SAVE_SETTINGS';
|
||||
|
||||
export interface BridgeRpcRequest {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'RPC';
|
||||
rpc: BridgeRpcType;
|
||||
requestId: string;
|
||||
path?: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
patch?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BridgeRpcResult {
|
||||
source: typeof ECBI_SHELL_SOURCE;
|
||||
type: 'RPC_RESULT';
|
||||
requestId: string;
|
||||
ok: boolean;
|
||||
data?: unknown;
|
||||
error?: { code: string; message: string };
|
||||
}
|
||||
|
||||
export interface BridgeFeatureEvent {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'FEATURE_EVENT';
|
||||
featureId: string;
|
||||
event: 'closed' | 'minimized' | 'restored';
|
||||
}
|
||||
|
||||
export type BridgeIncoming = BridgeRpcRequest | BridgeFeatureEvent;
|
||||
|
||||
export function isBridgeRpcRequest(data: unknown): data is BridgeRpcRequest {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeRpcRequest;
|
||||
return msg.source === ECBI_FEATURE_SOURCE && msg.type === 'RPC' && typeof msg.requestId === 'string';
|
||||
}
|
||||
|
||||
export function isBridgeFeatureEvent(data: unknown): data is BridgeFeatureEvent {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeFeatureEvent;
|
||||
return (
|
||||
msg.source === ECBI_FEATURE_SOURCE &&
|
||||
msg.type === 'FEATURE_EVENT' &&
|
||||
typeof msg.featureId === 'string'
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Main world 适配:把 Open API / chrome.storage 换成 postMessage RPC。
|
||||
* 功能包 IIFE 加载时调用 installMainWorldAdapters()。
|
||||
*/
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { setOpenApiRequestOverride } from '@/api/client';
|
||||
import { setSettingsOverride, type ExtensionSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_FEATURE_SOURCE,
|
||||
ECBI_SHELL_SOURCE,
|
||||
type BridgeRpcResult,
|
||||
type BridgeRpcType,
|
||||
} from './bridgeProtocol';
|
||||
|
||||
const RPC_TIMEOUT_MS = 30_000;
|
||||
|
||||
function postRpc<T>(rpc: BridgeRpcType, payload: Record<string, unknown> = {}): Promise<T> {
|
||||
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
reject(new ExtensionError('NETWORK_ERROR', `桥接超时(${rpc})`));
|
||||
}, RPC_TIMEOUT_MS);
|
||||
|
||||
function onMessage(event: MessageEvent) {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data as BridgeRpcResult | undefined;
|
||||
if (!data || data.source !== ECBI_SHELL_SOURCE || data.type !== 'RPC_RESULT') return;
|
||||
if (data.requestId !== requestId) return;
|
||||
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('message', onMessage);
|
||||
|
||||
if (!data.ok) {
|
||||
reject(
|
||||
new ExtensionError(
|
||||
(data.error?.code as never) || 'UNKNOWN',
|
||||
data.error?.message || '桥接调用失败',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve(data.data as T);
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage);
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'RPC',
|
||||
rpc,
|
||||
requestId,
|
||||
...payload,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
export function installMainWorldAdapters(): void {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
|
||||
setOpenApiRequestOverride(async <T,>(path: string, init: RequestInit = {}) => {
|
||||
const method = (init.method || 'GET').toUpperCase();
|
||||
const body = typeof init.body === 'string' ? init.body : undefined;
|
||||
return postRpc<T>('OPEN_API', { path, method, body });
|
||||
});
|
||||
|
||||
setSettingsOverride({
|
||||
get: () => postRpc<ExtensionSettings>('GET_SETTINGS'),
|
||||
save: (patch) =>
|
||||
postRpc<ExtensionSettings>('SAVE_SETTINGS', {
|
||||
patch: patch as Record<string, unknown>,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function emitFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'FEATURE_EVENT',
|
||||
featureId,
|
||||
event,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** 通过 Background 向页面 MAIN world 注入/调用功能脚本(绕过页面 CSP) */
|
||||
|
||||
interface BgResponse {
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
function sendToBackground(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage(message, (response: BgResponse | undefined) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
reject(new Error(chrome.runtime.lastError.message));
|
||||
return;
|
||||
}
|
||||
if (!response?.ok) {
|
||||
reject(new Error(response?.message || 'Background 执行失败'));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function injectMainWorldScript(code: string): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'INJECT_MAIN_SCRIPT',
|
||||
payload: { code },
|
||||
});
|
||||
}
|
||||
|
||||
export async function callMainWorldFeature(
|
||||
featureId: string,
|
||||
action: 'mount' | 'unmount',
|
||||
): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'CALL_MAIN_FEATURE',
|
||||
payload: { featureId, action },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { FeatureHandle } from '@/features/runtime/types';
|
||||
import {
|
||||
callMainWorldFeature,
|
||||
injectMainWorldScript,
|
||||
} from '@/features/runtime/mainWorldInject';
|
||||
|
||||
let active: { id: string; handle: FeatureHandle } | null = null;
|
||||
|
||||
type FeatureEventListener = (
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
) => void;
|
||||
|
||||
const listeners = new Set<FeatureEventListener>();
|
||||
|
||||
export function onFeatureEvent(listener: FeatureEventListener): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function notifyFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(featureId, event);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getActiveFeatureId(): string | null {
|
||||
return active?.id ?? null;
|
||||
}
|
||||
|
||||
export function clearActiveIfFeature(featureId: string): void {
|
||||
if (active?.id === featureId) {
|
||||
active = null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function mountFeature(featureId: string, code: string): Promise<void> {
|
||||
if (!code?.trim()) {
|
||||
throw new Error('缺少远程功能脚本,无法挂载');
|
||||
}
|
||||
if (active?.id === featureId) {
|
||||
// 同一功能重新打开:先卸再挂,确保用最新脚本
|
||||
await unmountActiveFeature();
|
||||
} else {
|
||||
await unmountActiveFeature();
|
||||
}
|
||||
|
||||
await injectMainWorldScript(code);
|
||||
await callMainWorldFeature(featureId, 'mount');
|
||||
|
||||
active = {
|
||||
id: featureId,
|
||||
handle: {
|
||||
unmount: async () => {
|
||||
await callMainWorldFeature(featureId, 'unmount');
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function unmountActiveFeature(): Promise<void> {
|
||||
if (!active) return;
|
||||
const current = active;
|
||||
active = null;
|
||||
try {
|
||||
await current.handle.unmount();
|
||||
} catch {
|
||||
// 页面可能已刷新,忽略
|
||||
}
|
||||
}
|
||||
|
||||
export function isFeatureUiVisible(): boolean {
|
||||
return active != null;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user