feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
+88
@@ -0,0 +1,88 @@
|
|||||||
|
# ============================================================
|
||||||
|
# D:\Agent 工作区根 .gitignore
|
||||||
|
# 【原则】只入库源码与文档;排除依赖缓存、运行数据、备份、敏感信息
|
||||||
|
# 【说明】子目录内已有 .gitignore(如 agent/)继续生效,此处只兜根级垃圾
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
# ---------- 敏感信息(严禁入库)----------
|
||||||
|
# 【注意】.env* 全家族拦截(含 .env.remarks.json 等真实凭据文件),仅放行模板
|
||||||
|
.env*
|
||||||
|
!.env.example
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
id_rsa
|
||||||
|
id_rsa.*
|
||||||
|
|
||||||
|
# ---------- 嵌套仓库归档(改名后的历史备份,留在本地不入库)----------
|
||||||
|
.git.bak/
|
||||||
|
|
||||||
|
# ---------- 依赖缓存(GB 级,必须排除)----------
|
||||||
|
.npm-cache/
|
||||||
|
.uv-cache/
|
||||||
|
.uv-python/
|
||||||
|
.cache/
|
||||||
|
|
||||||
|
# ---------- Python ----------
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.Python
|
||||||
|
.venv/
|
||||||
|
.venv.bak/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
*.egg-info/
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# ---------- Node / 前端 ----------
|
||||||
|
node_modules/
|
||||||
|
node_modules.bak/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
.vite/
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# ---------- Java / Maven / Gradle ----------
|
||||||
|
target/
|
||||||
|
*.class
|
||||||
|
.gradle/
|
||||||
|
|
||||||
|
# ---------- IDE / 编辑器 ----------
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.iml
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# ---------- 运行数据与日志 ----------
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
audit-*.jsonl
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
*.sqlite3
|
||||||
|
|
||||||
|
# ---------- 备份与临时产物 ----------
|
||||||
|
backup/
|
||||||
|
pytest_tmp/
|
||||||
|
.tmp/
|
||||||
|
*.tmp
|
||||||
|
*.bak
|
||||||
|
*.orig
|
||||||
|
|
||||||
|
# ---------- 本地状态(个人配置,不入库)----------
|
||||||
|
settings.local.json
|
||||||
|
|
||||||
|
# ---------- 大体积二进制附件(文档正文保留,附件不入库)----------
|
||||||
|
需向量化数据/图片和附件/
|
||||||
|
|
||||||
|
# ---------- 系统文件 ----------
|
||||||
|
Thumbs.db
|
||||||
|
.DS_Store
|
||||||
|
Desktop.ini
|
||||||
+441
@@ -0,0 +1,441 @@
|
|||||||
|
# CodeAgent 编程智能 Agent 系统 — 完整使用文档
|
||||||
|
|
||||||
|
> 版本:v2.0 | 更新日期:2026-10-23
|
||||||
|
> 仓库地址:https://github.com/SweetieHenry/CodeAgent.git
|
||||||
|
> **配套文档**:`Agent项目上下文.md`(新对话启动加载)、`Agent问题排查手册.md`(踩坑知识库)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
1. [系统概述](#1-系统概述)
|
||||||
|
2. [环境准备与启动](#2-环境准备与启动)
|
||||||
|
3. [核心功能模块](#3-核心功能模块)
|
||||||
|
- 3.1 [任务中心(对话式交互)](#31-任务中心对话式交互)
|
||||||
|
- 3.2 [项目管理](#32-项目管理)
|
||||||
|
- 3.3 [知识库管理](#33-知识库管理)
|
||||||
|
- 3.4 [文档问答](#34-文档问答)
|
||||||
|
- 3.5 [图片识别](#35-图片识别)
|
||||||
|
- 3.6 [提示词优化](#36-提示词优化)
|
||||||
|
- 3.7 [模型管理](#37-模型管理)
|
||||||
|
- 3.8 [数据库管理](#38-数据库管理)
|
||||||
|
- 3.9 [系统配置](#39-系统配置)
|
||||||
|
- 3.10 [日志中心](#310-日志中心)
|
||||||
|
- 3.11 [监控仪表盘](#311-监控仪表盘)
|
||||||
|
- 3.12 [高级工具箱](#312-高级工具箱)
|
||||||
|
4. [MCP 工具](#4-mcp-工具)
|
||||||
|
5. [API 速查](#5-api-速查)
|
||||||
|
6. [常见问题](#6-常见问题)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 系统概述
|
||||||
|
|
||||||
|
CodeAgent 是一个**企业级编程智能 Agent 系统**,能够理解自然语言开发需求,自动完成「需求分析 → 代码定位 → 代码修改 → 编译验证 → 问题排查 → 交付报告」的完整闭环。
|
||||||
|
|
||||||
|
### 技术架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ React + AntD 前端(6 组菜单,13 个页面) │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ FastAPI 后端(Python 3.13 + SQLite) │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ LangGraph 编排引擎(8 节点主图 + Worker)│
|
||||||
|
├──────────┬──────────┬───────────────────┤
|
||||||
|
│ 自研工具链 │ RAG 知识库 │ Claude CLI 引擎 │
|
||||||
|
│ file/search│ Chroma │ 直调/Agent 双模式 │
|
||||||
|
│ /executor │ + BGE │ │
|
||||||
|
├──────────┴──────────┴───────────────────┤
|
||||||
|
│ SQLite + Chroma 向量库 + 文件快照 │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 核心能力
|
||||||
|
|
||||||
|
| 能力 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 💬 **对话式改码** | 与 Claude 连续对话,流式输出,多轮追问 |
|
||||||
|
| 🤖 **双执行模式** | 直调 Claude(快)/ Agent 编排(全) |
|
||||||
|
| 📚 **知识库** | 文档向量化 + 智能检索(616+ 文本块) |
|
||||||
|
| 💬 **文档问答** | 任意目录文档 → 多轮对话式问答 |
|
||||||
|
| 🖼️ **图片识别** | GLM-4V-Flash 免费图片内容识别 |
|
||||||
|
| ✍️ **提示词优化** | 粗糙想法 → 高质量 AI 提示词 |
|
||||||
|
| 🗄️ **数据库管理** | MySQL/PG/SQLite 连接 + SQL CRUD |
|
||||||
|
| 📊 **监控仪表盘** | Token 成本/延迟/成功率实时监控 |
|
||||||
|
| 🔧 **MCP 工具** | 文件/搜索/Docker/禅道/Git 等 13 个工具 |
|
||||||
|
| 🛡️ **安全审计** | 全操作审计 + 回滚 + 分级审批 |
|
||||||
|
|
||||||
|
### 菜单布局(6 组)
|
||||||
|
|
||||||
|
| 分组 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| **工作台** | 任务中心、项目管理 |
|
||||||
|
| **知识智能** | 文档问答、知识库管理 |
|
||||||
|
| **工具集** | 提示词优化、图片识别、数据库管理、高级工具箱 |
|
||||||
|
| **模型资源** | 平台账号、模型管理 |
|
||||||
|
| **运维监控** | 监控仪表盘、日志中心 |
|
||||||
|
| **系统配置** | 系统配置 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 环境准备与启动
|
||||||
|
|
||||||
|
### 2.1 环境要求
|
||||||
|
|
||||||
|
| 软件 | 版本要求 | 用途 |
|
||||||
|
|---|---|---|
|
||||||
|
| Python | 3.13+ | 后端运行 |
|
||||||
|
| Node.js | 22+ | 前端构建 |
|
||||||
|
| Git | 2.5+ | 版本管理 |
|
||||||
|
| Java + Maven | 21 / 3.9+ | 目标项目编译验证 |
|
||||||
|
|
||||||
|
### 2.2 启动后端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd D:\Agent\agent\backend
|
||||||
|
.venv\Scripts\python.exe -m uvicorn app.main:app --host 127.0.0.1 --port 8002
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 启动前端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd D:\Agent\agent\frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 访问系统
|
||||||
|
|
||||||
|
浏览器打开:**http://localhost:5173**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 核心功能模块
|
||||||
|
|
||||||
|
### 3.1 任务中心(对话式交互)
|
||||||
|
|
||||||
|
> **用途**:对话式提交开发/修复需求,一条任务 = 一个完整对话
|
||||||
|
|
||||||
|
**核心交互**:
|
||||||
|
|
||||||
|
1. 点击「新建需求」按钮 → 弹出对话框
|
||||||
|
2. 选择**所属项目**(自动展示项目名称、服务路径、分支)
|
||||||
|
3. 选择**执行模式**:
|
||||||
|
- **直调 Claude**(默认):直接调用 Claude CLI,响应快,适合小改动
|
||||||
|
- **Agent 编排**:LangGraph 全流程(规划→分发→验证→报告),适合复杂任务
|
||||||
|
4. 选择**模型**(可在对话中随时切换)
|
||||||
|
5. 输入需求 → Enter 发送 → Claude 流式回复
|
||||||
|
|
||||||
|
**对话能力**:
|
||||||
|
- ✅ **连续对话**:一条任务 = 一个完整对话,支持多轮追问
|
||||||
|
- ✅ **流式输出**:Claude 的回复逐字展示(stream-json 流式解析)
|
||||||
|
- ✅ **Markdown 渲染**:代码块、表格、标题完整渲染
|
||||||
|
- ✅ **项目上下文**:自动传入项目名称、所有服务路径和分支
|
||||||
|
- ✅ **模型切换**:对话中可随时切换模型
|
||||||
|
- ✅ **知识检索开关**:可选择是否查询向量库
|
||||||
|
|
||||||
|
**任务列表**:
|
||||||
|
- 按创建时间倒序排序(最新在前)
|
||||||
|
- 支持搜索过滤
|
||||||
|
- 每行操作:对话 / 批准 / 驳回 / 停止 / 回滚 / 删除
|
||||||
|
|
||||||
|
**执行流程**:
|
||||||
|
```
|
||||||
|
直调模式:用户输入 → Claude CLI(会话管理/流式输出)→ 对话回复
|
||||||
|
Agent 模式:需求解析(弱模型) → 知识检索 → 任务规划(强模型) → 风险判定
|
||||||
|
→ [高风险] 人工审批 → 任务分发 → Worker 并行改码 → 编译验证
|
||||||
|
→ 结果评估 → 交付报告
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.2 项目管理
|
||||||
|
|
||||||
|
> **用途**:登记待开发/维护的项目信息,供任务提交时选择
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「新建项目」
|
||||||
|
2. 填写项目名称、代码根路径(必须 D 盘)
|
||||||
|
3. 添加**后端服务**(名称 + 路径 + 分支),可添加多个
|
||||||
|
4. 添加**前端服务**(名称 + 路径 + 分支),可添加多个
|
||||||
|
5. 保存
|
||||||
|
|
||||||
|
**支持能力**:
|
||||||
|
- ✅ 多后端/多前端服务管理(一个项目下多个服务)
|
||||||
|
- ✅ Git 分支下拉选择(自动读取仓库分支列表)
|
||||||
|
- ✅ 按项目名称搜索
|
||||||
|
- ✅ 上下箭头调整项目排序
|
||||||
|
- ✅ 分页展示(可调每页条数)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.3 知识库管理
|
||||||
|
|
||||||
|
> **用途**:管理项目文档知识库,供 Agent 改码时智能检索
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「入库(选择文档)」
|
||||||
|
2. 在弹窗中勾选要入库的文档(支持 md/docx/pdf/txt/csv/log)
|
||||||
|
3. 点击「向量化选中项」
|
||||||
|
|
||||||
|
**检索**:输入自然语言问题,返回相关文档片段(含来源和相关度)
|
||||||
|
|
||||||
|
**知识库特性**:
|
||||||
|
- ✅ 按 source 替换(重复入库不产生重复数据)
|
||||||
|
- ✅ 支持目录递归扫描
|
||||||
|
- ✅ 中文嵌入模型(bge-small-zh,命中率 6/6)
|
||||||
|
- ✅ 重建索引(清空后全量重建)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.4 文档问答
|
||||||
|
|
||||||
|
> **用途**:基于任意目录下的文档进行多轮对话问答
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「加载文档」→ 弹出目录选择器
|
||||||
|
2. 逐级导航选择目录(可同时勾选具体文件)
|
||||||
|
3. 点击「确认选择」加载文档
|
||||||
|
4. 直接输入问题开始对话
|
||||||
|
|
||||||
|
**核心特性**:
|
||||||
|
| 特性 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| **无需向量化** | 默认文本模式,加载即用 |
|
||||||
|
| **可选向量化** | 文档量大时点击「向量化」提升检索效率 |
|
||||||
|
| **多轮对话** | 上下文记忆,支持连续追问 |
|
||||||
|
| **对话历史** | 左侧列表保存所有对话,可随时继续 |
|
||||||
|
| **模型选择** | 每次提问可选不同模型 |
|
||||||
|
| **来源引用** | 每次回答标注文档来源 + 模型名 |
|
||||||
|
| **上下文压缩** | 超 20 轮自动摘要压缩 |
|
||||||
|
| **无文档也能聊** | 不加载文档直接纯 LLM 对话 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.5 图片识别
|
||||||
|
|
||||||
|
> **用途**:识别图片中的完整文字内容(Bug 截图/UI 稿/代码截图)
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 上传图片(最多 10 张,单张 ≤ 10MB)
|
||||||
|
2. 可选自定义提示词
|
||||||
|
3. 点击「开始识别」
|
||||||
|
|
||||||
|
**支持类型**:
|
||||||
|
| 图片类型 | 识别效果 |
|
||||||
|
|---|---|
|
||||||
|
| 报错截图 | 完整提取错误信息和堆栈 |
|
||||||
|
| 代码截图 | 逐行提取代码 |
|
||||||
|
| 表格/文档 | 按原格式完整转录 |
|
||||||
|
| UI 界面 | 提取所有可见文字/标签/按钮 |
|
||||||
|
|
||||||
|
**技术**:智谱 GLM-4V-Flash(免费,中文效果好)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.6 提示词优化
|
||||||
|
|
||||||
|
> **用途**:把粗糙的想法润色成高质量 AI 提示词
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 左侧输入粗糙想法/口语化表达
|
||||||
|
2. 点击「优化提示词」
|
||||||
|
3. 右侧查看润色结果 + 改动说明 + 待定问题
|
||||||
|
|
||||||
|
**输出内容**:
|
||||||
|
- 📝 **润色后**:可直接复制的高质量提示词
|
||||||
|
- ✏️ **改了什么**:补了什么、去掉了什么歧义
|
||||||
|
- ❓ **还需要你定**:影响结果的歧义选项
|
||||||
|
|
||||||
|
**核心原则**:保留原意、补全缺失、消除歧义、结构化,不替你做决定。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.7 模型管理
|
||||||
|
|
||||||
|
> **用途**:管理可用的 AI 模型(增删改查)
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
- 「模型管理」Tab → 表格展示所有配置的模型
|
||||||
|
- 「新增模型」→ 填写显示名称/模型 ID/Provider/角色
|
||||||
|
- **启用/停用**:Switch 开关控制是否出现在下拉框
|
||||||
|
- **排序**:控制下拉框顺序
|
||||||
|
|
||||||
|
**默认配置**:
|
||||||
|
| 模型 | Provider | 角色 |
|
||||||
|
|---|---|---|
|
||||||
|
| GLM-5.3 | ccswitch 代理 | 强模型(改码/评估) |
|
||||||
|
| GLM-5.3-Flash | ccswitch 代理 | 弱模型(解析/报告) |
|
||||||
|
| Mimo-v2.6-Pro | ccswitch 代理 | 通用 |
|
||||||
|
| DeepSeek-v4-Pro | ccswitch 代理 | 通用 |
|
||||||
|
| MiniMax-Latest | ccswitch 代理 | 通用 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.8 数据库管理
|
||||||
|
|
||||||
|
> **用途**:连接外部数据库,执行 SQL 增删改查
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 「数据库管理」Tab → 「新增连接」
|
||||||
|
2. 填写类型/主机/端口/库名/用户名/密码
|
||||||
|
3. 点击「测试」验证连接
|
||||||
|
4. 下方 SQL 面板执行查询/修改
|
||||||
|
|
||||||
|
**支持数据库**:MySQL、PostgreSQL、SQLite
|
||||||
|
|
||||||
|
**SQL 面板功能**:
|
||||||
|
- 多标签页 SQL 编辑器(可开多个、可重命名)
|
||||||
|
- 选中 SQL 只执行选中部分
|
||||||
|
- 表结构查询与修改(加列/改列/删列)
|
||||||
|
- 查询结果字段筛选
|
||||||
|
- 导出 CSV
|
||||||
|
- SQL 历史记录
|
||||||
|
- 表名下拉自动列表
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.9 系统配置
|
||||||
|
|
||||||
|
> **用途**:管理 `.env` 配置文件(增删改查 + 备注)
|
||||||
|
|
||||||
|
**两种模式**:
|
||||||
|
| Tab | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| **配置项管理** | 表格展示所有配置,支持搜索/新增/编辑/删除/备注 |
|
||||||
|
| **常用配置(分组编辑)** | 按分组(应用/模型/RAG 等)快速编辑 |
|
||||||
|
|
||||||
|
**安全设计**:敏感字段(API Key)保存时留空 `******` 表示不修改。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.10 日志中心
|
||||||
|
|
||||||
|
> **用途**:查看 Agent 所有操作日志(合规审计 + 问题排查)
|
||||||
|
|
||||||
|
**两种模式**:
|
||||||
|
| 模式 | 场景 | 数据范围 |
|
||||||
|
|---|---|---|
|
||||||
|
| **按日查看** | 合规精查(那天干了什么) | 单日 + 日期选择器 |
|
||||||
|
| **最近 7 天** | 排查问题(哪里出错了) | 跨天关键词全局搜索 |
|
||||||
|
|
||||||
|
**能力**:关键词搜索 + 操作类型过滤 + 统计卡片(操作总数/成功/失败/文件改动)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.11 监控仪表盘
|
||||||
|
|
||||||
|
> **用途**:监控模型调用成本/性能/任务执行统计
|
||||||
|
|
||||||
|
**监控指标**:
|
||||||
|
| 指标 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 模型调用次数 | 按模型分组统计 |
|
||||||
|
| Token 总消耗 | 输入/输出 Token 分别统计 |
|
||||||
|
| 预估成本 | 按模型单价计算(元) |
|
||||||
|
| 平均延迟 | 模型调用平均耗时 |
|
||||||
|
| 成功率 | 按模型统计成功率 |
|
||||||
|
| 任务统计 | 状态分布/平均耗时 |
|
||||||
|
| 系统健康 | 数据库/向量库/模型/Git/磁盘探活 |
|
||||||
|
|
||||||
|
**时间范围**:1 小时 / 6 小时 / 24 小时 / 7 天
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.12 高级工具箱
|
||||||
|
|
||||||
|
> **用途**:长期记忆、备份管理、MCP 工具
|
||||||
|
|
||||||
|
| Tab | 功能 | 用途 |
|
||||||
|
|---|---|---|
|
||||||
|
| **长期记忆** | 记录项目约定/规范/决策 | Agent 越用越准 |
|
||||||
|
| **备份管理** | 手动/自动备份 | 数据安全保障(12 小时自动备份,保留 30 天) |
|
||||||
|
| **MCP 工具** | 查看已注册工具列表 | Agent 插件系统 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. MCP 工具
|
||||||
|
|
||||||
|
MCP(Model Context Protocol)是 Agent 的"插件系统",提供标准化的外部工具调用。
|
||||||
|
|
||||||
|
### 本地可用(9 个,直接调用)
|
||||||
|
|
||||||
|
| 工具 | 功能 | 调用示例 |
|
||||||
|
|---|---|---|
|
||||||
|
| `filesystem` | 文件读/写/列目录/搜索 | `{"action":"list","path":"D:\\Agent"}` |
|
||||||
|
| `web_search` | 网页搜索 | `{"query":"Spring Boot 3 新特性"}` |
|
||||||
|
| `web_fetch` | 抓取网页内容 | `{"url":"https://example.com"}` |
|
||||||
|
| `memory` | 长期记忆存取 | `{"action":"remember","content":"..."}` |
|
||||||
|
| `docker` | Docker 容器管理 | `{"action":"ps"}` |
|
||||||
|
| `health_check` | 系统健康检查 | `{}` |
|
||||||
|
| `git` | Git 操作 | `{"action":"status","repo_path":"D:\\Project"}` |
|
||||||
|
| `zentao` | 禅道 Bug/任务管理 | `{"action":"create_bug","title":"..."}` |
|
||||||
|
| `knowledge_graph` | 知识图谱查询 | 已移除 |
|
||||||
|
|
||||||
|
### 需凭证(5 个)
|
||||||
|
|
||||||
|
| 工具 | 需要凭证 |
|
||||||
|
|---|---|
|
||||||
|
| `github` | GITHUB_TOKEN |
|
||||||
|
| `jira` | JIRA_TOKEN |
|
||||||
|
| `redis` | Redis 连接 |
|
||||||
|
| `database` | 数据库连接 |
|
||||||
|
| `email` | SMTP 凭证 |
|
||||||
|
|
||||||
|
### 调用方式
|
||||||
|
|
||||||
|
```bash
|
||||||
|
POST /api/mcp/call
|
||||||
|
{
|
||||||
|
"name": "git",
|
||||||
|
"arguments": {"action": "log", "repo_path": "D:\\Project\\jetrun_iot"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Agent 在执行任务时会**自动调用**合适的 MCP 工具,无需手动干预。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. API 速查
|
||||||
|
|
||||||
|
| 模块 | 端点 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| **任务** | `POST /api/tasks` | 提交任务 |
|
||||||
|
| | `GET /api/tasks/{id}` | 查询任务 |
|
||||||
|
| | `POST /api/tasks/{id}/stop` | 停止任务 |
|
||||||
|
| | `POST /api/tasks/{id}/approve` | HITL 审批 |
|
||||||
|
| | `POST /api/tasks/{id}/rollback` | 回滚改动 |
|
||||||
|
| **项目** | `POST /api/projects` | 创建项目 |
|
||||||
|
| | `GET /api/projects` | 项目列表(支持 name 搜索) |
|
||||||
|
| **知识库** | `POST /api/knowledge/ingest` | 入库 |
|
||||||
|
| | `POST /api/knowledge/query` | 检索 |
|
||||||
|
| **文档问答** | `POST /api/docqa/index` | 加载文档 |
|
||||||
|
| | `POST /api/docqa/chat` | 对话问答 |
|
||||||
|
| **数据库** | `POST /api/database/connections` | 创建连接 |
|
||||||
|
| | `POST /api/database/connections/{id}/execute` | 执行 SQL |
|
||||||
|
| **MCP** | `POST /api/mcp/call` | 调用工具 |
|
||||||
|
| **监控** | `GET /api/metrics/dashboard` | 仪表盘数据 |
|
||||||
|
| **健康** | `GET /api/health` | 健康检查 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 常见问题
|
||||||
|
|
||||||
|
| 问题 | 解决方案 |
|
||||||
|
|---|---|
|
||||||
|
| 启动报端口占用 | 换端口 `--port 8003`,前端 `vite.config.ts` 同步改 |
|
||||||
|
| 模型调用 401 | 检查 `.env` 中 API Key 是否正确 |
|
||||||
|
| git push 超时 | 配置代理 `git config --global http.proxy http://127.0.0.1:7897` |
|
||||||
|
| 向量化很慢 | 首次需下载嵌入模型(约 90MB),后续有缓存 |
|
||||||
|
| 任务执行很慢 | 检查「监控仪表盘」看模型延迟,可切换更快的模型 |
|
||||||
|
| 数据库连接失败 | 确认已安装 `pymysql`/`psycopg2-binary` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> 📌 本文档由 CodeAgent 系统开发过程中持续沉淀,与代码实现保持一致。
|
||||||
+1679
File diff suppressed because it is too large
Load Diff
+182
@@ -0,0 +1,182 @@
|
|||||||
|
# CodeAgent 项目上下文(新对话启动加载)
|
||||||
|
|
||||||
|
> **用途**:新开 Claude Code 对话时读取此文件,快速了解项目全貌。
|
||||||
|
> **更新日期**:2026-10-23
|
||||||
|
> **配套文档**:`Agent使用文档.md`(详细使用)、`Agent问题排查手册.md`(踩坑知识库)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、项目定位
|
||||||
|
|
||||||
|
**CodeAgent** 是企业级编程智能 Agent 系统,理解自然语言开发需求,自动完成「需求分析 → 代码定位 → 代码修改 → 编译验证 → 问题排查 → 交付报告」完整闭环。
|
||||||
|
|
||||||
|
**硬约束**:
|
||||||
|
1. 所有工程文件/产物/数据存 `D:\Agent`(含缓存/临时文件,零 C 盘占用)
|
||||||
|
2. 核心业务代码必须中文注释(功能/选型理由/思路/风险应对)
|
||||||
|
3. 模块化低耦合高内聚,LangGraph 图结构编排
|
||||||
|
4. 完整错误处理与优雅降级
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、技术架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────┐
|
||||||
|
│ React + AntD 前端(6 组菜单,13 个页面) │
|
||||||
|
├──────────────────────────────────────────┤
|
||||||
|
│ FastAPI 后端(Python 3.13 + SQLite) │
|
||||||
|
├──────────────────────────────────────────┤
|
||||||
|
│ LangGraph 8 节点主图 + Worker 子图 │
|
||||||
|
│ intake → retrieve → plan → gate → │
|
||||||
|
│ human_gate → dispatch → evaluate → finalize │
|
||||||
|
├──────────┬───────────┬──────────────────┤
|
||||||
|
│ 自研工具链 │ RAG 知识库 │ Claude CLI 引擎 │
|
||||||
|
│ file/search│ Chroma │ 直调/Agent 双模式 │
|
||||||
|
│ /executor │ + BGE │ │
|
||||||
|
├──────────┴───────────┴──────────────────┤
|
||||||
|
│ SQLite + Chroma 向量库 + 文件快照 │
|
||||||
|
└──────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 代码位置
|
||||||
|
| 组件 | 路径 |
|
||||||
|
|---|---|
|
||||||
|
| 后端 | `D:\Agent\agent\backend\app\` |
|
||||||
|
| 前端 | `D:\Agent\agent\frontend\src\` |
|
||||||
|
| 测试 | `D:\Agent\agent\backend\tests\`(62 个测试全绿) |
|
||||||
|
| 数据 | `D:\Agent\agent\data\`(SQLite/向量库/快照) |
|
||||||
|
| 项目代码 | `D:\Agent\code\`、`D:\Project\` 等(用户项目) |
|
||||||
|
|
||||||
|
### 关键文件
|
||||||
|
| 文件 | 职责 |
|
||||||
|
|---|---|
|
||||||
|
| `app/graph/state.py` | OrchestratorState/WorkerState 状态契约 |
|
||||||
|
| `app/graph/nodes.py` | 8 节点主图(intake/retrieve/plan/gate/dispatch/evaluate/finalize) |
|
||||||
|
| `app/graph/worker.py` | Worker 子图(locate→modify→verify→repair),引擎分流 |
|
||||||
|
| `app/models/model_router.py` | 模型路由(strong/weak 分工 + FallbackModel 降级链) |
|
||||||
|
| `app/tools/claude_engine.py` | Claude CLI 调用(会话管理/流式输出/进程管理) |
|
||||||
|
| `app/tasks/task_service.py` | 任务执行(create_and_run/_run_direct_claude/_run_graph) |
|
||||||
|
| `app/tasks/task_store.py` | SQLite 存储(状态机/chat_history/session_id) |
|
||||||
|
| `frontend/src/App.tsx` | 全局布局(6 组菜单)+ 全局登录过期检测 |
|
||||||
|
| `frontend/src/pages/TaskCenter.tsx` | 任务中心(对话式交互核心页面) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、核心机制速查
|
||||||
|
|
||||||
|
### 3.1 直调模式(对话式交互)
|
||||||
|
- **会话管理**:`--session-id`(首轮)/ `--resume`(续聊),Claude 自己管上下文
|
||||||
|
- **prompt 传递**:通过 **STDIN** 写入(不是命令行参数!多行中文会被截断)
|
||||||
|
- **流式输出**:`--output-format stream-json` + `--verbose`,逐行解析 delta.text
|
||||||
|
- **模型选择**:`_normalize_model_id()` 提取 model_id(`provider_key/model_id` → `model_id`)
|
||||||
|
- **配置隔离**:`CLAUDE_CONFIG_DIR` 指向临时目录,继承连接信息、替换模型
|
||||||
|
|
||||||
|
### 3.2 任务状态机
|
||||||
|
```
|
||||||
|
running → waiting_approval | done | failed | degraded
|
||||||
|
waiting_approval → running | failed | degraded
|
||||||
|
done → degraded | running (续聊可重新激活)
|
||||||
|
failed → done | degraded | running (降级链翻盘)
|
||||||
|
degraded → done | running
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 并发安全
|
||||||
|
- `_running_tasks` 集合:内存锁,防 TOCTOU 双跑
|
||||||
|
- `_running_processes` 字典:进程注册表,stop 时 kill
|
||||||
|
- `_event_buffer` 字典:SSE 启动前事件缓冲,subscribe 时回放
|
||||||
|
- 三路清理:`finally` 块 + `delete_task` + `stop_task`
|
||||||
|
|
||||||
|
### 3.4 前端对话框
|
||||||
|
- 一条任务 = 一个完整对话(`chat_history` 存 JSON 数组)
|
||||||
|
- SSE 流式展示(`claude_output` 事件逐字追加)
|
||||||
|
- `done` 时拉取完整 `chat_history` 兜底(防流式事件丢失)
|
||||||
|
- `react-markdown` 渲染完整回复(流式中用 pre-wrap 平铺)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、当前状态
|
||||||
|
|
||||||
|
### 已完成
|
||||||
|
- ✅ M1-M6 六个里程碑(62 测试全绿)
|
||||||
|
- ✅ 对话式交互(新建需求对话框、续聊、模型切换)
|
||||||
|
- ✅ 双执行模式(Agent 编排 + 直调 Claude CLI)
|
||||||
|
- ✅ 多项目多服务管理(后端/前端服务 + 分支)
|
||||||
|
- ✅ 全局菜单 6 组布局
|
||||||
|
- ✅ 平台账号管理(Playwright 抓取/定时任务/登录过期检测)
|
||||||
|
- ✅ 12 轮第一性原理排查(25+ bug 修复,详见排查手册)
|
||||||
|
|
||||||
|
### 已知待优化
|
||||||
|
- Checkpointer 持久化(InMemorySaver → AsyncSqliteSaver)
|
||||||
|
- 前端浏览器实机交互验证未做
|
||||||
|
- 多任务并发压测未做
|
||||||
|
- Agent 使用文档和排查手册需持续更新
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、开发规范
|
||||||
|
|
||||||
|
### 代码风格
|
||||||
|
- Python:中文注释(功能/选型理由/思路/风险应对),类型注解
|
||||||
|
- TypeScript:中文注释,AntD 组件优先
|
||||||
|
- 测试:后端 pytest(`./.venv/Scripts/python.exe -m pytest tests/`)
|
||||||
|
- 前端:`npx tsc -b` + `npx vite build` 验证
|
||||||
|
|
||||||
|
### 提交前验证
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd D:/Agent/agent/backend && ./.venv/Scripts/python.exe -m pytest tests/ -q --tb=line
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd D:/Agent/agent/frontend && npx tsc -b --pretty false && npx vite build
|
||||||
|
```
|
||||||
|
|
||||||
|
### 安全约束
|
||||||
|
- `.env` 在 `.gitignore`,禁止入库
|
||||||
|
- 路径守卫:读取放行任意本地路径,写入限定 D 盘白名单
|
||||||
|
- API Key 不在对话中暴露
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、12 轮排查总结(25 个 bug 的根因模式)
|
||||||
|
|
||||||
|
| 根因模式 | 数量 | 典型案例 |
|
||||||
|
|---|---|---|
|
||||||
|
| 路径不对称(加了没释放/建了没关闭) | 8 | 进程泄漏、锁不释放、SSE 残留 |
|
||||||
|
| 边界条件遗漏(空值/异常/竞态) | 7 | UUID 格式、TOCTOU、resume 死循环 |
|
||||||
|
| 数据类型不匹配(对象当 dict/数组当 JSON) | 4 | Pydantic 对象解析、parseServices |
|
||||||
|
| 信号路由错误(丢/重复/串台) | 3 | error 吞掉、文本重复、会话串台 |
|
||||||
|
| 状态残留(跨操作不清理) | 3 | chatStreaming、chatModel、缓冲泄漏 |
|
||||||
|
|
||||||
|
**第一性原理核心结论**:25 个 bug 的共同根因是**边界条件下的路径不对称**——加锁没释放、建连接没关闭、存数据没清理、改状态没保护。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、快速启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd D:/Agent/agent/backend
|
||||||
|
./.venv/Scripts/python.exe -m uvicorn app.main:app --host 0.0.0.0 --port 8317
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd D:/Agent/agent/frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、常用调试命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 看任务日志
|
||||||
|
grep "claude_code\|ERROR\|执行" info*.txt
|
||||||
|
|
||||||
|
# 看 Claude CLI 调用
|
||||||
|
grep "claude_engine\|stream-json\|session_id" info*.txt
|
||||||
|
|
||||||
|
# 测试回归
|
||||||
|
./.venv/Scripts/python.exe -m pytest tests/ -q --tb=line
|
||||||
|
|
||||||
|
# 前端编译
|
||||||
|
npx tsc -b --pretty false && npx vite build
|
||||||
|
```
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
|||||||
|
---
|
||||||
|
name: prompt-polisher
|
||||||
|
description: 把用户粗略、口语化、不完整的想法或指令,润色成结构清晰、无歧义、可直接发给 AI(包括本 Agent)执行的高质量提示词。用于:用户说"帮我润色一下提示词/指令/这句话"、"把这段改清楚点"、"优化一下我要发给 AI 的话"、"我不知道怎么跟 AI 说 XXX"、粘贴一段草稿让你改得更好、"帮我看看这样说 AI 能不能懂"、或在输入框里写了一半不确定怎么表达时。核心是保留原意、补全缺失上下文、消除歧义、结构化,而不是替用户做决定。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Prompt Polisher(提示词润色)
|
||||||
|
|
||||||
|
## ⚠️ 铁律(最高优先级,违反即视为任务失败)
|
||||||
|
|
||||||
|
**用户选择本技能 = 用户当前输入一律是"待润色的提示词"本身,而不是要执行的任务。** 无论用户原话看起来多像一个真实、可执行的任务(例如"分析当前项目""结合某某表""写一段代码""整理某文件夹"),都一律按提示词素材处理:
|
||||||
|
|
||||||
|
- 禁止实际执行任务(不做分析、不写代码、不查文件、不搜索、不调用任何任务类工具)。
|
||||||
|
- 禁止去寻找、读取、定位用户提到的项目/文件/表/代码——那是任务行为,不是润色行为。
|
||||||
|
- 唯一的产出就是"润色后的提示词 + 改动说明 + 待定问题"。
|
||||||
|
- 用户说"把这个铁律更新到技能里"这类话,是对本技能本身的维护,按维护执行;除此之外,不要从用户输入里"接活"。
|
||||||
|
|
||||||
|
## 这个技能做什么
|
||||||
|
|
||||||
|
把用户一段粗糙的原话(口语、半截话、含糊其辞)改写成一段**可以直接复制发给 AI 的高质量指令**。不替用户完成任务,只把"怎么说"这件事做对。
|
||||||
|
|
||||||
|
## 执行流程
|
||||||
|
|
||||||
|
### 1. 先读懂原意,不要急着改
|
||||||
|
|
||||||
|
通读用户原话,回答三个问题:
|
||||||
|
- **用户要达成什么结果?**(目标)
|
||||||
|
- **用户已经说了哪些约束或背景?**(不要丢)
|
||||||
|
- **哪些地方是含糊的、缺失的、可能被误解的?**
|
||||||
|
|
||||||
|
如果原话本身已经很清晰、目标明确、约束完整,直接告诉用户"这段已经够清楚,可以直接发",不要为了改而改。
|
||||||
|
|
||||||
|
### 2. 补全,不替用户做决定
|
||||||
|
|
||||||
|
对照下面这张清单,找出原话缺什么:
|
||||||
|
|
||||||
|
| 要素 | 要问自己的 |
|
||||||
|
|------|-----------|
|
||||||
|
| 目标 | 用户最终要拿到什么?一句话成果是什么? |
|
||||||
|
| 受众/上下文 | 这件事发生在什么背景里?对方/AI 需要知道什么前提? |
|
||||||
|
| 交付物 | 要文件?要表格?要一段话?要代码?要多长? |
|
||||||
|
| 约束 | 有什么不能碰的、必须保留的、格式要求? |
|
||||||
|
| 语气/风格 | 正式?口语?中文?英文? |
|
||||||
|
|
||||||
|
- **能从原话合理推断的**,直接补进去,并在"改动说明"里标注是你补的。
|
||||||
|
- **真正影响结果的歧义**(比如要 A 还是要 B 会走向完全不同的产物),不要自己选,列出 2–3 个选项让用户挑。
|
||||||
|
- **无关紧要的细节**,不要追问,按常理处理。
|
||||||
|
|
||||||
|
### 3. 改写原则
|
||||||
|
|
||||||
|
- **保留原意**:不夸大、不缩小、不加入用户没说的要求。
|
||||||
|
- **消除指代**:把"那个东西""它""这个""随便弄弄"换成具体描述。
|
||||||
|
- **结构化**:复杂任务拆成"目标 → 背景 → 具体要求 → 交付物 → 约束"几块,用小标题或编号,而不是一大段流水账。
|
||||||
|
- **可执行**:每一条要求都是 AI 能照着做的,而不是"做得好一点""看着办"。
|
||||||
|
- **不堆叠形容词**:删掉"非常""很""务必"这类空话,换成具体标准。
|
||||||
|
- **语言与用户原话一致**:用户用中文就输出中文,用英文就输出英文;不要擅自翻译。
|
||||||
|
|
||||||
|
### 4. 输出格式
|
||||||
|
|
||||||
|
按下面这个结构回复,不要加多余的寒暄:
|
||||||
|
|
||||||
|
```
|
||||||
|
【润色后】
|
||||||
|
(这里放可以直接复制的提示词,用代码块或引用块包裹,方便复制)
|
||||||
|
|
||||||
|
【改了什么】
|
||||||
|
- 补了什么(1–3 条)
|
||||||
|
- 去掉了什么歧义
|
||||||
|
- 哪几处是我替你假设的,请确认
|
||||||
|
|
||||||
|
【还需要你定】(如果有)
|
||||||
|
- 问题 1:选项 A / 选项 B
|
||||||
|
- 问题 2:……
|
||||||
|
```
|
||||||
|
|
||||||
|
如果没有需要用户定的歧义,最后一段可以省略。
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
**用户原话:**
|
||||||
|
"帮我弄个周报,把这周做的事整理一下,老板想看。"
|
||||||
|
|
||||||
|
**润色后:**
|
||||||
|
```
|
||||||
|
请帮我整理一份本周工作周报,面向我的直属老板。
|
||||||
|
|
||||||
|
要求:
|
||||||
|
1. 按"本周完成 / 进行中 / 下周计划"三段组织。
|
||||||
|
2. 每段用要点列表,每条一句话说清做了什么、结果是什么。
|
||||||
|
3. 如果我贴的素材里有项目名、数字、节点,原样保留,不要编造。
|
||||||
|
4. 整体控制在 300 字以内,语气正式但不客套。
|
||||||
|
5. 输出为纯文本,不要加封面、不要加图表。
|
||||||
|
```
|
||||||
|
|
||||||
|
**改了什么:**
|
||||||
|
- 补了受众(直属老板)和结构(三段式)。
|
||||||
|
- 把"整理一下"具体成"每条一句话、说清结果"。
|
||||||
|
- 加了"不要编造"和字数上限,防止 AI 自由发挥。
|
||||||
|
|
||||||
|
## 不要做的事
|
||||||
|
|
||||||
|
- **不要真的去执行那个任务(写周报、写代码、做分析、查文件、找项目)——你只负责把"指令"改好。** 这是铁律,见文首;哪怕用户原话就是"帮我分析项目 X"这类,也先按提示词素材润色,不要动手执行。
|
||||||
|
- 不要把一段话改成长篇大论的"教科书式提示词"(加一堆 role、step-by-step、chain-of-thought),用户要的是能用,不是炫技。
|
||||||
|
- 不要在润色后还保留口语化的模糊词。
|
||||||
|
- 不要假设用户要英文——除非他原话就是英文或明确要求。
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# ============================================================
|
||||||
|
# CodeAgent 项目 .gitignore
|
||||||
|
# 排除:密钥、虚拟环境、依赖包、运行数据、IDE 配置
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
# ---------- 敏感信息(严禁入库)----------
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
|
||||||
|
# ---------- Python ----------
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.Python
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
*.egg-info/
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# ---------- Node / 前端 ----------
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.vite/
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# ---------- IDE ----------
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.iml
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# ---------- 运行数据 ----------
|
||||||
|
data/
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
*.sqlite3
|
||||||
|
|
||||||
|
# ---------- 日志 ----------
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
audit-*.jsonl
|
||||||
|
|
||||||
|
# ---------- 系统文件 ----------
|
||||||
|
Thumbs.db
|
||||||
|
.DS_Store
|
||||||
|
Desktop.ini
|
||||||
|
|
||||||
|
# ---------- 临时文件 ----------
|
||||||
|
*.tmp
|
||||||
|
*.bak
|
||||||
|
*.orig
|
||||||
|
.cache/
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
# CodeAgent 编程智能 Agent 系统 — 完整使用文档
|
||||||
|
|
||||||
|
> 版本:v1.0 | 更新日期:2026-10-19
|
||||||
|
> 仓库地址:https://github.com/SweetieHenry/CodeAgent.git
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
1. [系统概述](#1-系统概述)
|
||||||
|
2. [环境准备与启动](#2-环境准备与启动)
|
||||||
|
3. [核心功能模块](#3-核心功能模块)
|
||||||
|
- 3.1 [任务中心](#31-任务中心)
|
||||||
|
- 3.2 [项目管理](#32-项目管理)
|
||||||
|
- 3.3 [知识库管理](#33-知识库管理)
|
||||||
|
- 3.4 [文档问答](#34-文档问答)
|
||||||
|
- 3.5 [图片识别](#35-图片识别)
|
||||||
|
- 3.6 [提示词优化](#36-提示词优化)
|
||||||
|
- 3.7 [模型管理](#37-模型管理)
|
||||||
|
- 3.8 [数据库管理](#38-数据库管理)
|
||||||
|
- 3.9 [系统配置](#39-系统配置)
|
||||||
|
- 3.10 [日志中心](#310-日志中心)
|
||||||
|
- 3.11 [监控仪表盘](#311-监控仪表盘)
|
||||||
|
- 3.12 [高级工具箱](#312-高级工具箱)
|
||||||
|
4. [MCP 工具](#4-mcp-工具)
|
||||||
|
5. [API 速查](#5-api-速查)
|
||||||
|
6. [常见问题](#6-常见问题)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 系统概述
|
||||||
|
|
||||||
|
CodeAgent 是一个**企业级编程智能 Agent 系统**,能够理解自然语言开发需求,自动完成「需求分析 → 代码定位 → 代码修改 → 编译验证 → 问题排查 → 交付报告」的完整闭环。
|
||||||
|
|
||||||
|
### 技术架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ React + AntD 前端(13 个功能页面) │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ FastAPI 后端(71 条 API) │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ LangGraph 编排引擎(8 节点主图 + Worker)│
|
||||||
|
├──────────┬──────────┬───────────────────┤
|
||||||
|
│ 自研工具链 │ RAG 知识库 │ MCP 工具(13个) │
|
||||||
|
├──────────┴──────────┴───────────────────┤
|
||||||
|
│ SQLite + Chroma + 文件系统 │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 核心能力
|
||||||
|
|
||||||
|
| 能力 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 🤖 **智能改码** | 自然语言需求 → 自动定位/修改代码 → 编译验证 |
|
||||||
|
| 📚 **知识库** | 文档向量化 + 智能检索(616+ 文本块) |
|
||||||
|
| 💬 **文档问答** | 任意目录文档 → 多轮对话式问答 |
|
||||||
|
| 🖼️ **图片识别** | GLM-4V-Flash 免费图片内容识别 |
|
||||||
|
| ✍️ **提示词优化** | 粗糙想法 → 高质量 AI 提示词 |
|
||||||
|
| 🗄️ **数据库管理** | MySQL/PG/SQLite 连接 + SQL CRUD |
|
||||||
|
| 📊 **监控仪表盘** | Token 成本/延迟/成功率实时监控 |
|
||||||
|
| 🔧 **MCP 工具** | 文件/搜索/Docker/禅道/Git 等 13 个工具 |
|
||||||
|
| 🛡️ **安全审计** | 全操作审计 + 回滚 + 分级审批 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 环境准备与启动
|
||||||
|
|
||||||
|
### 2.1 环境要求
|
||||||
|
|
||||||
|
| 软件 | 版本要求 | 用途 |
|
||||||
|
|---|---|---|
|
||||||
|
| Python | 3.13+ | 后端运行 |
|
||||||
|
| Node.js | 22+ | 前端构建 |
|
||||||
|
| Git | 2.5+ | 版本管理 |
|
||||||
|
| Java + Maven | 21 / 3.9+ | 目标项目编译验证 |
|
||||||
|
|
||||||
|
### 2.2 启动后端
|
||||||
|
|
||||||
|
后端有**两种启动方式**,按场景二选一——它们是互斥的,别混用:
|
||||||
|
|
||||||
|
| 场景 | 命令 | 是否热重载 |
|
||||||
|
|---|---|---|
|
||||||
|
| **跑改码任务 / 长任务**(日常使用) | `start_backend.ps1` | ❌ 关闭 |
|
||||||
|
| **改后端代码、要保存即生效** | `start_backend.dev.ps1` | ✅ 开启(只监听 `app/`) |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd D:\Agent\agent\backend
|
||||||
|
|
||||||
|
# 场景 A:跑任务(推荐默认,任务不会被打断)
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\start_backend.ps1
|
||||||
|
|
||||||
|
# 场景 B:改代码开发调试
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\start_backend.dev.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
> **⚠️ 为什么必须这样区分**
|
||||||
|
>
|
||||||
|
> Claude 干活会**写文件**(临时脚本、改源码)。如果后端开着 `--reload` 热重载,
|
||||||
|
> 一旦 Claude 写到被监听的目录,WatchFiles 就会自动重启后端进程,
|
||||||
|
> 正在执行的任务当场被杀,表现为对话「突然失败」,日志出现:
|
||||||
|
>
|
||||||
|
> ```
|
||||||
|
> WARNING: WatchFiles detected changes in '...'. Reloading...
|
||||||
|
> ERROR: ASGI callable returned without completing response.
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> **`--reload` 与「跑改码任务」结构上互斥**,不是调参能解决的。
|
||||||
|
> 跑任务请一律用 `start_backend.ps1`(无 reload)。
|
||||||
|
>
|
||||||
|
> 另外:从 **v0.2 起任务由独立 worker 进程执行**,即使后端重启也不会丢任务;
|
||||||
|
> 但流式推送仍走后端 SSE,跑任务时关掉 reload 体验才是完整的。
|
||||||
|
|
||||||
|
### 2.3 启动前端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd D:\Agent\agent\frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 访问系统
|
||||||
|
|
||||||
|
浏览器打开:**http://localhost:5173**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 核心功能模块
|
||||||
|
|
||||||
|
### 3.1 任务中心
|
||||||
|
|
||||||
|
> **用途**:提交开发/修复需求,Agent 自动执行改码闭环
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「提交需求」按钮
|
||||||
|
2. 选择**所属项目** → 选择**后端服务 / 前端服务**
|
||||||
|
3. 选择**任务类型**(新功能/Bug 修复)
|
||||||
|
4. 选择**模型偏好**(自动 / 指定模型)
|
||||||
|
5. 选择**快速模板**(可选,自动填充需求描述)
|
||||||
|
6. 输入**需求描述**(自然语言,可附截图)
|
||||||
|
7. 点击「提交」
|
||||||
|
|
||||||
|
**执行流程**:
|
||||||
|
```
|
||||||
|
需求解析(弱模型) → 知识检索 → 任务规划(强模型) → 风险判定
|
||||||
|
→ [高风险] 人工审批 → 任务分发 → Worker 并行改码 → 编译验证
|
||||||
|
→ 结果评估 → 交付报告
|
||||||
|
```
|
||||||
|
|
||||||
|
**高级功能**:
|
||||||
|
- **批量提交**:一次提交多条需求并行执行
|
||||||
|
- **任务排序**:上下箭头调整任务列表顺序
|
||||||
|
- **手动停止**:执行中任务可强制停止
|
||||||
|
- **一键回滚**:改坏的代码一键还原
|
||||||
|
- **HITL 审批**:高风险操作需人工确认后继续
|
||||||
|
|
||||||
|
**任务状态说明**:
|
||||||
|
| 状态 | 含义 |
|
||||||
|
|---|---|
|
||||||
|
| 🟢 执行中 | Agent 正在改码 |
|
||||||
|
| 🟡 待审批 | 高风险任务等待人工确认 |
|
||||||
|
| ✅ 已完成 | 改码 + 编译验证通过 |
|
||||||
|
| ❌ 失败 | 异常终止(可查看错误详情) |
|
||||||
|
| ⚠️ 降级完成 | 部分步骤失败但已收口 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.2 项目管理
|
||||||
|
|
||||||
|
> **用途**:登记待开发/维护的项目信息,供任务提交时选择
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「新建项目」
|
||||||
|
2. 填写项目名称、代码根路径(必须 D 盘)
|
||||||
|
3. 添加**后端服务**(名称 + 路径 + 分支),可添加多个
|
||||||
|
4. 添加**前端服务**(名称 + 路径 + 分支),可添加多个
|
||||||
|
5. 保存
|
||||||
|
|
||||||
|
**支持能力**:
|
||||||
|
- ✅ 多后端/多前端服务管理(一个项目下多个服务)
|
||||||
|
- ✅ Git 分支下拉选择(自动读取仓库分支列表)
|
||||||
|
- ✅ 按项目名称搜索
|
||||||
|
- ✅ 上下箭头调整项目排序
|
||||||
|
- ✅ 分页展示(可调每页条数)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.3 知识库管理
|
||||||
|
|
||||||
|
> **用途**:管理项目文档知识库,供 Agent 改码时智能检索
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「入库(选择文档)」
|
||||||
|
2. 在弹窗中勾选要入库的文档(支持 md/docx/pdf/txt/csv/log)
|
||||||
|
3. 点击「向量化选中项」
|
||||||
|
|
||||||
|
**检索**:输入自然语言问题,返回相关文档片段(含来源和相关度)
|
||||||
|
|
||||||
|
**知识库特性**:
|
||||||
|
- ✅ 按 source 替换(重复入库不产生重复数据)
|
||||||
|
- ✅ 支持目录递归扫描
|
||||||
|
- ✅ 中文嵌入模型(bge-small-zh,命中率 6/6)
|
||||||
|
- ✅ 重建索引(清空后全量重建)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.4 文档问答
|
||||||
|
|
||||||
|
> **用途**:基于任意目录下的文档进行多轮对话问答
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 点击「加载文档」→ 弹出目录选择器
|
||||||
|
2. 逐级导航选择目录(可同时勾选具体文件)
|
||||||
|
3. 点击「确认选择」加载文档
|
||||||
|
4. 直接输入问题开始对话
|
||||||
|
|
||||||
|
**核心特性**:
|
||||||
|
| 特性 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| **无需向量化** | 默认文本模式,加载即用 |
|
||||||
|
| **可选向量化** | 文档量大时点击「向量化」提升检索效率 |
|
||||||
|
| **多轮对话** | 上下文记忆,支持连续追问 |
|
||||||
|
| **对话历史** | 左侧列表保存所有对话,可随时继续 |
|
||||||
|
| **模型选择** | 每次提问可选不同模型 |
|
||||||
|
| **来源引用** | 每次回答标注文档来源 + 模型名 |
|
||||||
|
| **上下文压缩** | 超 20 轮自动摘要压缩 |
|
||||||
|
| **无文档也能聊** | 不加载文档直接纯 LLM 对话 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.5 图片识别
|
||||||
|
|
||||||
|
> **用途**:识别图片中的完整文字内容(Bug 截图/UI 稿/代码截图)
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 上传图片(最多 10 张,单张 ≤ 10MB)
|
||||||
|
2. 可选自定义提示词
|
||||||
|
3. 点击「开始识别」
|
||||||
|
|
||||||
|
**支持类型**:
|
||||||
|
| 图片类型 | 识别效果 |
|
||||||
|
|---|---|
|
||||||
|
| 报错截图 | 完整提取错误信息和堆栈 |
|
||||||
|
| 代码截图 | 逐行提取代码 |
|
||||||
|
| 表格/文档 | 按原格式完整转录 |
|
||||||
|
| UI 界面 | 提取所有可见文字/标签/按钮 |
|
||||||
|
|
||||||
|
**技术**:智谱 GLM-4V-Flash(免费,中文效果好)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.6 提示词优化
|
||||||
|
|
||||||
|
> **用途**:把粗糙的想法润色成高质量 AI 提示词
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 左侧输入粗糙想法/口语化表达
|
||||||
|
2. 点击「优化提示词」
|
||||||
|
3. 右侧查看润色结果 + 改动说明 + 待定问题
|
||||||
|
|
||||||
|
**输出内容**:
|
||||||
|
- 📝 **润色后**:可直接复制的高质量提示词
|
||||||
|
- ✏️ **改了什么**:补了什么、去掉了什么歧义
|
||||||
|
- ❓ **还需要你定**:影响结果的歧义选项
|
||||||
|
|
||||||
|
**核心原则**:保留原意、补全缺失、消除歧义、结构化,不替你做决定。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.7 模型管理
|
||||||
|
|
||||||
|
> **用途**:管理可用的 AI 模型(增删改查)
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
- 「模型管理」Tab → 表格展示所有配置的模型
|
||||||
|
- 「新增模型」→ 填写显示名称/模型 ID/Provider/角色
|
||||||
|
- **启用/停用**:Switch 开关控制是否出现在下拉框
|
||||||
|
- **排序**:控制下拉框顺序
|
||||||
|
|
||||||
|
**默认配置**:
|
||||||
|
| 模型 | Provider | 角色 |
|
||||||
|
|---|---|---|
|
||||||
|
| GLM-5.3 | ccswitch 代理 | 强模型(改码/评估) |
|
||||||
|
| GLM-5.3-Flash | ccswitch 代理 | 弱模型(解析/报告) |
|
||||||
|
| Mimo-v2.6-Pro | ccswitch 代理 | 通用 |
|
||||||
|
| DeepSeek-v4-Pro | ccswitch 代理 | 通用 |
|
||||||
|
| MiniMax-Latest | ccswitch 代理 | 通用 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.8 数据库管理
|
||||||
|
|
||||||
|
> **用途**:连接外部数据库,执行 SQL 增删改查
|
||||||
|
|
||||||
|
**操作流程**:
|
||||||
|
|
||||||
|
1. 「数据库管理」Tab → 「新增连接」
|
||||||
|
2. 填写类型/主机/端口/库名/用户名/密码
|
||||||
|
3. 点击「测试」验证连接
|
||||||
|
4. 下方 SQL 面板执行查询/修改
|
||||||
|
|
||||||
|
**支持数据库**:MySQL、PostgreSQL、SQLite
|
||||||
|
|
||||||
|
**SQL 面板功能**:
|
||||||
|
- 多标签页 SQL 编辑器(可开多个、可重命名)
|
||||||
|
- 选中 SQL 只执行选中部分
|
||||||
|
- 表结构查询与修改(加列/改列/删列)
|
||||||
|
- 查询结果字段筛选
|
||||||
|
- 导出 CSV
|
||||||
|
- SQL 历史记录
|
||||||
|
- 表名下拉自动列表
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.9 系统配置
|
||||||
|
|
||||||
|
> **用途**:管理 `.env` 配置文件(增删改查 + 备注)
|
||||||
|
|
||||||
|
**两种模式**:
|
||||||
|
| Tab | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| **配置项管理** | 表格展示所有配置,支持搜索/新增/编辑/删除/备注 |
|
||||||
|
| **常用配置(分组编辑)** | 按分组(应用/模型/RAG 等)快速编辑 |
|
||||||
|
|
||||||
|
**安全设计**:敏感字段(API Key)保存时留空 `******` 表示不修改。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.10 日志中心
|
||||||
|
|
||||||
|
> **用途**:查看 Agent 所有操作日志(合规审计 + 问题排查)
|
||||||
|
|
||||||
|
**两种模式**:
|
||||||
|
| 模式 | 场景 | 数据范围 |
|
||||||
|
|---|---|---|
|
||||||
|
| **按日查看** | 合规精查(那天干了什么) | 单日 + 日期选择器 |
|
||||||
|
| **最近 7 天** | 排查问题(哪里出错了) | 跨天关键词全局搜索 |
|
||||||
|
|
||||||
|
**能力**:关键词搜索 + 操作类型过滤 + 统计卡片(操作总数/成功/失败/文件改动)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.11 监控仪表盘
|
||||||
|
|
||||||
|
> **用途**:监控模型调用成本/性能/任务执行统计
|
||||||
|
|
||||||
|
**监控指标**:
|
||||||
|
| 指标 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 模型调用次数 | 按模型分组统计 |
|
||||||
|
| Token 总消耗 | 输入/输出 Token 分别统计 |
|
||||||
|
| 预估成本 | 按模型单价计算(元) |
|
||||||
|
| 平均延迟 | 模型调用平均耗时 |
|
||||||
|
| 成功率 | 按模型统计成功率 |
|
||||||
|
| 任务统计 | 状态分布/平均耗时 |
|
||||||
|
| 系统健康 | 数据库/向量库/模型/Git/磁盘探活 |
|
||||||
|
|
||||||
|
**时间范围**:1 小时 / 6 小时 / 24 小时 / 7 天
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.12 高级工具箱
|
||||||
|
|
||||||
|
> **用途**:长期记忆、备份管理、MCP 工具
|
||||||
|
|
||||||
|
| Tab | 功能 | 用途 |
|
||||||
|
|---|---|---|
|
||||||
|
| **长期记忆** | 记录项目约定/规范/决策 | Agent 越用越准 |
|
||||||
|
| **备份管理** | 手动/自动备份 | 数据安全保障(12 小时自动备份,保留 30 天) |
|
||||||
|
| **MCP 工具** | 查看已注册工具列表 | Agent 插件系统 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. MCP 工具
|
||||||
|
|
||||||
|
MCP(Model Context Protocol)是 Agent 的"插件系统",提供标准化的外部工具调用。
|
||||||
|
|
||||||
|
### 本地可用(9 个,直接调用)
|
||||||
|
|
||||||
|
| 工具 | 功能 | 调用示例 |
|
||||||
|
|---|---|---|
|
||||||
|
| `filesystem` | 文件读/写/列目录/搜索 | `{"action":"list","path":"D:\\Agent"}` |
|
||||||
|
| `web_search` | 网页搜索 | `{"query":"Spring Boot 3 新特性"}` |
|
||||||
|
| `web_fetch` | 抓取网页内容 | `{"url":"https://example.com"}` |
|
||||||
|
| `memory` | 长期记忆存取 | `{"action":"remember","content":"..."}` |
|
||||||
|
| `docker` | Docker 容器管理 | `{"action":"ps"}` |
|
||||||
|
| `health_check` | 系统健康检查 | `{}` |
|
||||||
|
| `git` | Git 操作 | `{"action":"status","repo_path":"D:\\Project"}` |
|
||||||
|
| `zentao` | 禅道 Bug/任务管理 | `{"action":"create_bug","title":"..."}` |
|
||||||
|
| `knowledge_graph` | 知识图谱查询 | 已移除 |
|
||||||
|
|
||||||
|
### 需凭证(5 个)
|
||||||
|
|
||||||
|
| 工具 | 需要凭证 |
|
||||||
|
|---|---|
|
||||||
|
| `github` | GITHUB_TOKEN |
|
||||||
|
| `jira` | JIRA_TOKEN |
|
||||||
|
| `redis` | Redis 连接 |
|
||||||
|
| `database` | 数据库连接 |
|
||||||
|
| `email` | SMTP 凭证 |
|
||||||
|
|
||||||
|
### 调用方式
|
||||||
|
|
||||||
|
```bash
|
||||||
|
POST /api/mcp/call
|
||||||
|
{
|
||||||
|
"name": "git",
|
||||||
|
"arguments": {"action": "log", "repo_path": "D:\\Project\\jetrun_iot"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Agent 在执行任务时会**自动调用**合适的 MCP 工具,无需手动干预。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. API 速查
|
||||||
|
|
||||||
|
| 模块 | 端点 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| **任务** | `POST /api/tasks` | 提交任务 |
|
||||||
|
| | `GET /api/tasks/{id}` | 查询任务 |
|
||||||
|
| | `POST /api/tasks/{id}/stop` | 停止任务 |
|
||||||
|
| | `POST /api/tasks/{id}/approve` | HITL 审批 |
|
||||||
|
| | `POST /api/tasks/{id}/rollback` | 回滚改动 |
|
||||||
|
| **项目** | `POST /api/projects` | 创建项目 |
|
||||||
|
| | `GET /api/projects` | 项目列表(支持 name 搜索) |
|
||||||
|
| **知识库** | `POST /api/knowledge/ingest` | 入库 |
|
||||||
|
| | `POST /api/knowledge/query` | 检索 |
|
||||||
|
| **文档问答** | `POST /api/docqa/index` | 加载文档 |
|
||||||
|
| | `POST /api/docqa/chat` | 对话问答 |
|
||||||
|
| **数据库** | `POST /api/database/connections` | 创建连接 |
|
||||||
|
| | `POST /api/database/connections/{id}/execute` | 执行 SQL |
|
||||||
|
| **MCP** | `POST /api/mcp/call` | 调用工具 |
|
||||||
|
| **监控** | `GET /api/metrics/dashboard` | 仪表盘数据 |
|
||||||
|
| **健康** | `GET /api/health` | 健康检查 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 常见问题
|
||||||
|
|
||||||
|
| 问题 | 解决方案 |
|
||||||
|
|---|---|
|
||||||
|
| 启动报端口占用 | 换端口 `--port 8003`,前端 `vite.config.ts` 同步改 |
|
||||||
|
| 模型调用 401 | 检查 `.env` 中 API Key 是否正确 |
|
||||||
|
| git push 超时 | 配置代理 `git config --global http.proxy http://127.0.0.1:7897` |
|
||||||
|
| 向量化很慢 | 首次需下载嵌入模型(约 90MB),后续有缓存 |
|
||||||
|
| 任务执行很慢 | 检查「监控仪表盘」看模型延迟,可切换更快的模型 |
|
||||||
|
| 数据库连接失败 | 确认已安装 `pymysql`/`psycopg2-binary` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> 📌 本文档由 CodeAgent 系统开发过程中持续沉淀,与代码实现保持一致。
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# ============================================================
|
||||||
|
# 编程智能 Agent 系统 —— 环境配置模板
|
||||||
|
# 使用方法:复制本文件为 .env,填入真实值
|
||||||
|
# 安全提醒:.env 已被 .gitignore 排除,禁止提交到任何版本库
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
# ---------- 应用基础 ----------
|
||||||
|
APP_NAME=编程智能 Agent 系统
|
||||||
|
APP_HOST=127.0.0.1
|
||||||
|
APP_PORT=8000
|
||||||
|
|
||||||
|
# ---------- 路径(硬约束 6:必须在 D 盘)----------
|
||||||
|
DATA_ROOT=D:\Agent\agent\data
|
||||||
|
CODE_ROOT=D:\Agent\code
|
||||||
|
PROJECT_ROOT=D:\Agent
|
||||||
|
|
||||||
|
# ---------- 模型服务(决策点 4:双模型路由,OpenAI 兼容口)----------
|
||||||
|
# 注意:真实密钥只写在 .env,禁止写入代码或提交到版本库
|
||||||
|
OPENAI_BASE_URL=https://token-plan-cn.xiaomimimo.com/v1
|
||||||
|
OPENAI_API_KEY=在这里填入你的密钥
|
||||||
|
STRONG_MODEL_NAME=在这里填入强模型ID(用于改码/排查)
|
||||||
|
WEAK_MODEL_NAME=在这里填入弱模型ID(用于解析/摘要)
|
||||||
|
MODEL_REQUEST_TIMEOUT=120
|
||||||
|
MODEL_MAX_RETRIES=3
|
||||||
|
|
||||||
|
# ---------- 白名单执行器安全参数(决策点 11)----------
|
||||||
|
EXEC_TIMEOUT_SECONDS=60
|
||||||
|
EXEC_OUTPUT_MAX_CHARS=20000
|
||||||
|
|
||||||
|
# ---------- RAG ----------
|
||||||
|
CHROMA_COLLECTION_NAME=project_knowledge
|
||||||
|
RETRIEVE_TOP_K=5
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Python
|
||||||
|
# ============================================================
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.Python
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 敏感配置(禁止提交!)
|
||||||
|
# ============================================================
|
||||||
|
.env
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 测试 / 覆盖率 / 打包产物
|
||||||
|
# ============================================================
|
||||||
|
.pytest_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg-info/
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# IDE(PyCharm 等)
|
||||||
|
# ============================================================
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 系统文件
|
||||||
|
# ============================================================
|
||||||
|
Thumbs.db
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 本地运行数据(SQLite/Chroma/审计/快照,体积大且可重建)
|
||||||
|
# ============================================================
|
||||||
|
app/data/
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""编程智能 Agent 系统 —— 后端应用包"""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""API 路由层:按业务域拆分(project / task / knowledge / stream)"""
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""
|
||||||
|
审计日志 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供审计日志的查询接口,支撑前端「审计可视化」页面。
|
||||||
|
对应 M5 交付目标:Agent 的每次动手操作可追溯、可审查。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 只读接口:审计日志是证据,绝不允许通过 API 修改/删除;
|
||||||
|
2. 按日期分文件的 JSONL 直接读取并过滤,无需额外数据库;
|
||||||
|
3. 支持按 action/result 过滤 + 分页,满足审查场景。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- GET /api/audit:读取当日(或指定日期)审计日志并过滤;
|
||||||
|
- 结构化返回,前端表格展示。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:日志文件过大读取慢。
|
||||||
|
应对:limit 上限 500 条,倒序返回最近的。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.audit.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/audit", tags=["审计日志"])
|
||||||
|
|
||||||
|
AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[dict[str, Any]]], summary="查询审计日志")
|
||||||
|
def list_audit_logs(
|
||||||
|
date: str = Query(default="", description="日期 YYYYMMDD,默认今日"),
|
||||||
|
action: str = Query(default="", description="操作类型过滤"),
|
||||||
|
limit: int = Query(default=100, ge=1, le=500, description="返回条数上限"),
|
||||||
|
) -> ApiResponse[list[dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
查询审计日志(支持按日期/操作类型过滤)。
|
||||||
|
|
||||||
|
【返回】最近 N 条审计记录,倒序(最新的在前)。
|
||||||
|
"""
|
||||||
|
date_str = date or datetime.now().strftime("%Y%m%d")
|
||||||
|
log_file = AUDIT_DIR / f"audit-{date_str}.jsonl"
|
||||||
|
|
||||||
|
if not log_file.exists():
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"日期 {date_str} 无审计记录",
|
||||||
|
data=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
entries: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
with open(log_file, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
if action and entry.get("action") != action:
|
||||||
|
continue
|
||||||
|
entries.append(entry)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"读取审计日志失败:{exc}", data=None)
|
||||||
|
|
||||||
|
# 倒序取最近 N 条
|
||||||
|
entries.reverse()
|
||||||
|
entries = entries[:limit]
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"共 {len(entries)} 条记录",
|
||||||
|
data=entries,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/summary", response_model=ApiResponse[dict[str, Any]], summary="审计统计")
|
||||||
|
def audit_summary(
|
||||||
|
date: str = Query(default="", description="日期 YYYYMMDD,默认今日"),
|
||||||
|
) -> ApiResponse[dict[str, Any]]:
|
||||||
|
"""返回当日审计操作的统计概览(按 action/result 分组计数)。"""
|
||||||
|
date_str = date or datetime.now().strftime("%Y%m%d")
|
||||||
|
log_file = AUDIT_DIR / f"audit-{date_str}.jsonl"
|
||||||
|
|
||||||
|
if not log_file.exists():
|
||||||
|
return ApiResponse(code=0, message="ok", data={"total": 0, "by_action": {}, "by_result": {}})
|
||||||
|
|
||||||
|
by_action: dict[str, int] = {}
|
||||||
|
by_result: dict[str, int] = {}
|
||||||
|
total = 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(log_file, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
total += 1
|
||||||
|
action = entry.get("action", "unknown")
|
||||||
|
result = entry.get("result", "unknown")
|
||||||
|
by_action[action] = by_action.get(action, 0) + 1
|
||||||
|
by_result[result] = by_result.get(result, 0) + 1
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"统计失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message="ok",
|
||||||
|
data={"total": total, "by_action": by_action, "by_result": by_result},
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""
|
||||||
|
自动备份 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】手动触发备份、查看备份列表、清理旧备份。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.backup_service import backup_now, list_backups
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.backup.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/backup", tags=["自动备份"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/now", response_model=ApiResponse[dict], summary="立即备份")
|
||||||
|
def backup_now_endpoint() -> ApiResponse[dict]:
|
||||||
|
"""立即执行全量备份(SQLite + 配置 + 向量库元数据)。"""
|
||||||
|
result = backup_now()
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "备份失败"), data=result)
|
||||||
|
return ApiResponse(code=0, message="备份完成", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/list", response_model=ApiResponse[list[dict]], summary="备份列表")
|
||||||
|
def list_backups_endpoint() -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有备份记录(含大小、文件数、时间)。"""
|
||||||
|
items = list_backups()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 个备份", data=items)
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"""
|
||||||
|
批量任务 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】一次提交多个需求,批量创建任务并行执行。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from app.api.task_api import get_task_service
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.schemas.task import TaskCreate
|
||||||
|
from app.tasks.task_service import TaskService
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.batch.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/batch", tags=["批量任务"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks", response_model=ApiResponse[dict], summary="批量提交任务")
|
||||||
|
async def batch_create_tasks(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
一次提交多个需求,批量创建任务。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"project_id": "proj_xxx",
|
||||||
|
"model_preference": "auto",
|
||||||
|
"items": [
|
||||||
|
{"requirement_text": "需求1", "task_type": "feature"},
|
||||||
|
{"requirement_text": "需求2", "task_type": "bugfix"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
project_id = payload.get("project_id", "")
|
||||||
|
model_preference = payload.get("model_preference", "auto")
|
||||||
|
items = payload.get("items", [])
|
||||||
|
|
||||||
|
if not project_id:
|
||||||
|
return ApiResponse(code=422, message="project_id 必填", data=None)
|
||||||
|
if not items or not isinstance(items, list):
|
||||||
|
return ApiResponse(code=422, message="items 必须是非空数组", data=None)
|
||||||
|
|
||||||
|
created = []
|
||||||
|
errors = []
|
||||||
|
|
||||||
|
for i, item in enumerate(items):
|
||||||
|
try:
|
||||||
|
requirement = item.get("requirement_text", "").strip()
|
||||||
|
if not requirement:
|
||||||
|
errors.append({"index": i, "error": "requirement_text 为空"})
|
||||||
|
continue
|
||||||
|
task_type = item.get("task_type", "feature")
|
||||||
|
|
||||||
|
payload_create = TaskCreate(
|
||||||
|
project_id=project_id,
|
||||||
|
requirement_text=requirement,
|
||||||
|
task_type=task_type,
|
||||||
|
model_preference=model_preference,
|
||||||
|
)
|
||||||
|
task = await service.create_and_run(payload_create)
|
||||||
|
created.append({"index": i, "task_id": task.id, "requirement": requirement[:50]})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
errors.append({"index": i, "error": str(exc)[:200]})
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if created else 1,
|
||||||
|
message=f"批量提交完成:成功 {len(created)},失败 {len(errors)}",
|
||||||
|
data={"created": created, "errors": errors},
|
||||||
|
)
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
"""
|
||||||
|
数据库管理 API
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】数据库连接配置的增删改查 + SQL 增删改查(CRUD)执行接口。
|
||||||
|
【安全设计】密码脱敏返回;SQL 强制参数化查询;操作审计日志。
|
||||||
|
【实现思路】连接管理 CRUD + SQL 执行/查询/分页查询。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from app.config.settings import Settings, load_settings
|
||||||
|
from app.schemas.database import (
|
||||||
|
DatabaseConnection,
|
||||||
|
DatabaseConnectionCreate,
|
||||||
|
DatabaseConnectionUpdate,
|
||||||
|
SqlExecuteRequest,
|
||||||
|
SqlExecuteResult,
|
||||||
|
SqlQueryRequest,
|
||||||
|
)
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.db_engine import (
|
||||||
|
_validate_identifier,
|
||||||
|
alter_table,
|
||||||
|
execute_sql,
|
||||||
|
get_table_structure,
|
||||||
|
list_tables,
|
||||||
|
query_with_pagination,
|
||||||
|
test_connection,
|
||||||
|
)
|
||||||
|
from app.store.db_connection_store import SqliteDatabaseConnectionStore
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.db.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/database", tags=["数据库管理"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 依赖注入 ----------
|
||||||
|
|
||||||
|
_store_singleton: Optional[SqliteDatabaseConnectionStore] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_store() -> SqliteDatabaseConnectionStore:
|
||||||
|
global _store_singleton
|
||||||
|
if _store_singleton is None:
|
||||||
|
settings = load_settings()
|
||||||
|
_store_singleton = SqliteDatabaseConnectionStore(settings.sqlite_db_path)
|
||||||
|
return _store_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 连接配置 CRUD ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/connections",
|
||||||
|
response_model=ApiResponse[list[DatabaseConnection]],
|
||||||
|
summary="连接配置列表",
|
||||||
|
)
|
||||||
|
def list_connections(
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[list[DatabaseConnection]]:
|
||||||
|
"""查询全部数据库连接配置(密码脱敏)。"""
|
||||||
|
try:
|
||||||
|
items = store.list_all()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections",
|
||||||
|
response_model=ApiResponse[DatabaseConnection],
|
||||||
|
summary="创建连接配置",
|
||||||
|
)
|
||||||
|
def create_connection(
|
||||||
|
payload: DatabaseConnectionCreate,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[DatabaseConnection]:
|
||||||
|
"""新增数据库连接配置(密码加密存储)。"""
|
||||||
|
try:
|
||||||
|
config = store.create(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"创建失败:{exc}", data=None)
|
||||||
|
log_action(action="db_connection_create", target=config.name, result="success")
|
||||||
|
return ApiResponse(code=0, message="连接配置创建成功", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/connections/{config_id}",
|
||||||
|
response_model=ApiResponse[DatabaseConnection],
|
||||||
|
summary="连接配置详情",
|
||||||
|
)
|
||||||
|
def get_connection(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[DatabaseConnection]:
|
||||||
|
try:
|
||||||
|
config = store.get(config_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
if config is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/connections/{config_id}",
|
||||||
|
response_model=ApiResponse[DatabaseConnection],
|
||||||
|
summary="更新连接配置",
|
||||||
|
)
|
||||||
|
def update_connection(
|
||||||
|
config_id: str,
|
||||||
|
payload: DatabaseConnectionUpdate,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[DatabaseConnection]:
|
||||||
|
try:
|
||||||
|
config = store.update(config_id, payload)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"更新失败:{exc}", data=None)
|
||||||
|
if config is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
log_action(action="db_connection_update", target=config.name, result="success")
|
||||||
|
return ApiResponse(code=0, message="连接配置更新成功", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/connections/{config_id}",
|
||||||
|
response_model=ApiResponse[bool],
|
||||||
|
summary="删除连接配置",
|
||||||
|
)
|
||||||
|
def delete_connection(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[bool]:
|
||||||
|
try:
|
||||||
|
deleted = store.delete(config_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"删除失败:{exc}", data=None)
|
||||||
|
if not deleted:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=False)
|
||||||
|
log_action(action="db_connection_delete", target=config_id, result="success")
|
||||||
|
return ApiResponse(code=0, message="连接配置删除成功", data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/test",
|
||||||
|
response_model=ApiResponse[dict],
|
||||||
|
summary="测试连接",
|
||||||
|
)
|
||||||
|
def test_db_connection(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""测试数据库连接是否成功。"""
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
result = test_connection(conn_info)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result["success"] else 1, message=result["message"], data=result
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- SQL CRUD 操作 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/execute",
|
||||||
|
response_model=ApiResponse[SqlExecuteResult],
|
||||||
|
summary="执行 SQL(通用)",
|
||||||
|
)
|
||||||
|
def execute_sql_endpoint(
|
||||||
|
config_id: str,
|
||||||
|
payload: SqlExecuteRequest,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[SqlExecuteResult]:
|
||||||
|
"""
|
||||||
|
执行 SQL 语句(INSERT / UPDATE / DELETE / SELECT 通用)。
|
||||||
|
|
||||||
|
【安全】强制参数化查询(params 字段),防 SQL 注入。
|
||||||
|
【请求体】{"sql": "INSERT INTO t VALUES (:a)", "params": {"a": "值"}}
|
||||||
|
"""
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
result = execute_sql(conn_info, payload.sql, payload.params)
|
||||||
|
log_action(
|
||||||
|
action="db_execute_sql",
|
||||||
|
target=conn_info.get("name", config_id),
|
||||||
|
result="success" if result.success else "failure",
|
||||||
|
details={"sql": payload.sql[:200], "affected": result.affected_rows},
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.success else 1, message=result.message, data=result
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/query",
|
||||||
|
response_model=ApiResponse[SqlExecuteResult],
|
||||||
|
summary="SQL 分页查询",
|
||||||
|
)
|
||||||
|
def query_sql_endpoint(
|
||||||
|
config_id: str,
|
||||||
|
payload: SqlQueryRequest,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[SqlExecuteResult]:
|
||||||
|
"""
|
||||||
|
SELECT 分页查询(支持按主键/条件查询)。
|
||||||
|
|
||||||
|
【请求体】{"sql": "SELECT * FROM t WHERE id = :id", "params": {"id": 1}, "page": 1, "page_size": 20}
|
||||||
|
"""
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
result = query_with_pagination(
|
||||||
|
conn_info, payload.sql, payload.params, payload.page, payload.page_size
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.success else 1, message=result.message, data=result
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 表结构查询与修改 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/connections/{config_id}/tables",
|
||||||
|
response_model=ApiResponse[list[str]],
|
||||||
|
summary="列出所有表",
|
||||||
|
)
|
||||||
|
def list_tables_endpoint(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[list[str]]:
|
||||||
|
"""列出数据库中的所有表名(供前端下拉选择)。"""
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
tables = list_tables(conn_info)
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(tables)} 张表", data=tables)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/connections/{config_id}/structure/{table_name}",
|
||||||
|
response_model=ApiResponse[dict],
|
||||||
|
summary="查询表结构",
|
||||||
|
)
|
||||||
|
def get_table_structure_endpoint(
|
||||||
|
config_id: str,
|
||||||
|
table_name: str,
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
查询表结构(列名、类型、可空、主键、默认值、注释)。
|
||||||
|
|
||||||
|
【支持】MySQL / PostgreSQL / SQLite
|
||||||
|
"""
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
result = get_table_structure(conn_info, table_name)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", "ok"),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/alter",
|
||||||
|
response_model=ApiResponse[dict],
|
||||||
|
summary="修改表结构",
|
||||||
|
)
|
||||||
|
def alter_table_endpoint(
|
||||||
|
config_id: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
修改表结构(加列/改列/删列)。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"table": "users",
|
||||||
|
"action": "add / modify / drop",
|
||||||
|
"column_name": "email",
|
||||||
|
"column_type": "VARCHAR(255)",
|
||||||
|
"nullable": true,
|
||||||
|
"default": "",
|
||||||
|
"comment": "邮箱"
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
table = payload.get("table", "")
|
||||||
|
action = payload.get("action", "")
|
||||||
|
column_name = payload.get("column_name", "")
|
||||||
|
if not table or not action or not column_name:
|
||||||
|
return ApiResponse(code=422, message="table、action、column_name 必填", data=None)
|
||||||
|
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
result = alter_table(
|
||||||
|
conn_info,
|
||||||
|
table_name=table,
|
||||||
|
action=action,
|
||||||
|
column_name=column_name,
|
||||||
|
column_type=payload.get("column_type", ""),
|
||||||
|
nullable=payload.get("nullable", True),
|
||||||
|
default=payload.get("default", ""),
|
||||||
|
comment=payload.get("comment", ""),
|
||||||
|
)
|
||||||
|
log_action(
|
||||||
|
action="db_alter_table",
|
||||||
|
target=f"{table} {action} {column_name}",
|
||||||
|
result="success" if result.get("success") else "failure",
|
||||||
|
details={"column_type": payload.get("column_type", "")},
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", "操作完成"),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 结构化 CRUD(便捷封装)----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/insert",
|
||||||
|
response_model=ApiResponse[SqlExecuteResult],
|
||||||
|
summary="插入记录(结构化)",
|
||||||
|
)
|
||||||
|
def insert_record(
|
||||||
|
config_id: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[SqlExecuteResult]:
|
||||||
|
"""
|
||||||
|
结构化插入记录(自动生成 INSERT SQL)。
|
||||||
|
|
||||||
|
【请求体】{"table": "users", "data": {"name": "张三", "age": 25}}
|
||||||
|
或多条:{"table": "users", "data": [{"name": "A"}, {"name": "B"}]}
|
||||||
|
"""
|
||||||
|
table = payload.get("table", "")
|
||||||
|
data = payload.get("data")
|
||||||
|
if not table or not data:
|
||||||
|
return ApiResponse(code=422, message="table 和 data 必填", data=None)
|
||||||
|
|
||||||
|
# 校验表名与列名合法性(防 SQL 注入)
|
||||||
|
try:
|
||||||
|
_validate_identifier(table, "表名")
|
||||||
|
except ValueError as exc:
|
||||||
|
return ApiResponse(code=422, message=str(exc), data=None)
|
||||||
|
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
records = data if isinstance(data, list) else [data]
|
||||||
|
total_affected = 0
|
||||||
|
for record in records:
|
||||||
|
try:
|
||||||
|
for col in record.keys():
|
||||||
|
_validate_identifier(col, "列名")
|
||||||
|
except ValueError as exc:
|
||||||
|
return ApiResponse(code=422, message=str(exc), data=None)
|
||||||
|
columns = ", ".join(record.keys())
|
||||||
|
placeholders = ", ".join(f":{k}" for k in record.keys())
|
||||||
|
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
|
||||||
|
result = execute_sql(conn_info, sql, record)
|
||||||
|
if not result.success:
|
||||||
|
return ApiResponse(code=1, message=result.message, data=result)
|
||||||
|
total_affected += result.affected_rows
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"插入 {total_affected} 条记录成功",
|
||||||
|
data=SqlExecuteResult(
|
||||||
|
success=True,
|
||||||
|
message=f"插入 {total_affected} 条记录成功",
|
||||||
|
affected_rows=total_affected,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/update-rows",
|
||||||
|
response_model=ApiResponse[SqlExecuteResult],
|
||||||
|
summary="更新记录(结构化)",
|
||||||
|
)
|
||||||
|
def update_record(
|
||||||
|
config_id: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[SqlExecuteResult]:
|
||||||
|
"""
|
||||||
|
结构化更新记录(自动生成 UPDATE SQL)。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"table": "users",
|
||||||
|
"data": {"name": "新名"},
|
||||||
|
"where": "id = :id",
|
||||||
|
"params": {"id": 1}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
table = payload.get("table", "")
|
||||||
|
data = payload.get("data")
|
||||||
|
where = payload.get("where", "")
|
||||||
|
params = payload.get("params", {})
|
||||||
|
if not table or not data or not where:
|
||||||
|
return ApiResponse(code=422, message="table、data、where 必填", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
_validate_identifier(table, "表名")
|
||||||
|
for col in data.keys():
|
||||||
|
_validate_identifier(col, "列名")
|
||||||
|
except ValueError as exc:
|
||||||
|
return ApiResponse(code=422, message=str(exc), data=None)
|
||||||
|
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
set_clause = ", ".join(f"{k} = :_set_{k}" for k in data.keys())
|
||||||
|
sql = f"UPDATE {table} SET {set_clause} WHERE {where}"
|
||||||
|
merged_params = {**params, **{f"_set_{k}": v for k, v in data.items()}}
|
||||||
|
|
||||||
|
result = execute_sql(conn_info, sql, merged_params)
|
||||||
|
log_action(
|
||||||
|
action="db_update",
|
||||||
|
target=f"{table} WHERE {where}",
|
||||||
|
result="success" if result.success else "failure",
|
||||||
|
details={"affected": result.affected_rows},
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.success else 1, message=result.message, data=result
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/connections/{config_id}/delete-rows",
|
||||||
|
response_model=ApiResponse[SqlExecuteResult],
|
||||||
|
summary="删除记录(结构化)",
|
||||||
|
)
|
||||||
|
def delete_record(
|
||||||
|
config_id: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
store: SqliteDatabaseConnectionStore = Depends(get_db_store),
|
||||||
|
) -> ApiResponse[SqlExecuteResult]:
|
||||||
|
"""
|
||||||
|
结构化删除记录(自动生成 DELETE SQL)。
|
||||||
|
|
||||||
|
【请求体】{"table": "users", "where": "id = :id", "params": {"id": 1}}
|
||||||
|
"""
|
||||||
|
table = payload.get("table", "")
|
||||||
|
where = payload.get("where", "")
|
||||||
|
params = payload.get("params", {})
|
||||||
|
if not table or not where:
|
||||||
|
return ApiResponse(code=422, message="table 和 where 必填", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
_validate_identifier(table, "表名")
|
||||||
|
except ValueError as exc:
|
||||||
|
return ApiResponse(code=422, message=str(exc), data=None)
|
||||||
|
|
||||||
|
conn_info = store.get_with_password(config_id)
|
||||||
|
if conn_info is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
|
||||||
|
sql = f"DELETE FROM {table} WHERE {where}"
|
||||||
|
result = execute_sql(conn_info, sql, params)
|
||||||
|
log_action(
|
||||||
|
action="db_delete",
|
||||||
|
target=f"{table} WHERE {where}",
|
||||||
|
result="success" if result.success else "failure",
|
||||||
|
details={"affected": result.affected_rows},
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.success else 1, message=result.message, data=result
|
||||||
|
)
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"""
|
||||||
|
文档问答 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】基于指定目录下文档的多轮对话式问答接口。
|
||||||
|
【实现思路】目录索引 + 对话问答 + 会话管理。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.doc_qa_service import (
|
||||||
|
chat,
|
||||||
|
clear_conversation,
|
||||||
|
delete_conversation,
|
||||||
|
list_conversations,
|
||||||
|
load_directory,
|
||||||
|
vectorize,
|
||||||
|
_conversations,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.doc_qa.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/docqa", tags=["文档问答"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/browse", response_model=ApiResponse[dict], summary="浏览目录")
|
||||||
|
def browse_directory(path: str = "") -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
列出指定目录下的子目录和文件(供前端目录选择器浏览)。
|
||||||
|
|
||||||
|
【请求参数】path:目录路径(留空返回 D:\\ 根目录)
|
||||||
|
【返回】{path, parent, directories: [...], files: [...]}
|
||||||
|
"""
|
||||||
|
if not path:
|
||||||
|
path = "D:\\"
|
||||||
|
|
||||||
|
target = Path(path)
|
||||||
|
if not target.exists() or not target.is_dir():
|
||||||
|
return ApiResponse(code=404, message=f"目录不存在:{path}", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
dirs = []
|
||||||
|
files = []
|
||||||
|
for item in sorted(target.iterdir()):
|
||||||
|
if item.name.startswith("."):
|
||||||
|
continue
|
||||||
|
if item.is_dir():
|
||||||
|
dirs.append({"name": item.name, "path": str(item), "type": "dir"})
|
||||||
|
else:
|
||||||
|
size = item.stat().st_size
|
||||||
|
files.append({
|
||||||
|
"name": item.name,
|
||||||
|
"path": str(item),
|
||||||
|
"type": "file",
|
||||||
|
"size": size,
|
||||||
|
"ext": item.suffix.lower(),
|
||||||
|
})
|
||||||
|
|
||||||
|
parent = str(target.parent) if target.parent != target else None
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"共 {len(dirs)} 个子目录,{len(files)} 个文件",
|
||||||
|
data={
|
||||||
|
"path": str(target),
|
||||||
|
"parent": parent,
|
||||||
|
"directories": dirs,
|
||||||
|
"files": files,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except PermissionError:
|
||||||
|
return ApiResponse(code=403, message=f"无权限访问:{path}", data=None)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"浏览失败:{exc}", data=None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/index", response_model=ApiResponse[dict], summary="加载文档")
|
||||||
|
def create_index(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
加载文档到内存(**不做向量化**,秒级完成)。
|
||||||
|
|
||||||
|
【请求体】
|
||||||
|
{"directory": "D:\\xx"} — 加载目录下全部文档
|
||||||
|
{"file_paths": ["D:\\xx\\a.md", ...]} — 加载指定文件(可多选)
|
||||||
|
两者至少提供其一
|
||||||
|
【返回】conversation_id
|
||||||
|
"""
|
||||||
|
directory = payload.get("directory", "")
|
||||||
|
file_paths = payload.get("file_paths", [])
|
||||||
|
|
||||||
|
if not directory and not file_paths:
|
||||||
|
return ApiResponse(code=422, message="directory 或 file_paths 必须提供其一", data=None)
|
||||||
|
|
||||||
|
result = load_directory(
|
||||||
|
directory=Path(directory) if directory else None,
|
||||||
|
file_paths=file_paths if file_paths else None,
|
||||||
|
)
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "解析失败"), data=result)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"文档加载完成:{result.get('file_count', 0)} 个文件(可直接提问)",
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/vectorize", response_model=ApiResponse[dict], summary="手动向量化")
|
||||||
|
def vectorize_endpoint(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
手动触发向量化(**可选操作**,大文档/高频问答时用)。
|
||||||
|
|
||||||
|
【请求体】{"conversation_id": "conv_xxx"}
|
||||||
|
"""
|
||||||
|
conversation_id = payload.get("conversation_id", "")
|
||||||
|
if not conversation_id:
|
||||||
|
return ApiResponse(code=422, message="conversation_id 必填", data=None)
|
||||||
|
|
||||||
|
result = vectorize(conversation_id)
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "向量化失败"), data=result)
|
||||||
|
return ApiResponse(code=0, message=result.get("message", "向量化完成"), data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/chat", response_model=ApiResponse[dict], summary="文档问答")
|
||||||
|
def chat_endpoint(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
基于文档内容回答用户问题(多轮对话)。无文档时走纯 LLM 问答。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"conversation_id": "conv_xxx",
|
||||||
|
"question": "问题内容",
|
||||||
|
"model_preference": "auto" 或具体模型 ID
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
conversation_id = payload.get("conversation_id", "")
|
||||||
|
question = (payload.get("question") or "").strip()
|
||||||
|
model_preference = payload.get("model_preference", "auto")
|
||||||
|
|
||||||
|
# 无对话时创建纯对话会话(不需要文档)
|
||||||
|
if not conversation_id:
|
||||||
|
conversation_id = f"conv_{uuid.uuid4().hex[:12]}"
|
||||||
|
from app.services.doc_qa_service import _conversations, _save_persisted
|
||||||
|
import time
|
||||||
|
|
||||||
|
_conversations[conversation_id] = {
|
||||||
|
"directory": "",
|
||||||
|
"documents": [],
|
||||||
|
"vectorized": False,
|
||||||
|
"collection_name": None,
|
||||||
|
"history": [],
|
||||||
|
"total_chars": 0,
|
||||||
|
"title": question[:20] + ("…" if len(question) > 20 else ""),
|
||||||
|
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
}
|
||||||
|
_save_persisted()
|
||||||
|
|
||||||
|
if not question:
|
||||||
|
return ApiResponse(code=422, message="question 必填", data=None)
|
||||||
|
|
||||||
|
result = chat(conversation_id, question, model_preference=model_preference)
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "问答失败"), data=result)
|
||||||
|
result["conversation_id"] = conversation_id
|
||||||
|
return ApiResponse(code=0, message="ok", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/clear", response_model=ApiResponse[bool], summary="清除会话历史")
|
||||||
|
def clear_endpoint(payload: dict[str, Any]) -> ApiResponse[bool]:
|
||||||
|
"""清除指定会话的对话历史。"""
|
||||||
|
conversation_id = payload.get("conversation_id", "")
|
||||||
|
if not conversation_id:
|
||||||
|
return ApiResponse(code=422, message="conversation_id 必填", data=None)
|
||||||
|
ok = clear_conversation(conversation_id)
|
||||||
|
return ApiResponse(code=0, message="历史已清除", data=ok)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/conversations/{conversation_id}", response_model=ApiResponse[bool], summary="删除会话"
|
||||||
|
)
|
||||||
|
def delete_conversation_endpoint(conversation_id: str) -> ApiResponse[bool]:
|
||||||
|
"""彻底删除指定会话。"""
|
||||||
|
ok = delete_conversation(conversation_id)
|
||||||
|
if not ok:
|
||||||
|
return ApiResponse(code=404, message="会话不存在", data=False)
|
||||||
|
return ApiResponse(code=0, message="会话已删除", data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/conversations", response_model=ApiResponse[list[dict]], summary="会话列表")
|
||||||
|
def conversations_endpoint() -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有活跃的问答会话(含标题、时间、消息数)。"""
|
||||||
|
items = list_conversations()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 个会话", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/conversations/{conversation_id}",
|
||||||
|
response_model=ApiResponse[dict],
|
||||||
|
summary="会话详情(含历史消息)",
|
||||||
|
)
|
||||||
|
def conversation_detail(conversation_id: str) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
获取指定会话的完整对话历史(含消息列表)。
|
||||||
|
|
||||||
|
【返回】{title, directory, history: [{role, content}]}
|
||||||
|
"""
|
||||||
|
conv = _conversations.get(conversation_id)
|
||||||
|
if conv is None:
|
||||||
|
return ApiResponse(code=404, message="会话不存在", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message="ok",
|
||||||
|
data={
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"title": conv.get("title", "未命名对话"),
|
||||||
|
"directory": conv.get("directory", ""),
|
||||||
|
"history": conv.get("history", []),
|
||||||
|
"total_chars": conv.get("total_chars", 0),
|
||||||
|
"file_count": len(conv.get("documents", [])),
|
||||||
|
"vectorized": conv.get("vectorized", False),
|
||||||
|
"created_at": conv.get("created_at", ""),
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
健康检查 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】全链路健康探活接口。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.health_service import check_all
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.health.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/health", tags=["健康检查"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[dict], summary="全链路健康检查")
|
||||||
|
def health_check() -> ApiResponse[dict]:
|
||||||
|
"""服务/数据库/向量库/模型/Git/磁盘 全链路探活。"""
|
||||||
|
result = check_all()
|
||||||
|
code = 0 if result["status"] == "healthy" else 1
|
||||||
|
return ApiResponse(
|
||||||
|
code=code,
|
||||||
|
message=f"整体状态:{result['status']}({result['healthy_count']}/{result['total_count']} 正常)",
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
"""
|
||||||
|
知识库管理 API
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供知识库的入库、检索、重建、统计接口,支撑前端「知识库管理页」。
|
||||||
|
对应《核心诉求》文档知识管理模块的对外能力。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
FastAPI + 统一 ApiResponse(与项目管理 API 同构):
|
||||||
|
前端只认一种响应结构,错误处理全局一致(硬约束 5)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- 依赖注入 KnowledgeService,便于单测替换为内存实现;
|
||||||
|
- 入库接口支持「全量入库 / 单文件入库 / 重建」三种粒度;
|
||||||
|
- 检索接口返回带来源与相关度的结果,供前端展示。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:入库耗时长(素材多)导致请求超时。
|
||||||
|
应对:一期同步执行 + 超时调大;二期改异步任务 + 进度推送(M3 任务框架复用)。
|
||||||
|
风险2:检索时向量库为空。
|
||||||
|
应对:返回空列表 + 明确提示「知识库为空,请先入库」。
|
||||||
|
风险3:素材目录路径配错。
|
||||||
|
应对:接口显式接收 path 参数并校验存在性,报中文错误。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
|
||||||
|
from app.config.settings import Settings, load_settings
|
||||||
|
from app.knowledge.embeddings import EmbeddingProvider, get_embedding_provider
|
||||||
|
from app.knowledge.knowledge_service import KnowledgeService
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/knowledge", tags=["知识库管理"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 依赖注入(懒加载单例)----------
|
||||||
|
|
||||||
|
_service_singleton: Optional[KnowledgeService] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_knowledge_service() -> KnowledgeService:
|
||||||
|
"""获取知识库服务单例(含向量库与向量化实现)。"""
|
||||||
|
global _service_singleton
|
||||||
|
if _service_singleton is None:
|
||||||
|
settings = load_settings()
|
||||||
|
provider: EmbeddingProvider = get_embedding_provider(
|
||||||
|
provider="", # 走配置默认(chinese),失败自动降级
|
||||||
|
cache_dir=str(settings.data_root / "embedding_cache"),
|
||||||
|
)
|
||||||
|
vs = KnowledgeVectorStore(
|
||||||
|
persist_dir=settings.chroma_dir,
|
||||||
|
collection_name=settings.chroma_collection_name,
|
||||||
|
embedding_provider=provider,
|
||||||
|
)
|
||||||
|
_service_singleton = KnowledgeService(vs, provider)
|
||||||
|
return _service_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 入库 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/ingest", response_model=ApiResponse[dict[str, Any]], summary="知识库入库"
|
||||||
|
)
|
||||||
|
def ingest_knowledge(
|
||||||
|
directory: str = Query(
|
||||||
|
default="",
|
||||||
|
description="素材目录(留空则使用默认目录 D:\\Agent\\需向量化数据)",
|
||||||
|
),
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
settings: Settings = Depends(get_settings),
|
||||||
|
) -> ApiResponse[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
把指定目录下的文档(md/docx/pdf)解析、切分、向量化入库。
|
||||||
|
|
||||||
|
【数据正确性】按 source 替换(先删旧 chunk 再写新),多次点击不重复入库。
|
||||||
|
【返回】scanned_files / ingested_chunks / deleted_old_chunks / warnings
|
||||||
|
"""
|
||||||
|
target = Path(directory) if directory else settings.project_root / "需向量化数据"
|
||||||
|
if not target.exists():
|
||||||
|
return ApiResponse(code=404, message=f"素材目录不存在:{target}", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = service.ingest_directory(target)
|
||||||
|
except Exception as exc: # 兜底:任何入库异常转业务错误
|
||||||
|
logger.exception("知识库入库失败")
|
||||||
|
return ApiResponse(code=500, message=f"知识库入库失败:{exc}", data=None)
|
||||||
|
|
||||||
|
if result.get("ingested_chunks", 0) == 0:
|
||||||
|
return ApiResponse(code=1, message="未入库任何文本,请检查素材", data=result)
|
||||||
|
return ApiResponse(code=0, message="知识库入库完成", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/ingest-files", response_model=ApiResponse[dict[str, Any]], summary="批量入库指定文件"
|
||||||
|
)
|
||||||
|
def ingest_selected_files(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
) -> ApiResponse[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
批量入库勾选的文件(**按 source 替换,不重复追加**)。
|
||||||
|
|
||||||
|
【请求体】{"file_paths": ["D:\\Agent\\需向量化数据\\a.md", "..."]}
|
||||||
|
【用途】前端文件选择 UI 勾选后调用,只向量化选中的文档。
|
||||||
|
"""
|
||||||
|
file_paths = payload.get("file_paths")
|
||||||
|
if not isinstance(file_paths, list) or not file_paths:
|
||||||
|
return ApiResponse(code=422, message="请至少选择一个文件", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = service.ingest_files(file_paths)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("批量入库失败")
|
||||||
|
return ApiResponse(code=500, message=f"批量入库失败:{exc}", data=None)
|
||||||
|
|
||||||
|
if result.get("ingested_chunks", 0) == 0:
|
||||||
|
return ApiResponse(code=1, message="所选文件均无可用文本", data=result)
|
||||||
|
return ApiResponse(code=0, message="所选文件入库完成", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/files", response_model=ApiResponse[list[dict[str, Any]]], summary="列出可入库文件"
|
||||||
|
)
|
||||||
|
def list_ingestible_files(
|
||||||
|
directory: str = Query(default="", description="目录(留空用默认)"),
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
settings: Settings = Depends(get_settings),
|
||||||
|
) -> ApiResponse[list[dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
递归列出目录下全部可入库文件(供前端文件选择 UI)。
|
||||||
|
|
||||||
|
【返回】文件列表,每项含 path / relative_path / name / size / file_type。
|
||||||
|
只列受支持类型(md/markdown/docx/pdf),图片与压缩包自动跳过。
|
||||||
|
"""
|
||||||
|
target = Path(directory) if directory else settings.project_root / "需向量化数据"
|
||||||
|
if not target.exists():
|
||||||
|
return ApiResponse(code=404, message=f"素材目录不存在:{target}", data=None)
|
||||||
|
try:
|
||||||
|
files = service.list_ingestible_files(target)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"列取文件失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(files)} 个文件", data=files)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/rebuild", response_model=ApiResponse[dict[str, Any]], summary="重建知识库索引"
|
||||||
|
)
|
||||||
|
def rebuild_knowledge(
|
||||||
|
directory: str = Query(default="", description="素材目录(留空用默认)"),
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
settings: Settings = Depends(get_settings),
|
||||||
|
) -> ApiResponse[dict[str, Any]]:
|
||||||
|
"""清空现有索引后全量重建(素材大改后使用)。"""
|
||||||
|
target = Path(directory) if directory else settings.project_root / "需向量化数据"
|
||||||
|
if not target.exists():
|
||||||
|
return ApiResponse(code=404, message=f"素材目录不存在:{target}", data=None)
|
||||||
|
try:
|
||||||
|
result = service.rebuild(target)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("重建索引失败")
|
||||||
|
return ApiResponse(code=500, message=f"重建索引失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="知识库重建完成", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 检索 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/query", response_model=ApiResponse[list[dict[str, Any]]], summary="知识库检索"
|
||||||
|
)
|
||||||
|
def query_knowledge(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
settings: Settings = Depends(get_settings),
|
||||||
|
) -> ApiResponse[list[dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
自然语言检索项目知识库。
|
||||||
|
|
||||||
|
【请求体】{"question": "网关离线怎么排查", "top_k": 5}
|
||||||
|
【返回】命中列表,含 text / metadata / score / source / filename
|
||||||
|
"""
|
||||||
|
question = (payload.get("question") or "").strip()
|
||||||
|
if not question:
|
||||||
|
return ApiResponse(code=422, message="检索问题不能为空", data=None)
|
||||||
|
|
||||||
|
top_k = int(payload.get("top_k") or settings.retrieve_top_k)
|
||||||
|
top_k = max(1, min(top_k, 20)) # 限流,防止一次拉爆
|
||||||
|
|
||||||
|
try:
|
||||||
|
hits = service.query(question, top_k=top_k)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("知识库检索失败")
|
||||||
|
return ApiResponse(code=500, message=f"知识库检索失败:{exc}", data=None)
|
||||||
|
|
||||||
|
if not hits:
|
||||||
|
return ApiResponse(
|
||||||
|
code=0, message="知识库为空或无匹配结果,请先执行入库", data=[]
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="ok", data=hits)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 统计 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats", response_model=ApiResponse[dict[str, Any]], summary="知识库统计")
|
||||||
|
def knowledge_stats(
|
||||||
|
service: KnowledgeService = Depends(get_knowledge_service),
|
||||||
|
) -> ApiResponse[dict[str, Any]]:
|
||||||
|
"""返回向量库统计(chunk 总数、向量化实现)。"""
|
||||||
|
try:
|
||||||
|
return ApiResponse(code=0, message="ok", data=service.stats())
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"统计失败:{exc}", data=None)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""
|
||||||
|
知识库自动更新 API
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】手动触发知识库自动更新、查看更新状态。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.knowledge_autoupdate import check_and_update
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge_autoupdate.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/knowledge", tags=["知识库管理"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/auto-update", response_model=ApiResponse[dict], summary="自动更新知识库")
|
||||||
|
def auto_update() -> ApiResponse[dict]:
|
||||||
|
"""检查素材目录变更并自动更新知识库(增量/全量)。"""
|
||||||
|
result = check_and_update()
|
||||||
|
code = 0 if "失败" not in result.get("message", "") else 1
|
||||||
|
return ApiResponse(code=code, message=result.get("message", "完成"), data=result)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""
|
||||||
|
知识图谱 API
|
||||||
|
============"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.knowledge_graph_service import extract_triples, get_kg_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge_graph.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/kg", tags=["知识图谱"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats", response_model=ApiResponse[dict], summary="图谱统计")
|
||||||
|
def graph_stats() -> ApiResponse[dict]:
|
||||||
|
store = get_kg_store()
|
||||||
|
return ApiResponse(code=0, message="ok", data=store.get_graph_stats())
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/extract", response_model=ApiResponse[dict], summary="抽取三元组")
|
||||||
|
def extract_endpoint(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""从文本中抽取实体关系三元组。"""
|
||||||
|
text = payload.get("text", "")
|
||||||
|
if not text:
|
||||||
|
return ApiResponse(code=422, message="text 必填", data=None)
|
||||||
|
result = extract_triples(
|
||||||
|
text=text,
|
||||||
|
source=payload.get("source", ""),
|
||||||
|
model_preference=payload.get("model_preference", "auto"),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message=f"抽取 {result['count']} 个三元组", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/add", response_model=ApiResponse[dict], summary="添加三元组")
|
||||||
|
def add_triple(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
store = get_kg_store()
|
||||||
|
triple_id = store.add_triple(
|
||||||
|
subject=payload.get("subject", ""),
|
||||||
|
predicate=payload.get("predicate", ""),
|
||||||
|
obj=payload.get("object", ""),
|
||||||
|
source=payload.get("source", ""),
|
||||||
|
confidence=float(payload.get("confidence", 1.0)),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="三元组已添加", data={"id": triple_id})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/search", response_model=ApiResponse[dict], summary="搜索实体")
|
||||||
|
def search_entities(keyword: str = "") -> ApiResponse[dict]:
|
||||||
|
if not keyword:
|
||||||
|
return ApiResponse(code=422, message="keyword 必填", data=None)
|
||||||
|
store = get_kg_store()
|
||||||
|
entities = store.search_entities(keyword)
|
||||||
|
relations = store.query_relation(keyword)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0, message=f"找到 {len(entities)} 个实体", data={"entities": entities, "relations": relations}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/entity/{name}", response_model=ApiResponse[dict], summary="实体关系查询")
|
||||||
|
def entity_relations(name: str) -> ApiResponse[dict]:
|
||||||
|
store = get_kg_store()
|
||||||
|
outgoing = store.query_by_subject(name)
|
||||||
|
incoming = store.query_by_object(name)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0, message="ok", data={"outgoing": outgoing, "incoming": incoming}
|
||||||
|
)
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
日志聚合 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】本地日志查询 + 推送到外部日志系统(预留 Webhook)。
|
||||||
|
对应功能 35:日志聚合。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.log_aggregation.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/logs", tags=["日志聚合"])
|
||||||
|
|
||||||
|
# 审计日志目录
|
||||||
|
AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[dict], summary="查询日志")
|
||||||
|
def query_logs(
|
||||||
|
keyword: str = Query(default="", description="关键字过滤"),
|
||||||
|
limit: int = Query(default=100, ge=1, le=500),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""查询审计日志(支持关键字过滤)。"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
logs = []
|
||||||
|
for f in sorted(AUDIT_DIR.glob("audit-*.jsonl"), reverse=True)[:7]:
|
||||||
|
try:
|
||||||
|
with open(f, encoding="utf-8") as fp:
|
||||||
|
for line in fp:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
entry = json.loads(line)
|
||||||
|
if keyword and keyword.lower() not in str(entry).lower():
|
||||||
|
continue
|
||||||
|
logs.append(entry)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
|
||||||
|
logs.reverse()
|
||||||
|
logs = logs[:limit]
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(logs)} 条", data={"logs": logs})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/push", response_model=ApiResponse[dict], summary="推送日志到外部系统")
|
||||||
|
def push_logs(payload: dict) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
推送日志到外部日志系统(Webhook/ELK/Loki 预留接口)。
|
||||||
|
|
||||||
|
【请求体】{"target": "webhook_url", "logs": [...]}
|
||||||
|
"""
|
||||||
|
target = payload.get("target", "")
|
||||||
|
logs = payload.get("logs", [])
|
||||||
|
if not target:
|
||||||
|
return ApiResponse(code=422, message="target(Webhook URL)必填", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.post(target, json={"logs": logs}, timeout=10.0)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if resp.status_code < 400 else 1,
|
||||||
|
message=f"推送完成(HTTP {resp.status_code})",
|
||||||
|
data={"status_code": resp.status_code},
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return ApiResponse(code=1, message=f"推送失败:{exc}", data=None)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""
|
||||||
|
MCP 协议 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】MCP 工具注册/查询/调用。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.mcp_service import registry
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.mcp.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/mcp", tags=["MCP 协议"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tools", response_model=ApiResponse[list[dict]], summary="MCP 工具列表")
|
||||||
|
def list_tools() -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有已注册的 MCP 工具。"""
|
||||||
|
tools = registry.list_tools()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(tools)} 个工具", data=tools)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/call", response_model=ApiResponse[dict], summary="调用 MCP 工具")
|
||||||
|
def call_tool(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""调用指定 MCP 工具。"""
|
||||||
|
name = payload.get("name", "")
|
||||||
|
arguments = payload.get("arguments", {})
|
||||||
|
if not name:
|
||||||
|
return ApiResponse(code=422, message="name 必填", data=None)
|
||||||
|
result = registry.call_tool(name, arguments)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", "ok"),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""
|
||||||
|
长期记忆 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】长期记忆的增删改查与智能召回。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.memory_service import get_memory_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.memory.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/memory", tags=["长期记忆"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[dict]], summary="记忆列表")
|
||||||
|
def list_memories(project_id: str = "", category: str = "") -> ApiResponse[list[dict]]:
|
||||||
|
"""列出记忆(可按项目/分类筛选)。"""
|
||||||
|
store = get_memory_store()
|
||||||
|
items = store.list_memories(project_id, category)
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 条记忆", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="记录记忆")
|
||||||
|
def create_memory(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""记录一条长期记忆。"""
|
||||||
|
content = (payload.get("content") or "").strip()
|
||||||
|
if not content:
|
||||||
|
return ApiResponse(code=422, message="content 必填", data=None)
|
||||||
|
|
||||||
|
store = get_memory_store()
|
||||||
|
mem_id = store.remember(
|
||||||
|
content=content,
|
||||||
|
project_id=payload.get("project_id", ""),
|
||||||
|
category=payload.get("category", "general"),
|
||||||
|
source=payload.get("source", ""),
|
||||||
|
tags=payload.get("tags", []),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="记忆已保存", data={"id": mem_id})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/recall", response_model=ApiResponse[list[dict]], summary="召回记忆")
|
||||||
|
def recall_memory(payload: dict[str, Any]) -> ApiResponse[list[dict]]:
|
||||||
|
"""按查询召回相关记忆。"""
|
||||||
|
query = (payload.get("query") or "").strip()
|
||||||
|
if not query:
|
||||||
|
return ApiResponse(code=422, message="query 必填", data=None)
|
||||||
|
|
||||||
|
store = get_memory_store()
|
||||||
|
items = store.recall(
|
||||||
|
query=query,
|
||||||
|
project_id=payload.get("project_id", ""),
|
||||||
|
top_k=int(payload.get("top_k", 5)),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message=f"召回 {len(items)} 条", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{mem_id}", response_model=ApiResponse[bool], summary="删除记忆")
|
||||||
|
def delete_memory(mem_id: str) -> ApiResponse[bool]:
|
||||||
|
store = get_memory_store()
|
||||||
|
ok = store.delete(mem_id)
|
||||||
|
return ApiResponse(code=0 if ok else 404, message="删除成功" if ok else "记忆不存在", data=ok)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
监控指标 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】监控仪表盘、成本统计、性能指标查询接口。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.metrics_service import get_dashboard
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.metrics.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/metrics", tags=["监控指标"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dashboard", response_model=ApiResponse[dict], summary="监控仪表盘")
|
||||||
|
def dashboard(hours: int = Query(default=24, ge=1, le=720, description="统计时间范围(小时)")) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
获取监控仪表盘数据:模型 token/成本/延迟/调用次数 + 任务状态分布。
|
||||||
|
"""
|
||||||
|
result = get_dashboard(hours)
|
||||||
|
return ApiResponse(code=0, message=f"最近 {hours} 小时", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/trend", response_model=ApiResponse[dict], summary="用量趋势")
|
||||||
|
def trend(days: int = Query(default=7, ge=1, le=90, description="统计天数")) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
按天聚合用量趋势(最近 N 天)。
|
||||||
|
|
||||||
|
【返回】daily(每日用量)、provider_trend(各平台每日)、summary(日均/峰值)
|
||||||
|
"""
|
||||||
|
from app.services.metrics_service import get_trend
|
||||||
|
|
||||||
|
result = get_trend(days)
|
||||||
|
return ApiResponse(code=0, message=f"最近 {days} 天趋势", data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/forecast", response_model=ApiResponse[dict], summary="成本预测")
|
||||||
|
def forecast(days: int = Query(default=7, ge=1, le=90, description="预测依据天数")) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
基于最近 N 天用量预测未来 30 天成本。
|
||||||
|
|
||||||
|
【算法】按日均成本线性外推 + 最近 3 天加权平均。
|
||||||
|
"""
|
||||||
|
from app.services.metrics_service import get_cost_forecast
|
||||||
|
|
||||||
|
result = get_cost_forecast(days)
|
||||||
|
return ApiResponse(code=0, message="成本预测完成", data=result)
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
"""
|
||||||
|
模型配置管理 API
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】模型偏好配置的增删改查接口,供前端「模型管理」页使用。
|
||||||
|
【安全设计】API key 不入库不返回,只返回 provider_key 引用。
|
||||||
|
【实现思路】标准 CRUD + 启用/停用 + 重置默认。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends
|
||||||
|
|
||||||
|
from app.config.settings import Settings, load_settings
|
||||||
|
from app.schemas.model_config import ModelConfig, ModelConfigCreate, ModelConfigUpdate
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.store.model_config_store import SqliteModelConfigStore
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.model_config.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/models", tags=["模型配置管理"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 依赖注入 ----------
|
||||||
|
|
||||||
|
_store_singleton: Optional[SqliteModelConfigStore] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_model_config_store() -> SqliteModelConfigStore:
|
||||||
|
global _store_singleton
|
||||||
|
if _store_singleton is None:
|
||||||
|
settings = load_settings()
|
||||||
|
_store_singleton = SqliteModelConfigStore(settings.sqlite_db_path)
|
||||||
|
return _store_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 降级链管理(痛点 2:额度用完自动切换)----------
|
||||||
|
# ⚠️ 固定路径路由必须在 /{config_id} 参数路由之前注册,否则会被参数路由吞掉
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/fallback-chain", response_model=ApiResponse[list[dict]], summary="降级链列表"
|
||||||
|
)
|
||||||
|
def get_fallback_chain(
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[list[dict]]:
|
||||||
|
"""获取降级链(按 fallback_order 排序,含限额状态)。"""
|
||||||
|
configs = store.list_all(only_enabled=True)
|
||||||
|
configs.sort(key=lambda c: (c.fallback_order, c.sort_order))
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"共 {len(configs)} 个模型",
|
||||||
|
data=[
|
||||||
|
{
|
||||||
|
"id": c.id,
|
||||||
|
"display_name": c.display_name,
|
||||||
|
"model_id": c.model_id,
|
||||||
|
"provider_key": c.provider_key,
|
||||||
|
"model_role": c.model_role,
|
||||||
|
"fallback_order": c.fallback_order,
|
||||||
|
}
|
||||||
|
for c in configs
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/fallback-chain", response_model=ApiResponse[dict], summary="更新降级链顺序"
|
||||||
|
)
|
||||||
|
def update_fallback_chain(
|
||||||
|
payload: dict[str, Any] = Body(...),
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
批量更新降级链顺序(拖拽排序后调用)。
|
||||||
|
|
||||||
|
【请求体】{"items": [{"id": "model_xxx", "fallback_order": 1}, ...]}
|
||||||
|
"""
|
||||||
|
items = payload.get("items", [])
|
||||||
|
if not items:
|
||||||
|
return ApiResponse(code=422, message="items 不能为空", data=None)
|
||||||
|
|
||||||
|
updated = 0
|
||||||
|
for item in items:
|
||||||
|
mid = item.get("id")
|
||||||
|
order = item.get("fallback_order")
|
||||||
|
if mid and order is not None:
|
||||||
|
from app.schemas.model_config import ModelConfigUpdate
|
||||||
|
|
||||||
|
store.update(mid, ModelConfigUpdate(fallback_order=int(order)))
|
||||||
|
updated += 1
|
||||||
|
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message=f"降级链已更新({updated} 个模型)", data={"updated": updated})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/options", response_model=ApiResponse[list[dict[str, str]]], summary="可用模型选项"
|
||||||
|
)
|
||||||
|
def list_model_options(
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[list[dict[str, str]]]:
|
||||||
|
"""
|
||||||
|
列出提交任务时可选的模型(供前端下拉框)。
|
||||||
|
|
||||||
|
【返回】[{value: "auto", label: "..."}, {value: "ccswitch/glm-5.3", label: "..."}]
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
configs = store.list_all(only_enabled=True)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
|
||||||
|
options = [{"value": "auto", "label": "自动(推荐)— 按节点智能分工"}]
|
||||||
|
for cfg in configs:
|
||||||
|
options.append(
|
||||||
|
{
|
||||||
|
"value": f"{cfg.provider_key}/{cfg.model_id}",
|
||||||
|
"label": f"{cfg.display_name}({cfg.provider_key})",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="ok", data=options)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- CRUD(参数路由放在固定路径之后)----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[ModelConfig]], summary="模型配置列表")
|
||||||
|
def list_model_configs(
|
||||||
|
only_enabled: bool = False,
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[list[ModelConfig]]:
|
||||||
|
"""查询全部模型配置(可过滤只看启用的)。"""
|
||||||
|
try:
|
||||||
|
items = store.list_all(only_enabled=only_enabled)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[ModelConfig], summary="创建模型配置")
|
||||||
|
def create_model_config(
|
||||||
|
payload: ModelConfigCreate,
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[ModelConfig]:
|
||||||
|
"""新增一个模型配置。"""
|
||||||
|
try:
|
||||||
|
config = store.create(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"创建失败:{exc}", data=None)
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message="模型配置创建成功", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{config_id}", response_model=ApiResponse[ModelConfig], summary="模型配置详情")
|
||||||
|
def get_model_config(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[ModelConfig]:
|
||||||
|
try:
|
||||||
|
config = store.get(config_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
if config is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{config_id}", response_model=ApiResponse[ModelConfig], summary="更新模型配置")
|
||||||
|
def update_model_config(
|
||||||
|
config_id: str,
|
||||||
|
payload: ModelConfigUpdate,
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[ModelConfig]:
|
||||||
|
try:
|
||||||
|
config = store.update(config_id, payload)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"更新失败:{exc}", data=None)
|
||||||
|
if config is None:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=None)
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message="模型配置更新成功", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{config_id}", response_model=ApiResponse[bool], summary="删除模型配置")
|
||||||
|
def delete_model_config(
|
||||||
|
config_id: str,
|
||||||
|
store: SqliteModelConfigStore = Depends(get_model_config_store),
|
||||||
|
) -> ApiResponse[bool]:
|
||||||
|
try:
|
||||||
|
deleted = store.delete(config_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"删除失败:{exc}", data=None)
|
||||||
|
if not deleted:
|
||||||
|
return ApiResponse(code=404, message=f"配置不存在:{config_id}", data=False)
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message="模型配置删除成功", data=True)
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
"""
|
||||||
|
平台账号管理 API
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】管理多个 AI 平台账号(品牌/账号/套餐/控制台URL),
|
||||||
|
支持登录保存 Cookie、自动抓取用量、查看用量快照。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.platform.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/platform", tags=["平台账号管理"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/accounts", response_model=ApiResponse[list[dict]], summary="账号列表")
|
||||||
|
def list_accounts() -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有平台账号(Cookie 脱敏)。"""
|
||||||
|
store = get_platform_store()
|
||||||
|
items = store.list_all()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 个账号", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/accounts", response_model=ApiResponse[dict], summary="创建账号")
|
||||||
|
def create_account(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""创建平台账号(品牌/账号名/套餐/控制台 URL)。"""
|
||||||
|
brand = (payload.get("brand") or "").strip()
|
||||||
|
account_name = (payload.get("account_name") or "").strip()
|
||||||
|
console_url = (payload.get("console_url") or "").strip()
|
||||||
|
if not brand or not account_name or not console_url:
|
||||||
|
return ApiResponse(code=422, message="brand、account_name、console_url 必填", data=None)
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
account = store.create(
|
||||||
|
brand=brand,
|
||||||
|
account_name=account_name,
|
||||||
|
plan_name=payload.get("plan_name", ""),
|
||||||
|
console_url=console_url,
|
||||||
|
description=payload.get("description", ""),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="账号创建成功", data=account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/accounts/{account_id}", response_model=ApiResponse[dict], summary="更新账号")
|
||||||
|
def update_account(account_id: str, payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
store = get_platform_store()
|
||||||
|
account = store.update(account_id, **payload)
|
||||||
|
if account is None:
|
||||||
|
return ApiResponse(code=404, message=f"账号不存在:{account_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="账号更新成功", data=account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/accounts/{account_id}", response_model=ApiResponse[bool], summary="删除账号")
|
||||||
|
def delete_account(account_id: str) -> ApiResponse[bool]:
|
||||||
|
store = get_platform_store()
|
||||||
|
ok = store.delete(account_id)
|
||||||
|
return ApiResponse(code=0 if ok else 404, message="删除成功" if ok else "账号不存在", data=ok)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 登录与抓取 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/accounts/{account_id}/login/start", response_model=ApiResponse[dict], summary="打开浏览器登录")
|
||||||
|
def start_login_account(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
第一步:打开浏览器(保持存活),用户在浏览器中登录。
|
||||||
|
|
||||||
|
【流程】打开浏览器 → 你手动登录 → 点「登录完成」保存 Cookie
|
||||||
|
"""
|
||||||
|
from app.services.platform_scraper import start_login
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
account = store.get(account_id)
|
||||||
|
if account is None:
|
||||||
|
return ApiResponse(code=404, message=f"账号不存在:{account_id}", data=None)
|
||||||
|
|
||||||
|
result = start_login(account_id, account["console_url"])
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/accounts/{account_id}/login/finish", response_model=ApiResponse[dict], summary="登录完成保存Cookie")
|
||||||
|
def finish_login_account(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
第二步:用户点击「登录完成」后,保存 Cookie + localStorage 并关闭浏览器。
|
||||||
|
"""
|
||||||
|
from app.services.platform_scraper import finish_login
|
||||||
|
|
||||||
|
result = finish_login(account_id, save=True)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/accounts/{account_id}/login/cancel", response_model=ApiResponse[dict], summary="取消登录"
|
||||||
|
)
|
||||||
|
def cancel_login_account(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""取消登录,关闭浏览器(不保存 Cookie)。"""
|
||||||
|
from app.services.platform_scraper import finish_login
|
||||||
|
|
||||||
|
result = finish_login(account_id, save=False)
|
||||||
|
return ApiResponse(code=0, message=result.get("message", "已取消"), data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/accounts/{account_id}/login", response_model=ApiResponse[dict], summary="登录保存Cookie(兼容)")
|
||||||
|
def login_account(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""兼容旧接口:一步式登录。"""
|
||||||
|
from app.services.platform_scraper import login_and_save_cookies
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
account = store.get(account_id)
|
||||||
|
if account is None:
|
||||||
|
return ApiResponse(code=404, message=f"账号不存在:{account_id}", data=None)
|
||||||
|
|
||||||
|
result = login_and_save_cookies(account["console_url"], account_id)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/accounts/{account_id}/scrape", response_model=ApiResponse[dict], summary="抓取用量")
|
||||||
|
def scrape_account(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
用已保存的 Cookie 后台抓取用量数据。
|
||||||
|
|
||||||
|
【返回】用量百分比、已用/剩余/总量、到期日期、截图路径
|
||||||
|
"""
|
||||||
|
from app.services.platform_scraper import scrape_usage
|
||||||
|
|
||||||
|
result = scrape_usage(account_id)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/scrape-all", response_model=ApiResponse[list[dict]], summary="批量抓取所有账号")
|
||||||
|
def scrape_all() -> ApiResponse[list[dict]]:
|
||||||
|
"""批量抓取所有已激活账号的用量(串行执行)。"""
|
||||||
|
from app.services.platform_scraper import scrape_all_accounts
|
||||||
|
|
||||||
|
results = scrape_all_accounts()
|
||||||
|
success = sum(1 for r in results if r.get("success"))
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"批量抓取完成:成功 {success}/{len(results)}",
|
||||||
|
data=results,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 登录状态检测 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/login-status", response_model=ApiResponse[list[dict]], summary="登录过期检测")
|
||||||
|
def get_login_status() -> ApiResponse[list[dict]]:
|
||||||
|
"""
|
||||||
|
获取登录过期的账号列表(供前端右上角提示)。
|
||||||
|
|
||||||
|
【返回】[{account_id, brand, account_name, detected_at}, ...]
|
||||||
|
"""
|
||||||
|
from app.services.platform_scraper import get_login_expired
|
||||||
|
|
||||||
|
expired = get_login_expired()
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"{len(expired)} 个账号登录过期" if expired else "全部正常",
|
||||||
|
data=expired,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/accounts/{account_id}/login/clear-expired",
|
||||||
|
response_model=ApiResponse[dict],
|
||||||
|
summary="清除登录过期标记",
|
||||||
|
)
|
||||||
|
def clear_login_expired(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""重新登录后,清除该账号的登录过期标记。"""
|
||||||
|
from app.services.platform_scraper import clear_login_expired as _clear
|
||||||
|
|
||||||
|
_clear(account_id)
|
||||||
|
return ApiResponse(code=0, message="已清除", data={"account_id": account_id})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 定时抓取任务 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/scrape-progress", response_model=ApiResponse[dict], summary="抓取进度")
|
||||||
|
def get_scrape_progress() -> ApiResponse[dict]:
|
||||||
|
"""获取当前抓取进度(供前端轮询显示进度条)。"""
|
||||||
|
from app.services.platform_scraper import get_scrape_progress as _get_progress
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message="ok", data=_get_progress())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/schedule", response_model=ApiResponse[dict], summary="定时抓取配置")
|
||||||
|
def get_schedule() -> ApiResponse[dict]:
|
||||||
|
"""获取定时抓取配置(含运行状态)。"""
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
config = store.get_schedule()
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
config["scheduler_running"] = scheduler.is_running()
|
||||||
|
return ApiResponse(code=0, message="ok", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/schedule", response_model=ApiResponse[dict], summary="更新定时抓取配置")
|
||||||
|
def update_schedule(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
更新定时抓取配置并即时生效(含登录过期检测配置)。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"enabled": true, "interval_minutes": 360,
|
||||||
|
"account_ids": ["id1", "id2"],
|
||||||
|
"login_detect_enabled": true, "login_detect_interval": 60
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
enabled = payload.get("enabled")
|
||||||
|
interval_minutes = payload.get("interval_minutes")
|
||||||
|
account_ids = payload.get("account_ids")
|
||||||
|
login_detect_enabled = payload.get("login_detect_enabled")
|
||||||
|
login_detect_interval = payload.get("login_detect_interval")
|
||||||
|
|
||||||
|
config = store.update_schedule(
|
||||||
|
enabled=enabled,
|
||||||
|
interval_minutes=interval_minutes,
|
||||||
|
account_ids=account_ids,
|
||||||
|
login_detect_enabled=login_detect_enabled,
|
||||||
|
login_detect_interval=login_detect_interval,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 根据 enabled 即时启动/停止调度器
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
if enabled:
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.get_event_loop().create_task(scheduler.start())
|
||||||
|
except RuntimeError:
|
||||||
|
pass # 无事件循环时(如测试)跳过
|
||||||
|
else:
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.get_event_loop().create_task(scheduler.stop())
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
config["scheduler_running"] = scheduler.is_running()
|
||||||
|
return ApiResponse(code=0, message="定时配置已更新", data=config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/schedule/trigger", response_model=ApiResponse[dict], summary="立即执行一次抓取")
|
||||||
|
async def trigger_schedule() -> ApiResponse[dict]:
|
||||||
|
"""立即触发一次定时抓取(不等定时)。"""
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
result = await scheduler.trigger_now()
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/schedule/start", response_model=ApiResponse[dict], summary="启动调度器")
|
||||||
|
async def start_schedule() -> ApiResponse[dict]:
|
||||||
|
"""启动定时抓取调度器。"""
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
result = await scheduler.start()
|
||||||
|
return ApiResponse(
|
||||||
|
code=0 if result.get("success") else 1,
|
||||||
|
message=result.get("message", ""),
|
||||||
|
data=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/schedule/stop", response_model=ApiResponse[dict], summary="停止调度器")
|
||||||
|
async def stop_schedule() -> ApiResponse[dict]:
|
||||||
|
"""停止定时抓取调度器。"""
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
result = await scheduler.stop()
|
||||||
|
return ApiResponse(code=0, message=result.get("message", ""), data=result)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 用量查询 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/accounts/{account_id}/usage", response_model=ApiResponse[dict], summary="查询用量"
|
||||||
|
)
|
||||||
|
def get_usage(account_id: str) -> ApiResponse[dict]:
|
||||||
|
"""获取账号最新用量快照。"""
|
||||||
|
store = get_platform_store()
|
||||||
|
snapshot = store.get_latest_snapshot(account_id)
|
||||||
|
if snapshot is None:
|
||||||
|
return ApiResponse(code=0, message="暂无用量数据,请先抓取", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=snapshot)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/accounts/{account_id}/usage/history",
|
||||||
|
response_model=ApiResponse[list[dict]],
|
||||||
|
summary="用量历史",
|
||||||
|
)
|
||||||
|
def get_usage_history(account_id: str, limit: int = 30) -> ApiResponse[list[dict]]:
|
||||||
|
"""获取用量快照历史(供趋势分析)。"""
|
||||||
|
store = get_platform_store()
|
||||||
|
items = store.get_snapshots(account_id, limit)
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 条快照", data=items)
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
"""
|
||||||
|
项目管理 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供「待开发的系统/项目」的增删改查接口,以及按项目读取本地 Git 分支列表
|
||||||
|
的接口(支撑前端「前端仓库分支 / 后端仓库分支」下拉框)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. FastAPI:与 LangGraph 同为 Python 生态、异步原生、自动 OpenAPI 文档,
|
||||||
|
且基准文档附录已列明该依赖,符合硬约束 1。
|
||||||
|
2. 统一 ApiResponse 包裹:前端只认一种响应结构,错误码/提示语集中治理,
|
||||||
|
避免每个接口各写一套错误格式(硬约束 5 的「明确错误提示」)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- 依赖注入 ProjectStore / GitReadService:便于单测时替换为内存实现;
|
||||||
|
- 业务异常统一在本层捕获并转成结构化 ApiResponse,绝不把裸异常抛给前端;
|
||||||
|
- Git 分支读取失败(路径不是仓库等)不阻塞项目 CRUD,降级返回空列表 + 提示。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:项目路径存在但未 git init → 分支接口报错。
|
||||||
|
应对:返回 code=1 的业务错误 + 明确中文提示,而不是 500;
|
||||||
|
前端据此提示「该路径不是 Git 仓库」。
|
||||||
|
风险2:并发创建同名项目 → 名称冲突。
|
||||||
|
应对:一期允许同名(id 唯一即可),名称唯一约束留到后续按需加。
|
||||||
|
风险3:删除项目时存在关联任务 → 孤儿数据。
|
||||||
|
应对:一期任务表尚未启用,先在 delete 处留钩子注释;M3 上任务表时补级联。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
from app.config.settings import Settings, load_settings
|
||||||
|
from app.schemas.project import (
|
||||||
|
ApiResponse,
|
||||||
|
Project,
|
||||||
|
ProjectCreate,
|
||||||
|
ProjectUpdate,
|
||||||
|
)
|
||||||
|
from app.services.git_service import GitError, GitReadService
|
||||||
|
from app.store.project_store import ProjectStore, SqliteProjectStore
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["项目管理"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 依赖注入(便于单测替换)----------
|
||||||
|
|
||||||
|
_store_singleton: Optional[ProjectStore] = None
|
||||||
|
_git_singleton: Optional[GitReadService] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_store() -> ProjectStore:
|
||||||
|
"""获取项目存储实例(懒加载单例)。"""
|
||||||
|
global _store_singleton
|
||||||
|
if _store_singleton is None:
|
||||||
|
settings = load_settings()
|
||||||
|
_store_singleton = SqliteProjectStore(settings.sqlite_db_path)
|
||||||
|
return _store_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_git_service() -> GitReadService:
|
||||||
|
"""获取 Git 只读服务实例(懒加载单例)。"""
|
||||||
|
global _git_singleton
|
||||||
|
if _git_singleton is None:
|
||||||
|
_git_singleton = GitReadService()
|
||||||
|
return _git_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
"""获取全局配置(供路由内读取路径约束)。"""
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 项目 CRUD ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/projects", response_model=ApiResponse[Project], summary="创建项目")
|
||||||
|
def create_project(
|
||||||
|
payload: ProjectCreate,
|
||||||
|
store: ProjectStore = Depends(get_store),
|
||||||
|
) -> ApiResponse[Project]:
|
||||||
|
"""
|
||||||
|
创建一个待开发的项目登记记录。
|
||||||
|
|
||||||
|
- name:项目名称
|
||||||
|
- code_root_path:本地代码根路径(必须在 D 盘,硬约束 6)
|
||||||
|
- backend_path / frontend_path:后端/前端子路径(相对 code_root_path)
|
||||||
|
- backend_branch / frontend_branch:对应 Git 分支名
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
project = store.create(payload)
|
||||||
|
except Exception as exc: # 兜底:任何存储异常都转成业务错误,不 500
|
||||||
|
return ApiResponse(code=500, message=f"创建项目失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="项目创建成功", data=project)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/projects", response_model=ApiResponse[list[Project]], summary="项目列表")
|
||||||
|
def list_projects(
|
||||||
|
name: str = "",
|
||||||
|
store: ProjectStore = Depends(get_store),
|
||||||
|
) -> ApiResponse[list[Project]]:
|
||||||
|
"""
|
||||||
|
查询全部已登记项目(按排序值排列)。
|
||||||
|
|
||||||
|
【查询参数】name:按项目名称模糊筛选(留空返回全部)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
items = store.list_all()
|
||||||
|
if name:
|
||||||
|
keyword = name.strip().lower()
|
||||||
|
items = [p for p in items if keyword in p.name.lower()]
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询项目列表失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/projects/{project_id}", response_model=ApiResponse[Project], summary="项目详情"
|
||||||
|
)
|
||||||
|
def get_project(
|
||||||
|
project_id: str, store: ProjectStore = Depends(get_store)
|
||||||
|
) -> ApiResponse[Project]:
|
||||||
|
"""按 ID 查询单个项目详情。"""
|
||||||
|
try:
|
||||||
|
project = store.get(project_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询项目失败:{exc}", data=None)
|
||||||
|
if project is None:
|
||||||
|
return ApiResponse(code=404, message=f"项目不存在:{project_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=project)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/projects/{project_id}", response_model=ApiResponse[Project], summary="更新项目"
|
||||||
|
)
|
||||||
|
def update_project(
|
||||||
|
project_id: str,
|
||||||
|
payload: ProjectUpdate,
|
||||||
|
store: ProjectStore = Depends(get_store),
|
||||||
|
) -> ApiResponse[Project]:
|
||||||
|
"""按需更新项目字段(只覆盖显式传入的字段)。"""
|
||||||
|
try:
|
||||||
|
project = store.update(project_id, payload)
|
||||||
|
except ValueError as exc: # 校验错误(如非 D 盘路径)
|
||||||
|
return ApiResponse(code=422, message=f"参数校验失败:{exc}", data=None)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"更新项目失败:{exc}", data=None)
|
||||||
|
if project is None:
|
||||||
|
return ApiResponse(code=404, message=f"项目不存在:{project_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="项目更新成功", data=project)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/projects/{project_id}", response_model=ApiResponse[bool], summary="删除项目"
|
||||||
|
)
|
||||||
|
def delete_project(
|
||||||
|
project_id: str, store: ProjectStore = Depends(get_store)
|
||||||
|
) -> ApiResponse[bool]:
|
||||||
|
"""删除指定项目。"""
|
||||||
|
# TODO(M3):项目删除时级联清理关联任务记录,避免孤儿数据
|
||||||
|
try:
|
||||||
|
deleted = store.delete(project_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"删除项目失败:{exc}", data=None)
|
||||||
|
if not deleted:
|
||||||
|
return ApiResponse(code=404, message=f"项目不存在:{project_id}", data=False)
|
||||||
|
return ApiResponse(code=0, message="项目删除成功", data=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Git 分支读取 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/projects/{project_id}/branches",
|
||||||
|
response_model=ApiResponse[dict[str, list[str]]],
|
||||||
|
summary="读取项目 Git 分支",
|
||||||
|
)
|
||||||
|
def list_project_branches(
|
||||||
|
project_id: str,
|
||||||
|
store: ProjectStore = Depends(get_store),
|
||||||
|
git_service: GitReadService = Depends(get_git_service),
|
||||||
|
) -> ApiResponse[dict[str, list[str]]]:
|
||||||
|
"""
|
||||||
|
读取该项目「后端仓库」与「前端仓库」的本地 Git 分支列表,
|
||||||
|
供前端「前端仓库分支 / 后端仓库分支」下拉框使用。
|
||||||
|
|
||||||
|
【返回结构】
|
||||||
|
{
|
||||||
|
"backend": ["master", "develop", ...],
|
||||||
|
"frontend": ["master", "feature-xxx", ...]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
project = store.get(project_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询项目失败:{exc}", data=None)
|
||||||
|
if project is None:
|
||||||
|
return ApiResponse(code=404, message=f"项目不存在:{project_id}", data=None)
|
||||||
|
|
||||||
|
code_root = Path(project.code_root_path)
|
||||||
|
result: dict[str, list[str]] = {"backend": [], "frontend": []}
|
||||||
|
warnings: list[str] = []
|
||||||
|
|
||||||
|
# 后端仓库分支
|
||||||
|
backend_dir = code_root / project.backend_path
|
||||||
|
try:
|
||||||
|
if git_service.is_git_repo(backend_dir):
|
||||||
|
result["backend"] = git_service.list_branches(backend_dir)
|
||||||
|
else:
|
||||||
|
warnings.append(f"后端路径不是 Git 仓库:{backend_dir}")
|
||||||
|
except GitError as exc:
|
||||||
|
warnings.append(f"读取后端分支失败:{exc}")
|
||||||
|
|
||||||
|
# 前端仓库分支
|
||||||
|
frontend_dir = code_root / project.frontend_path
|
||||||
|
try:
|
||||||
|
if git_service.is_git_repo(frontend_dir):
|
||||||
|
result["frontend"] = git_service.list_branches(frontend_dir)
|
||||||
|
else:
|
||||||
|
warnings.append(f"前端路径不是 Git 仓库:{frontend_dir}")
|
||||||
|
except GitError as exc:
|
||||||
|
warnings.append(f"读取前端分支失败:{exc}")
|
||||||
|
|
||||||
|
# 有告警时仍返回数据(降级),但提示语带出原因
|
||||||
|
message = "ok" if not warnings else ";".join(warnings)
|
||||||
|
return ApiResponse(code=0 if not warnings else 1, message=message, data=result)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""
|
||||||
|
提示词优化 API
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】把用户粗糙的想法润色成高质量提示词。
|
||||||
|
【实现思路】调用 prompt-polisher Skill 规则 + LLM,返回结构化结果。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.prompt_polisher_service import polish
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.prompt_polisher.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/prompt-polish", tags=["提示词优化"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="优化提示词")
|
||||||
|
def polish_prompt(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
把粗糙/口语化的想法润色成高质量提示词。
|
||||||
|
|
||||||
|
【请求体】
|
||||||
|
{"text": "帮我弄个周报", "model_preference": "auto"}
|
||||||
|
【返回】
|
||||||
|
{polish_result, changes, questions, model}
|
||||||
|
"""
|
||||||
|
text = (payload.get("text") or "").strip()
|
||||||
|
model_preference = payload.get("model_preference", "auto")
|
||||||
|
|
||||||
|
if not text:
|
||||||
|
return ApiResponse(code=422, message="请输入要优化的内容", data=None)
|
||||||
|
|
||||||
|
result = polish(text, model_preference)
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "优化失败"), data=None)
|
||||||
|
return ApiResponse(code=0, message="优化完成", data=result)
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""
|
||||||
|
Provider 服务通道 API
|
||||||
|
====================
|
||||||
|
|
||||||
|
【功能说明】管理多个 AI 模型服务通道(GLM/DeepSeek/Mimo 等平台)的地址与密钥。
|
||||||
|
【实现思路】CRUD + 连接测试,密钥加密存储、脱敏返回。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.store.provider_store import get_provider_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.provider.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/providers", tags=["Provider 管理"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[dict]], summary="Provider 列表")
|
||||||
|
def list_providers() -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有 Provider(密钥脱敏)。"""
|
||||||
|
store = get_provider_store()
|
||||||
|
items = store.list_all()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 个 Provider", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="创建 Provider")
|
||||||
|
def create_provider(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""创建 Provider(一个 AI 平台的连接配置)。"""
|
||||||
|
name = (payload.get("name") or "").strip()
|
||||||
|
base_url = (payload.get("base_url") or "").strip()
|
||||||
|
if not name or not base_url:
|
||||||
|
return ApiResponse(code=422, message="name 和 base_url 必填", data=None)
|
||||||
|
|
||||||
|
store = get_provider_store()
|
||||||
|
if store.get_by_name(name):
|
||||||
|
return ApiResponse(code=409, message=f"Provider「{name}」已存在", data=None)
|
||||||
|
|
||||||
|
provider = store.create(
|
||||||
|
name=name,
|
||||||
|
base_url=base_url,
|
||||||
|
api_key=payload.get("api_key", ""),
|
||||||
|
description=payload.get("description", ""),
|
||||||
|
)
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message="Provider 创建成功", data=provider)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{provider_id}", response_model=ApiResponse[dict], summary="更新 Provider")
|
||||||
|
def update_provider(provider_id: str, payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""更新 Provider 配置。"""
|
||||||
|
store = get_provider_store()
|
||||||
|
provider = store.update(provider_id, **payload)
|
||||||
|
if provider is None:
|
||||||
|
return ApiResponse(code=404, message=f"Provider 不存在:{provider_id}", data=None)
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0, message="Provider 更新成功", data=provider)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{provider_id}", response_model=ApiResponse[bool], summary="删除 Provider")
|
||||||
|
def delete_provider(provider_id: str) -> ApiResponse[bool]:
|
||||||
|
"""删除 Provider。"""
|
||||||
|
store = get_provider_store()
|
||||||
|
ok = store.delete(provider_id)
|
||||||
|
if ok:
|
||||||
|
from app.models.model_router import invalidate_model_cache
|
||||||
|
|
||||||
|
invalidate_model_cache()
|
||||||
|
return ApiResponse(code=0 if ok else 404, message="删除成功" if ok else "Provider 不存在", data=ok)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{provider_id}/test", response_model=ApiResponse[dict], summary="测试连接")
|
||||||
|
def test_provider(provider_id: str) -> ApiResponse[dict]:
|
||||||
|
"""测试 Provider 连接是否正常(GET /models 轻量探测)。"""
|
||||||
|
store = get_provider_store()
|
||||||
|
# 按 ID 查真实 key(测试连接必须用真实 key,不能用脱敏值)
|
||||||
|
provider = store.get_with_key_by_id(provider_id)
|
||||||
|
if provider is None:
|
||||||
|
# 兼容:按 name 查
|
||||||
|
provider = store.get_with_key(provider_id)
|
||||||
|
|
||||||
|
if provider is None:
|
||||||
|
return ApiResponse(code=404, message=f"Provider 不存在:{provider_id}", data=None)
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = httpx.get(
|
||||||
|
f"{provider['base_url']}/models",
|
||||||
|
headers={"Authorization": f"Bearer {provider['api_key']}"},
|
||||||
|
timeout=10.0,
|
||||||
|
)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
data = resp.json()
|
||||||
|
model_count = len(data.get("data", [])) if isinstance(data, dict) else 0
|
||||||
|
msg = f"连接成功({model_count} 个模型)"
|
||||||
|
return ApiResponse(code=0, message=msg, data={"success": True, "message": msg, "model_count": model_count})
|
||||||
|
msg = f"连接失败(HTTP {resp.status_code})"
|
||||||
|
return ApiResponse(code=1, message=msg, data={"success": False, "message": msg})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
msg = f"连接失败:{exc}"
|
||||||
|
return ApiResponse(code=1, message=msg, data={"success": False, "message": msg})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{provider_id}/fetch-models", response_model=ApiResponse[list[str]], summary="拉取可用模型"
|
||||||
|
)
|
||||||
|
def fetch_models(provider_id: str) -> ApiResponse[list[str]]:
|
||||||
|
"""
|
||||||
|
调用 Provider 的 /models 接口拉取所有可用模型 ID。
|
||||||
|
|
||||||
|
【返回】模型 ID 列表(如 ["glm-5.3", "deepseek-v4-pro", ...])
|
||||||
|
"""
|
||||||
|
store = get_provider_store()
|
||||||
|
provider = store.get_with_key_by_id(provider_id)
|
||||||
|
if provider is None:
|
||||||
|
provider = store.get_with_key(provider_id)
|
||||||
|
if provider is None:
|
||||||
|
return ApiResponse(code=404, message=f"Provider 不存在:{provider_id}", data=None)
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = httpx.get(
|
||||||
|
f"{provider['base_url']}/models",
|
||||||
|
headers={"Authorization": f"Bearer {provider['api_key']}"},
|
||||||
|
timeout=15.0,
|
||||||
|
)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
data = resp.json()
|
||||||
|
models = []
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for item in data.get("data", []):
|
||||||
|
if isinstance(item, dict) and item.get("id"):
|
||||||
|
models.append(item["id"])
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"拉取到 {len(models)} 个模型",
|
||||||
|
data=models,
|
||||||
|
)
|
||||||
|
return ApiResponse(
|
||||||
|
code=1,
|
||||||
|
message=f"拉取失败(HTTP {resp.status_code})",
|
||||||
|
data=[],
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return ApiResponse(code=1, message=f"拉取失败:{exc}", data=[])
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
"""
|
||||||
|
系统配置 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】读取/写入 .env 配置文件,供前端「系统配置」页实时编辑。
|
||||||
|
【实现思路】解析 .env 为 dict → 返回前端;前端修改后写回 .env(保留注释)。
|
||||||
|
【注】敏感字段脱敏逻辑已移除,全部明文处理。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.settings.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/settings", tags=["系统配置"])
|
||||||
|
|
||||||
|
# .env 文件路径
|
||||||
|
ENV_PATH = Path(r"D:\Agent\agent\backend\.env")
|
||||||
|
|
||||||
|
# 备注存储文件(.env 不支持元数据,单独存 JSON)
|
||||||
|
REMARKS_PATH = Path(r"D:\Agent\agent\backend\.env.remarks.json")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_remarks() -> dict[str, str]:
|
||||||
|
"""加载备注字典。"""
|
||||||
|
if not REMARKS_PATH.exists():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
return json.loads(REMARKS_PATH.read_text(encoding="utf-8"))
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _save_remarks(remarks: dict[str, str]) -> None:
|
||||||
|
"""保存备注字典。"""
|
||||||
|
REMARKS_PATH.write_text(
|
||||||
|
json.dumps(remarks, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_env(text: str) -> dict[str, str]:
|
||||||
|
"""解析 .env 文本为 key-value dict(保留注释行原样)。"""
|
||||||
|
result: dict[str, str] = {}
|
||||||
|
for line in text.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
match = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$", line)
|
||||||
|
if match:
|
||||||
|
key, value = match.group(1), match.group(2).strip()
|
||||||
|
if " #" in value:
|
||||||
|
value = value.split(" #")[0].strip()
|
||||||
|
result[key] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _write_env(env_dict: dict[str, str]) -> None:
|
||||||
|
"""
|
||||||
|
将 key-value 写回 .env(保留原有注释和格式)。
|
||||||
|
|
||||||
|
【策略】逐行扫描原文件:
|
||||||
|
- 匹配到已有 key → 更新值;
|
||||||
|
- 未匹配到的 key → 追加到文件末尾;
|
||||||
|
- 注释和空行原样保留。
|
||||||
|
"""
|
||||||
|
if not ENV_PATH.exists():
|
||||||
|
raise FileNotFoundError(f".env 文件不存在:{ENV_PATH}")
|
||||||
|
|
||||||
|
original_lines = ENV_PATH.read_text(encoding="utf-8").splitlines()
|
||||||
|
written_keys: set[str] = set()
|
||||||
|
new_lines: list[str] = []
|
||||||
|
|
||||||
|
for line in original_lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
match = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$", stripped)
|
||||||
|
if match:
|
||||||
|
key = match.group(1)
|
||||||
|
if key in env_dict:
|
||||||
|
new_lines.append(f"{key}={env_dict[key]}")
|
||||||
|
written_keys.add(key)
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
|
||||||
|
for key, value in env_dict.items():
|
||||||
|
if key not in written_keys:
|
||||||
|
new_lines.append(f"{key}={value}")
|
||||||
|
|
||||||
|
ENV_PATH.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
|
||||||
|
logger.info("配置已写入 .env:%d 个字段", len(env_dict))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[dict[str, str]], summary="读取系统配置")
|
||||||
|
def get_settings() -> ApiResponse[dict[str, str]]:
|
||||||
|
"""读取 .env 配置(全部明文返回)。"""
|
||||||
|
if not ENV_PATH.exists():
|
||||||
|
return ApiResponse(code=404, message=f".env 文件不存在:{ENV_PATH}", data=None)
|
||||||
|
try:
|
||||||
|
text = ENV_PATH.read_text(encoding="utf-8")
|
||||||
|
env_dict = _parse_env(text)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"读取配置失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=env_dict)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("", response_model=ApiResponse[dict[str, str]], summary="写入系统配置")
|
||||||
|
def update_settings(payload: dict[str, Any]) -> ApiResponse[dict[str, str]]:
|
||||||
|
"""更新 .env 配置(只更新提交的字段,其余保持不变)。"""
|
||||||
|
if not payload:
|
||||||
|
return ApiResponse(code=422, message="配置内容不能为空", data=None)
|
||||||
|
try:
|
||||||
|
current_text = ENV_PATH.read_text(encoding="utf-8") if ENV_PATH.exists() else ""
|
||||||
|
current_env = _parse_env(current_text)
|
||||||
|
merged = {k: str(v) for k, v in payload.items()}
|
||||||
|
_write_env(merged)
|
||||||
|
load_settings.cache_clear()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"写入配置失败:{exc}", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
text = ENV_PATH.read_text(encoding="utf-8")
|
||||||
|
env_dict = _parse_env(text)
|
||||||
|
except Exception:
|
||||||
|
env_dict = {}
|
||||||
|
return ApiResponse(code=0, message="配置已保存并同步到 .env", data=env_dict)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 配置项 CRUD ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/items", response_model=ApiResponse[list[dict[str, str]]], summary="配置项列表"
|
||||||
|
)
|
||||||
|
def list_settings_items(keyword: str = "") -> ApiResponse[list[dict[str, str]]]:
|
||||||
|
"""列出全部配置项(含备注,支持关键字筛选)。"""
|
||||||
|
if not ENV_PATH.exists():
|
||||||
|
return ApiResponse(code=0, message="ok", data=[])
|
||||||
|
try:
|
||||||
|
text = ENV_PATH.read_text(encoding="utf-8")
|
||||||
|
env_dict = _parse_env(text)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"读取失败:{exc}", data=None)
|
||||||
|
|
||||||
|
remarks = _load_remarks()
|
||||||
|
items = [
|
||||||
|
{"key": k, "value": v, "remark": remarks.get(k, "")}
|
||||||
|
for k, v in env_dict.items()
|
||||||
|
if not keyword or keyword.lower() in k.lower()
|
||||||
|
]
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 项", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/items", response_model=ApiResponse[dict], summary="新增配置项")
|
||||||
|
def create_settings_item(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""新增一个配置项(追加到 .env,备注存 JSON)。"""
|
||||||
|
key = (payload.get("key") or "").strip()
|
||||||
|
value = str(payload.get("value", ""))
|
||||||
|
remark = str(payload.get("remark", ""))
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
return ApiResponse(code=422, message="配置名不能为空", data=None)
|
||||||
|
if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key):
|
||||||
|
return ApiResponse(code=422, message="配置名只能包含字母、数字、下划线,且不以数字开头", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
current_text = ENV_PATH.read_text(encoding="utf-8") if ENV_PATH.exists() else ""
|
||||||
|
current_env = _parse_env(current_text)
|
||||||
|
if key in current_env:
|
||||||
|
return ApiResponse(code=409, message=f"配置 {key} 已存在", data=None)
|
||||||
|
|
||||||
|
with open(ENV_PATH, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"\n{key}={value}\n")
|
||||||
|
|
||||||
|
# 保存备注
|
||||||
|
if remark:
|
||||||
|
remarks = _load_remarks()
|
||||||
|
remarks[key] = remark
|
||||||
|
_save_remarks(remarks)
|
||||||
|
|
||||||
|
load_settings.cache_clear()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"新增失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message=f"配置 {key} 已添加", data={"key": key})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/items/{item_key}", response_model=ApiResponse[dict], summary="修改配置项")
|
||||||
|
def update_settings_item(item_key: str, payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
"""修改指定配置项的值、备注(或改名)。"""
|
||||||
|
if not item_key:
|
||||||
|
return ApiResponse(code=422, message="配置名不能为空", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
current_text = ENV_PATH.read_text(encoding="utf-8") if ENV_PATH.exists() else ""
|
||||||
|
current_env = _parse_env(current_text)
|
||||||
|
if item_key not in current_env:
|
||||||
|
return ApiResponse(code=404, message=f"配置 {item_key} 不存在", data=None)
|
||||||
|
|
||||||
|
new_value = payload.get("value", current_env[item_key])
|
||||||
|
new_key = payload.get("new_key", item_key)
|
||||||
|
remark = payload.get("remark")
|
||||||
|
|
||||||
|
if new_key != item_key:
|
||||||
|
if new_key in current_env:
|
||||||
|
return ApiResponse(code=409, message=f"目标名 {new_key} 已存在", data=None)
|
||||||
|
current_env.pop(item_key, None)
|
||||||
|
|
||||||
|
current_env[new_key] = str(new_value)
|
||||||
|
_write_env(current_env)
|
||||||
|
|
||||||
|
# 更新备注
|
||||||
|
remarks = _load_remarks()
|
||||||
|
if remark is not None:
|
||||||
|
if new_key != item_key and item_key in remarks:
|
||||||
|
remarks.pop(item_key, None)
|
||||||
|
remarks[new_key] = str(remark)
|
||||||
|
elif new_key != item_key and item_key in remarks:
|
||||||
|
remarks[new_key] = remarks.pop(item_key, "")
|
||||||
|
_save_remarks(remarks)
|
||||||
|
|
||||||
|
load_settings.cache_clear()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"修改失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message=f"配置 {new_key} 已更新", data={"key": new_key})
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/items/{item_key}", response_model=ApiResponse[bool], summary="删除配置项"
|
||||||
|
)
|
||||||
|
def delete_settings_item(item_key: str) -> ApiResponse[bool]:
|
||||||
|
"""删除指定配置项(从 .env 文件中移除)。"""
|
||||||
|
try:
|
||||||
|
current_text = ENV_PATH.read_text(encoding="utf-8") if ENV_PATH.exists() else ""
|
||||||
|
current_env = _parse_env(current_text)
|
||||||
|
if item_key not in current_env:
|
||||||
|
return ApiResponse(code=404, message=f"配置 {item_key} 不存在", data=False)
|
||||||
|
|
||||||
|
original_lines = ENV_PATH.read_text(encoding="utf-8").splitlines()
|
||||||
|
new_lines = []
|
||||||
|
for line in original_lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
match = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$", stripped)
|
||||||
|
if match and match.group(1) == item_key:
|
||||||
|
continue
|
||||||
|
new_lines.append(line)
|
||||||
|
|
||||||
|
ENV_PATH.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
# 删除备注
|
||||||
|
remarks = _load_remarks()
|
||||||
|
if item_key in remarks:
|
||||||
|
remarks.pop(item_key, None)
|
||||||
|
_save_remarks(remarks)
|
||||||
|
|
||||||
|
load_settings.cache_clear()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"删除失败:{exc}", data=False)
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message=f"配置 {item_key} 已删除", data=True)
|
||||||
@@ -0,0 +1,454 @@
|
|||||||
|
"""
|
||||||
|
任务 API(REST + SSE)
|
||||||
|
=====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供任务提交、查询、审批、SSE 进度订阅接口,是前端「任务入口」的后端能力。
|
||||||
|
对应《核心诉求》第 3/4 条:输入需求 → Agent 自动执行。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. SSE 选 sse-starlette(基准文档附录已列):
|
||||||
|
比 WebSocket 轻、HTTP 原生、自动重连友好,长任务进度推送的标准做法。
|
||||||
|
2. 事件粒度 = 图节点级:前端能看到「正在执行第几个节点」,
|
||||||
|
对应可观测性要求(决策点 9:主图可观测)。
|
||||||
|
3. 审批接口走 POST + 决策体:与 LangGraph Command(resume=...) 对接。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- POST /tasks:创建任务并异步启动,立即返回 task_id;
|
||||||
|
- GET /tasks/{id}/stream:SSE 持续推送节点事件直到 done/error;
|
||||||
|
- POST /tasks/{id}/approve:提交审批结果,从断点恢复。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:SSE 长连接占用资源。
|
||||||
|
应对:客户端断开时 finally 取消订阅,释放队列。
|
||||||
|
风险2:任务已完成后再发审批。
|
||||||
|
应对:校验 status==waiting_approval 才允许,否则返回业务错误。
|
||||||
|
风险3:并发提交同一任务的审批。
|
||||||
|
应对:状态迁移表约束(waiting_approval → running),
|
||||||
|
并发第二次会因非法迁移被拒绝。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends
|
||||||
|
from sse_starlette.sse import EventSourceResponse
|
||||||
|
|
||||||
|
from app.config.settings import Settings, load_settings
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.schemas.task import Task, TaskCreate
|
||||||
|
from app.tasks.task_service import TaskService
|
||||||
|
from app.tasks.task_store import SqliteTaskStore
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tasks.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/tasks", tags=["任务执行"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 依赖注入 ----------
|
||||||
|
|
||||||
|
_service_singleton: Optional[TaskService] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_task_service() -> TaskService:
|
||||||
|
"""获取任务服务单例。"""
|
||||||
|
global _service_singleton
|
||||||
|
if _service_singleton is None:
|
||||||
|
settings = load_settings()
|
||||||
|
store = SqliteTaskStore(settings.sqlite_db_path)
|
||||||
|
_service_singleton = TaskService(store)
|
||||||
|
return _service_singleton
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 模型选项(供前端下拉框)----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/models/options", response_model=ApiResponse[list[dict[str, str]]], summary="可用模型选项"
|
||||||
|
)
|
||||||
|
def list_model_options() -> ApiResponse[list[dict[str, str]]]:
|
||||||
|
"""
|
||||||
|
列出提交任务时可选的模型偏好(供前端下拉框)。
|
||||||
|
|
||||||
|
【返回】[{value: "auto", label: "..."}, {value: "<模型ID>", label: "..."}]
|
||||||
|
【说明】value 会原样回传给 POST /api/tasks 的 model_preference 字段。
|
||||||
|
"""
|
||||||
|
from app.models.model_router import list_available_models
|
||||||
|
|
||||||
|
try:
|
||||||
|
options = list_available_models()
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"获取模型选项失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=options)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 任务提交与查询 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[Task], summary="提交任务")
|
||||||
|
async def create_task(
|
||||||
|
payload: TaskCreate,
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[Task]:
|
||||||
|
"""
|
||||||
|
提交一个开发/修复需求,异步启动 Agent 执行。
|
||||||
|
|
||||||
|
【请求体】{"project_id": "proj_xxx", "requirement_text": "实现XX功能", "task_type": "feature"}
|
||||||
|
【返回】任务实体(status=running),可通过 /tasks/{id}/stream 看进度
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
task = await service.create_and_run(payload)
|
||||||
|
except Exception as exc: # 兜底:任何异常转业务错误
|
||||||
|
logger.exception("任务创建失败")
|
||||||
|
return ApiResponse(code=500, message=f"任务创建失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="任务已提交,正在执行", data=task)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[Task]], summary="任务列表")
|
||||||
|
def list_tasks(
|
||||||
|
project_id: str | None = None,
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[list[Task]]:
|
||||||
|
"""查询任务列表(可按项目过滤)。"""
|
||||||
|
try:
|
||||||
|
tasks = service.list_tasks(project_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=tasks)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}", response_model=ApiResponse[Task], summary="任务详情")
|
||||||
|
def get_task(
|
||||||
|
task_id: str,
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[Task]:
|
||||||
|
"""查询单个任务的状态与报告。"""
|
||||||
|
task = service.get_task(task_id)
|
||||||
|
if task is None:
|
||||||
|
return ApiResponse(code=404, message=f"任务不存在:{task_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="ok", data=task)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 对话续聊(一条任务 = 一个完整对话) ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{task_id}/chat",
|
||||||
|
response_model=ApiResponse[Task],
|
||||||
|
summary="对话续聊",
|
||||||
|
)
|
||||||
|
async def continue_chat(
|
||||||
|
task_id: str,
|
||||||
|
payload: dict = Body(...),
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[Task]:
|
||||||
|
"""
|
||||||
|
在已有任务上追加对话消息(一条任务 = 一个完整对话)。
|
||||||
|
|
||||||
|
【请求体】{"message": "你好", "model": "mimo-v2.6-pro"}
|
||||||
|
【返回】任务实体(含最新对话历史)
|
||||||
|
"""
|
||||||
|
message = (payload.get("message") or "").strip()
|
||||||
|
model = (payload.get("model") or "").strip()
|
||||||
|
if not message:
|
||||||
|
return ApiResponse(code=422, message="message 不能为空", data=None)
|
||||||
|
try:
|
||||||
|
task = await service.continue_chat(task_id, message, model=model)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"对话失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message="消息已发送", data=task)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 任务停止 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{task_id}/stop", response_model=ApiResponse[Task], summary="手动停止任务")
|
||||||
|
def stop_task(
|
||||||
|
task_id: str,
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[Task]:
|
||||||
|
"""
|
||||||
|
手动停止执行中的任务(标记为 failed,可后续删除)。
|
||||||
|
|
||||||
|
【前置】仅 running / waiting_approval 状态可停止
|
||||||
|
"""
|
||||||
|
task = service.get_task(task_id)
|
||||||
|
if task is None:
|
||||||
|
return ApiResponse(code=404, message=f"任务不存在:{task_id}", data=None)
|
||||||
|
if task.status not in ("running", "waiting_approval"):
|
||||||
|
return ApiResponse(
|
||||||
|
code=409,
|
||||||
|
message=f"任务当前状态为 {task.status},无需停止",
|
||||||
|
data=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 【BUG-1 修复】先 kill 子进程,再改状态——防止进程继续跑
|
||||||
|
from app.tools.claude_engine import kill_process
|
||||||
|
kill_process(task_id)
|
||||||
|
|
||||||
|
# 【BUG-2 修复】停止后立即释放并发锁,允许用户马上发新消息
|
||||||
|
service._running_tasks.discard(task_id)
|
||||||
|
|
||||||
|
updated = service.update_task_status(
|
||||||
|
task_id, status="failed", error="用户手动停止"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"停止失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message="任务已停止", data=updated)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 批量删除 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/sort", response_model=ApiResponse[dict], summary="更新任务排序"
|
||||||
|
)
|
||||||
|
def update_task_sort(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
更新任务的排序值(上下箭头调整顺序)。
|
||||||
|
|
||||||
|
【请求体】{"task_id": "xxx", "sort_order": 0}
|
||||||
|
"""
|
||||||
|
task_id = payload.get("task_id")
|
||||||
|
sort_order = payload.get("sort_order")
|
||||||
|
if not task_id or sort_order is None:
|
||||||
|
return ApiResponse(code=422, message="task_id 和 sort_order 必填", data=None)
|
||||||
|
|
||||||
|
task = service.update_task_sort_order(task_id, int(sort_order))
|
||||||
|
if task is None:
|
||||||
|
return ApiResponse(code=404, message=f"任务不存在:{task_id}", data=None)
|
||||||
|
return ApiResponse(code=0, message="排序更新成功", data={"id": task.id, "sort_order": task.sort_order})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/batch-delete", response_model=ApiResponse[dict], summary="批量删除任务"
|
||||||
|
)
|
||||||
|
def batch_delete_tasks(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
批量删除指定任务(含历史报告与审批记录)。
|
||||||
|
|
||||||
|
【请求体】{"task_ids": ["task_a", "task_b", ...]}
|
||||||
|
【返回】{deleted, failed, messages: [...]}
|
||||||
|
【注意】执行中的任务需先停止(或忽略执行中任务),只删已结束的。
|
||||||
|
"""
|
||||||
|
task_ids = payload.get("task_ids")
|
||||||
|
if not isinstance(task_ids, list) or not task_ids:
|
||||||
|
return ApiResponse(code=422, message="请至少选择一个任务", data=None)
|
||||||
|
|
||||||
|
deleted: list[str] = []
|
||||||
|
failed: list[dict[str, str]] = []
|
||||||
|
|
||||||
|
for task_id in task_ids:
|
||||||
|
try:
|
||||||
|
task = service.get_task(task_id)
|
||||||
|
if task is None:
|
||||||
|
failed.append({"id": task_id, "reason": "任务不存在"})
|
||||||
|
continue
|
||||||
|
if task.status == "running":
|
||||||
|
failed.append({"id": task_id, "reason": "任务执行中,请先停止"})
|
||||||
|
continue
|
||||||
|
# 调存储层删除
|
||||||
|
ok = service.delete_task(task_id)
|
||||||
|
if ok:
|
||||||
|
deleted.append(task_id)
|
||||||
|
else:
|
||||||
|
failed.append({"id": task_id, "reason": "删除失败"})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
failed.append({"id": task_id, "reason": f"删除异常:{exc}"})
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"批量删除完成:成功 {len(deleted)},失败 {len(failed)}",
|
||||||
|
data={"deleted": deleted, "failed": failed},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- SSE 进度推送 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}/stream", summary="任务进度 SSE 流")
|
||||||
|
async def stream_task(
|
||||||
|
task_id: str,
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> EventSourceResponse:
|
||||||
|
"""
|
||||||
|
SSE 持续推送任务执行进度。
|
||||||
|
|
||||||
|
【事件类型】claude_output / node_end / status_change / error / done
|
||||||
|
【客户端】EventSource 或 fetch + ReadableStream
|
||||||
|
|
||||||
|
【L5 实现要点】改为**尾随事件日志文件**,而不是进程内内存总线:
|
||||||
|
- 任务由独立 worker 进程执行,内存总线跨不了进程;
|
||||||
|
- API 重启后 SSE 重连,可从日志文件续上,历史事件不丢;
|
||||||
|
- 因此即使后端被 reload,前端重连仍能看到完整输出。
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def event_generator():
|
||||||
|
"""SSE 事件生成器:尾随事件日志并持续推送。"""
|
||||||
|
from app.tasks.event_log import get_event_log
|
||||||
|
|
||||||
|
log = get_event_log()
|
||||||
|
offset = 0
|
||||||
|
|
||||||
|
# 先推一条连接确认事件
|
||||||
|
yield {
|
||||||
|
"event": "connected",
|
||||||
|
"data": f'{{"task_id": "{task_id}", "message": "进度流已连接"}}',
|
||||||
|
}
|
||||||
|
|
||||||
|
idle_rounds = 0
|
||||||
|
# 空闲上限:约 60 秒无任何事件则收流(防止客户端挂死)
|
||||||
|
max_idle = 400
|
||||||
|
# 心跳限频:约 3 秒一次,而不是每次空轮询都发(避免刷屏)
|
||||||
|
heartbeat_every = 20
|
||||||
|
|
||||||
|
while True:
|
||||||
|
events, offset = log.read_from(task_id, offset)
|
||||||
|
if events:
|
||||||
|
idle_rounds = 0
|
||||||
|
for ev in events:
|
||||||
|
yield {
|
||||||
|
"event": ev.get("event", "message"),
|
||||||
|
"data": json.dumps(ev, ensure_ascii=False),
|
||||||
|
}
|
||||||
|
if ev.get("event") in ("done", "error"):
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
idle_rounds += 1
|
||||||
|
# 心跳保活(部分代理会断空闲连接),但要限频
|
||||||
|
if idle_rounds % heartbeat_every == 0:
|
||||||
|
yield {"event": "heartbeat", "data": "{}"}
|
||||||
|
|
||||||
|
# 任务已终态:把日志尾部剩余事件吃干净再退出
|
||||||
|
task = service.get_task(task_id)
|
||||||
|
if task and task.status in ("done", "failed", "degraded"):
|
||||||
|
tail_events, offset = log.read_from(task_id, offset)
|
||||||
|
for ev in tail_events:
|
||||||
|
yield {
|
||||||
|
"event": ev.get("event", "message"),
|
||||||
|
"data": json.dumps(ev, ensure_ascii=False),
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
if idle_rounds >= max_idle:
|
||||||
|
return
|
||||||
|
|
||||||
|
await asyncio.sleep(0.15)
|
||||||
|
|
||||||
|
return EventSourceResponse(event_generator())
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- HITL 审批 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{task_id}/approve", response_model=ApiResponse[Task], summary="提交审批结果"
|
||||||
|
)
|
||||||
|
async def approve_task(
|
||||||
|
task_id: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: TaskService = Depends(get_task_service),
|
||||||
|
) -> ApiResponse[Task]:
|
||||||
|
"""
|
||||||
|
提交人工审批结果并从断点恢复执行(HITL)。
|
||||||
|
|
||||||
|
【请求体】{"decision": "approve"|"reject"|"edit", "comment": "意见"}
|
||||||
|
【前置】任务须处于 waiting_approval 状态
|
||||||
|
"""
|
||||||
|
decision = payload.get("decision", "")
|
||||||
|
if decision not in ("approve", "reject", "edit"):
|
||||||
|
return ApiResponse(
|
||||||
|
code=422,
|
||||||
|
message="decision 必须是 approve / reject / edit 之一",
|
||||||
|
data=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
task = service.get_task(task_id)
|
||||||
|
if task is None:
|
||||||
|
return ApiResponse(code=404, message=f"任务不存在:{task_id}", data=None)
|
||||||
|
if task.status != "waiting_approval":
|
||||||
|
return ApiResponse(
|
||||||
|
code=409,
|
||||||
|
message=f"任务当前状态为 {task.status},无法提交审批",
|
||||||
|
data=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
updated = await service.resume_task(
|
||||||
|
task_id,
|
||||||
|
{"decision": decision, "comment": payload.get("comment", "")},
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("审批恢复失败")
|
||||||
|
return ApiResponse(code=500, message=f"审批恢复失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(code=0, message="审批已提交,任务恢复执行", data=updated)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 任务回滚 ----------
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{task_id}/rollback", response_model=ApiResponse[dict], summary="回滚任务改动"
|
||||||
|
)
|
||||||
|
def rollback_task(
|
||||||
|
task_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
回滚指定任务的代码改动(决策点 12:快照 + Git 双通道)。
|
||||||
|
|
||||||
|
【请求体】{"strategy": "auto"|"snapshot"|"git"}(默认 auto:Git 优先、快照兜底)
|
||||||
|
【返回】{success, strategy_used, restored_files, message}
|
||||||
|
"""
|
||||||
|
from app.tasks.rollback_service import RollbackService
|
||||||
|
|
||||||
|
strategy = (payload or {}).get("strategy", "auto")
|
||||||
|
service = RollbackService()
|
||||||
|
|
||||||
|
# 先确认任务存在
|
||||||
|
task_svc = get_task_service()
|
||||||
|
task = task_svc.get_task(task_id)
|
||||||
|
if task is None:
|
||||||
|
return ApiResponse(code=404, message=f"任务不存在:{task_id}", data=None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = service.rollback_task(task_id, strategy=strategy)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("回滚失败")
|
||||||
|
return ApiResponse(code=500, message=f"回滚失败:{exc}", data=None)
|
||||||
|
|
||||||
|
if result.get("success"):
|
||||||
|
return ApiResponse(code=0, message=result["message"], data=result)
|
||||||
|
return ApiResponse(code=1, message=result["message"], data=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{task_id}/backups", response_model=ApiResponse[list[dict]], summary="查询任务快照"
|
||||||
|
)
|
||||||
|
def list_task_backups(task_id: str) -> ApiResponse[list[dict]]:
|
||||||
|
"""查询指定任务的全部快照记录(供前端展示可回滚范围)。"""
|
||||||
|
from app.tasks.rollback_service import RollbackService
|
||||||
|
|
||||||
|
service = RollbackService()
|
||||||
|
try:
|
||||||
|
backups = service.get_task_backups(task_id)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"查询快照失败:{exc}", data=None)
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(backups)} 条快照", data=backups)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""
|
||||||
|
任务模板 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】任务模板的增删改查。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.template_service import TemplateStore, get_template_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.template.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/templates", tags=["任务模板"])
|
||||||
|
|
||||||
|
|
||||||
|
def get_store() -> TemplateStore:
|
||||||
|
return get_template_store()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[dict]], summary="模板列表")
|
||||||
|
def list_templates(
|
||||||
|
category: str = "",
|
||||||
|
store: TemplateStore = Depends(get_store),
|
||||||
|
) -> ApiResponse[list[dict]]:
|
||||||
|
"""列出所有任务模板(可按分类筛选)。"""
|
||||||
|
items = store.list_all(category)
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message=f"共 {len(items)} 个模板",
|
||||||
|
data=[
|
||||||
|
{
|
||||||
|
"id": t.id,
|
||||||
|
"name": t.name,
|
||||||
|
"category": t.category,
|
||||||
|
"content": t.content,
|
||||||
|
"description": t.description,
|
||||||
|
"tags": t.tags,
|
||||||
|
"created_at": t.created_at,
|
||||||
|
}
|
||||||
|
for t in items
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="创建模板")
|
||||||
|
def create_template(payload: dict[str, Any], store: TemplateStore = Depends(get_store)) -> ApiResponse[dict]:
|
||||||
|
"""创建任务模板。"""
|
||||||
|
name = (payload.get("name") or "").strip()
|
||||||
|
content = (payload.get("content") or "").strip()
|
||||||
|
if not name or not content:
|
||||||
|
return ApiResponse(code=422, message="name 和 content 必填", data=None)
|
||||||
|
|
||||||
|
t = store.create(
|
||||||
|
name=name,
|
||||||
|
category=payload.get("category", "通用"),
|
||||||
|
content=content,
|
||||||
|
description=payload.get("description", ""),
|
||||||
|
tags=payload.get("tags", []),
|
||||||
|
)
|
||||||
|
return ApiResponse(code=0, message="模板创建成功", data={"id": t.id})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{template_id}", response_model=ApiResponse[dict], summary="更新模板")
|
||||||
|
def update_template(template_id: str, payload: dict[str, Any], store: TemplateStore = Depends(get_store)) -> ApiResponse[dict]:
|
||||||
|
"""更新模板。"""
|
||||||
|
t = store.update(template_id, **payload)
|
||||||
|
if t is None:
|
||||||
|
return ApiResponse(code=404, message="模板不存在", data=None)
|
||||||
|
return ApiResponse(code=0, message="模板更新成功", data={"id": t.id})
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{template_id}", response_model=ApiResponse[bool], summary="删除模板")
|
||||||
|
def delete_template(template_id: str, store: TemplateStore = Depends(get_store)) -> ApiResponse[bool]:
|
||||||
|
"""删除模板。"""
|
||||||
|
ok = store.delete(template_id)
|
||||||
|
return ApiResponse(code=0 if ok else 404, message="删除成功" if ok else "模板不存在", data=ok)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""
|
||||||
|
测试生成 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】为指定代码自动生成单元测试。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.testgen_service import generate_tests
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.testgen.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/testgen", tags=["测试生成"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="生成单元测试")
|
||||||
|
def generate_tests_endpoint(payload: dict) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
为指定代码生成单元测试。
|
||||||
|
|
||||||
|
【请求体】{
|
||||||
|
"source_code": "public class Foo { ... }",
|
||||||
|
"file_name": "Foo.java",
|
||||||
|
"test_framework": "junit5",
|
||||||
|
"model_preference": "auto"
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
source_code = payload.get("source_code", "")
|
||||||
|
result = generate_tests(
|
||||||
|
source_code=source_code,
|
||||||
|
file_name=payload.get("file_name", ""),
|
||||||
|
test_framework=payload.get("test_framework", "junit5"),
|
||||||
|
model_preference=payload.get("model_preference", "auto"),
|
||||||
|
)
|
||||||
|
if not result.get("success"):
|
||||||
|
return ApiResponse(code=1, message=result.get("message", "生成失败"), data=None)
|
||||||
|
return ApiResponse(code=0, message="测试生成完成", data=result)
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"""
|
||||||
|
文件上传 API
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】接收前端上传的图片,保存到本地 D:\\Agent\\agent\\data\\uploads\\ 目录。
|
||||||
|
【安全设计】只允许常见图片格式;限制文件大小;文件名用时间戳+随机数避免冲突。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, UploadFile, File
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.upload.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/uploads", tags=["文件上传"])
|
||||||
|
|
||||||
|
# 允许的图片格式
|
||||||
|
ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"}
|
||||||
|
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
|
||||||
|
|
||||||
|
|
||||||
|
class UploadResult(BaseModel):
|
||||||
|
"""上传结果"""
|
||||||
|
|
||||||
|
filename: str
|
||||||
|
url: str
|
||||||
|
size: int
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/images", response_model=ApiResponse[UploadResult], summary="上传图片"
|
||||||
|
)
|
||||||
|
async def upload_image(
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
) -> ApiResponse[UploadResult]:
|
||||||
|
"""
|
||||||
|
上传图片文件(需求描述附件)。
|
||||||
|
|
||||||
|
【支持格式】png / jpg / jpeg / gif / bmp / webp
|
||||||
|
【大小限制】10MB
|
||||||
|
【存储位置】D:\\Agent\\agent\\data\\uploads\\images\\
|
||||||
|
"""
|
||||||
|
if not file.filename:
|
||||||
|
return ApiResponse(code=422, message="文件名不能为空", data=None)
|
||||||
|
|
||||||
|
# 校验扩展名
|
||||||
|
ext = Path(file.filename).suffix.lower()
|
||||||
|
if ext not in ALLOWED_EXTENSIONS:
|
||||||
|
return ApiResponse(
|
||||||
|
code=422,
|
||||||
|
message=f"不支持的文件格式:{ext}(支持:{', '.join(sorted(ALLOWED_EXTENSIONS))})",
|
||||||
|
data=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 读取内容
|
||||||
|
content = await file.read()
|
||||||
|
if len(content) > MAX_FILE_SIZE:
|
||||||
|
return ApiResponse(
|
||||||
|
code=422,
|
||||||
|
message=f"文件过大({len(content) / 1024 / 1024:.1f}MB),最大 10MB",
|
||||||
|
data=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 保存文件(用时间戳+随机数避免冲突)
|
||||||
|
settings = load_settings()
|
||||||
|
upload_dir = settings.data_root / "uploads" / "images"
|
||||||
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
safe_name = f"{uuid.uuid4().hex[:12]}_{Path(file.filename).name}"
|
||||||
|
file_path = upload_dir / safe_name
|
||||||
|
|
||||||
|
try:
|
||||||
|
file_path.write_bytes(content)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("图片保存失败")
|
||||||
|
return ApiResponse(code=500, message=f"保存失败:{exc}", data=None)
|
||||||
|
|
||||||
|
url = f"/uploads/images/{safe_name}"
|
||||||
|
logger.info("图片已上传:%s(%d 字节)", safe_name, len(content))
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message="上传成功",
|
||||||
|
data=UploadResult(filename=safe_name, url=url, size=len(content)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/images/analyze", response_model=ApiResponse[dict], summary="识别图片内容"
|
||||||
|
)
|
||||||
|
async def analyze_image_endpoint(payload: dict) -> ApiResponse[dict]:
|
||||||
|
"""
|
||||||
|
调用智谱 GLM-4V-Flash 识别图片内容(Bug 截图、UI 稿等)。
|
||||||
|
|
||||||
|
【请求体】{"urls": ["/uploads/images/xxx.png", ...]}
|
||||||
|
【返回】{"description": "图片内容的文字描述"}
|
||||||
|
"""
|
||||||
|
urls = payload.get("urls", [])
|
||||||
|
if not urls:
|
||||||
|
return ApiResponse(code=422, message="请提供图片 URL 列表", data=None)
|
||||||
|
|
||||||
|
from app.services.vision_service import analyze_images
|
||||||
|
|
||||||
|
# URL 转本地文件路径
|
||||||
|
settings = load_settings()
|
||||||
|
upload_dir = settings.data_root / "uploads"
|
||||||
|
file_paths = []
|
||||||
|
for url in urls:
|
||||||
|
url = str(url).lstrip("/")
|
||||||
|
# "/uploads/images/xxx.png" → "D:\Agent\agent\data\uploads\images\xxx.png"
|
||||||
|
file_path = upload_dir / url.replace("uploads/", "", 1) if url.startswith("uploads/") else upload_dir / url
|
||||||
|
file_paths.append(str(file_path))
|
||||||
|
|
||||||
|
try:
|
||||||
|
description = analyze_images(file_paths)
|
||||||
|
except Exception as exc:
|
||||||
|
return ApiResponse(code=500, message=f"图片识别失败:{exc}", data=None)
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
code=0,
|
||||||
|
message="识别完成",
|
||||||
|
data={"description": description, "count": len(urls)},
|
||||||
|
)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""
|
||||||
|
工作空间 API
|
||||||
|
============"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.schemas.project import ApiResponse
|
||||||
|
from app.services.workspace_service import get_workspace_store
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.workspace.api")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/workspace", tags=["工作空间"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ApiResponse[list[dict]], summary="空间列表")
|
||||||
|
def list_workspaces() -> ApiResponse[list[dict]]:
|
||||||
|
store = get_workspace_store()
|
||||||
|
items = store.list_all()
|
||||||
|
return ApiResponse(code=0, message=f"共 {len(items)} 个空间", data=items)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ApiResponse[dict], summary="创建空间")
|
||||||
|
def create_workspace(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||||
|
name = (payload.get("name") or "").strip()
|
||||||
|
if not name:
|
||||||
|
return ApiResponse(code=422, message="name 必填", data=None)
|
||||||
|
store = get_workspace_store()
|
||||||
|
ws = store.create(name=name, description=payload.get("description", ""))
|
||||||
|
return ApiResponse(code=0, message="空间创建成功", data=ws)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{ws_id}", response_model=ApiResponse[bool], summary="删除空间")
|
||||||
|
def delete_workspace(ws_id: str) -> ApiResponse[bool]:
|
||||||
|
store = get_workspace_store()
|
||||||
|
ok = store.delete(ws_id)
|
||||||
|
return ApiResponse(code=0 if ok else 400, message="删除成功" if ok else "删除失败(默认空间不可删)", data=ok)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""应用配置层:.env 加载、路径约束、模型接入参数"""
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"""
|
||||||
|
应用配置模块
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
基于 pydantic-settings 统一加载 .env 与环境变量,提供全局单例配置对象。
|
||||||
|
覆盖:模型服务接入、SQLite/Chroma 落盘路径、白名单执行器安全参数等。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 pydantic-settings 而非裸 os.environ:自带类型校验与默认值,
|
||||||
|
密钥缺失时在启动期即报错,而非运行到模型调用才失败(fail-fast)。
|
||||||
|
2. 路径全部收敛为 D:\\Agent 绝对路径,满足核心诉求「硬性约束 6」
|
||||||
|
(全部工程产物落 D:\\Agent,禁止其他盘符)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- Settings 类声明全部可配置项 → load_settings() 读取 .env 并缓存实例;
|
||||||
|
- 所有下游模块只 import settings,不自己读 env,保证配置来源唯一。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:.env 缺失或密钥为空 → 启动即抛异常。
|
||||||
|
应对:.env.example 提供模板;启动日志打印「已加载配置」但不打印密钥明文。
|
||||||
|
风险2:路径含中文或空格 → 部分子进程调用失败。
|
||||||
|
应对:所有路径在 settings 校验后统一 resolve() 为绝对路径;
|
||||||
|
调用 git/白名单命令时用 list 参数传参(不经 shell 拼接)。
|
||||||
|
风险3:密钥被误提交到 Git → 泄露。
|
||||||
|
应对:.gitignore 强制排除 .env;本模块绝不把密钥写入日志。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic import Field, field_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
"""全局应用配置(从 .env / 环境变量加载)"""
|
||||||
|
|
||||||
|
# ---------- 应用基础 ----------
|
||||||
|
app_name: str = Field(default="编程智能 Agent 系统", description="应用名称")
|
||||||
|
app_host: str = Field(default="127.0.0.1", description="监听地址")
|
||||||
|
app_port: int = Field(default=8000, description="监听端口")
|
||||||
|
|
||||||
|
# ---------- 路径(硬约束 6:全部落 D:\\Agent)----------
|
||||||
|
data_root: Path = Field(
|
||||||
|
default=Path(r"D:\Agent\agent\data"),
|
||||||
|
description="运行数据根目录(SQLite/Chroma/审计/快照)",
|
||||||
|
)
|
||||||
|
code_root: Path = Field(
|
||||||
|
default=Path(r"D:\Agent\code"),
|
||||||
|
description="目标项目代码根目录(决策点 3:本地 Git 管理)",
|
||||||
|
)
|
||||||
|
project_root: Path = Field(
|
||||||
|
default=Path(r"D:\Agent"),
|
||||||
|
description="工程总根目录",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 模型服务(模型来源:模型管理 page)----------
|
||||||
|
model_request_timeout: int = Field(default=120, description="单次模型请求超时(秒)")
|
||||||
|
model_max_retries: int = Field(default=3, description="模型调用最大重试次数")
|
||||||
|
|
||||||
|
# ---------- ccswitch 本地代理(聚合多模型源)----------
|
||||||
|
ccswitch_base_url: str = Field(
|
||||||
|
default="http://127.0.0.1:8317/v1",
|
||||||
|
description="ccswitch 代理地址(OpenAI 兼容,聚合 glm/mimo/deepseek 等)",
|
||||||
|
)
|
||||||
|
ccswitch_api_key: str = Field(default="", description="ccswitch 代理密钥")
|
||||||
|
|
||||||
|
# ---------- 智谱 GLM-4V-Flash(图片识别)----------
|
||||||
|
zhipu_api_key: str = Field(default="", description="智谱 API Key")
|
||||||
|
zhipu_base_url: str = Field(
|
||||||
|
default="https://open.bigmodel.cn/api/paas/v4", description="智谱 API 地址"
|
||||||
|
)
|
||||||
|
zhipu_vision_model: str = Field(
|
||||||
|
default="glm-4v-flash", description="智谱视觉模型 ID"
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 禅道项目管理 ----------
|
||||||
|
zentao_url: str = Field(default="", description="禅道平台地址(如 http://zentao.company.com/zentao)")
|
||||||
|
zentao_account: str = Field(default="", description="禅道登录账号(用于自动获取/刷新 API Token)")
|
||||||
|
zentao_password: str = Field(default="", description="禅道登录密码(用于自动获取/刷新 API Token)")
|
||||||
|
zentao_token: str = Field(
|
||||||
|
default="",
|
||||||
|
description="禅道 API Token(可选:手工长期令牌;留空则用账号密码自动获取并续期)",
|
||||||
|
)
|
||||||
|
zentao_token_ttl_seconds: int = Field(
|
||||||
|
default=6 * 24 * 3600,
|
||||||
|
description="禅道 Token 有效期兜底值(秒);接口未返回 expireTime 时使用",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 白名单执行器安全参数(决策点 11)----------
|
||||||
|
exec_timeout_seconds: int = Field(default=60, description="白名单命令超时(秒)")
|
||||||
|
exec_output_max_chars: int = Field(default=20000, description="命令输出截断上限(字符)")
|
||||||
|
|
||||||
|
# ---------- RAG ----------
|
||||||
|
chroma_collection_name: str = Field(
|
||||||
|
default="project_knowledge", description="知识库默认集合名"
|
||||||
|
)
|
||||||
|
retrieve_top_k: int = Field(default=5, description="检索默认召回条数")
|
||||||
|
|
||||||
|
# ---------- 改码引擎(可插拔,方案 B)----------
|
||||||
|
coding_engine: str = Field(
|
||||||
|
default="builtin",
|
||||||
|
description="改码引擎:builtin=自研工具链(默认);claude_code=Claude Code CLI",
|
||||||
|
)
|
||||||
|
claude_timeout_seconds: int = Field(
|
||||||
|
default=300, description="Claude Code 执行超时(秒)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=Path(r"D:\Agent\agent\backend\.env"),
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 校验器 ----------
|
||||||
|
@field_validator("data_root", "code_root", "project_root")
|
||||||
|
@classmethod
|
||||||
|
def _ensure_absolute_d_drive(cls, v: Path) -> Path:
|
||||||
|
"""强制路径为 D 盘绝对路径,违反硬约束 6 时直接拒绝启动。"""
|
||||||
|
resolved = v.expanduser().resolve()
|
||||||
|
drive = resolved.drive.upper()
|
||||||
|
if not drive.startswith("D"):
|
||||||
|
raise ValueError(
|
||||||
|
f"路径 {resolved} 不在 D 盘,违反核心诉求「硬性约束 6」:"
|
||||||
|
"全部工程文件/运行产物/向量库数据必须存放于 D:\\Agent 下"
|
||||||
|
)
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sqlite_db_path(self) -> Path:
|
||||||
|
"""业务元数据 + LangGraph Checkpointer 共用的 SQLite 文件路径。"""
|
||||||
|
return self.data_root / "agent.db"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def chroma_dir(self) -> Path:
|
||||||
|
"""Chroma 向量库持久化目录。"""
|
||||||
|
return self.data_root / "chroma"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def audit_dir(self) -> Path:
|
||||||
|
"""工具执行审计日志目录。"""
|
||||||
|
return self.data_root / "audit"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def backup_dir(self) -> Path:
|
||||||
|
"""改码前文件快照目录(Git 之外的二道保险)。"""
|
||||||
|
return self.data_root / "backups"
|
||||||
|
|
||||||
|
def ensure_directories(self) -> None:
|
||||||
|
"""启动期一次性创建全部运行目录,避免运行中因目录缺失失败。"""
|
||||||
|
for p in (
|
||||||
|
self.data_root,
|
||||||
|
self.chroma_dir,
|
||||||
|
self.audit_dir,
|
||||||
|
self.backup_dir,
|
||||||
|
self.code_root,
|
||||||
|
):
|
||||||
|
p.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def load_settings() -> Settings:
|
||||||
|
"""
|
||||||
|
加载并缓存全局配置实例。
|
||||||
|
|
||||||
|
【返回】Settings 配置对象。
|
||||||
|
【异常】配置校验失败时抛 ValueError,由调用方(main)捕获并优雅降级退出。
|
||||||
|
"""
|
||||||
|
settings = Settings()
|
||||||
|
settings.ensure_directories()
|
||||||
|
return settings
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""LangGraph 编排层包:状态契约 / 主图节点 / Worker 子图 / 编排器"""
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
"""
|
||||||
|
主图节点实现(8 个节点)
|
||||||
|
========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
实现 Orchestrator 主图的全部计算节点:
|
||||||
|
intake → retrieve → plan → gate_check → human_gate → dispatch → evaluate → finalize
|
||||||
|
每个节点只做一件事,节点间通过状态通信(低耦合,硬约束 3)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 节点函数签名统一 `def node(state) -> dict`,返回状态更新片段,
|
||||||
|
与 LangGraph 标准约定一致,便于测试与替换。
|
||||||
|
2. 模型调用分强弱:intake/finalize 用弱模型,plan/evaluate 用强模型
|
||||||
|
(决策点 4 双模型路由),成本与效果兼顾。
|
||||||
|
3. 无模型节点(retrieve/gate_check/dispatch)纯逻辑,
|
||||||
|
可单测、可 mock,不依赖外部服务。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- 每个节点内部 try/except:失败写入 error 字段并降级,绝不抛出拖垮图;
|
||||||
|
- 结构化产出用 JSON 解析 + 字段补全,解析失败时用兜底默认值;
|
||||||
|
- human_gate 用 interrupt() 实现人工审批(HITL,决策点 7)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:模型返回非 JSON(自由文本)。
|
||||||
|
应对:_parse_json_loose 提取首个 JSON 块;失败时用最小可用默认结构。
|
||||||
|
风险2:知识库为空/检索失败。
|
||||||
|
应对:retrieve 失败返回空列表,不阻塞后续节点(决策点 6 降级)。
|
||||||
|
风险3:计划步骤过多导致 Worker 爆炸。
|
||||||
|
应对:plan 节点限流最多 8 步,超出合并。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from langgraph.types import interrupt
|
||||||
|
|
||||||
|
from app.graph.state import (
|
||||||
|
RISK_HIGH,
|
||||||
|
RISK_NORMAL,
|
||||||
|
STATUS_DEGRADED,
|
||||||
|
STATUS_RUNNING,
|
||||||
|
STATUS_WAITING_APPROVAL,
|
||||||
|
OrchestratorState,
|
||||||
|
)
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.graph.nodes")
|
||||||
|
|
||||||
|
# 计划步骤上限(防止任务拆解爆炸)
|
||||||
|
MAX_PLAN_STEPS = 8
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 工具函数 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_json_loose(text: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
从模型输出中宽松提取 JSON。
|
||||||
|
|
||||||
|
【理由】模型常在 JSON 外包裹 ```json 说明文字,严格 json.loads 必挂。
|
||||||
|
【实现】先截取 ```json ... ``` 块,再找首个 {...},都失败返回空 dict。
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return {}
|
||||||
|
# 去掉代码围栏
|
||||||
|
fence = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
|
||||||
|
if fence:
|
||||||
|
try:
|
||||||
|
return json.loads(fence.group(1))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
# 找首个大括号块
|
||||||
|
brace = re.search(r"\{.*\}", text, re.DOTALL)
|
||||||
|
if brace:
|
||||||
|
try:
|
||||||
|
return json.loads(brace.group(0))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_invoke(model: Any, prompt: str, fallback: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
安全调用模型并解析 JSON,任何失败返回兜底结构(硬约束 5)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
resp = model.invoke(prompt)
|
||||||
|
content = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
parsed = _parse_json_loose(content)
|
||||||
|
return parsed if parsed else fallback
|
||||||
|
except Exception as exc: # noqa: BLE001 - 节点级兜底
|
||||||
|
logger.warning("模型调用失败,使用兜底:%s", exc)
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_model(state: OrchestratorState, role: str) -> Any:
|
||||||
|
"""
|
||||||
|
按任务的 model_preference 选模型。
|
||||||
|
|
||||||
|
【分流】preference=auto → 双模型分工;否则强制使用指定模型。
|
||||||
|
"""
|
||||||
|
return get_model_for_task(state.get("model_preference", "auto"), role)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 1:需求解析(弱模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def intake_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
需求解析节点:把自然语言需求转成结构化任务描述。
|
||||||
|
|
||||||
|
【输入】raw_requirement, project_id
|
||||||
|
【输出】requirement(覆盖式)+ status
|
||||||
|
【产出结构】{type, summary, boundaries[], acceptance[]}
|
||||||
|
"""
|
||||||
|
raw = state.get("raw_requirement", "")
|
||||||
|
fallback = {
|
||||||
|
"type": "feature",
|
||||||
|
"summary": raw[:200],
|
||||||
|
"boundaries": [],
|
||||||
|
"acceptance": ["代码可编译通过"],
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt = f"""你是资深需求分析师。请把下面的开发/修复需求解析成结构化 JSON。
|
||||||
|
|
||||||
|
【原始需求】
|
||||||
|
{raw}
|
||||||
|
|
||||||
|
【输出要求】只输出 JSON,不要任何解释,字段如下:
|
||||||
|
{{
|
||||||
|
"type": "feature 或 bugfix",
|
||||||
|
"summary": "一句话概括需求(50字内)",
|
||||||
|
"boundaries": ["影响范围边界1", "边界2"],
|
||||||
|
"acceptance": ["验收标准1", "验收标准2"]
|
||||||
|
}}"""
|
||||||
|
|
||||||
|
requirement = _safe_invoke(_pick_model(state, "weak"), prompt, fallback)
|
||||||
|
# 字段补全,防止模型漏字段
|
||||||
|
requirement.setdefault("type", "feature")
|
||||||
|
requirement.setdefault("summary", raw[:200])
|
||||||
|
requirement.setdefault("boundaries", [])
|
||||||
|
requirement.setdefault("acceptance", fallback["acceptance"])
|
||||||
|
|
||||||
|
logger.info("需求解析完成:type=%s", requirement.get("type"))
|
||||||
|
return {"requirement": requirement, "status": STATUS_RUNNING}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 2:知识检索(无模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def retrieve_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
知识检索节点:从项目知识库召回相关经验。
|
||||||
|
|
||||||
|
【输入】requirement.summary + raw_requirement + use_vector_search
|
||||||
|
【输出】knowledge_hits(追加式)
|
||||||
|
【降级】检索失败返回空列表,不阻塞主流程(决策点 6)
|
||||||
|
【开关】use_vector_search=False 时跳过检索(用户提交前可选)
|
||||||
|
"""
|
||||||
|
# 用户关闭向量检索时直接跳过
|
||||||
|
if not state.get("use_vector_search", True):
|
||||||
|
logger.info("用户已关闭向量检索,跳过知识检索节点")
|
||||||
|
return {"knowledge_hits": []}
|
||||||
|
|
||||||
|
requirement = state.get("requirement", {})
|
||||||
|
query = " ".join(
|
||||||
|
filter(
|
||||||
|
None,
|
||||||
|
[
|
||||||
|
requirement.get("summary", ""),
|
||||||
|
state.get("raw_requirement", "")[:200],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
if not query:
|
||||||
|
return {"knowledge_hits": []}
|
||||||
|
|
||||||
|
try:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
from app.knowledge.embeddings import get_embedding_provider
|
||||||
|
from app.knowledge.knowledge_service import KnowledgeService
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
provider = get_embedding_provider(
|
||||||
|
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||||
|
)
|
||||||
|
vs = KnowledgeVectorStore(
|
||||||
|
persist_dir=settings.chroma_dir,
|
||||||
|
collection_name=settings.chroma_collection_name,
|
||||||
|
embedding_provider=provider,
|
||||||
|
)
|
||||||
|
service = KnowledgeService(vs, provider)
|
||||||
|
hits = service.query(query, top_k=settings.retrieve_top_k)
|
||||||
|
logger.info("知识检索完成:query=%s,命中=%d", query[:50], len(hits))
|
||||||
|
return {"knowledge_hits": hits}
|
||||||
|
except Exception as exc: # noqa: BLE001 - 检索失败降级
|
||||||
|
logger.warning("知识检索失败,降级为空:%s", exc)
|
||||||
|
return {"knowledge_hits": []}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 3:任务规划(强模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def plan_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
任务规划节点:把结构化需求拆解为可执行步骤。
|
||||||
|
|
||||||
|
【输入】requirement + knowledge_hits
|
||||||
|
【输出】plan(覆盖式):{steps: [TaskStep, ...]}
|
||||||
|
"""
|
||||||
|
requirement = state.get("requirement", {})
|
||||||
|
hits = state.get("knowledge_hits", [])
|
||||||
|
|
||||||
|
knowledge_brief = "\n".join(
|
||||||
|
f"- [{h.get('filename', '')}] {h.get('text', '')[:120]}"
|
||||||
|
for h in hits[:5]
|
||||||
|
) or "(无相关知识)"
|
||||||
|
|
||||||
|
fallback = {
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"step_id": "step_1",
|
||||||
|
"description": requirement.get("summary", "执行开发任务"),
|
||||||
|
"target_hints": [],
|
||||||
|
"expected_output": "代码修改完成并通过编译",
|
||||||
|
"step_type": requirement.get("type", "feature"),
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt = f"""你是资深开发负责人。请把需求拆解成不超过 {MAX_PLAN_STEPS} 个可执行的代码修改步骤。
|
||||||
|
|
||||||
|
【需求摘要】{requirement.get('summary', '')}
|
||||||
|
【需求类型】{requirement.get('type', 'feature')}
|
||||||
|
【影响边界】{requirement.get('boundaries', [])}
|
||||||
|
【验收标准】{requirement.get('acceptance', [])}
|
||||||
|
【相关知识】
|
||||||
|
{knowledge_brief}
|
||||||
|
|
||||||
|
【输出要求】只输出 JSON:
|
||||||
|
{{
|
||||||
|
"steps": [
|
||||||
|
{{
|
||||||
|
"step_id": "step_1",
|
||||||
|
"description": "这一步要做什么",
|
||||||
|
"target_hints": ["可能涉及的文件/模块线索"],
|
||||||
|
"expected_output": "这一步的产出",
|
||||||
|
"step_type": "feature|bugfix|refactor"
|
||||||
|
}}
|
||||||
|
]
|
||||||
|
}}"""
|
||||||
|
|
||||||
|
plan = _safe_invoke(_pick_model(state, "strong"), prompt, fallback)
|
||||||
|
steps = plan.get("steps") or fallback["steps"]
|
||||||
|
|
||||||
|
# 限流:最多 MAX_PLAN_STEPS 步
|
||||||
|
if len(steps) > MAX_PLAN_STEPS:
|
||||||
|
logger.warning("计划步骤 %d 超限,截断到 %d", len(steps), MAX_PLAN_STEPS)
|
||||||
|
steps = steps[:MAX_PLAN_STEPS]
|
||||||
|
|
||||||
|
# 字段补全
|
||||||
|
for i, step in enumerate(steps):
|
||||||
|
step.setdefault("step_id", f"step_{i + 1}")
|
||||||
|
step.setdefault("description", "")
|
||||||
|
step.setdefault("target_hints", [])
|
||||||
|
step.setdefault("expected_output", "")
|
||||||
|
step.setdefault("step_type", requirement.get("type", "feature"))
|
||||||
|
|
||||||
|
logger.info("任务规划完成:%d 个步骤", len(steps))
|
||||||
|
return {"plan": {"steps": steps}}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 4:风险闸门(无模型,规则)----------
|
||||||
|
|
||||||
|
|
||||||
|
def gate_check_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
风险闸门节点:按规则判定任务风险等级。
|
||||||
|
|
||||||
|
【硬风险(risk_level=high → 触发人工审批)】
|
||||||
|
- 步骤含删除/移除/清空等破坏性词(真高危);
|
||||||
|
- 影响边界跨模块(公共/核心/全部)。
|
||||||
|
【软警告(risk_warnings → 不中断,报告提示)】
|
||||||
|
- 步骤数超过 5(改动面较大,但可自动执行)。
|
||||||
|
|
||||||
|
【调整说明】原设计步骤数也走硬中断,实测误触发频繁(模型拆解偏细),
|
||||||
|
改为软提示:不打断执行,仅在报告中列出提醒。
|
||||||
|
"""
|
||||||
|
plan = state.get("plan", {})
|
||||||
|
steps = plan.get("steps", [])
|
||||||
|
requirement = state.get("requirement", {})
|
||||||
|
boundaries = requirement.get("boundaries", [])
|
||||||
|
|
||||||
|
hard_signals: list[str] = []
|
||||||
|
soft_warnings: list[str] = []
|
||||||
|
|
||||||
|
# 规则 1:破坏性关键词(硬风险)
|
||||||
|
destructive_keywords = ["删除", "移除", "清空", "销毁", "drop", "delete", "remove"]
|
||||||
|
for step in steps:
|
||||||
|
desc = step.get("description", "").lower()
|
||||||
|
if any(kw in desc for kw in destructive_keywords):
|
||||||
|
hard_signals.append(f"步骤含破坏性操作:{step.get('step_id')}")
|
||||||
|
|
||||||
|
# 规则 2:跨模块影响(硬风险)
|
||||||
|
cross_module_keywords = ["公共", "核心", "全部", "所有模块", "跨模块"]
|
||||||
|
for b in boundaries:
|
||||||
|
if any(kw in str(b) for kw in cross_module_keywords):
|
||||||
|
hard_signals.append(f"影响范围跨模块:{b}")
|
||||||
|
|
||||||
|
# 规则 3:步骤过多(软警告,不中断)
|
||||||
|
if len(steps) > 5:
|
||||||
|
soft_warnings.append(f"步骤数 {len(steps)} 超过 5,改动面较大,建议关注执行结果")
|
||||||
|
|
||||||
|
risk_level = RISK_HIGH if hard_signals else RISK_NORMAL
|
||||||
|
logger.info(
|
||||||
|
"风险判定:%s,硬信号=%s,软警告=%s", risk_level, hard_signals, soft_warnings
|
||||||
|
)
|
||||||
|
|
||||||
|
result: dict[str, Any] = {
|
||||||
|
"risk_level": risk_level,
|
||||||
|
"risk_warnings": soft_warnings,
|
||||||
|
}
|
||||||
|
if hard_signals:
|
||||||
|
# 硬信号写入 error 通道供审批界面展示
|
||||||
|
result["error"] = ";".join(hard_signals)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 5:人工审批(HITL,interrupt)----------
|
||||||
|
|
||||||
|
|
||||||
|
def human_gate_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
人工审批节点:**仅硬风险**任务在此中断,等待人工批准/驳回。
|
||||||
|
|
||||||
|
【硬风险判定】risk_level == high(破坏性操作 / 跨模块影响)。
|
||||||
|
【软警告】risk_warnings 只记录不中断,报告中体现(如步骤数>5)。
|
||||||
|
【机制】LangGraph interrupt():运行到此暂停并保存检查点,
|
||||||
|
前端通过 Command(resume=...) 提交审批结果后继续。
|
||||||
|
【低风险/软警告】直接放行,不中断(决策点 7「分级管控」)。
|
||||||
|
"""
|
||||||
|
risk_level = state.get("risk_level", RISK_NORMAL)
|
||||||
|
if risk_level != RISK_HIGH:
|
||||||
|
logger.info("风险等级 %s,自动放行(软警告不影响执行)", risk_level)
|
||||||
|
return {"approval": {"decision": "auto_approved", "reason": "低风险自动放行"}}
|
||||||
|
|
||||||
|
# 高风险:中断等待人工决策
|
||||||
|
logger.info("风险等级 high,触发人工审批中断")
|
||||||
|
decision = interrupt(
|
||||||
|
{
|
||||||
|
"type": "approval_request",
|
||||||
|
"message": "该任务被判定为高风险,需要人工审批后才能继续执行",
|
||||||
|
"risk_signals": state.get("error", ""),
|
||||||
|
"plan": state.get("plan", {}),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# decision 形如 {"decision": "approve"|"reject"|"edit", "comment": "..."}
|
||||||
|
if isinstance(decision, dict):
|
||||||
|
approval = decision
|
||||||
|
else:
|
||||||
|
approval = {"decision": str(decision), "comment": ""}
|
||||||
|
|
||||||
|
logger.info("人工审批结果:%s", approval)
|
||||||
|
return {"approval": approval, "error": ""}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 6:任务分发(无模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
任务分发节点:读取计划步骤,产出待执行的步骤清单。
|
||||||
|
|
||||||
|
【输入】plan, approval
|
||||||
|
【输出】worker_results 由 Send API 并行写入(本节点只做路由准备)
|
||||||
|
【说明】真正的并行分发在 conditional_edges 里用 Send 完成,
|
||||||
|
本节点负责检查审批结果并把步骤规范化。
|
||||||
|
"""
|
||||||
|
approval = state.get("approval", {})
|
||||||
|
decision = approval.get("decision", "auto_approved")
|
||||||
|
|
||||||
|
if decision == "reject":
|
||||||
|
logger.info("审批驳回,跳过 Worker 执行")
|
||||||
|
return {
|
||||||
|
"status": STATUS_DEGRADED,
|
||||||
|
"error": f"任务被人工驳回:{approval.get('comment', '')}",
|
||||||
|
}
|
||||||
|
|
||||||
|
steps = state.get("plan", {}).get("steps", [])
|
||||||
|
logger.info("准备分发 %d 个步骤给 Worker", len(steps))
|
||||||
|
return {"status": STATUS_RUNNING}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 7:结果评估(强模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
结果评估节点:对照验收标准评估 Worker 产出。
|
||||||
|
|
||||||
|
【输入】worker_results + requirement.acceptance
|
||||||
|
【输出】evaluation(覆盖式):{passed, defects[], score}
|
||||||
|
"""
|
||||||
|
requirement = state.get("requirement", {})
|
||||||
|
results = state.get("worker_results", [])
|
||||||
|
acceptance = requirement.get("acceptance", [])
|
||||||
|
|
||||||
|
results_brief = "\n".join(
|
||||||
|
f"- 步骤 {r.get('step_id', '?')}: {r.get('summary', '')} "
|
||||||
|
f"(状态={r.get('status', 'unknown')})"
|
||||||
|
for r in results
|
||||||
|
) or "(无 Worker 产出)"
|
||||||
|
|
||||||
|
fallback = {
|
||||||
|
"passed": True,
|
||||||
|
"defects": [],
|
||||||
|
"score": 80,
|
||||||
|
"comment": "自动评估兜底:未获取到模型评估结果",
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt = f"""你是资深代码审查专家。请评估代码修改结果是否满足验收标准。
|
||||||
|
|
||||||
|
【验收标准】
|
||||||
|
{acceptance}
|
||||||
|
|
||||||
|
【执行结果】
|
||||||
|
{results_brief}
|
||||||
|
|
||||||
|
【输出要求】只输出 JSON:
|
||||||
|
{{
|
||||||
|
"passed": true 或 false,
|
||||||
|
"defects": ["缺陷1", "缺陷2"],
|
||||||
|
"score": 0到100的整数,
|
||||||
|
"comment": "总体评价(50字内)"
|
||||||
|
}}"""
|
||||||
|
|
||||||
|
evaluation = _safe_invoke(_pick_model(state, "strong"), prompt, fallback)
|
||||||
|
evaluation.setdefault("passed", True)
|
||||||
|
evaluation.setdefault("defects", [])
|
||||||
|
evaluation.setdefault("score", 80)
|
||||||
|
evaluation.setdefault("comment", "")
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"评估完成:passed=%s,score=%s", evaluation.get("passed"), evaluation.get("score")
|
||||||
|
)
|
||||||
|
eval_retry = int(state.get("eval_retry", 0) or 0)
|
||||||
|
# 评估不通过时递增修复轮数(供 _route_after_evaluate 判断是否继续修复)
|
||||||
|
if not evaluation.get("passed", True):
|
||||||
|
eval_retry += 1
|
||||||
|
return {"evaluation": evaluation, "eval_retry": eval_retry}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 8:交付报告(弱模型)----------
|
||||||
|
|
||||||
|
|
||||||
|
def finalize_node(state: OrchestratorState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
交付报告节点:生成中文交付报告。
|
||||||
|
|
||||||
|
【输入】全状态
|
||||||
|
【输出】report(覆盖式)+ status(done/degraded/failed)
|
||||||
|
"""
|
||||||
|
requirement = state.get("requirement", {})
|
||||||
|
evaluation = state.get("evaluation", {})
|
||||||
|
results = state.get("worker_results", [])
|
||||||
|
error = state.get("error", "")
|
||||||
|
risk_warnings = state.get("risk_warnings", [])
|
||||||
|
|
||||||
|
# 状态收口:有 error 或评估不通过 → degraded
|
||||||
|
if error or not evaluation.get("passed", True):
|
||||||
|
final_status = STATUS_DEGRADED
|
||||||
|
else:
|
||||||
|
final_status = "done" # noqa: S105 - 状态字面量
|
||||||
|
|
||||||
|
fallback_report = (
|
||||||
|
f"# 任务交付报告\n\n"
|
||||||
|
f"## 需求\n{requirement.get('summary', state.get('raw_requirement', ''))}\n\n"
|
||||||
|
f"## 评估结论\n{'通过' if evaluation.get('passed') else '未通过'}"
|
||||||
|
f"(得分 {evaluation.get('score', 0)})\n\n"
|
||||||
|
f"## 执行步骤数\n{len(results)}\n\n"
|
||||||
|
f"## 风险提示\n{chr(10).join('⚠️ ' + w for w in risk_warnings) or '无'}\n\n"
|
||||||
|
f"## 遗留问题\n{error or '无'}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
warnings_text = "\n".join(f"⚠️ {w}" for w in risk_warnings) or "无"
|
||||||
|
|
||||||
|
prompt = f"""你是技术负责人。请用中文生成一份简洁的交付报告(Markdown 格式)。
|
||||||
|
|
||||||
|
【需求】{requirement.get('summary', '')}
|
||||||
|
【验收标准】{requirement.get('acceptance', [])}
|
||||||
|
【执行步骤数】{len(results)}
|
||||||
|
【评估结论】通过={evaluation.get('passed')},得分={evaluation.get('score')},缺陷={evaluation.get('defects', [])}
|
||||||
|
【风险提示】
|
||||||
|
{warnings_text}
|
||||||
|
【遗留问题】{error or '无'}
|
||||||
|
|
||||||
|
【输出要求】直接输出 Markdown 报告文本,包含:需求概述、执行摘要、评估结论、风险提示、遗留风险、后续建议。"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = _pick_model(state, "weak").invoke(prompt)
|
||||||
|
report = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
if not report or len(report.strip()) < 20:
|
||||||
|
report = fallback_report
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("报告生成失败,使用兜底模板:%s", exc)
|
||||||
|
report = fallback_report
|
||||||
|
|
||||||
|
logger.info("报告生成完成,状态收口为 %s", final_status)
|
||||||
|
return {"report": report, "status": final_status}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
"""
|
||||||
|
主图编排器(Orchestrator)
|
||||||
|
==========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
构建 LangGraph 主图:8 节点 + 条件路由 + Send API 并行分发 Worker,
|
||||||
|
挂载 SQLite Checkpointer 支持断点续跑与 HITL 中断恢复。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 采用 Orchestrator-Worker 模式(决策点 9 选 C):
|
||||||
|
主图固定骨架(可观测、可审计),Worker 自主循环(灵活改码)。
|
||||||
|
2. Send API 实现步骤级并行:每个 TaskStep 独立 Worker 实例,
|
||||||
|
结果用 operator.add reducer 追加合并(状态契约已设计)。
|
||||||
|
3. SqliteSaver 持久化检查点:任务可中断/恢复/时间旅行,
|
||||||
|
满足决策点 12「本地 Git + 检查点」双安全网,且数据落 D 盘。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
主图拓扑:
|
||||||
|
START → intake → retrieve → plan → gate_check
|
||||||
|
→ human_gate(interrupt) → dispatch
|
||||||
|
→ [Send × N] worker 子图(并行)
|
||||||
|
→ evaluate → finalize → END
|
||||||
|
- dispatch 后用 conditional_edges 返回 Send 列表,实现动态并行;
|
||||||
|
- evaluate 不通过且重试未超限 → 回 dispatch 重新执行(Evaluator-Optimizer)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:Send 并行度失控(步骤多时打爆模型限流)。
|
||||||
|
应对:plan 节点已限流 ≤8 步;后续可加信号量控制并发。
|
||||||
|
风险2:检查点文件损坏。
|
||||||
|
应对:SqliteSaver 用 WAL 模式;损坏时任务标 failed,支持人工重建。
|
||||||
|
风险3:interrupt 恢复时上下文丢失。
|
||||||
|
应对:检查点保存全状态,Command(resume=...) 可精确恢复到中断点。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from langgraph.graph import END, START, StateGraph
|
||||||
|
from langgraph.types import Send
|
||||||
|
|
||||||
|
from app.graph.nodes import (
|
||||||
|
dispatch_node,
|
||||||
|
evaluate_node,
|
||||||
|
finalize_node,
|
||||||
|
gate_check_node,
|
||||||
|
human_gate_node,
|
||||||
|
intake_node,
|
||||||
|
plan_node,
|
||||||
|
retrieve_node,
|
||||||
|
)
|
||||||
|
from app.graph.state import OrchestratorState, WorkerState
|
||||||
|
from app.graph.worker import get_worker_graph
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.graph.orchestrator")
|
||||||
|
|
||||||
|
# 评估不通过时的最大修复轮数(Evaluator-Optimizer)
|
||||||
|
MAX_EVAL_RETRY = 2
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Worker 调度 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def worker_node(state: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Worker 执行节点(包裹子图)。
|
||||||
|
|
||||||
|
【为什么要有这层包裹】
|
||||||
|
若直接把 Worker 子图挂到主图并用 Send 分发,子图的**整个状态**
|
||||||
|
(含 task_id/project_id 等 LastValue 字段)都会写回主图,
|
||||||
|
并行 N 个 Worker 就会触发 InvalidUpdateError
|
||||||
|
「Can receive only one value per step」。
|
||||||
|
故用节点函数包裹:只把 worker_results(带 operator.add reducer)
|
||||||
|
写回主图,其余字段留在子图内部,互不冲突。
|
||||||
|
"""
|
||||||
|
worker_graph = get_worker_graph()
|
||||||
|
worker_state: WorkerState = {
|
||||||
|
"task_id": state.get("task_id", ""),
|
||||||
|
"project_id": state.get("project_id", ""),
|
||||||
|
"step": state.get("step", {}),
|
||||||
|
"retry_count": state.get("retry_count", 0),
|
||||||
|
"model_preference": state.get("model_preference", "auto"),
|
||||||
|
}
|
||||||
|
final = worker_graph.invoke(worker_state)
|
||||||
|
|
||||||
|
# 压缩成单条结果,只写 worker_results(reducer 追加合并)
|
||||||
|
result = {
|
||||||
|
"step_id": final.get("step", {}).get("step_id", ""),
|
||||||
|
"status": "success" if not final.get("error") else "partial",
|
||||||
|
"summary": final.get("step", {}).get("description", ""),
|
||||||
|
"located_files": final.get("located_files", []),
|
||||||
|
"edits_count": len(final.get("edits", [])),
|
||||||
|
"verify_passed": final.get("verify_result", {}).get("passed", False),
|
||||||
|
"retry_count": final.get("retry_count", 0),
|
||||||
|
"error": final.get("error", ""),
|
||||||
|
}
|
||||||
|
return {"worker_results": [result]}
|
||||||
|
|
||||||
|
|
||||||
|
def _dispatch_workers(state: OrchestratorState) -> list[Send] | str:
|
||||||
|
"""
|
||||||
|
条件路由:把每个 TaskStep 分发给 Worker 子图(Send API 并行)。
|
||||||
|
|
||||||
|
【返回】
|
||||||
|
- Send 列表:正常分发(每步一个 Worker);
|
||||||
|
- "skip":审批驳回或无步骤时跳过 Worker 阶段。
|
||||||
|
"""
|
||||||
|
approval = state.get("approval", {})
|
||||||
|
if approval.get("decision") == "reject":
|
||||||
|
return "skip"
|
||||||
|
|
||||||
|
steps = state.get("plan", {}).get("steps", [])
|
||||||
|
if not steps:
|
||||||
|
logger.warning("计划为空,跳过 Worker 执行")
|
||||||
|
return "skip"
|
||||||
|
|
||||||
|
sends = [
|
||||||
|
Send(
|
||||||
|
"worker",
|
||||||
|
{
|
||||||
|
"task_id": state.get("task_id", ""),
|
||||||
|
"project_id": state.get("project_id", ""),
|
||||||
|
"step": step,
|
||||||
|
"retry_count": 0,
|
||||||
|
"model_preference": state.get("model_preference", "auto"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for step in steps
|
||||||
|
]
|
||||||
|
logger.info("Send API 分发 %d 个 Worker", len(sends))
|
||||||
|
return sends
|
||||||
|
|
||||||
|
|
||||||
|
def _route_after_dispatch(state: OrchestratorState) -> str:
|
||||||
|
"""dispatch 后路由:被驳回直接进入 evaluate 收口。"""
|
||||||
|
return "evaluate"
|
||||||
|
|
||||||
|
|
||||||
|
def _route_after_evaluate(state: OrchestratorState) -> str:
|
||||||
|
"""
|
||||||
|
评估后路由:不通过且修复轮数未用尽 → 重跑 Worker;否则 finalize。
|
||||||
|
|
||||||
|
【踩坑记录】不能用 error.count("评估未通过") 计数——该字符串从未写入
|
||||||
|
error 通道,导致计数永远为 0 → 评估不通过时无限回 dispatch。
|
||||||
|
正确做法:用独立的 eval_retry 字段计数(覆盖式更新)。
|
||||||
|
"""
|
||||||
|
evaluation = state.get("evaluation", {})
|
||||||
|
eval_retry = int(state.get("eval_retry", 0) or 0)
|
||||||
|
if not evaluation.get("passed", True) and eval_retry < MAX_EVAL_RETRY:
|
||||||
|
logger.info("评估未通过,进入第 %d 轮修复", eval_retry + 1)
|
||||||
|
return "dispatch"
|
||||||
|
return "finalize"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 构建主图 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def build_orchestrator_graph(checkpointer: Any = None):
|
||||||
|
"""
|
||||||
|
构建主图。
|
||||||
|
|
||||||
|
【参数】checkpointer:检查点器(SqliteSaver),None 则不持久化(仅测试用)。
|
||||||
|
"""
|
||||||
|
builder = StateGraph(OrchestratorState)
|
||||||
|
|
||||||
|
# 主图 8 节点
|
||||||
|
builder.add_node("intake", intake_node)
|
||||||
|
builder.add_node("retrieve", retrieve_node)
|
||||||
|
builder.add_node("plan", plan_node)
|
||||||
|
builder.add_node("gate_check", gate_check_node)
|
||||||
|
builder.add_node("human_gate", human_gate_node)
|
||||||
|
builder.add_node("dispatch", dispatch_node)
|
||||||
|
builder.add_node("evaluate", evaluate_node)
|
||||||
|
builder.add_node("finalize", finalize_node)
|
||||||
|
|
||||||
|
# Worker 子图通过节点函数包裹挂载(见 worker_node 注释:避免并行写冲突)
|
||||||
|
builder.add_node("worker", worker_node)
|
||||||
|
|
||||||
|
# 主流程边
|
||||||
|
builder.add_edge(START, "intake")
|
||||||
|
builder.add_edge("intake", "retrieve")
|
||||||
|
builder.add_edge("retrieve", "plan")
|
||||||
|
builder.add_edge("plan", "gate_check")
|
||||||
|
builder.add_edge("gate_check", "human_gate")
|
||||||
|
builder.add_edge("human_gate", "dispatch")
|
||||||
|
|
||||||
|
# dispatch → Worker 并行(Send API)
|
||||||
|
builder.add_conditional_edges(
|
||||||
|
"dispatch",
|
||||||
|
_dispatch_workers,
|
||||||
|
["worker", "evaluate"], # Send 目标 或 skip 直达 evaluate
|
||||||
|
)
|
||||||
|
|
||||||
|
# Worker 汇合 → evaluate → 条件路由 → finalize
|
||||||
|
builder.add_edge("worker", "evaluate")
|
||||||
|
builder.add_conditional_edges(
|
||||||
|
"evaluate",
|
||||||
|
_route_after_evaluate,
|
||||||
|
{"dispatch": "dispatch", "finalize": "finalize"},
|
||||||
|
)
|
||||||
|
builder.add_edge("finalize", END)
|
||||||
|
|
||||||
|
return builder.compile(checkpointer=checkpointer)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Checkpointer 工厂 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def create_sqlite_checkpointer(db_path: Path):
|
||||||
|
"""
|
||||||
|
创建检查点器(数据落 D 盘,硬约束 6)。
|
||||||
|
|
||||||
|
【踩坑记录】
|
||||||
|
1. SqliteSaver.from_conn_string() 返回 context manager,不是 Saver 实例;
|
||||||
|
2. SqliteSaver 不支持异步方法(astream/aget_state),必须用 AsyncSqliteSaver;
|
||||||
|
3. AsyncSqliteSaver.from_conn_string() 也是 context manager,需要 async 生命周期管理。
|
||||||
|
【一期方案】暂用 InMemorySaver(内存检查点)保证流程跑通,
|
||||||
|
持久化检查点待后续用 AsyncSqliteSaver + 异步生命周期重构。
|
||||||
|
"""
|
||||||
|
from langgraph.checkpoint.memory import InMemorySaver
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"使用 InMemorySaver(内存检查点)——进程重启后断点会丢失。"
|
||||||
|
"持久化检查点待 AsyncSqliteSaver 异步生命周期重构后启用。"
|
||||||
|
)
|
||||||
|
saver = InMemorySaver()
|
||||||
|
logger.info("Checkpointer 已创建(InMemorySaver,目标路径:%s)", db_path)
|
||||||
|
return saver
|
||||||
|
|
||||||
|
|
||||||
|
# 模块级单例
|
||||||
|
_orchestrator = None
|
||||||
|
_checkpointer = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_orchestrator(db_path: Path | None = None):
|
||||||
|
"""
|
||||||
|
获取主图单例(含 SQLite 检查点)。
|
||||||
|
|
||||||
|
【参数】db_path:检查点库路径;默认 D:\\Agent\\agent\\data\\checkpoint.db
|
||||||
|
"""
|
||||||
|
global _orchestrator, _checkpointer
|
||||||
|
if _orchestrator is None:
|
||||||
|
if db_path is None:
|
||||||
|
db_path = Path(r"D:\Agent\agent\data\checkpoint.db")
|
||||||
|
_checkpointer = create_sqlite_checkpointer(db_path)
|
||||||
|
_orchestrator = build_orchestrator_graph(checkpointer=_checkpointer)
|
||||||
|
logger.info("主图编排器已构建(含 Checkpointer)")
|
||||||
|
return _orchestrator
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""
|
||||||
|
LangGraph 状态契约
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
定义主图(OrchestratorState)与 Worker 子图(WorkerState)的状态结构,
|
||||||
|
是整个 Agent 编排层的"数据总线"。所有节点通过状态读写协作。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 用 TypedDict 而非 Pydantic:LangGraph 对 TypedDict 支持最原生,
|
||||||
|
基准文档第十~十一部分均以 TypedDict 演示,保持一致降低心智负担。
|
||||||
|
2. Reducer(归约器)是状态设计的核心:
|
||||||
|
- `Annotated[list, operator.add]`:并行 Worker 结果**追加合并**,
|
||||||
|
避免互相覆盖(这是企业级 Agent 最常见的状态设计坑);
|
||||||
|
- 单值字段(requirement/plan/evaluation)用覆盖语义。
|
||||||
|
3. error / status 走独立通道:任何节点失败都写入 error 并把 status 置为
|
||||||
|
degraded/failed,满足硬约束 5「异常不能直接崩溃,要有明确提示」。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- 主图状态承载任务全生命周期数据;
|
||||||
|
- Worker 状态只关注单个 TaskStep 的执行细节,与主图解耦;
|
||||||
|
- status 枚举:running / waiting_approval / done / failed / degraded。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:并行 Worker 同时写同一字段 → 数据丢失。
|
||||||
|
应对:所有多值字段必须用 operator.add reducer,单测覆盖并行写入。
|
||||||
|
风险2:状态字段膨胀导致 checkpoint 变大。
|
||||||
|
应对:大文本(如完整 diff)只存摘要 + 指向文件的路径,不塞进状态。
|
||||||
|
风险3:节点返回值与状态字段名不匹配 → 静默不更新。
|
||||||
|
应对:节点返回 dict 的 key 必须与状态字段同名,单元测试断言。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import operator
|
||||||
|
from typing import Annotated, Any, TypedDict
|
||||||
|
|
||||||
|
|
||||||
|
class TaskStep(TypedDict, total=False):
|
||||||
|
"""计划中的单个可执行步骤"""
|
||||||
|
|
||||||
|
step_id: str
|
||||||
|
description: str
|
||||||
|
target_hints: list[str]
|
||||||
|
expected_output: str
|
||||||
|
step_type: str # feature | bugfix | refactor
|
||||||
|
|
||||||
|
|
||||||
|
class OrchestratorState(TypedDict, total=False):
|
||||||
|
"""主图状态(Orchestrator)——任务全生命周期数据总线"""
|
||||||
|
|
||||||
|
# ---- 标识 ----
|
||||||
|
task_id: str
|
||||||
|
project_id: str
|
||||||
|
|
||||||
|
# ---- 需求 ----
|
||||||
|
raw_requirement: str
|
||||||
|
requirement: dict[str, Any] # intake 结构化产出(覆盖式)
|
||||||
|
use_vector_search: bool # 是否查询向量库(提交前可选)
|
||||||
|
|
||||||
|
# ---- 知识召回(追加式,可多次写入)----
|
||||||
|
knowledge_hits: Annotated[list[dict[str, Any]], operator.add]
|
||||||
|
|
||||||
|
# ---- 计划 ----
|
||||||
|
plan: dict[str, Any] # {steps: [TaskStep, ...]}(覆盖式)
|
||||||
|
|
||||||
|
# ---- 风险与审批 ----
|
||||||
|
risk_level: str # normal | high(high 才触发人工审批)
|
||||||
|
risk_warnings: Annotated[list[str], operator.add] # 软警告(不中断,仅报告提示)
|
||||||
|
approval: dict[str, Any] # human_gate 审批结果
|
||||||
|
|
||||||
|
# ---- Worker 产出(追加式,支持并行)----
|
||||||
|
worker_results: Annotated[list[dict[str, Any]], operator.add]
|
||||||
|
|
||||||
|
# ---- 评估与交付 ----
|
||||||
|
evaluation: dict[str, Any]
|
||||||
|
eval_retry: int # 评估修复轮数(Evaluator-Optimizer 计数)
|
||||||
|
report: str
|
||||||
|
|
||||||
|
# ---- 错误与状态 ----
|
||||||
|
error: str
|
||||||
|
status: str # running | waiting_approval | done | failed | degraded
|
||||||
|
|
||||||
|
|
||||||
|
class WorkerState(TypedDict, total=False):
|
||||||
|
"""Worker 子图状态——单个 TaskStep 的执行细节"""
|
||||||
|
|
||||||
|
task_id: str
|
||||||
|
project_id: str
|
||||||
|
step: TaskStep # 当前执行的步骤
|
||||||
|
model_preference: str # 任务级模型偏好:auto 或具体模型 ID
|
||||||
|
|
||||||
|
# ---- 执行产出(追加式)----
|
||||||
|
located_files: Annotated[list[str], operator.add]
|
||||||
|
edits: Annotated[list[dict[str, Any]], operator.add]
|
||||||
|
|
||||||
|
# ---- 验证 ----
|
||||||
|
verify_result: dict[str, Any]
|
||||||
|
retry_count: int
|
||||||
|
|
||||||
|
# ---- 错误 ----
|
||||||
|
error: str
|
||||||
|
|
||||||
|
|
||||||
|
# 状态字段常量(避免字符串硬编码散落各处)
|
||||||
|
STATUS_RUNNING = "running"
|
||||||
|
STATUS_WAITING_APPROVAL = "waiting_approval"
|
||||||
|
STATUS_DONE = "done"
|
||||||
|
STATUS_FAILED = "failed"
|
||||||
|
STATUS_DEGRADED = "degraded"
|
||||||
|
|
||||||
|
RISK_NORMAL = "normal"
|
||||||
|
RISK_HIGH = "high"
|
||||||
@@ -0,0 +1,496 @@
|
|||||||
|
"""
|
||||||
|
Worker 子图(真实改码循环)
|
||||||
|
===========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
执行单个 TaskStep 的子图:locate → modify → verify(失败则 repair 重试 ≤3 次)。
|
||||||
|
M4 已接入真实自研工具链:文件定位、模型生成编辑、写盘落地、编译验证。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 2「纯自研工具链」:改码动作由强模型生成结构化编辑指令,
|
||||||
|
再用 file_tools.edit_file 精确替换——不靠外部编码引擎,机制透明可控。
|
||||||
|
2. 编辑指令走「精确字符串替换」:最小改动面、diff 可读、可单测,
|
||||||
|
比整文件重写安全得多(避免模型重写引入无关改动)。
|
||||||
|
3. verify 走白名单执行器跑编译(决策点 8):机器可判定、确定性强。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- locate:search_tools.find_files / grep_files 真实定位目标文件;
|
||||||
|
- modify:强模型读文件 → 产出 [{file, old_str, new_str}] 编辑计划 → 逐条落地;
|
||||||
|
- verify:executor.run_compile_check 跑 Maven/npm 编译;
|
||||||
|
- repair:验证失败后把错误信息回灌给模型重新生成编辑(≤3 次)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:模型生成的 old_str 与文件不匹配。
|
||||||
|
应对:edit_file 严格唯一匹配,失败记录到 edits 并进 repair 循环重试。
|
||||||
|
风险2:模型重写范围过大(改无关代码)。
|
||||||
|
应对:prompt 明确要求「最小改动」;edit_file 只做精确替换不整文件覆盖。
|
||||||
|
风险3:编译失败耗时(Maven 慢)。
|
||||||
|
应对:executor 超时 60s;verify 结果记 stderr 摘要供 repair 参考。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from langgraph.graph import END, START, StateGraph
|
||||||
|
|
||||||
|
from app.graph.state import WorkerState
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
from app.tools import file_tools, search_tools
|
||||||
|
from app.tools.executor import run_compile_check
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.graph.worker")
|
||||||
|
|
||||||
|
# 单步骤最大重试次数(防无限循环烧 token)
|
||||||
|
MAX_RETRY = 3
|
||||||
|
|
||||||
|
# 每步最多读取的文件数(控制上下文规模)
|
||||||
|
MAX_FILES_PER_STEP = 3
|
||||||
|
|
||||||
|
# 每个文件最多读取行数(防止大文件撑爆上下文)
|
||||||
|
MAX_LINES_PER_FILE = 400
|
||||||
|
|
||||||
|
|
||||||
|
def _get_coding_engine() -> str:
|
||||||
|
"""读取改码引擎配置(builtin / claude_code)。"""
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
return (load_settings().coding_engine or "builtin").strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_json_loose(text: str) -> Any:
|
||||||
|
"""从模型输出宽松提取 JSON(兼容 ```json 围栏)。"""
|
||||||
|
if not text:
|
||||||
|
return {}
|
||||||
|
fence = re.search(r"```(?:json)?\s*(\[.*?\]|\{.*?\})\s*```", text, re.DOTALL)
|
||||||
|
if fence:
|
||||||
|
try:
|
||||||
|
return json.loads(fence.group(1))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
arr = re.search(r"\[.*\]", text, re.DOTALL)
|
||||||
|
if arr:
|
||||||
|
try:
|
||||||
|
return json.loads(arr.group(0))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
brace = re.search(r"\{.*\}", text, re.DOTALL)
|
||||||
|
if brace:
|
||||||
|
try:
|
||||||
|
return json.loads(brace.group(0))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 1:代码定位(真实)----------
|
||||||
|
|
||||||
|
|
||||||
|
def locate_node(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
代码定位节点:按 target_hints 在项目目录下真实定位候选文件。
|
||||||
|
|
||||||
|
【能力】支持文件名片段匹配 + 正则内容搜索(决策点 6:符号检索)。
|
||||||
|
"""
|
||||||
|
step = state.get("step", {})
|
||||||
|
hints = step.get("target_hints", []) or []
|
||||||
|
project_id = state.get("project_id", "")
|
||||||
|
|
||||||
|
if not hints:
|
||||||
|
logger.info("步骤 %s 无目标线索", step.get("step_id"))
|
||||||
|
return {"located_files": []}
|
||||||
|
|
||||||
|
code_root = Path(r"D:\Agent\code")
|
||||||
|
candidates: set[str] = set()
|
||||||
|
|
||||||
|
for hint in hints[:5]:
|
||||||
|
hint_str = str(hint).strip()
|
||||||
|
if not hint_str:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
# 1. 文件名模糊查找
|
||||||
|
found = search_tools.find_files(hint_str, code_root, max_results=10)
|
||||||
|
candidates.update(found.get("files", []))
|
||||||
|
# 2. 内容正则搜索(把线索当关键词搜内容)
|
||||||
|
if len(candidates) < 10:
|
||||||
|
grepped = search_tools.grep_files(
|
||||||
|
re.escape(hint_str), code_root, max_results=5
|
||||||
|
)
|
||||||
|
candidates.update(r["file"] for r in grepped.get("results", []))
|
||||||
|
except Exception as exc: # noqa: BLE001 - 单条线索失败不影响其余
|
||||||
|
logger.warning("定位线索 %s 失败:%s", hint_str, exc)
|
||||||
|
|
||||||
|
result_list = sorted(candidates)[:20]
|
||||||
|
logger.info("步骤 %s 定位到 %d 个候选文件", step.get("step_id"), len(result_list))
|
||||||
|
return {"located_files": result_list}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 2:代码修改(真实)----------
|
||||||
|
|
||||||
|
|
||||||
|
def modify_node(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
代码修改节点:按配置分流到自研工具链或 Claude Code 引擎。
|
||||||
|
|
||||||
|
【引擎分流】
|
||||||
|
CODING_ENGINE=builtin → 自研工具链(默认):强模型生成编辑指令 → edit_file 落地
|
||||||
|
CODING_ENGINE=claude_code → Claude Code CLI:claude 自主读/理解/改/验证
|
||||||
|
|
||||||
|
【可插拔设计(方案 B)】两种引擎共存,改配置值即可切换/回退,主图零改动。
|
||||||
|
"""
|
||||||
|
engine = _get_coding_engine()
|
||||||
|
if engine == "claude_code":
|
||||||
|
return _modify_by_claude_code(state)
|
||||||
|
return _modify_by_builtin(state)
|
||||||
|
|
||||||
|
|
||||||
|
def _modify_by_claude_code(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""Claude Code 引擎:调用 claude CLI 自主完成改码。"""
|
||||||
|
step = state.get("step", {})
|
||||||
|
located = state.get("located_files", []) or []
|
||||||
|
retry = state.get("retry_count", 0)
|
||||||
|
task_id = state.get("task_id", "")
|
||||||
|
prev_error = state.get("error", "")
|
||||||
|
|
||||||
|
from app.tools.claude_engine import ClaudeCodeError, build_prompt, execute
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
project_root = Path(r"D:\Agent\code")
|
||||||
|
# 从定位到的文件推断项目根(找最近的 pom.xml/package.json)
|
||||||
|
for fp in located[:3]:
|
||||||
|
current = Path(fp).parent
|
||||||
|
for _ in range(8):
|
||||||
|
if (current / "pom.xml").exists() or (current / "package.json").exists():
|
||||||
|
project_root = current
|
||||||
|
break
|
||||||
|
if current.parent == current:
|
||||||
|
break
|
||||||
|
current = current.parent
|
||||||
|
if project_root != Path(r"D:\Agent\code"):
|
||||||
|
break
|
||||||
|
|
||||||
|
prompt = build_prompt(
|
||||||
|
step_description=step.get("description", ""),
|
||||||
|
expected_output=step.get("expected_output", ""),
|
||||||
|
target_files=located,
|
||||||
|
prev_error=prev_error,
|
||||||
|
retry=retry,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = execute(
|
||||||
|
project_root=project_root,
|
||||||
|
prompt=prompt,
|
||||||
|
task_id=task_id,
|
||||||
|
timeout=settings.claude_timeout_seconds,
|
||||||
|
model=state.get("model_preference", "") or "",
|
||||||
|
)
|
||||||
|
edit_record = {
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "claude_code_edit",
|
||||||
|
"target_files": located[:5],
|
||||||
|
"summary": result.get("summary", ""),
|
||||||
|
"duration": result.get("duration", 0),
|
||||||
|
"success": result.get("success", False),
|
||||||
|
"retry": retry,
|
||||||
|
"engine": "claude_code",
|
||||||
|
}
|
||||||
|
return {"edits": [edit_record]}
|
||||||
|
except ClaudeCodeError as exc:
|
||||||
|
logger.error("Claude Code 引擎执行失败:%s", exc)
|
||||||
|
return {
|
||||||
|
"edits": [
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "failed",
|
||||||
|
"reason": f"Claude Code 执行失败:{exc}",
|
||||||
|
"engine": "claude_code",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _modify_by_builtin(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
自研工具链引擎(默认):强模型生成编辑指令,工具链真实落地。
|
||||||
|
|
||||||
|
【流程】
|
||||||
|
1. 读取候选文件内容(截断到 MAX_LINES_PER_FILE);
|
||||||
|
2. 调用强模型产出结构化编辑计划 [{file, old_str, new_str, reason}];
|
||||||
|
3. 用 file_tools.edit_file 逐条精确替换;
|
||||||
|
4. 记录每条编辑结果(成功/失败)到 edits。
|
||||||
|
"""
|
||||||
|
step = state.get("step", {})
|
||||||
|
located = state.get("located_files", []) or []
|
||||||
|
retry = state.get("retry_count", 0)
|
||||||
|
task_id = state.get("task_id", "")
|
||||||
|
prev_error = state.get("error", "")
|
||||||
|
|
||||||
|
if not located:
|
||||||
|
logger.warning("步骤 %s 无定位到文件,跳过修改", step.get("step_id"))
|
||||||
|
return {
|
||||||
|
"edits": [
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "skipped",
|
||||||
|
"reason": "未定位到目标文件",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# 读取候选文件内容(最多 3 个,每个最多 400 行)
|
||||||
|
file_contents = []
|
||||||
|
for fp in located[:MAX_FILES_PER_STEP]:
|
||||||
|
try:
|
||||||
|
read_result = file_tools.read_file(fp, end_line=MAX_LINES_PER_FILE)
|
||||||
|
file_contents.append(
|
||||||
|
{
|
||||||
|
"path": read_result["path"],
|
||||||
|
"content": read_result["content"],
|
||||||
|
"total_lines": read_result["total_lines"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("读取文件失败 %s:%s", fp, exc)
|
||||||
|
|
||||||
|
if not file_contents:
|
||||||
|
return {
|
||||||
|
"edits": [
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "failed",
|
||||||
|
"reason": "候选文件全部读取失败",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# 构造 prompt 让模型生成编辑计划
|
||||||
|
files_desc = "\n\n".join(
|
||||||
|
f"【文件】{f['path']}(共 {f['total_lines']} 行)\n```\n{f['content']}\n```"
|
||||||
|
for f in file_contents
|
||||||
|
)
|
||||||
|
retry_hint = f"\n【上次修改失败原因,请修正】{prev_error}" if prev_error else ""
|
||||||
|
|
||||||
|
prompt = f"""你是资深 Java 开发工程师。请针对下面的修改步骤,生成最小化的代码编辑指令。
|
||||||
|
|
||||||
|
【修改步骤】{step.get('description', '')}
|
||||||
|
【预期产出】{step.get('expected_output', '')}
|
||||||
|
【重试次数】{retry}{retry_hint}
|
||||||
|
|
||||||
|
【当前代码】
|
||||||
|
{files_desc}
|
||||||
|
|
||||||
|
【输出要求】只输出 JSON 数组,每个元素是一次精确替换:
|
||||||
|
[
|
||||||
|
{{
|
||||||
|
"file": "完整文件路径",
|
||||||
|
"old_str": "要替换的原文(必须与文件内容完全一致,含缩进)",
|
||||||
|
"new_str": "替换后的新文本",
|
||||||
|
"reason": "改动理由(简短)"
|
||||||
|
}}
|
||||||
|
]
|
||||||
|
|
||||||
|
【硬性约束】
|
||||||
|
1. old_str 必须来自上面给出的代码原文,逐字符一致(含空格换行);
|
||||||
|
2. 单次 old_str 长度不超过 20 行,只改必要部分,禁止整文件重写;
|
||||||
|
3. 若无需改动,返回空数组 [];
|
||||||
|
4. 只输出 JSON,不要任何解释。"""
|
||||||
|
|
||||||
|
edits: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
# 按任务模型偏好选模型:auto → 强模型;否则用指定模型
|
||||||
|
model = get_model_for_task(state.get("model_preference", "auto"), "strong")
|
||||||
|
resp = model.invoke(prompt)
|
||||||
|
content = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
plan = _parse_json_loose(content)
|
||||||
|
if isinstance(plan, dict):
|
||||||
|
plan = plan.get("edits", [])
|
||||||
|
if not isinstance(plan, list):
|
||||||
|
plan = []
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("生成编辑计划失败:%s", exc)
|
||||||
|
return {
|
||||||
|
"edits": [
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "failed",
|
||||||
|
"reason": f"生成编辑计划失败:{exc}",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# 逐条落地编辑
|
||||||
|
for item in plan[:10]: # 单步最多 10 次编辑
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
target = item.get("file", "")
|
||||||
|
old_str = item.get("old_str", "")
|
||||||
|
new_str = item.get("new_str", "")
|
||||||
|
if not target or not old_str:
|
||||||
|
edits.append({"action": "skipped", "reason": "编辑项缺少 file/old_str", "item": item})
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
result = file_tools.edit_file(target, old_str, new_str, task_id=task_id)
|
||||||
|
edits.append(
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "edited",
|
||||||
|
"file": target,
|
||||||
|
"replacements": result["replacements"],
|
||||||
|
"backup_path": result.get("backup_path"),
|
||||||
|
"reason": item.get("reason", ""),
|
||||||
|
"retry": retry,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
logger.info("编辑成功:%s(%d 处)", target, result["replacements"])
|
||||||
|
except Exception as exc: # noqa: BLE001 - 单条失败继续其余
|
||||||
|
edits.append(
|
||||||
|
{
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"action": "failed",
|
||||||
|
"file": target,
|
||||||
|
"reason": str(exc)[:300],
|
||||||
|
"retry": retry,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
logger.warning("编辑失败:%s %s", target, exc)
|
||||||
|
|
||||||
|
return {"edits": edits}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 3:编译验证(真实)----------
|
||||||
|
|
||||||
|
|
||||||
|
def verify_node(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
验证节点:对项目执行编译级验证(决策点 8)。
|
||||||
|
|
||||||
|
【能力】自动识别 Maven/npm 项目,跑 compile/build;
|
||||||
|
【返回】verify_result:{passed, command, stderr_tail}
|
||||||
|
"""
|
||||||
|
step = state.get("step", {})
|
||||||
|
located = state.get("located_files", []) or []
|
||||||
|
edits = state.get("edits", []) or []
|
||||||
|
|
||||||
|
# 若本步没有任何成功编辑且无定位,直接视为不通过
|
||||||
|
has_edit = any(e.get("action") == "edited" for e in edits)
|
||||||
|
if not located and not has_edit:
|
||||||
|
return {
|
||||||
|
"verify_result": {
|
||||||
|
"passed": False,
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"message": "无定位结果且无有效编辑",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 推断项目根目录:用定位到的文件向上找 pom.xml/package.json
|
||||||
|
project_root = None
|
||||||
|
for fp in located[:3]:
|
||||||
|
current = Path(fp).parent
|
||||||
|
for _ in range(8): # 最多向上找 8 层
|
||||||
|
if (current / "pom.xml").exists() or (current / "package.json").exists():
|
||||||
|
project_root = current
|
||||||
|
break
|
||||||
|
if current.parent == current:
|
||||||
|
break
|
||||||
|
current = current.parent
|
||||||
|
if project_root:
|
||||||
|
break
|
||||||
|
|
||||||
|
if project_root is None:
|
||||||
|
# 兜底:用 D:\Agent\code 下第一个含 pom 的目录
|
||||||
|
code_root = Path(r"D:\Agent\code")
|
||||||
|
for pom in code_root.rglob("pom.xml"):
|
||||||
|
project_root = pom.parent
|
||||||
|
break
|
||||||
|
|
||||||
|
if project_root is None:
|
||||||
|
return {
|
||||||
|
"verify_result": {
|
||||||
|
"passed": True, # 无项目可验证时放行(避免误杀)
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"message": "未识别到可验证的项目结构,跳过编译验证",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = run_compile_check(project_root)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"verify_result": {
|
||||||
|
"passed": False,
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"message": f"编译验证执行失败:{exc}",
|
||||||
|
"stderr_tail": "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stderr_tail = (result.get("stderr") or "")[-1500:]
|
||||||
|
return {
|
||||||
|
"verify_result": {
|
||||||
|
"passed": result["passed"],
|
||||||
|
"step_id": step.get("step_id", ""),
|
||||||
|
"command": result.get("command", ""),
|
||||||
|
"message": "编译通过" if result["passed"] else "编译失败",
|
||||||
|
"stderr_tail": stderr_tail,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 节点 4:修复循环 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def repair_node(state: WorkerState) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
修复节点:验证失败后把错误信息回灌,重新进入 modify 生成编辑。
|
||||||
|
"""
|
||||||
|
retry = state.get("retry_count", 0) + 1
|
||||||
|
verify = state.get("verify_result", {})
|
||||||
|
error_msg = f"第 {retry} 次修复尝试;编译失败:{verify.get('stderr_tail', '')[-500:]}"
|
||||||
|
logger.info("进入修复循环第 %d 次", retry)
|
||||||
|
return {"retry_count": retry, "error": error_msg}
|
||||||
|
|
||||||
|
|
||||||
|
def _route_after_verify(state: WorkerState) -> str:
|
||||||
|
"""条件路由:验证通过或重试用尽 → END;否则 → repair。"""
|
||||||
|
verify = state.get("verify_result", {})
|
||||||
|
retry = state.get("retry_count", 0)
|
||||||
|
if verify.get("passed") or retry >= MAX_RETRY:
|
||||||
|
return END
|
||||||
|
return "repair"
|
||||||
|
|
||||||
|
|
||||||
|
def build_worker_graph():
|
||||||
|
"""构建 Worker 子图。"""
|
||||||
|
builder = StateGraph(WorkerState)
|
||||||
|
builder.add_node("locate", locate_node)
|
||||||
|
builder.add_node("modify", modify_node)
|
||||||
|
builder.add_node("verify", verify_node)
|
||||||
|
builder.add_node("repair", repair_node)
|
||||||
|
|
||||||
|
builder.add_edge(START, "locate")
|
||||||
|
builder.add_edge("locate", "modify")
|
||||||
|
builder.add_edge("modify", "verify")
|
||||||
|
builder.add_conditional_edges(
|
||||||
|
"verify",
|
||||||
|
_route_after_verify,
|
||||||
|
{"repair": "repair", END: END},
|
||||||
|
)
|
||||||
|
builder.add_edge("repair", "modify")
|
||||||
|
return builder.compile()
|
||||||
|
|
||||||
|
|
||||||
|
_worker_graph = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_worker_graph():
|
||||||
|
"""获取 Worker 子图单例。"""
|
||||||
|
global _worker_graph
|
||||||
|
if _worker_graph is None:
|
||||||
|
_worker_graph = build_worker_graph()
|
||||||
|
return _worker_graph
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""知识库模块包:解析 / 切分 / 向量化 / 检索"""
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
"""
|
||||||
|
文档加载模块
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
把知识库原始素材(Markdown / Word / PDF)解析成统一切分前的文档对象。
|
||||||
|
覆盖《核心诉求》文档知识管理模块的「文档解析组件」职责。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 按决策点 6「仅文档正文」:只解析 md/docx/pdf 三种正文格式,
|
||||||
|
图片与 zip 跳过(截图多是操作示意,OCR 噪声大、性价比低)。
|
||||||
|
2. 不引入 Unstructured 全家桶(决策点 6 已定):python-docx + pdfminer.six
|
||||||
|
+ 原生读取 md 足够,依赖轻、行为可预期、便于教学对照。
|
||||||
|
3. 解析产物统一为 LangChain Document(page_content + metadata),
|
||||||
|
与基准文档 9.3「文档加载器」同构,下游切分/向量化可直接复用生态能力。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- detect_loader() 按扩展名分派到具体解析器;
|
||||||
|
- 每个解析器产出 list[Document],metadata 统一带 source/文件名/类型;
|
||||||
|
- 目录递归扫描,过滤出受支持扩展名,跳过图片与压缩包。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:pdfminer 解析扫描版 PDF 得到空文本。
|
||||||
|
应对:空文本的文档返回 0 个 chunk 并记 warning,不抛异常、不入库脏数据。
|
||||||
|
风险2:docx 中含表格/图片说明,纯段落提取会丢信息。
|
||||||
|
应对:一期提取段落文本(表格文本在 python-docx 中也算段落级内容),
|
||||||
|
在 metadata 标注 docx 类型,二期可升级结构化解析。
|
||||||
|
风险3:文件编码不是 UTF-8(历史 md 可能是 GBK)。
|
||||||
|
应对:优先 UTF-8 读取,失败后回退 GBK + errors=replace,避免解码崩溃。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.loader")
|
||||||
|
|
||||||
|
# 受支持的正文扩展名(决策点 6:仅文档正文,不含图片/压缩包)
|
||||||
|
SUPPORTED_EXTENSIONS = {".md", ".markdown", ".docx", ".pdf", ".txt", ".csv", ".log"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LoadedDocument:
|
||||||
|
"""
|
||||||
|
解析后的文档对象(对齐 LangChain Document 结构)。
|
||||||
|
|
||||||
|
【字段】
|
||||||
|
page_content:正文文本(后续会被切分)
|
||||||
|
metadata:来源信息(source 文件路径、文件名、类型、序号)
|
||||||
|
"""
|
||||||
|
|
||||||
|
page_content: str
|
||||||
|
metadata: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_text_with_fallback(path: Path) -> str:
|
||||||
|
"""
|
||||||
|
读取文本文件,UTF-8 优先、GBK 兜底。
|
||||||
|
|
||||||
|
【理由】历史文档可能混有 GBK 编码,直接 UTF-8 严格解码会抛异常;
|
||||||
|
回退 + errors=replace 保证「能读多少读多少」,不让单文件拖垮整批入库。
|
||||||
|
"""
|
||||||
|
raw = path.read_bytes()
|
||||||
|
for encoding in ("utf-8", "gbk"):
|
||||||
|
try:
|
||||||
|
return raw.decode(encoding)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
return raw.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_markdown(path: Path) -> list[LoadedDocument]:
|
||||||
|
"""解析 Markdown:整篇作为一个文档(切分阶段再按标题语义拆)。"""
|
||||||
|
text = _read_text_with_fallback(path)
|
||||||
|
return [
|
||||||
|
LoadedDocument(
|
||||||
|
page_content=text,
|
||||||
|
metadata={
|
||||||
|
"source": str(path),
|
||||||
|
"filename": path.name,
|
||||||
|
"file_type": "markdown",
|
||||||
|
"section": "全文",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_text(path: Path) -> list[LoadedDocument]:
|
||||||
|
"""
|
||||||
|
解析纯文本文件(.txt / .csv / .log)。
|
||||||
|
|
||||||
|
【实现】直接读取全文,与 Markdown 同构,切分阶段统一处理。
|
||||||
|
"""
|
||||||
|
text = _read_text_with_fallback(path)
|
||||||
|
return [
|
||||||
|
LoadedDocument(
|
||||||
|
page_content=text,
|
||||||
|
metadata={
|
||||||
|
"source": str(path),
|
||||||
|
"filename": path.name,
|
||||||
|
"file_type": "text",
|
||||||
|
"section": "全文",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_docx(path: Path) -> list[LoadedDocument]:
|
||||||
|
"""
|
||||||
|
解析 Word 文档(.docx)。
|
||||||
|
|
||||||
|
【实现】python-docx 提取全部段落文本,按空行保留段落边界。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from docx import Document as DocxDocument
|
||||||
|
except ImportError as exc: # 依赖缺失时给出可执行的安装提示
|
||||||
|
raise RuntimeError(
|
||||||
|
"缺少 python-docx 依赖,请执行:uv pip install python-docx"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
doc = DocxDocument(str(path))
|
||||||
|
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text and p.text.strip()]
|
||||||
|
text = "\n\n".join(paragraphs)
|
||||||
|
return [
|
||||||
|
LoadedDocument(
|
||||||
|
page_content=text,
|
||||||
|
metadata={
|
||||||
|
"source": str(path),
|
||||||
|
"filename": path.name,
|
||||||
|
"file_type": "docx",
|
||||||
|
"section": "全文",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_pdf(path: Path) -> list[LoadedDocument]:
|
||||||
|
"""
|
||||||
|
解析 PDF 文档。
|
||||||
|
|
||||||
|
【实现】pdfminer.six 按页提取文本,每页一个文档,
|
||||||
|
metadata 记录页码,便于检索结果回溯到具体页。
|
||||||
|
【降级】pypdf 作为备选提取器(两者任一成功即可)。
|
||||||
|
"""
|
||||||
|
pages_text: list[str] = []
|
||||||
|
extract_error: Exception | None = None
|
||||||
|
|
||||||
|
# 首选 pdfminer.six
|
||||||
|
try:
|
||||||
|
from pdfminer.high_level import extract_text
|
||||||
|
|
||||||
|
full = extract_text(str(path))
|
||||||
|
if full and full.strip():
|
||||||
|
# pdfminer 不直接给分页,按 \f(分页符)切
|
||||||
|
pages_text = [p.strip() for p in full.split("\f") if p.strip()] or [full.strip()]
|
||||||
|
except Exception as exc: # noqa: BLE001 - 解析失败需降级而非中断
|
||||||
|
extract_error = exc
|
||||||
|
logger.warning("pdfminer 解析失败,尝试 pypdf:%s %s", path.name, exc)
|
||||||
|
|
||||||
|
# 备选 pypdf
|
||||||
|
if not pages_text:
|
||||||
|
try:
|
||||||
|
from pypdf import PdfReader
|
||||||
|
|
||||||
|
reader = PdfReader(str(path))
|
||||||
|
pages_text = [
|
||||||
|
(page.extract_text() or "").strip()
|
||||||
|
for page in reader.pages
|
||||||
|
]
|
||||||
|
pages_text = [p for p in pages_text if p]
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
extract_error = exc
|
||||||
|
logger.warning("pypdf 解析也失败:%s %s", path.name, exc)
|
||||||
|
|
||||||
|
if not pages_text:
|
||||||
|
logger.warning(
|
||||||
|
"PDF 无可用文本(可能是扫描版):%s,原因=%s", path.name, extract_error
|
||||||
|
)
|
||||||
|
return []
|
||||||
|
|
||||||
|
return [
|
||||||
|
LoadedDocument(
|
||||||
|
page_content=t,
|
||||||
|
metadata={
|
||||||
|
"source": str(path),
|
||||||
|
"filename": path.name,
|
||||||
|
"file_type": "pdf",
|
||||||
|
"section": f"第{i + 1}页",
|
||||||
|
"page": i + 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for i, t in enumerate(pages_text)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
_LOADERS = {
|
||||||
|
".md": _load_markdown,
|
||||||
|
".markdown": _load_markdown,
|
||||||
|
".docx": _load_docx,
|
||||||
|
".pdf": _load_pdf,
|
||||||
|
".txt": _load_text,
|
||||||
|
".csv": _load_text,
|
||||||
|
".log": _load_text,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def load_file(path: Path) -> list[LoadedDocument]:
|
||||||
|
"""
|
||||||
|
解析单个文件。
|
||||||
|
|
||||||
|
【返回】LoadedDocument 列表(PDF 按页返回多条,其余返回 1 条)。
|
||||||
|
【异常】未知扩展名抛 ValueError;解析器缺失依赖抛 RuntimeError。
|
||||||
|
"""
|
||||||
|
suffix = path.suffix.lower()
|
||||||
|
loader = _LOADERS.get(suffix)
|
||||||
|
if loader is None:
|
||||||
|
raise ValueError(f"不支持的文件类型:{suffix}(支持:{sorted(SUPPORTED_EXTENSIONS)})")
|
||||||
|
return loader(path)
|
||||||
|
|
||||||
|
|
||||||
|
def load_directory(directory: Path) -> tuple[list[LoadedDocument], list[str]]:
|
||||||
|
"""
|
||||||
|
递归扫描目录并解析全部受支持文件。
|
||||||
|
|
||||||
|
【返回】(文档列表, 警告列表)
|
||||||
|
警告列表用于记录被跳过的文件与解析失败项,不中断整批流程(硬约束 5)。
|
||||||
|
"""
|
||||||
|
docs: list[LoadedDocument] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
root = Path(directory)
|
||||||
|
|
||||||
|
if not root.exists():
|
||||||
|
warnings.append(f"目录不存在:{root}")
|
||||||
|
return docs, warnings
|
||||||
|
|
||||||
|
for file_path in sorted(root.rglob("*")):
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
suffix = file_path.suffix.lower()
|
||||||
|
if suffix in {".png", ".jpg", ".jpeg", ".gif", ".zip", ".doc"}:
|
||||||
|
warnings.append(f"跳过不支持的文件类型:{file_path.name}")
|
||||||
|
continue
|
||||||
|
if suffix not in SUPPORTED_EXTENSIONS:
|
||||||
|
warnings.append(f"跳过未知类型文件:{file_path.name}")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
docs.extend(load_file(file_path))
|
||||||
|
except Exception as exc: # noqa: BLE001 - 单文件失败不影响整批
|
||||||
|
warnings.append(f"解析失败:{file_path.name},原因:{exc}")
|
||||||
|
logger.warning("解析失败:%s %s", file_path, exc)
|
||||||
|
|
||||||
|
return docs, warnings
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""
|
||||||
|
向量化抽象层
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供文本向量化能力的统一接口,支持两种实现:
|
||||||
|
1. OpenAI 兼容 embeddings API(若模型服务支持);
|
||||||
|
2. 本地轻量模型(chromadb 内置 ONNX 嵌入,免装 torch)。
|
||||||
|
对应《核心诉求》文档处理链路的「向量化」环节。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 可插拔抽象:决策点 4 只定了「双模型路由」做对话,
|
||||||
|
向量化是独立能力——模型服务未必提供 embeddings 接口,
|
||||||
|
必须有本地兜底,否则知识库链路直接瘫痪(硬约束 5 降级)。
|
||||||
|
2. 本地实现选 chromadb 内置 ONNX 嵌入而非 sentence-transformers:
|
||||||
|
后者要拉 torch(约 2GB),前者开箱即用、体积小;
|
||||||
|
中文检索质量不足时可在配置里切换到 API 实现或升级本地模型。
|
||||||
|
3. 配置驱动:.env 里 EMBEDDING_PROVIDER 决定用哪条路,
|
||||||
|
业务代码零改动即可切换(与决策点 5「存储可平迁」同一设计哲学)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- EmbeddingProvider 抽象基类声明 embed_documents / embed_query;
|
||||||
|
- OpenAIEmbeddingProvider 走 langchain_openai.OpenAIEmbeddings;
|
||||||
|
- LocalEmbeddingProvider 走 chromadb 内置 embedding function;
|
||||||
|
- get_embedding_provider() 工厂按配置返回单例。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:API embeddings 不可用 → 入库失败。
|
||||||
|
应对:工厂函数启动时探测,失败自动降级本地并记 warning。
|
||||||
|
风险2:本地模型对中文效果差 → 召回不准。
|
||||||
|
应对:metadata 记录所用 provider;一期在管理页展示,
|
||||||
|
召回不达标时切 API 或升级 BGE 中文模型(文档回写踩坑)。
|
||||||
|
风险3:首次使用本地嵌入需下载模型到缓存(约 80MB)。
|
||||||
|
应对:缓存路径固定到 D 盘(EMBEDDING_CACHE_DIR),守住硬约束 6。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.embeddings")
|
||||||
|
|
||||||
|
|
||||||
|
class EmbeddingProvider(ABC):
|
||||||
|
"""向量化能力抽象接口(决策点 5 同款:实现可替换)"""
|
||||||
|
|
||||||
|
name: str = "abstract"
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||||
|
"""批量向量化文档文本。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def embed_query(self, text: str) -> list[float]:
|
||||||
|
"""向量化查询文本(与文档向量同空间)。"""
|
||||||
|
|
||||||
|
|
||||||
|
class OpenAIEmbeddingProvider(EmbeddingProvider):
|
||||||
|
"""OpenAI 兼容 embeddings API 实现"""
|
||||||
|
|
||||||
|
name = "openai_api"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str,
|
||||||
|
api_key: str,
|
||||||
|
model: str = "text-embedding-3-small",
|
||||||
|
timeout: int = 30,
|
||||||
|
) -> None:
|
||||||
|
from langchain_openai import OpenAIEmbeddings
|
||||||
|
|
||||||
|
self._model_name = model
|
||||||
|
self._client = OpenAIEmbeddings(
|
||||||
|
model=model,
|
||||||
|
base_url=base_url,
|
||||||
|
api_key=api_key,
|
||||||
|
timeout=timeout,
|
||||||
|
max_retries=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||||
|
return self._client.embed_documents(texts)
|
||||||
|
|
||||||
|
def embed_query(self, text: str) -> list[float]:
|
||||||
|
return self._client.embed_query(text)
|
||||||
|
|
||||||
|
|
||||||
|
class LocalEmbeddingProvider(EmbeddingProvider):
|
||||||
|
"""
|
||||||
|
本地嵌入实现(chromadb 内置 ONNX 模型,免 torch)。
|
||||||
|
|
||||||
|
【说明】chromadb 默认使用 all-MiniLM-L6-v2(多语言轻量模型)。
|
||||||
|
中文召回若不达标,可在 .env 切到 OpenAIEmbeddingProvider 或升级模型。
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "local_onnx"
|
||||||
|
|
||||||
|
def __init__(self, cache_dir: str | None = None) -> None:
|
||||||
|
# 把模型缓存强制指向 D 盘,避免写 C 盘(硬约束 6)
|
||||||
|
if cache_dir:
|
||||||
|
os.environ.setdefault("HF_HOME", cache_dir)
|
||||||
|
os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", cache_dir)
|
||||||
|
|
||||||
|
from chromadb.utils import embedding_functions
|
||||||
|
|
||||||
|
self._ef = embedding_functions.DefaultEmbeddingFunction()
|
||||||
|
|
||||||
|
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||||
|
return self._ef(texts)
|
||||||
|
|
||||||
|
def embed_query(self, text: str) -> list[float]:
|
||||||
|
return self._ef([text])[0]
|
||||||
|
|
||||||
|
|
||||||
|
class ChineseEmbeddingProvider(EmbeddingProvider):
|
||||||
|
"""
|
||||||
|
中文专用本地嵌入实现(fastembed + BAAI/bge-small-zh-v1.5)。
|
||||||
|
|
||||||
|
【选型理由】
|
||||||
|
1. 实测 chromadb 内置 all-MiniLM-L6-v2 在中文检索上召回偏弱
|
||||||
|
(「网关离线」「磁盘满了」等查询误命中无关文档),
|
||||||
|
违背《核心诉求》「精准匹配与高召回」要求。
|
||||||
|
2. 选 bge-small-zh-v1.5:BAAI 开源中文向量模型,MTEB 中文榜表现好;
|
||||||
|
走 fastembed(ONNX 运行时),**无需 torch**,体积小、启动快。
|
||||||
|
3. 仍属「本地实现」,不依赖网络 API(模型服务实测无 embeddings 接口)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:首次使用需下载模型(约 90MB)。
|
||||||
|
应对:缓存路径强制走 FASTEMBED_CACHE_PATH(配置为 D 盘),守住硬约束 6。
|
||||||
|
风险2:模型下载受网络影响。
|
||||||
|
应对:工厂函数捕获失败并降级到 chromadb 内置实现,不阻塞链路。
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "bge-small-zh"
|
||||||
|
|
||||||
|
def __init__(self, cache_dir: str | None = None) -> None:
|
||||||
|
if cache_dir:
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.environ.setdefault("FASTEMBED_CACHE_PATH", cache_dir)
|
||||||
|
# 国内网络直连 HuggingFace 会超时(实测 WinError 10060),
|
||||||
|
# 默认走国内镜像 hf-mirror.com;有海外代理时可在 .env 覆盖 HF_ENDPOINT。
|
||||||
|
os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com")
|
||||||
|
os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
|
||||||
|
|
||||||
|
from fastembed import TextEmbedding
|
||||||
|
|
||||||
|
self._model = TextEmbedding("BAAI/bge-small-zh-v1.5")
|
||||||
|
self._dim = 512
|
||||||
|
|
||||||
|
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||||
|
# fastembed 返回 numpy.float32,Chroma 只接受普通 Python float,
|
||||||
|
# 必须逐元素转换,否则抛「Expected embeddings to be a list of floats」
|
||||||
|
return [[float(x) for x in vec] for vec in self._model.embed(texts)]
|
||||||
|
|
||||||
|
def embed_query(self, text: str) -> list[float]:
|
||||||
|
# fastembed 惯例:查询加检索指令前缀,能提升召回质量
|
||||||
|
prefixed = f"为这个句子生成表示以用于检索相关文章:{text}"
|
||||||
|
vec = next(iter(self._model.embed([prefixed])))
|
||||||
|
return [float(x) for x in vec]
|
||||||
|
|
||||||
|
|
||||||
|
def get_embedding_provider(
|
||||||
|
provider: str = "",
|
||||||
|
*,
|
||||||
|
base_url: str = "",
|
||||||
|
api_key: str = "",
|
||||||
|
model: str = "",
|
||||||
|
cache_dir: str = "",
|
||||||
|
) -> EmbeddingProvider:
|
||||||
|
"""
|
||||||
|
工厂函数:按配置返回向量化实现,失败自动降级。
|
||||||
|
|
||||||
|
【降级链】
|
||||||
|
openai_api → 失败降级 chinese → 失败降级 local_onnx;
|
||||||
|
chinese → 失败降级 local_onnx;
|
||||||
|
默认 chinese(中文语料召回质量最优的本地方案)。
|
||||||
|
"""
|
||||||
|
provider = (provider or os.environ.get("EMBEDDING_PROVIDER", "chinese")).lower()
|
||||||
|
|
||||||
|
if provider == "openai_api":
|
||||||
|
try:
|
||||||
|
impl = OpenAIEmbeddingProvider(
|
||||||
|
base_url=base_url or os.environ.get("OPENAI_BASE_URL", ""),
|
||||||
|
api_key=api_key or os.environ.get("OPENAI_API_KEY", ""),
|
||||||
|
model=model
|
||||||
|
or os.environ.get("EMBEDDING_MODEL_NAME", "text-embedding-3-small"),
|
||||||
|
)
|
||||||
|
impl.embed_query("连通性探测")
|
||||||
|
logger.info("向量化实现已启用:OpenAI 兼容 API(模型=%s)", impl._model_name)
|
||||||
|
return impl
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("API 向量化不可用,降级本地实现:%s", exc)
|
||||||
|
provider = "chinese"
|
||||||
|
|
||||||
|
if provider in ("chinese", "bge", "default"):
|
||||||
|
try:
|
||||||
|
impl = ChineseEmbeddingProvider(cache_dir=cache_dir or None)
|
||||||
|
logger.info("向量化实现已启用:中文 BGE-small-zh(fastembed ONNX)")
|
||||||
|
return impl
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("中文嵌入模型初始化失败,降级 chromadb 内置:%s", exc)
|
||||||
|
|
||||||
|
impl = LocalEmbeddingProvider(cache_dir=cache_dir or None)
|
||||||
|
logger.info("向量化实现已启用:本地 ONNX(chromadb 默认 all-MiniLM-L6-v2)")
|
||||||
|
return impl
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
"""
|
||||||
|
知识库服务编排层
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
编排「解析 → 切分 → 向量化入库 → 检索」完整链路,
|
||||||
|
对外暴露入库、检索、重建索引、统计能力。
|
||||||
|
是《核心诉求》文档知识管理模块的业务门面。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 门面模式:API 层只调本模块,不直接碰 loader/splitter/vector_store,
|
||||||
|
模块边界清晰(硬约束 3 低耦合高内聚)。
|
||||||
|
2. 入库粒度按「文件」管理(每个 chunk 的 metadata 带 source),
|
||||||
|
支持单文件增量重建,而不是只能全量清库。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- ingest_directory():扫描目录 → 解析 → 切分 → 入库,返回统计与告警;
|
||||||
|
- ingest_file():单文件增量入库(先删旧 chunk 再写新);
|
||||||
|
- query():自然语言检索,返回带来源的命中结果;
|
||||||
|
- rebuild():清空后全量重建(素材大改后使用)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:素材目录里有大量图片/zip → 解析告警刷屏。
|
||||||
|
应对:load_directory 已跳过并归入 warnings,统计里单列跳过数。
|
||||||
|
风险2:入库中途失败 → 半成品索引。
|
||||||
|
应对:按文件为单位提交(单文件内原子),失败文件进 warnings,
|
||||||
|
不影响其他文件;必要时用 rebuild() 一键重建。
|
||||||
|
风险3:检索耗时随数据量增长。
|
||||||
|
应对:Chroma 自带 HNSW 索引;top_k 限流;后续可加缓存。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.knowledge.document_loader import load_directory, load_file
|
||||||
|
from app.knowledge.embeddings import EmbeddingProvider
|
||||||
|
from app.knowledge.text_splitter import split_documents
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.service")
|
||||||
|
|
||||||
|
|
||||||
|
class KnowledgeService:
|
||||||
|
"""知识库业务门面:解析/切分/入库/检索"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vector_store: KnowledgeVectorStore,
|
||||||
|
embedding_provider: EmbeddingProvider,
|
||||||
|
) -> None:
|
||||||
|
self._vs = vector_store
|
||||||
|
self._embedding = embedding_provider
|
||||||
|
|
||||||
|
# ---------- 入库 ----------
|
||||||
|
|
||||||
|
def ingest_directory(self, directory: Path) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
扫描目录并全量入库(**按 source 替换,不重复追加**)。
|
||||||
|
|
||||||
|
【数据正确性关键】入库前先按 source 删除旧 chunk,再写入新 chunk,
|
||||||
|
连点多次不会产生重复数据(M6 发现的隐患在此修复)。
|
||||||
|
"""
|
||||||
|
directory = Path(directory)
|
||||||
|
logger.info("开始知识库入库:%s", directory)
|
||||||
|
|
||||||
|
docs, warnings = load_directory(directory)
|
||||||
|
scanned = len({d.metadata.get("source") for d in docs})
|
||||||
|
|
||||||
|
chunks = split_documents(docs)
|
||||||
|
if not chunks:
|
||||||
|
return {
|
||||||
|
"scanned_files": scanned,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"skipped": len(warnings),
|
||||||
|
"warnings": warnings + ["未解析出任何可入库文本"],
|
||||||
|
}
|
||||||
|
|
||||||
|
# 按 source 先清旧再写新(replace-by-source)
|
||||||
|
sources = {d.metadata.get("source", "") for d in docs if d.metadata.get("source")}
|
||||||
|
deleted_old = 0
|
||||||
|
for src in sources:
|
||||||
|
deleted_old += self._vs.delete_by_source(src)
|
||||||
|
|
||||||
|
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in chunks]
|
||||||
|
texts = [c.page_content for c in chunks]
|
||||||
|
metas = [c.metadata for c in chunks]
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._vs.add_documents(texts, metas, ids)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 入库失败要报清楚
|
||||||
|
logger.error("向量入库失败:%s", exc)
|
||||||
|
return {
|
||||||
|
"scanned_files": scanned,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"skipped": len(warnings),
|
||||||
|
"warnings": warnings + [f"向量入库失败:{exc}"],
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"scanned_files": scanned,
|
||||||
|
"ingested_chunks": len(chunks),
|
||||||
|
"deleted_old_chunks": deleted_old,
|
||||||
|
"skipped": len(warnings),
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
|
||||||
|
def ingest_files(self, file_paths: list[str]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
批量入库指定文件(**按 source 替换**)。
|
||||||
|
|
||||||
|
【用途】前端文件选择 UI 勾选后调用,只向量化选中的文档。
|
||||||
|
【数据正确性】每个文件先按 source 删旧 chunk 再写新,多次勾选不重复。
|
||||||
|
"""
|
||||||
|
file_paths = [str(p) for p in file_paths if str(p).strip()]
|
||||||
|
if not file_paths:
|
||||||
|
return {
|
||||||
|
"requested_files": 0,
|
||||||
|
"success_files": 0,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"deleted_old_chunks": 0,
|
||||||
|
"warnings": ["未选择任何文件"],
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("批量入库指定文件:%d 个", len(file_paths))
|
||||||
|
all_chunks = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
success_files = 0
|
||||||
|
deleted_old = 0
|
||||||
|
|
||||||
|
for fp in file_paths:
|
||||||
|
try:
|
||||||
|
docs = load_file(Path(fp))
|
||||||
|
chunks = split_documents(docs)
|
||||||
|
if not chunks:
|
||||||
|
warnings.append(f"文件无可入库文本:{Path(fp).name}")
|
||||||
|
continue
|
||||||
|
# replace-by-source
|
||||||
|
deleted_old += self._vs.delete_by_source(fp)
|
||||||
|
all_chunks.extend(chunks)
|
||||||
|
success_files += 1
|
||||||
|
except Exception as exc: # noqa: BLE001 - 单文件失败不影响其余
|
||||||
|
warnings.append(f"解析失败:{Path(fp).name},原因:{exc}")
|
||||||
|
logger.warning("解析失败:%s %s", fp, exc)
|
||||||
|
|
||||||
|
if not all_chunks:
|
||||||
|
return {
|
||||||
|
"requested_files": len(file_paths),
|
||||||
|
"success_files": 0,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"deleted_old_chunks": deleted_old,
|
||||||
|
"warnings": warnings or ["全部文件均无可入库文本"],
|
||||||
|
}
|
||||||
|
|
||||||
|
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in all_chunks]
|
||||||
|
try:
|
||||||
|
self._vs.add_documents(
|
||||||
|
[c.page_content for c in all_chunks],
|
||||||
|
[c.metadata for c in all_chunks],
|
||||||
|
ids,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("批量入库失败:%s", exc)
|
||||||
|
return {
|
||||||
|
"requested_files": len(file_paths),
|
||||||
|
"success_files": 0,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"deleted_old_chunks": deleted_old,
|
||||||
|
"warnings": warnings + [f"向量入库失败:{exc}"],
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"requested_files": len(file_paths),
|
||||||
|
"success_files": success_files,
|
||||||
|
"ingested_chunks": len(all_chunks),
|
||||||
|
"deleted_old_chunks": deleted_old,
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_ingestible_files(self, directory: Path) -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
递归列出目录下全部可入库文件(供前端文件选择 UI)。
|
||||||
|
|
||||||
|
【返回】列表,每项含 path / relative_path / name / size / file_type
|
||||||
|
"""
|
||||||
|
from app.knowledge.document_loader import SUPPORTED_EXTENSIONS
|
||||||
|
|
||||||
|
root = Path(directory)
|
||||||
|
if not root.exists():
|
||||||
|
return []
|
||||||
|
|
||||||
|
files: list[dict[str, Any]] = []
|
||||||
|
for p in sorted(root.rglob("*")):
|
||||||
|
if not p.is_file():
|
||||||
|
continue
|
||||||
|
if p.suffix.lower() not in SUPPORTED_EXTENSIONS:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
size = p.stat().st_size
|
||||||
|
except OSError:
|
||||||
|
size = 0
|
||||||
|
files.append(
|
||||||
|
{
|
||||||
|
"path": str(p),
|
||||||
|
"relative_path": str(p.relative_to(root)).replace("\\", "/"),
|
||||||
|
"name": p.name,
|
||||||
|
"size": size,
|
||||||
|
"file_type": p.suffix.lower().lstrip("."),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return files
|
||||||
|
|
||||||
|
def ingest_file(self, file_path: Path) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
单文件增量入库(先删旧 chunk 再写新 chunk)。
|
||||||
|
|
||||||
|
【返回】统计字典:file / deleted_old / ingested_chunks / warnings
|
||||||
|
"""
|
||||||
|
file_path = Path(file_path)
|
||||||
|
deleted = self._vs.delete_by_source(str(file_path))
|
||||||
|
|
||||||
|
try:
|
||||||
|
docs = load_file(file_path)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"file": file_path.name,
|
||||||
|
"deleted_old": deleted,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"warnings": [f"解析失败:{exc}"],
|
||||||
|
}
|
||||||
|
|
||||||
|
chunks = split_documents(docs)
|
||||||
|
if not chunks:
|
||||||
|
return {
|
||||||
|
"file": file_path.name,
|
||||||
|
"deleted_old": deleted,
|
||||||
|
"ingested_chunks": 0,
|
||||||
|
"warnings": ["该文件无可入库文本"],
|
||||||
|
}
|
||||||
|
|
||||||
|
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in chunks]
|
||||||
|
self._vs.add_documents(
|
||||||
|
[c.page_content for c in chunks],
|
||||||
|
[c.metadata for c in chunks],
|
||||||
|
ids,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"file": file_path.name,
|
||||||
|
"deleted_old": deleted,
|
||||||
|
"ingested_chunks": len(chunks),
|
||||||
|
"warnings": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
def rebuild(self, directory: Path) -> dict[str, Any]:
|
||||||
|
"""清空后全量重建(素材大改后使用)。"""
|
||||||
|
logger.info("重建知识库索引:%s", directory)
|
||||||
|
self._vs.clear()
|
||||||
|
return self.ingest_directory(directory)
|
||||||
|
|
||||||
|
# ---------- 检索 ----------
|
||||||
|
|
||||||
|
def query(self, question: str, top_k: int = 5) -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
自然语言检索项目知识。
|
||||||
|
|
||||||
|
【返回】命中列表,每项含 text / metadata / score / source。
|
||||||
|
"""
|
||||||
|
hits = self._vs.search(question, top_k=top_k)
|
||||||
|
for h in hits:
|
||||||
|
h["source"] = h.get("metadata", {}).get("source", "")
|
||||||
|
h["filename"] = h.get("metadata", {}).get("filename", "")
|
||||||
|
return hits
|
||||||
|
|
||||||
|
# ---------- 统计 ----------
|
||||||
|
|
||||||
|
def stats(self) -> dict[str, Any]:
|
||||||
|
"""返回向量库统计信息。"""
|
||||||
|
return {
|
||||||
|
"total_chunks": self._vs.count,
|
||||||
|
"embedding_provider": self._embedding.name,
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""
|
||||||
|
文本切分模块
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
把解析后的长文档切分成适合向量化的小块(chunk),
|
||||||
|
保证语义完整性(不从句子中间硬切),对应《核心诉求》的「文本切分」环节。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. Markdown 用 MarkdownHeaderTextSplitter 先按标题层级拆节,
|
||||||
|
再用 RecursiveCharacterTextSplitter 做二次细粒度切分——
|
||||||
|
这是基准文档 9.4「五种分块策略」中语义 + 递归的组合拳,
|
||||||
|
能保留「一节一主题」的结构,检索召回显著优于盲切。
|
||||||
|
2. 普通文本(docx/pdf)直接走递归字符切分,按段落/句子/字符逐级降级。
|
||||||
|
3. 分块大小取 512 字符、重叠 64:中文文档经验值,
|
||||||
|
既保证单块语义完整,又控制 embedding 成本与检索粒度。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- split_documents() 入口按 file_type 分派;
|
||||||
|
- 每个 chunk 的 metadata 继承父文档信息,并补 chunk_index / chunk_total;
|
||||||
|
- 切分器参数集中声明,便于后续按召回效果调优。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:chunk 过大导致检索粒度粗、embedding 截断。
|
||||||
|
应对:硬上限 1000 字符强制二次切分;超长块记 warning。
|
||||||
|
风险2:chunk 过小导致语义碎片化、召回噪声大。
|
||||||
|
应对:下限保护——小于 50 字符的尾块并入前一块,不单独入库。
|
||||||
|
风险3:Markdown 标题解析失败(非标准 md)。
|
||||||
|
应对:捕获异常回退到纯递归切分,不中断。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from langchain_text_splitters import (
|
||||||
|
MarkdownHeaderTextSplitter,
|
||||||
|
RecursiveCharacterTextSplitter,
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.knowledge.document_loader import LoadedDocument
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.splitter")
|
||||||
|
|
||||||
|
# 切分参数(中文文档经验值,可按召回效果调优)
|
||||||
|
CHUNK_SIZE = 512
|
||||||
|
CHUNK_OVERLAP = 64
|
||||||
|
MIN_CHUNK_SIZE = 50 # 小于此长度的尾块并入前块,避免语义碎片
|
||||||
|
|
||||||
|
# Markdown 标题层级 → metadata 键名
|
||||||
|
MD_HEADERS = [
|
||||||
|
("#", "header_1"),
|
||||||
|
("##", "header_2"),
|
||||||
|
("###", "header_3"),
|
||||||
|
("####", "header_4"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _build_text_splitter() -> RecursiveCharacterTextSplitter:
|
||||||
|
"""构造递归字符切分器(按段落→句子→字符逐级降级切分)。"""
|
||||||
|
return RecursiveCharacterTextSplitter(
|
||||||
|
chunk_size=CHUNK_SIZE,
|
||||||
|
chunk_overlap=CHUNK_OVERLAP,
|
||||||
|
separators=["\n\n", "\n", "。", "!", "?", ";", " ", ""],
|
||||||
|
keep_separator=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _split_markdown(text: str) -> list[tuple[str, dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
Markdown 语义切分:先按标题拆节,再细粒度切分。
|
||||||
|
|
||||||
|
【返回】(块文本, 附加元数据) 列表。
|
||||||
|
"""
|
||||||
|
splitter = MarkdownHeaderTextSplitter(
|
||||||
|
headers_to_split_on=MD_HEADERS,
|
||||||
|
strip_headers=False,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
sections = splitter.split_text(text)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 非标准 md 时降级
|
||||||
|
logger.warning("Markdown 标题切分失败,回退纯递归切分:%s", exc)
|
||||||
|
return [(text, {})]
|
||||||
|
|
||||||
|
results: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
fine_splitter = _build_text_splitter()
|
||||||
|
for sec in sections:
|
||||||
|
content = sec.page_content.strip()
|
||||||
|
if not content:
|
||||||
|
continue
|
||||||
|
chunks = fine_splitter.split_text(content)
|
||||||
|
for chunk in chunks:
|
||||||
|
results.append((chunk, dict(sec.metadata)))
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def _split_plain(text: str) -> list[tuple[str, dict[str, Any]]]:
|
||||||
|
"""普通文本(docx/pdf)递归切分。"""
|
||||||
|
splitter = _build_text_splitter()
|
||||||
|
return [(chunk, {}) for chunk in splitter.split_text(text) if chunk.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_tiny_chunks(chunks: list[tuple[str, dict[str, Any]]]) -> list[tuple[str, dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
尾块过小则并入前一块,避免语义碎片。
|
||||||
|
|
||||||
|
【理由】最后一个 chunk 常常只有十几个字符(如「参考文献」),
|
||||||
|
单独入库只会制造检索噪声。
|
||||||
|
"""
|
||||||
|
if len(chunks) <= 1:
|
||||||
|
return chunks
|
||||||
|
merged = list(chunks)
|
||||||
|
last_text, last_meta = merged[-1]
|
||||||
|
if len(last_text) < MIN_CHUNK_SIZE:
|
||||||
|
prev_text, prev_meta = merged[-2]
|
||||||
|
merged[-2] = (prev_text + "\n" + last_text, prev_meta)
|
||||||
|
merged.pop()
|
||||||
|
logger.debug("合并过小尾块(%d 字符)", len(last_text))
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def split_documents(docs: list[LoadedDocument]) -> list[LoadedDocument]:
|
||||||
|
"""
|
||||||
|
把整批文档切分成 chunk。
|
||||||
|
|
||||||
|
【返回】LoadedDocument 列表,每个元素是一个 chunk,
|
||||||
|
metadata 携带完整来源信息 + header 结构 + chunk_index。
|
||||||
|
"""
|
||||||
|
all_chunks: list[LoadedDocument] = []
|
||||||
|
|
||||||
|
for doc in docs:
|
||||||
|
text = doc.page_content.strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if doc.metadata.get("file_type") == "markdown":
|
||||||
|
pieces = _split_markdown(text)
|
||||||
|
else:
|
||||||
|
pieces = _split_plain(text)
|
||||||
|
|
||||||
|
pieces = _merge_tiny_chunks(pieces)
|
||||||
|
total = len(pieces)
|
||||||
|
|
||||||
|
for idx, (chunk_text, extra_meta) in enumerate(pieces):
|
||||||
|
meta = dict(doc.metadata)
|
||||||
|
meta.update(extra_meta)
|
||||||
|
meta["chunk_index"] = idx
|
||||||
|
meta["chunk_total"] = total
|
||||||
|
all_chunks.append(LoadedDocument(page_content=chunk_text, metadata=meta))
|
||||||
|
|
||||||
|
logger.info("文档切分完成:%d 篇 → %d 个 chunk", len(docs), len(all_chunks))
|
||||||
|
return all_chunks
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
"""
|
||||||
|
向量存储模块
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
封装 Chroma 向量库的连接、入库、检索、删除能力,
|
||||||
|
对应《核心诉求》的「持久化存入向量数据库」与「智能检索」环节。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 Chroma(决策点 5 已锁定):嵌入式、免 Docker、数据落 D 盘,
|
||||||
|
Windows 单机场景最省事;Postgres/Milvus 平迁通道已在接口层预留。
|
||||||
|
2. 用 PersistentClient 指定 D 盘目录,而非默认内存/用户目录——
|
||||||
|
硬约束 6 要求向量库数据也必须落 D:\\Agent。
|
||||||
|
3. 检索用 similarity_search_with_score(L2 距离),
|
||||||
|
同时返回分数,便于前端展示「相关度」与设定召回阈值。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- KnowledgeVectorStore 封装 collection 的增删查;
|
||||||
|
- 入库时把 chunk 文本 + metadata 一起写入,检索结果可回溯到源文件;
|
||||||
|
- 支持按 source 批量删除(重建索引时按文件增量替换)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:Chroma 目录被并发进程锁定。
|
||||||
|
应对:单例连接 + 启动时校验目录可写;Windows 下避免多进程同开。
|
||||||
|
风险2:metadata 值含非法类型(Chroma 只接受 str/int/float/bool)。
|
||||||
|
应对:入库前统一清洗,非标量转字符串。
|
||||||
|
风险3:检索空集合或库损坏。
|
||||||
|
应对:捕获异常返回空结果 + warning,不抛给上层(硬约束 5)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.vectorstore")
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_metadata(meta: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
清洗 metadata 为 Chroma 可接受的标量类型。
|
||||||
|
|
||||||
|
【规则】str/int/float/bool/None 保留(None 丢弃),
|
||||||
|
其他类型转字符串;列表取 join。
|
||||||
|
"""
|
||||||
|
clean: dict[str, Any] = {}
|
||||||
|
for key, value in meta.items():
|
||||||
|
if value is None:
|
||||||
|
continue
|
||||||
|
if isinstance(value, (str, int, float, bool)):
|
||||||
|
clean[key] = value
|
||||||
|
elif isinstance(value, (list, tuple)):
|
||||||
|
clean[key] = ", ".join(str(v) for v in value)
|
||||||
|
else:
|
||||||
|
clean[key] = str(value)
|
||||||
|
return clean
|
||||||
|
|
||||||
|
|
||||||
|
class KnowledgeVectorStore:
|
||||||
|
"""Chroma 向量库封装(决策点 5:实现可平迁)"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
persist_dir: Path,
|
||||||
|
collection_name: str,
|
||||||
|
embedding_provider: Any,
|
||||||
|
) -> None:
|
||||||
|
import chromadb
|
||||||
|
from chromadb.config import Settings as ChromaSettings
|
||||||
|
|
||||||
|
self._persist_dir = Path(persist_dir)
|
||||||
|
self._persist_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._collection_name = collection_name
|
||||||
|
self._embedding = embedding_provider
|
||||||
|
|
||||||
|
# PersistentClient 强制数据落 D 盘指定目录
|
||||||
|
self._client = chromadb.PersistentClient(
|
||||||
|
path=str(self._persist_dir),
|
||||||
|
settings=ChromaSettings(anonymized_telemetry=False),
|
||||||
|
)
|
||||||
|
self._collection = self._client.get_or_create_collection(
|
||||||
|
name=collection_name,
|
||||||
|
metadata={"hnsw:space": "l2"},
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"向量库已连接:目录=%s,集合=%s,当前条数=%d",
|
||||||
|
self._persist_dir,
|
||||||
|
collection_name,
|
||||||
|
self._collection.count(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def count(self) -> int:
|
||||||
|
"""当前集合中的向量条数。"""
|
||||||
|
return self._collection.count()
|
||||||
|
|
||||||
|
def add_documents(
|
||||||
|
self,
|
||||||
|
texts: list[str],
|
||||||
|
metadatas: list[dict[str, Any]],
|
||||||
|
ids: list[str],
|
||||||
|
) -> int:
|
||||||
|
"""
|
||||||
|
批量入库。
|
||||||
|
|
||||||
|
【返回】实际写入条数。
|
||||||
|
【要求】texts / metadatas / ids 三者长度一致。
|
||||||
|
"""
|
||||||
|
if not texts:
|
||||||
|
return 0
|
||||||
|
if not (len(texts) == len(metadatas) == len(ids)):
|
||||||
|
raise ValueError("texts / metadatas / ids 长度必须一致")
|
||||||
|
|
||||||
|
clean_metas = [_sanitize_metadata(m) for m in metadatas]
|
||||||
|
embeddings = self._embedding.embed_documents(texts)
|
||||||
|
|
||||||
|
self._collection.add(
|
||||||
|
documents=texts,
|
||||||
|
metadatas=clean_metas,
|
||||||
|
ids=ids,
|
||||||
|
embeddings=embeddings,
|
||||||
|
)
|
||||||
|
logger.info("向量入库完成:%d 条", len(texts))
|
||||||
|
return len(texts)
|
||||||
|
|
||||||
|
def search(self, query: str, top_k: int = 5) -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
语义检索。
|
||||||
|
|
||||||
|
【返回】列表,每项含 text / metadata / score(L2 距离,越小越相似)。
|
||||||
|
【降级】检索失败返回空列表并记 warning,不抛异常。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if self._collection.count() == 0:
|
||||||
|
logger.warning("向量库为空,检索返回空结果")
|
||||||
|
return []
|
||||||
|
query_emb = self._embedding.embed_query(query)
|
||||||
|
result = self._collection.query(
|
||||||
|
query_embeddings=[query_emb],
|
||||||
|
n_results=min(top_k, self._collection.count()),
|
||||||
|
include=["documents", "metadatas", "distances"],
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 检索失败降级为空
|
||||||
|
logger.warning("向量检索失败:%s", exc)
|
||||||
|
return []
|
||||||
|
|
||||||
|
docs = result.get("documents", [[]])[0] or []
|
||||||
|
metas = result.get("metadatas", [[]])[0] or []
|
||||||
|
dists = result.get("distances", [[]])[0] or []
|
||||||
|
|
||||||
|
hits: list[dict[str, Any]] = []
|
||||||
|
for text, meta, dist in zip(docs, metas, dists):
|
||||||
|
hits.append(
|
||||||
|
{
|
||||||
|
"text": text,
|
||||||
|
"metadata": meta or {},
|
||||||
|
"score": float(dist) if dist is not None else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return hits
|
||||||
|
|
||||||
|
def delete_by_source(self, source: str) -> int:
|
||||||
|
"""
|
||||||
|
按来源文件删除全部 chunk(重建索引时用)。
|
||||||
|
|
||||||
|
【返回】删除条数。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
existing = self._collection.get(where={"source": source})
|
||||||
|
ids = existing.get("ids", []) or []
|
||||||
|
if not ids:
|
||||||
|
return 0
|
||||||
|
self._collection.delete(ids=ids)
|
||||||
|
logger.info("按来源删除 %d 条:%s", len(ids), source)
|
||||||
|
return len(ids)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("按来源删除失败:%s %s", source, exc)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def clear(self) -> None:
|
||||||
|
"""清空整个集合(重建索引时用)。"""
|
||||||
|
try:
|
||||||
|
self._client.delete_collection(self._collection_name)
|
||||||
|
self._collection = self._client.get_or_create_collection(
|
||||||
|
name=self._collection_name,
|
||||||
|
metadata={"hnsw:space": "l2"},
|
||||||
|
)
|
||||||
|
logger.info("向量集合已清空并重建:%s", self._collection_name)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("清空向量集合失败:%s", exc)
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
"""
|
||||||
|
FastAPI 应用入口
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
组装 FastAPI 应用:挂载路由、统一异常处理、启动期初始化存储目录与配置。
|
||||||
|
一期只挂「项目管理」路由,M3 起追加任务/流式/审批路由。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. FastAPI + uvicorn:基准文档附录已列明,异步友好,SSE 由 sse-starlette 承接。
|
||||||
|
2. 全局异常处理器:把任何未捕获异常转成统一 ApiResponse,
|
||||||
|
满足硬约束 5「任何异常场景下系统不能直接崩溃,需给出明确的错误提示」。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- create_app() 工厂函数(而非直接实例化全局 app):便于单测时构造隔离实例;
|
||||||
|
- 启动事件里 ensure_directories(),保证 D 盘运行目录就绪;
|
||||||
|
- 所有路由统一前缀 /api,便于前端代理与版本管理。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:配置加载失败(如密钥缺失)导致进程直接退出。
|
||||||
|
应对:启动时 try/except,打印中文错误后 raise 让 uvicorn 明确报错,
|
||||||
|
而不是静默起一个半残服务。
|
||||||
|
风险2:前端跨域(React 开发服务器 5173 → 后端 8000)。
|
||||||
|
应对:挂 CORSMiddleware,允许本地开发源;生产部署时收紧 origins。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
from app.api.audit_api import router as audit_router
|
||||||
|
from app.api.backup_api import router as backup_router
|
||||||
|
from app.api.batch_api import router as batch_router
|
||||||
|
from app.api.database_api import router as database_router
|
||||||
|
from app.api.doc_qa_api import router as doc_qa_router
|
||||||
|
from app.api.health_api import router as health_router
|
||||||
|
from app.api.knowledge_api import router as knowledge_router
|
||||||
|
from app.api.knowledge_autoupdate_api import router as knowledge_autoupdate_router
|
||||||
|
from app.api.log_aggregation_api import router as logs_router
|
||||||
|
from app.api.mcp_api import router as mcp_router
|
||||||
|
from app.api.memory_api import router as memory_router
|
||||||
|
from app.api.metrics_api import router as metrics_router
|
||||||
|
from app.api.model_config_api import router as model_config_router
|
||||||
|
from app.api.platform_api import router as platform_router
|
||||||
|
from app.api.project_api import router as project_router
|
||||||
|
from app.api.provider_api import router as provider_router
|
||||||
|
from app.api.prompt_polish_api import router as prompt_polish_router
|
||||||
|
from app.api.settings_api import router as settings_router
|
||||||
|
from app.api.template_api import router as template_router
|
||||||
|
from app.api.testgen_api import router as testgen_router
|
||||||
|
from app.api.workspace_api import router as workspace_router
|
||||||
|
from app.api.task_api import router as task_router
|
||||||
|
from app.api.upload_api import router as upload_router
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
# ---------- 日志配置(中文输出)----------
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("agent.app")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
"""应用生命周期:启动时初始化配置与目录,关闭时打印收尾日志。"""
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
logger.info(
|
||||||
|
"应用启动成功:数据目录=%s,代码目录=%s",
|
||||||
|
settings.data_root,
|
||||||
|
settings.code_root,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error("应用启动失败(配置加载异常):%s", exc)
|
||||||
|
raise
|
||||||
|
|
||||||
|
# 启动时恢复孤儿任务。
|
||||||
|
# 【L4】不再盲目标 failed:任务由独立 worker 进程执行,
|
||||||
|
# API 重启期间 worker 可能还在跑。先查 worker PID 存活:
|
||||||
|
# 进程活着 → 任务仍在执行,不要动(否则会误杀正在跑的任务)
|
||||||
|
# 进程已死 → 才标记失败
|
||||||
|
try:
|
||||||
|
from app.api.task_api import get_task_service
|
||||||
|
from app.worker.__main__ import is_pid_alive
|
||||||
|
|
||||||
|
svc = get_task_service()
|
||||||
|
all_tasks = svc.list_tasks()
|
||||||
|
orphan_count = 0
|
||||||
|
alive_count = 0
|
||||||
|
for t in all_tasks:
|
||||||
|
if t.status != "running":
|
||||||
|
continue
|
||||||
|
worker_pid = getattr(t, "worker_pid", 0) or 0
|
||||||
|
if worker_pid and is_pid_alive(worker_pid):
|
||||||
|
alive_count += 1
|
||||||
|
logger.info(
|
||||||
|
"任务 %s 的 worker 仍存活(pid=%s),继续执行", t.id, worker_pid
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
svc.update_task_status(
|
||||||
|
t.id, status="failed", error="服务重启导致执行中断,请重新发起对话"
|
||||||
|
)
|
||||||
|
orphan_count += 1
|
||||||
|
if orphan_count:
|
||||||
|
logger.warning("启动时恢复 %d 个孤儿任务(running → failed)", orphan_count)
|
||||||
|
if alive_count:
|
||||||
|
logger.info("启动时发现 %d 个任务仍在由 worker 执行,已保留", alive_count)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("孤儿任务恢复失败(不影响主流程):%s", exc)
|
||||||
|
|
||||||
|
# 【13.9】检测热重载模式:开发热重载与长任务执行天然互斥,必须显式告警。
|
||||||
|
# Claude 改码任务会写文件 → WatchFiles 触发 reload → 正在跑的任务被杀
|
||||||
|
# → session_id / 对话历史落库丢失 → 续聊开出新会话(自毁反馈回路)。
|
||||||
|
try:
|
||||||
|
import sys
|
||||||
|
|
||||||
|
reload_on = any(a == "--reload" or a.startswith("--reload") for a in sys.argv)
|
||||||
|
if reload_on:
|
||||||
|
logger.warning(
|
||||||
|
"⚠️ 当前以 --reload 热重载模式运行:执行改码任务时后端会被自动重启,"
|
||||||
|
"导致任务中断、会话丢失。跑长任务请改用 start_backend.ps1(无 reload)"
|
||||||
|
"或 start_backend.dev.ps1(--reload-dir app 限定监听范围)"
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 启动定时抓取调度器(若配置为启用)
|
||||||
|
try:
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
config = store.get_schedule()
|
||||||
|
if config.get("enabled"):
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
await scheduler.start()
|
||||||
|
logger.info("定时抓取调度器已自动启动(间隔 %d 分钟)", config.get("interval_minutes", 360))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("定时调度器启动失败(不影响主流程):%s", exc)
|
||||||
|
|
||||||
|
yield
|
||||||
|
|
||||||
|
# 关闭时停止调度器
|
||||||
|
try:
|
||||||
|
from app.services.platform_scheduler import get_scheduler
|
||||||
|
|
||||||
|
scheduler = get_scheduler()
|
||||||
|
await scheduler.stop()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
logger.info("应用已关闭")
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
"""
|
||||||
|
构建 FastAPI 应用实例。
|
||||||
|
|
||||||
|
【返回】配置完成的 FastAPI 应用(已挂路由与中间件)。
|
||||||
|
"""
|
||||||
|
settings = load_settings()
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.app_name,
|
||||||
|
description="编程智能 Agent 系统 —— 项目管理与任务入口 API",
|
||||||
|
version="0.1.0",
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 统一 CORS:本地开发允许 React 开发服务器跨域
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"], # 一期本地单机;生产部署时改为白名单
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 全局异常兜底:任何未捕获异常 → 统一 ApiResponse 结构(硬约束 5)
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
logger.exception("未捕获异常:%s %s", request.url.path, exc)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=500,
|
||||||
|
content={
|
||||||
|
"code": 500,
|
||||||
|
"message": f"服务器内部错误:{type(exc).__name__}: {exc}",
|
||||||
|
"data": None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 挂载业务路由
|
||||||
|
app.include_router(project_router)
|
||||||
|
app.include_router(knowledge_router)
|
||||||
|
app.include_router(task_router)
|
||||||
|
app.include_router(audit_router)
|
||||||
|
app.include_router(model_config_router)
|
||||||
|
app.include_router(provider_router)
|
||||||
|
app.include_router(platform_router)
|
||||||
|
app.include_router(database_router)
|
||||||
|
app.include_router(settings_router)
|
||||||
|
app.include_router(upload_router)
|
||||||
|
app.include_router(doc_qa_router)
|
||||||
|
app.include_router(prompt_polish_router)
|
||||||
|
app.include_router(health_router)
|
||||||
|
app.include_router(backup_router)
|
||||||
|
app.include_router(metrics_router)
|
||||||
|
app.include_router(template_router)
|
||||||
|
app.include_router(batch_router)
|
||||||
|
app.include_router(memory_router)
|
||||||
|
app.include_router(knowledge_autoupdate_router)
|
||||||
|
app.include_router(testgen_router)
|
||||||
|
app.include_router(workspace_router)
|
||||||
|
app.include_router(logs_router)
|
||||||
|
app.include_router(mcp_router)
|
||||||
|
|
||||||
|
# 静态文件服务:上传的图片
|
||||||
|
upload_dir = settings.data_root / "uploads" / "images"
|
||||||
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
app.mount("/uploads", StaticFiles(directory=str(settings.data_root / "uploads")), name="uploads")
|
||||||
|
|
||||||
|
@app.get("/health", tags=["健康检查"], summary="服务健康检查")
|
||||||
|
def health() -> dict:
|
||||||
|
"""健康检查接口,供前端/运维探活。"""
|
||||||
|
return {"status": "ok", "app": settings.app_name}
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
# uvicorn 入口:uvicorn app.main:app --reload
|
||||||
|
app = create_app()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""模型层包:双模型路由封装"""
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
"""
|
||||||
|
双模型路由封装(多 Provider 模型注册表)
|
||||||
|
========================================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
统一管理模型服务源(OpenAI 兼容口),按模型 ID 自动路由到对应 provider。
|
||||||
|
**模型来源唯一入口:模型管理(model_config 表)**,不再单独配置直连模型。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 langchain_openai.ChatOpenAI:全部 provider 都是 OpenAI 兼容协议;
|
||||||
|
2. 注册表从 model_config 表读取:模型管理是唯一真相源,增删改即时生效;
|
||||||
|
3. "auto" 模式按 model_role(strong/weak)智能选模型。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- _build_registry():从 model_config 表读取已启用模型,构建注册表;
|
||||||
|
- get_model_for_task(pref, role):pref=auto 按 role 选;否则按注册名查;
|
||||||
|
- list_available_models():列出全部可用模型供前端下拉框。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:模型管理为空(无可用模型)。
|
||||||
|
应对:启动时初始化默认模型(ccswitch 的 glm-5.3 / glm-5.3-flash)。
|
||||||
|
风险2:用户指定的模型被停用/删除。
|
||||||
|
应对:报错提示"模型不存在或已停用",不静默降级。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from langchain_core.language_models.chat_models import BaseChatModel
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.models")
|
||||||
|
|
||||||
|
|
||||||
|
class ModelConfigError(RuntimeError):
|
||||||
|
"""模型配置缺失/非法时抛出(中文可读)"""
|
||||||
|
|
||||||
|
|
||||||
|
# ========== RPM/TPM 限流器 ==========
|
||||||
|
class ModelRateLimiter:
|
||||||
|
"""模型调用限流器(RPM + TPM,滑动窗口)。"""
|
||||||
|
|
||||||
|
def __init__(self, max_rpm: int = 100, max_tpm: int = 10_000_000) -> None:
|
||||||
|
self._max_rpm = max_rpm
|
||||||
|
self._max_tpm = max_tpm
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._request_times: list[float] = []
|
||||||
|
self._token_count = 0
|
||||||
|
self._token_reset_time = time.time()
|
||||||
|
|
||||||
|
def acquire(self, estimated_tokens: int = 1000) -> bool:
|
||||||
|
"""获取调用许可(超限自动等待)。"""
|
||||||
|
with self._lock:
|
||||||
|
now = time.time()
|
||||||
|
self._request_times = [t for t in self._request_times if now - t < 60]
|
||||||
|
if now - self._token_reset_time > 60:
|
||||||
|
self._token_count = 0
|
||||||
|
self._token_reset_time = now
|
||||||
|
if len(self._request_times) >= self._max_rpm:
|
||||||
|
wait = 60 - (now - self._request_times[0])
|
||||||
|
if wait > 0:
|
||||||
|
logger.warning("RPM 限流,等待 %.1f 秒", wait)
|
||||||
|
time.sleep(wait)
|
||||||
|
now = time.time()
|
||||||
|
self._request_times = [t for t in self._request_times if now - t < 60]
|
||||||
|
if self._token_count + estimated_tokens > self._max_tpm:
|
||||||
|
wait = 60 - (now - self._token_reset_time)
|
||||||
|
if wait > 0:
|
||||||
|
logger.warning("TPM 限流,等待 %.1f 秒", wait)
|
||||||
|
time.sleep(wait)
|
||||||
|
self._token_count = 0
|
||||||
|
self._token_reset_time = time.time()
|
||||||
|
self._request_times.append(time.time())
|
||||||
|
self._token_count += estimated_tokens
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
_rate_limiter = ModelRateLimiter(max_rpm=100, max_tpm=10_000_000)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ProviderConfig:
|
||||||
|
"""模型 Provider 配置(OpenAI 兼容口)"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
base_url: str
|
||||||
|
api_key: str
|
||||||
|
|
||||||
|
|
||||||
|
def _get_provider_by_key(provider_key: str) -> ProviderConfig:
|
||||||
|
"""
|
||||||
|
按 provider_key 从 Provider 表读取连接配置(支持多平台直连)。
|
||||||
|
|
||||||
|
【查询顺序】
|
||||||
|
1. Provider 表按 name 查(如 "ccswitch"、"zhipu"、"deepseek");
|
||||||
|
2. 未命中则兜底到 .env 的 ccswitch 配置(向后兼容)。
|
||||||
|
"""
|
||||||
|
settings = load_settings()
|
||||||
|
|
||||||
|
# 1) 从 Provider 表查(多平台直连)
|
||||||
|
try:
|
||||||
|
from app.store.provider_store import get_provider_store
|
||||||
|
|
||||||
|
store = get_provider_store()
|
||||||
|
info = store.get_with_key(provider_key)
|
||||||
|
if info and info.get("api_key"):
|
||||||
|
return ProviderConfig(
|
||||||
|
name=f"provider:{info['name']}",
|
||||||
|
base_url=info["base_url"],
|
||||||
|
api_key=info["api_key"],
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("查询 Provider %s 失败:%s", provider_key, exc)
|
||||||
|
|
||||||
|
# 2) 兜底:ccswitch 配置(向后兼容旧模型)
|
||||||
|
return ProviderConfig(
|
||||||
|
name="ccswitch 代理(兜底)",
|
||||||
|
base_url=settings.ccswitch_base_url,
|
||||||
|
api_key=settings.ccswitch_api_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_model(model_name: str, provider: ProviderConfig, provider_key: str = "") -> BaseChatModel:
|
||||||
|
"""按 provider 配置构造模型实例(带指标采集)。"""
|
||||||
|
if not provider.api_key:
|
||||||
|
raise ModelConfigError(f"Provider「{provider.name}」缺少 API 密钥,请检查 .env")
|
||||||
|
from langchain_openai import ChatOpenAI
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
# 用于指标聚合的 provider 标识(如 ccswitch / zhipu)
|
||||||
|
provider_label = provider_key or provider.name.replace("provider:", "").split("(")[0].strip()
|
||||||
|
|
||||||
|
class MetricsChatOpenAI(ChatOpenAI):
|
||||||
|
"""带指标采集的 ChatOpenAI(覆写 invoke 自动记录 token/延迟/成本)"""
|
||||||
|
|
||||||
|
def invoke(self, input, config=None, **kwargs):
|
||||||
|
import time as _time
|
||||||
|
|
||||||
|
start = _time.time()
|
||||||
|
try:
|
||||||
|
resp = super().invoke(input, config=config, **kwargs)
|
||||||
|
latency = (_time.time() - start) * 1000
|
||||||
|
usage = getattr(resp, "usage_metadata", None) or {}
|
||||||
|
input_tokens = usage.get("input_tokens", 0) if isinstance(usage, dict) else 0
|
||||||
|
output_tokens = usage.get("output_tokens", 0) if isinstance(usage, dict) else 0
|
||||||
|
try:
|
||||||
|
from app.services.metrics_service import record_model_call
|
||||||
|
|
||||||
|
record_model_call(
|
||||||
|
model_name=model_name,
|
||||||
|
provider=provider_label,
|
||||||
|
input_tokens=input_tokens,
|
||||||
|
output_tokens=output_tokens,
|
||||||
|
latency_ms=latency,
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return resp
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
latency = (_time.time() - start) * 1000
|
||||||
|
try:
|
||||||
|
from app.services.metrics_service import record_model_call
|
||||||
|
|
||||||
|
record_model_call(
|
||||||
|
model_name=model_name,
|
||||||
|
provider=provider_label,
|
||||||
|
latency_ms=latency,
|
||||||
|
success=False,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
raise exc
|
||||||
|
|
||||||
|
return MetricsChatOpenAI(
|
||||||
|
model=model_name,
|
||||||
|
base_url=provider.base_url,
|
||||||
|
api_key=provider.api_key,
|
||||||
|
timeout=settings.model_request_timeout,
|
||||||
|
max_retries=settings.model_max_retries,
|
||||||
|
temperature=0.2,
|
||||||
|
max_tokens=4000,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 自动降级链(痛点 2:额度用完无缝切换)==========
|
||||||
|
|
||||||
|
|
||||||
|
class FallbackModel:
|
||||||
|
"""
|
||||||
|
降级链模型:主模型额度用完后自动切换到下一个模型。
|
||||||
|
|
||||||
|
【设计思路】
|
||||||
|
主模型调用 → 捕获额度/限流错误 → 按 fallback_order 依次尝试下一个
|
||||||
|
→ 全部失败才抛错,返回时标注实际使用的模型。
|
||||||
|
|
||||||
|
【触发条件】
|
||||||
|
- HTTP 429(Too Many Requests / 限流)
|
||||||
|
- insufficient_quota / quota_exceeded(额度用完)
|
||||||
|
- billing_hard_limit_reached(账单限额)
|
||||||
|
- rate_limit_exceeded(速率限制)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, models: list, model_names: list[str]):
|
||||||
|
self._models = models
|
||||||
|
self._model_names = model_names
|
||||||
|
|
||||||
|
@property
|
||||||
|
def model_name(self) -> str:
|
||||||
|
"""返回主模型名称。"""
|
||||||
|
return self._model_names[0] if self._model_names else "unknown"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_quota_error(exc: Exception) -> bool:
|
||||||
|
"""判断是否为额度/限流错误(触发降级)。"""
|
||||||
|
msg = str(exc).lower()
|
||||||
|
keywords = [
|
||||||
|
"429", "too many requests",
|
||||||
|
"quota", "insufficient", "rate limit",
|
||||||
|
"billing", "limit_reached",
|
||||||
|
"usage", "exceeded",
|
||||||
|
]
|
||||||
|
return any(kw in msg for kw in keywords)
|
||||||
|
|
||||||
|
def invoke(self, input, config=None, **kwargs):
|
||||||
|
"""调用模型(带自动降级)。"""
|
||||||
|
last_exc = None
|
||||||
|
for i, model in enumerate(self._models):
|
||||||
|
name = self._model_names[i] if i < len(self._model_names) else f"model_{i}"
|
||||||
|
try:
|
||||||
|
result = model.invoke(input, config=config, **kwargs)
|
||||||
|
if i > 0:
|
||||||
|
logger.warning("模型降级切换成功:%s → %s", self._model_names[0], name)
|
||||||
|
try:
|
||||||
|
from app.services.metrics_service import record_model_call
|
||||||
|
|
||||||
|
record_model_call(
|
||||||
|
model_name=f"switch_to:{name}",
|
||||||
|
provider="fallback",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return result
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
last_exc = exc
|
||||||
|
if self._is_quota_error(exc) and i < len(self._models) - 1:
|
||||||
|
next_name = self._model_names[i + 1] if i + 1 < len(self._model_names) else "?"
|
||||||
|
logger.warning(
|
||||||
|
"模型 %s 额度/限流(%s),自动切换到 %s",
|
||||||
|
name,
|
||||||
|
str(exc)[:100],
|
||||||
|
next_name,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
raise exc
|
||||||
|
raise last_exc or ModelConfigError("降级链中所有模型均不可用")
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
"""透传其他属性到主模型(如 model_name、_llm_type 等)。"""
|
||||||
|
if name in ("_models", "_model_names"):
|
||||||
|
raise AttributeError(name)
|
||||||
|
return getattr(self._models[0], name)
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 注册表(从模型管理 DB 读取)==========
|
||||||
|
|
||||||
|
|
||||||
|
def _build_registry() -> dict[str, dict]:
|
||||||
|
"""
|
||||||
|
从模型管理(model_config 表)读取已启用模型,构建注册表。
|
||||||
|
|
||||||
|
【返回】{注册名: {model_id, provider_key, model_role, display_name}}
|
||||||
|
【注册名】provider_key/model_id(如 ccswitch/glm-5.3)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from app.store.model_config_store import SqliteModelConfigStore
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
store = SqliteModelConfigStore(settings.sqlite_db_path)
|
||||||
|
configs = store.list_all(only_enabled=True)
|
||||||
|
|
||||||
|
registry: dict[str, dict] = {}
|
||||||
|
for cfg in configs:
|
||||||
|
key = f"{cfg.provider_key}/{cfg.model_id}"
|
||||||
|
registry[key] = {
|
||||||
|
"model_id": cfg.model_id,
|
||||||
|
"provider_key": cfg.provider_key,
|
||||||
|
"model_role": cfg.model_role,
|
||||||
|
"display_name": cfg.display_name,
|
||||||
|
# 降级链排序依赖 fallback_order,必须写入注册表,否则永远取默认 999
|
||||||
|
"fallback_order": cfg.fallback_order,
|
||||||
|
"is_enabled": cfg.is_enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("模型注册表已构建:%d 个模型(来自模型管理)", len(registry))
|
||||||
|
return registry
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("构建模型注册表失败:%s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# 模块级注册表 + 无效化标记(模型管理变更后需重建)
|
||||||
|
_REGISTRY: dict[str, dict] = {}
|
||||||
|
_REGISTRY_BUILT = False
|
||||||
|
|
||||||
|
|
||||||
|
def _get_registry() -> dict[str, dict]:
|
||||||
|
"""获取注册表(懒加载,模型管理变更后自动重建)。"""
|
||||||
|
global _REGISTRY, _REGISTRY_BUILT
|
||||||
|
if not _REGISTRY_BUILT:
|
||||||
|
_REGISTRY = _build_registry()
|
||||||
|
_REGISTRY_BUILT = True
|
||||||
|
return _REGISTRY
|
||||||
|
|
||||||
|
|
||||||
|
def invalidate_model_cache() -> None:
|
||||||
|
"""模型管理变更后调用,强制重建注册表。"""
|
||||||
|
global _REGISTRY, _REGISTRY_BUILT
|
||||||
|
_REGISTRY = {}
|
||||||
|
_REGISTRY_BUILT = False
|
||||||
|
get_strong_model.cache_clear()
|
||||||
|
get_weak_model.cache_clear()
|
||||||
|
get_model_by_name.cache_clear()
|
||||||
|
logger.info("模型注册表缓存已清空,下次调用时重建")
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_model_by_role(role: str) -> BaseChatModel:
|
||||||
|
"""
|
||||||
|
按角色(strong/weak)从注册表选模型("auto" 模式用)。
|
||||||
|
|
||||||
|
【规则】取 model_role 匹配的第一个已启用模型;无匹配则取第一个可用模型。
|
||||||
|
"""
|
||||||
|
registry = _get_registry()
|
||||||
|
if not registry:
|
||||||
|
raise ModelConfigError("模型管理中无可用模型,请先在「模型管理」页添加")
|
||||||
|
|
||||||
|
# 按角色优先匹配
|
||||||
|
for key, info in registry.items():
|
||||||
|
if info["model_role"] == role:
|
||||||
|
real_id = info["model_id"]
|
||||||
|
provider = _get_provider_by_key(info["provider_key"])
|
||||||
|
logger.info("auto 选模型:role=%s → %s(%s)", role, key, info["display_name"])
|
||||||
|
return _build_model(real_id, provider, info["provider_key"])
|
||||||
|
|
||||||
|
# 无匹配角色:取第一个可用模型
|
||||||
|
key, info = next(iter(registry.items()))
|
||||||
|
real_id = info["model_id"]
|
||||||
|
provider = _get_provider_by_key(info["provider_key"])
|
||||||
|
logger.warning("无 model_role=%s 的模型,降级用 %s", role, key)
|
||||||
|
return _build_model(real_id, provider, info["provider_key"])
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_strong_model() -> BaseChatModel:
|
||||||
|
"""强模型(改码/排查/评估)——auto 模式按 model_role=strong 选。"""
|
||||||
|
return _pick_model_by_role("strong")
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_weak_model() -> BaseChatModel:
|
||||||
|
"""弱模型(解析/摘要/报告)——auto 模式按 model_role=weak 选。"""
|
||||||
|
return _pick_model_by_role("weak")
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=16)
|
||||||
|
def get_model_by_name(model_key: str) -> BaseChatModel:
|
||||||
|
"""
|
||||||
|
按注册名获取模型实例(用户显式指定时用)。
|
||||||
|
|
||||||
|
【参数】model_key:注册表中的键(如 "ccswitch/glm-5.3")。
|
||||||
|
【降级】不在注册表中时,用 ccswitch 兜底尝试。
|
||||||
|
"""
|
||||||
|
registry = _get_registry()
|
||||||
|
provider_key = ""
|
||||||
|
if model_key in registry:
|
||||||
|
info = registry[model_key]
|
||||||
|
real_id = info["model_id"]
|
||||||
|
provider_key = info["provider_key"]
|
||||||
|
provider = _get_provider_by_key(provider_key)
|
||||||
|
else:
|
||||||
|
# 降级:模型不在注册表时,按 ID 直接用 ccswitch 调用
|
||||||
|
settings = load_settings()
|
||||||
|
real_id = model_key.split("/", 1)[-1] if "/" in model_key else model_key
|
||||||
|
provider_key = model_key.split("/", 1)[0] if "/" in model_key else "ccswitch"
|
||||||
|
provider = ProviderConfig(
|
||||||
|
name="ccswitch 代理(兜底)",
|
||||||
|
base_url=settings.ccswitch_base_url,
|
||||||
|
api_key=settings.ccswitch_api_key,
|
||||||
|
)
|
||||||
|
logger.warning("模型 %s 不在注册表中,走 ccswitch 兜底", model_key)
|
||||||
|
return _build_model(real_id, provider, provider_key)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_fallback_chain(primary_model: BaseChatModel, primary_name: str, exclude_key: str = "") -> BaseChatModel:
|
||||||
|
"""
|
||||||
|
构建降级链模型(主模型 + 按 fallback_order 排序的备用模型)。
|
||||||
|
|
||||||
|
【逻辑】
|
||||||
|
主模型调用失败(额度/限流)→ 自动按 fallback_order 依次尝试备用模型。
|
||||||
|
"""
|
||||||
|
registry = _get_registry()
|
||||||
|
if not registry:
|
||||||
|
return primary_model
|
||||||
|
|
||||||
|
# 按 fallback_order 排序(越小越优先);只排除主模型自身
|
||||||
|
sorted_items = sorted(
|
||||||
|
[(k, v) for k, v in registry.items() if k != exclude_key],
|
||||||
|
key=lambda x: x[1].get("fallback_order", 999),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 取前 5 个备用模型(防止链过长)
|
||||||
|
fallback_models = []
|
||||||
|
fallback_names = [primary_name]
|
||||||
|
for key, info in sorted_items[:5]:
|
||||||
|
try:
|
||||||
|
provider = _get_provider_by_key(info["provider_key"])
|
||||||
|
m = _build_model(info["model_id"], provider, info["provider_key"])
|
||||||
|
fallback_models.append(m)
|
||||||
|
fallback_names.append(f"{info['model_id']}({info['provider_key']})")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not fallback_models:
|
||||||
|
return primary_model
|
||||||
|
|
||||||
|
# 主模型放首位,备用模型依次排后
|
||||||
|
all_models = [primary_model] + fallback_models
|
||||||
|
return FallbackModel(models=all_models, model_names=fallback_names)
|
||||||
|
|
||||||
|
|
||||||
|
def get_fallback_chain_ids() -> list[str]:
|
||||||
|
"""
|
||||||
|
返回降级链的 model_id 列表(按 fallback_order 排序)。
|
||||||
|
|
||||||
|
【用途】直调 Claude CLI 模式下,auto 不选模型时按此顺序依次尝试调用。
|
||||||
|
【返回】["mimo-v2.6-pro", "glm-5.3", ...](已启用的模型,fallback_order 升序)
|
||||||
|
"""
|
||||||
|
registry = _get_registry()
|
||||||
|
if not registry:
|
||||||
|
return []
|
||||||
|
sorted_items = sorted(
|
||||||
|
registry.items(),
|
||||||
|
key=lambda x: x[1].get("fallback_order", 999),
|
||||||
|
)
|
||||||
|
# 去重(同一 model_id 可能有多条配置,按 fallback_order 取第一次出现的)
|
||||||
|
seen: set[str] = set()
|
||||||
|
result: list[str] = []
|
||||||
|
for _, info in sorted_items:
|
||||||
|
mid = info["model_id"]
|
||||||
|
if mid not in seen and info.get("is_enabled", True):
|
||||||
|
seen.add(mid)
|
||||||
|
result.append(mid)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def get_model_for_task(model_preference: str, role: str) -> BaseChatModel:
|
||||||
|
"""
|
||||||
|
按任务的模型偏好返回模型实例(核心分流逻辑,含自动降级链)。
|
||||||
|
|
||||||
|
【语义】
|
||||||
|
model_preference == "auto" 或空
|
||||||
|
→ 按 role(strong/weak)从模型管理选对应模型 + 降级链
|
||||||
|
其他(如 "ccswitch/glm-5.3")
|
||||||
|
→ 强制使用该模型 + 降级链(该模型为首选)
|
||||||
|
【降级】主模型额度用完 → 自动按 fallback_order 无缝切换下一个
|
||||||
|
"""
|
||||||
|
pref = (model_preference or "auto").strip()
|
||||||
|
if not pref or pref.lower() == "auto":
|
||||||
|
model = get_strong_model() if role == "strong" else get_weak_model()
|
||||||
|
# auto 模式下,降级链包含所有模型(按 fallback_order)
|
||||||
|
return _build_fallback_chain(model, f"auto/{role}")
|
||||||
|
|
||||||
|
# 显式指定模型
|
||||||
|
model = get_model_by_name(pref)
|
||||||
|
return _build_fallback_chain(model, pref, exclude_key=pref)
|
||||||
|
|
||||||
|
|
||||||
|
def list_available_models() -> list[dict[str, str]]:
|
||||||
|
"""
|
||||||
|
列出全部可选模型(供前端下拉框,来源:模型管理已启用的模型)。
|
||||||
|
|
||||||
|
【返回】[{value: "auto", label: "..."}, {value: "ccswitch/glm-5.3", label: "..."}, ...]
|
||||||
|
"""
|
||||||
|
registry = _get_registry()
|
||||||
|
options: list[dict[str, str]] = [
|
||||||
|
{"value": "auto", "label": "自动(推荐)— 按节点智能分工"},
|
||||||
|
]
|
||||||
|
|
||||||
|
role_labels = {"strong": "强模型", "weak": "弱模型", "general": "通用"}
|
||||||
|
|
||||||
|
for key, info in registry.items():
|
||||||
|
role_text = role_labels.get(info["model_role"], info["model_role"])
|
||||||
|
label = f"{info['display_name']} — {role_text}({info['provider_key']})"
|
||||||
|
options.append({"value": key, "label": label})
|
||||||
|
|
||||||
|
return options
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""数据契约层:Pydantic 模型,API 层与存储层共用"""
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
Pydantic 数据模型 —— 数据库连接配置
|
||||||
|
===================================
|
||||||
|
|
||||||
|
【功能说明】数据库连接配置的数据契约,支持前端增删改查。
|
||||||
|
【安全设计】密码加密存储,前端不回显明文。
|
||||||
|
【实现思路】DatabaseConnectionCreate 入参 → DatabaseConnection 实体。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseConnectionCreate(BaseModel):
|
||||||
|
"""创建数据库连接配置"""
|
||||||
|
|
||||||
|
name: str = Field(..., min_length=1, max_length=100, description="连接名称")
|
||||||
|
db_type: str = Field(
|
||||||
|
..., description="数据库类型:mysql / postgresql / sqlite"
|
||||||
|
)
|
||||||
|
host: str = Field(default="localhost", description="主机地址")
|
||||||
|
port: int = Field(default=3306, description="端口号")
|
||||||
|
database: str = Field(..., min_length=1, description="数据库名(SQLite 为文件路径)")
|
||||||
|
username: str = Field(default="", description="用户名")
|
||||||
|
password: str = Field(default="", description="密码(加密存储)")
|
||||||
|
description: str = Field(default="", max_length=200, description="备注说明")
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseConnectionUpdate(BaseModel):
|
||||||
|
"""更新数据库连接配置(全部可选)"""
|
||||||
|
|
||||||
|
name: Optional[str] = Field(default=None, min_length=1, max_length=100)
|
||||||
|
db_type: Optional[str] = None
|
||||||
|
host: Optional[str] = None
|
||||||
|
port: Optional[int] = None
|
||||||
|
database: Optional[str] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
password: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseConnection(BaseModel):
|
||||||
|
"""数据库连接配置完整实体(密码脱敏)"""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
db_type: str
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
database: str
|
||||||
|
username: str
|
||||||
|
password: str = Field(default="", description="加密存储,返回时脱敏为 ******")
|
||||||
|
description: str
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class SqlExecuteRequest(BaseModel):
|
||||||
|
"""SQL 执行请求"""
|
||||||
|
|
||||||
|
sql: str = Field(..., min_length=1, description="SQL 语句")
|
||||||
|
params: Optional[list | dict] = Field(default=None, description="参数化查询参数")
|
||||||
|
|
||||||
|
|
||||||
|
class SqlQueryRequest(BaseModel):
|
||||||
|
"""SQL 查询请求(带分页)"""
|
||||||
|
|
||||||
|
sql: str = Field(..., min_length=1, description="SELECT 语句")
|
||||||
|
params: Optional[list | dict] = Field(default=None, description="参数化查询参数")
|
||||||
|
page: int = Field(default=1, ge=1, description="页码")
|
||||||
|
page_size: int = Field(default=20, ge=1, le=100, description="每页条数")
|
||||||
|
|
||||||
|
|
||||||
|
class SqlExecuteResult(BaseModel):
|
||||||
|
"""SQL 执行结果"""
|
||||||
|
|
||||||
|
success: bool
|
||||||
|
message: str
|
||||||
|
affected_rows: int = 0
|
||||||
|
data: list[dict] = Field(default_factory=list)
|
||||||
|
columns: list[str] = Field(default_factory=list)
|
||||||
|
total: int = 0
|
||||||
|
page: int = 1
|
||||||
|
page_size: int = 20
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""
|
||||||
|
Pydantic 数据模型 —— 模型配置
|
||||||
|
============================
|
||||||
|
|
||||||
|
【功能说明】模型偏好配置的数据契约,支持前端增删改查。
|
||||||
|
【技术选型理由】Pydantic v2 与 FastAPI 原生集成,与 Project/Task 同构。
|
||||||
|
【安全设计】API key 不入库,只存 provider_key 引用(映射到 .env 里的真实密钥)。
|
||||||
|
【实现思路】ModelConfigCreate 入参 → ModelConfig 实体 → 库表。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class ModelConfigCreate(BaseModel):
|
||||||
|
"""创建模型配置的入参"""
|
||||||
|
|
||||||
|
display_name: str = Field(
|
||||||
|
..., min_length=1, max_length=100, description="显示名称(前端下拉框展示)"
|
||||||
|
)
|
||||||
|
model_id: str = Field(
|
||||||
|
..., min_length=1, max_length=100,
|
||||||
|
description="真实模型 ID(发送给 API 的 model 字段,如 glm-5.3)",
|
||||||
|
)
|
||||||
|
provider_key: str = Field(
|
||||||
|
default="ccswitch",
|
||||||
|
description="Provider 标识(映射到 .env 里的 base_url/api_key):ccswitch | direct",
|
||||||
|
)
|
||||||
|
model_role: str = Field(
|
||||||
|
default="general",
|
||||||
|
description="模型定位:strong=强模型 | weak=弱模型 | general=通用",
|
||||||
|
)
|
||||||
|
is_enabled: bool = Field(default=True, description="是否启用(停用后不出现在下拉框)")
|
||||||
|
sort_order: int = Field(default=0, description="排序值(越小越靠前)")
|
||||||
|
fallback_order: int = Field(
|
||||||
|
default=999,
|
||||||
|
description="降级链顺序(越小越优先,额度用完后按此顺序无缝切换)",
|
||||||
|
)
|
||||||
|
description: str = Field(default="", max_length=200, description="备注说明")
|
||||||
|
|
||||||
|
|
||||||
|
class ModelConfigUpdate(BaseModel):
|
||||||
|
"""更新模型配置(全部字段可选)"""
|
||||||
|
|
||||||
|
display_name: Optional[str] = Field(default=None, min_length=1, max_length=100)
|
||||||
|
model_id: Optional[str] = Field(default=None, min_length=1, max_length=100)
|
||||||
|
provider_key: Optional[str] = None
|
||||||
|
model_role: Optional[str] = None
|
||||||
|
is_enabled: Optional[bool] = None
|
||||||
|
sort_order: Optional[int] = None
|
||||||
|
fallback_order: Optional[int] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ModelConfig(BaseModel):
|
||||||
|
"""模型配置完整实体"""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
display_name: str
|
||||||
|
model_id: str
|
||||||
|
provider_key: str
|
||||||
|
model_role: str
|
||||||
|
is_enabled: bool
|
||||||
|
sort_order: int
|
||||||
|
fallback_order: int = 999
|
||||||
|
description: str
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""
|
||||||
|
Pydantic 数据模型
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
定义项目(Project)与通用响应的数据契约。
|
||||||
|
支持多后端多前端(一个项目下可维护多个服务)。
|
||||||
|
【技术选型理由】
|
||||||
|
Pydantic v2 + JSON 字段存储多条目(SQLite 轻量场景够用)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Generic, Optional, TypeVar
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceEntry(BaseModel):
|
||||||
|
"""后端/前端服务条目"""
|
||||||
|
|
||||||
|
label: str = Field(..., min_length=1, max_length=50, description="服务名称")
|
||||||
|
path: str = Field(..., min_length=1, description="代码路径")
|
||||||
|
branch: str = Field(default="master", description="Git 分支名")
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectCreate(BaseModel):
|
||||||
|
"""创建项目的入参模型"""
|
||||||
|
|
||||||
|
name: str = Field(..., min_length=1, max_length=100, description="项目名称")
|
||||||
|
code_root_path: str = Field(..., min_length=1, description="项目本地代码根路径")
|
||||||
|
backend_path: str = Field(default="backend", description="后端子路径(兼容旧版)")
|
||||||
|
frontend_path: str = Field(default="frontend", description="前端子路径(兼容旧版)")
|
||||||
|
backend_branch: str = Field(default="master", description="后端 Git 分支(兼容旧版)")
|
||||||
|
frontend_branch: str = Field(default="master", description="前端 Git 分支(兼容旧版)")
|
||||||
|
backends: list[ServiceEntry] = Field(
|
||||||
|
default_factory=list, description="多个后端服务列表"
|
||||||
|
)
|
||||||
|
frontends: list[ServiceEntry] = Field(
|
||||||
|
default_factory=list, description="多个前端服务列表"
|
||||||
|
)
|
||||||
|
description: str = Field(default="", max_length=500, description="项目备注")
|
||||||
|
sort_order: int = Field(default=0, description="排序值")
|
||||||
|
|
||||||
|
@field_validator("code_root_path")
|
||||||
|
@classmethod
|
||||||
|
def _must_be_d_drive(cls, v: str) -> str:
|
||||||
|
normalized = v.strip().replace("/", "\\")
|
||||||
|
if not normalized.upper().startswith("D:"):
|
||||||
|
raise ValueError(f"代码路径必须位于 D 盘(硬约束 6),当前值:{v}")
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectUpdate(BaseModel):
|
||||||
|
"""更新项目的入参模型(全部字段可选,按需覆盖)"""
|
||||||
|
|
||||||
|
name: Optional[str] = Field(default=None, min_length=1, max_length=100)
|
||||||
|
code_root_path: Optional[str] = None
|
||||||
|
backend_path: Optional[str] = None
|
||||||
|
frontend_path: Optional[str] = None
|
||||||
|
backend_branch: Optional[str] = None
|
||||||
|
frontend_branch: Optional[str] = None
|
||||||
|
backends: Optional[list[ServiceEntry]] = None
|
||||||
|
frontends: Optional[list[ServiceEntry]] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
sort_order: Optional[int] = Field(default=None, description="排序值")
|
||||||
|
|
||||||
|
@field_validator("code_root_path")
|
||||||
|
@classmethod
|
||||||
|
def _must_be_d_drive(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is None:
|
||||||
|
return v
|
||||||
|
normalized = v.strip().replace("/", "\\")
|
||||||
|
if not normalized.upper().startswith("D:"):
|
||||||
|
raise ValueError(f"代码路径必须位于 D 盘(硬约束 6),当前值:{v}")
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
class Project(ProjectCreate):
|
||||||
|
"""项目完整实体:在入参字段基础上补充系统字段"""
|
||||||
|
|
||||||
|
id: str = Field(..., description="项目唯一 ID")
|
||||||
|
created_at: datetime = Field(..., description="创建时间")
|
||||||
|
updated_at: datetime = Field(..., description="最近更新时间")
|
||||||
|
|
||||||
|
|
||||||
|
class ApiResponse(BaseModel, Generic[T]):
|
||||||
|
"""统一 API 响应包裹,前端只依赖这一种结构"""
|
||||||
|
|
||||||
|
code: int = Field(default=0, description="业务状态码:0 成功,非 0 失败")
|
||||||
|
message: str = Field(default="ok", description="人类可读的提示信息(中文)")
|
||||||
|
data: Optional[T] = Field(default=None, description="业务数据载荷")
|
||||||
|
|
||||||
|
|
||||||
|
class PageResult(BaseModel, Generic[T]):
|
||||||
|
"""分页结果(预留:项目列表一期数据量小,先做全量列表)"""
|
||||||
|
|
||||||
|
total: int = Field(default=0, description="总条数")
|
||||||
|
items: list[T] = Field(default_factory=list, description="当前页数据")
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorDetail(BaseModel):
|
||||||
|
"""错误详情(用于前端精确展示失败原因)"""
|
||||||
|
|
||||||
|
error_type: str = Field(description="异常类型")
|
||||||
|
error_msg: str = Field(description="异常信息(中文可读)")
|
||||||
|
context: dict[str, Any] = Field(default_factory=dict, description="补充上下文")
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""
|
||||||
|
Pydantic 数据模型 —— 任务
|
||||||
|
=========================
|
||||||
|
|
||||||
|
【功能说明】任务实体与请求体契约,供 API 层与存储层共用。
|
||||||
|
【技术选型理由】Pydantic v2 与 FastAPI 原生集成,和 Project 模型同构。
|
||||||
|
【实现思路】TaskCreate 入参 → Task 实体(含系统字段)。
|
||||||
|
【潜在风险与应对】字段与存储层漂移:单一来源定义,存储层只做映射。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class TaskCreate(BaseModel):
|
||||||
|
"""创建任务的入参模型"""
|
||||||
|
|
||||||
|
project_id: str = Field(..., description="所属项目 ID")
|
||||||
|
requirement_text: str = Field(
|
||||||
|
..., min_length=1, max_length=5000, description="需求/Bug 描述(自然语言)"
|
||||||
|
)
|
||||||
|
task_type: str = Field(default="feature", description="feature | bugfix")
|
||||||
|
model_preference: str = Field(
|
||||||
|
default="auto",
|
||||||
|
description=(
|
||||||
|
"模型偏好:auto=由 LangGraph 自动按节点分工选模型;"
|
||||||
|
"或填具体模型 ID(如 mimo-v2.6-pro)强制整个任务用同一模型"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
use_vector_search: bool = Field(
|
||||||
|
default=True,
|
||||||
|
description="是否查询向量数据库(false=跳过知识检索节点)",
|
||||||
|
)
|
||||||
|
execution_mode: str = Field(
|
||||||
|
default="agent",
|
||||||
|
description=(
|
||||||
|
"执行模式:agent=LangGraph 全流程编排(规划→分发→Worker→验证);"
|
||||||
|
"direct_claude=直接调用 Claude CLI 一次改码(适合小改动/探索式开发)"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
sort_order: int = Field(default=0, description="排序值(越小越靠前)")
|
||||||
|
|
||||||
|
|
||||||
|
class Task(BaseModel):
|
||||||
|
"""任务完整实体"""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
project_id: str
|
||||||
|
requirement_text: str
|
||||||
|
task_type: str
|
||||||
|
status: str # running | waiting_approval | done | failed | degraded
|
||||||
|
thread_id: str = Field(description="LangGraph 检查点线程 ID(断点续跑用)")
|
||||||
|
model_preference: str = Field(
|
||||||
|
default="auto",
|
||||||
|
description="模型偏好:auto 或具体模型 ID(用户提交时可指定)",
|
||||||
|
)
|
||||||
|
use_vector_search: bool = Field(
|
||||||
|
default=True,
|
||||||
|
description="是否查询向量数据库(false=跳过知识检索)",
|
||||||
|
)
|
||||||
|
execution_mode: str = Field(
|
||||||
|
default="agent",
|
||||||
|
description="执行模式:agent | direct_claude",
|
||||||
|
)
|
||||||
|
sort_order: int = Field(default=0, description="排序值(越小越靠前)")
|
||||||
|
report: str = ""
|
||||||
|
error: str = ""
|
||||||
|
pending_approval: str = Field(
|
||||||
|
default="", description="待审批内容 JSON(HITL 中断时写入,供前端审批卡片展示)"
|
||||||
|
)
|
||||||
|
chat_history: str = Field(
|
||||||
|
default="[]",
|
||||||
|
description="对话消息 JSON 数组(一条任务 = 一个完整对话)",
|
||||||
|
)
|
||||||
|
session_id: str = Field(
|
||||||
|
default="",
|
||||||
|
description="Claude CLI 会话 ID(--resume 续聊用,终端同款机制)",
|
||||||
|
)
|
||||||
|
session_ready: bool = Field(
|
||||||
|
default=False,
|
||||||
|
description="Claude 会话是否已真实建立(CLI 吐出 init 事件后为 true)",
|
||||||
|
)
|
||||||
|
worker_pid: int = Field(
|
||||||
|
default=0,
|
||||||
|
description="执行该任务的 worker 进程 PID(孤儿恢复判断存活用)",
|
||||||
|
)
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class TaskEvent(BaseModel):
|
||||||
|
"""SSE 推送的单个事件(节点级进度)"""
|
||||||
|
|
||||||
|
event: str # node_start | node_end | status_change | error | done
|
||||||
|
node: str = ""
|
||||||
|
message: str = ""
|
||||||
|
data: dict = Field(default_factory=dict)
|
||||||
|
timestamp: str = ""
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""领域服务层:Git 读取、文件工具等可独立单测的能力"""
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""
|
||||||
|
自动备份服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
定时备份 SQLite 数据库、配置文件、向量库元数据到指定目录。
|
||||||
|
支持手动触发和定时调度。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 SQLite 版本化备份(.backup):在线备份不锁库;
|
||||||
|
2. 备份文件用时间戳命名:便于保留多个版本;
|
||||||
|
3. 自动清理过期备份(保留最近 N 天)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- backup_now():立即执行备份;
|
||||||
|
- auto_backup_loop():后台定时循环(每 N 小时);
|
||||||
|
- 清理超过保留期的旧备份。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.backup")
|
||||||
|
|
||||||
|
# 备份配置
|
||||||
|
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups\auto")
|
||||||
|
RETENTION_DAYS = 30 # 保留最近 30 天
|
||||||
|
BACKUP_INTERVAL_SECONDS = 12 * 3600 # 每 12 小时一次
|
||||||
|
|
||||||
|
|
||||||
|
def backup_now() -> dict:
|
||||||
|
"""
|
||||||
|
立即执行全量备份。
|
||||||
|
|
||||||
|
【备份内容】SQLite + .env + 配置 + 向量库元数据
|
||||||
|
【返回】{success, backup_path, files, size_bytes}
|
||||||
|
"""
|
||||||
|
settings = load_settings()
|
||||||
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
backup_path = BACKUP_DIR / f"backup_{timestamp}"
|
||||||
|
backup_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
files_copied = []
|
||||||
|
total_bytes = 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. SQLite 数据库(在线备份,不锁库)
|
||||||
|
db_path = settings.sqlite_db_path
|
||||||
|
if db_path.exists():
|
||||||
|
dest = backup_path / "agent.db"
|
||||||
|
# 用 SQLite .backup API(安全在线备份)
|
||||||
|
src_conn = sqlite3.connect(str(db_path))
|
||||||
|
dest_conn = sqlite3.connect(str(dest))
|
||||||
|
try:
|
||||||
|
src_conn.backup(dest_conn)
|
||||||
|
finally:
|
||||||
|
# 【修复】close 必须在 finally,否则 backup 抛异常时两个连接都泄漏
|
||||||
|
dest_conn.close()
|
||||||
|
src_conn.close()
|
||||||
|
size = dest.stat().st_size
|
||||||
|
total_bytes += size
|
||||||
|
files_copied.append({"name": "agent.db", "size": size})
|
||||||
|
|
||||||
|
# 2. .env 配置
|
||||||
|
env_path = Path(r"D:\Agent\agent\backend\.env")
|
||||||
|
if env_path.exists():
|
||||||
|
dest = backup_path / ".env"
|
||||||
|
shutil.copy2(env_path, dest)
|
||||||
|
size = dest.stat().st_size
|
||||||
|
total_bytes += size
|
||||||
|
files_copied.append({"name": ".env", "size": size})
|
||||||
|
|
||||||
|
# 3. 备注文件
|
||||||
|
remarks_path = Path(r"D:\Agent\agent\backend\.env.remarks.json")
|
||||||
|
if remarks_path.exists():
|
||||||
|
dest = backup_path / ".env.remarks.json"
|
||||||
|
shutil.copy2(remarks_path, dest)
|
||||||
|
size = dest.stat().st_size
|
||||||
|
total_bytes += size
|
||||||
|
files_copied.append({"name": ".env.remarks.json", "size": size})
|
||||||
|
|
||||||
|
# 4. 向量库元数据(只备 SQLite,不备大文件)
|
||||||
|
chroma_db = settings.chroma_dir / "chroma.sqlite3"
|
||||||
|
if chroma_db.exists():
|
||||||
|
dest = backup_path / "chroma.sqlite3"
|
||||||
|
shutil.copy2(chroma_db, dest)
|
||||||
|
size = dest.stat().st_size
|
||||||
|
total_bytes += size
|
||||||
|
files_copied.append({"name": "chroma.sqlite3", "size": size})
|
||||||
|
|
||||||
|
# 5. 清理过期备份
|
||||||
|
cleaned = _cleanup_old_backups()
|
||||||
|
|
||||||
|
logger.info("备份完成:%s(%d 个文件,%.1fKB)", backup_path, len(files_copied), total_bytes / 1024)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"backup_path": str(backup_path),
|
||||||
|
"files": files_copied,
|
||||||
|
"size_bytes": total_bytes,
|
||||||
|
"cleaned_old": cleaned,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("备份失败")
|
||||||
|
return {"success": False, "message": f"备份失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _cleanup_old_backups() -> int:
|
||||||
|
"""清理超过保留期的旧备份。"""
|
||||||
|
if not BACKUP_DIR.exists():
|
||||||
|
return 0
|
||||||
|
cutoff = time.time() - RETENTION_DAYS * 86400
|
||||||
|
cleaned = 0
|
||||||
|
for item in BACKUP_DIR.iterdir():
|
||||||
|
if item.is_dir() and item.stat().st_mtime < cutoff:
|
||||||
|
shutil.rmtree(item, ignore_errors=True)
|
||||||
|
cleaned += 1
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def list_backups() -> list[dict]:
|
||||||
|
"""列出所有备份(供前端展示)。"""
|
||||||
|
if not BACKUP_DIR.exists():
|
||||||
|
return []
|
||||||
|
items = []
|
||||||
|
for item in sorted(BACKUP_DIR.iterdir(), reverse=True):
|
||||||
|
if item.is_dir():
|
||||||
|
total_size = sum(f.stat().st_size for f in item.rglob("*") if f.is_file())
|
||||||
|
file_count = sum(1 for f in item.rglob("*") if f.is_file())
|
||||||
|
items.append({
|
||||||
|
"name": item.name,
|
||||||
|
"path": str(item),
|
||||||
|
"size_bytes": total_size,
|
||||||
|
"file_count": file_count,
|
||||||
|
"created_at": datetime.fromtimestamp(item.stat().st_mtime).isoformat(),
|
||||||
|
})
|
||||||
|
return items
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
"""
|
||||||
|
数据库操作引擎
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
基于 SQLAlchemy 对目标数据库执行 SQL CRUD 操作。
|
||||||
|
支持 MySQL / PostgreSQL / SQLite 三种数据库。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 SQLAlchemy:统一抽象多种数据库,改类型只改连接串;
|
||||||
|
2. 参数化查询:防 SQL 注入(硬约束 5 安全兜底);
|
||||||
|
3. 连接池 + 短连接:每次操作独立连接,避免连接泄漏。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- create_engine():按连接配置创建 SQLAlchemy 引擎;
|
||||||
|
- execute_sql():通用 SQL 执行(INSERT/UPDATE/DELETE/SELECT);
|
||||||
|
- query_with_pagination():SELECT 分页查询;
|
||||||
|
- test_connection():连接测试。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:SQL 注入。
|
||||||
|
应对:强制使用参数化查询,不拼接用户输入。
|
||||||
|
风险2:大批量数据操作。
|
||||||
|
应对:分页 + LIMIT 限制,防止全表扫描。
|
||||||
|
风险3:数据库连接泄漏。
|
||||||
|
应对:每次操作用 context manager 确保关闭连接。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
|
||||||
|
from app.schemas.database import SqlExecuteResult
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.db_engine")
|
||||||
|
|
||||||
|
# 合法表名/列名(防 SQL 注入)
|
||||||
|
_IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_identifier(name: str, kind: str = "表名") -> str:
|
||||||
|
"""校验 SQL 标识符(表名/列名)合法性,防注入。"""
|
||||||
|
if not name or not _IDENTIFIER_RE.match(name):
|
||||||
|
raise ValueError(f"非法{kind}:{name!r}(只允许字母、数字、下划线,且不以数字开头)")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _build_engine(conn_info: dict):
|
||||||
|
"""按连接配置创建 SQLAlchemy 引擎。"""
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
|
||||||
|
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||||
|
if db_type == "sqlite":
|
||||||
|
db_path = conn_info.get("database", ":memory:")
|
||||||
|
url = f"sqlite:///{db_path}"
|
||||||
|
elif db_type == "mysql":
|
||||||
|
# URL 编码用户名和密码,防止特殊字符(@ : / # 等)破坏连接串
|
||||||
|
user = quote_plus(str(conn_info.get("username", "")))
|
||||||
|
pwd = quote_plus(str(conn_info.get("password", "")))
|
||||||
|
url = (
|
||||||
|
f"mysql+pymysql://{user}:{pwd}"
|
||||||
|
f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}"
|
||||||
|
)
|
||||||
|
elif db_type == "postgresql":
|
||||||
|
user = quote_plus(str(conn_info.get("username", "")))
|
||||||
|
pwd = quote_plus(str(conn_info.get("password", "")))
|
||||||
|
url = (
|
||||||
|
f"postgresql://{user}:{pwd}"
|
||||||
|
f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"不支持的数据库类型:{db_type}")
|
||||||
|
|
||||||
|
return create_engine(url, pool_pre_ping=True, pool_recycle=3600)
|
||||||
|
|
||||||
|
|
||||||
|
def list_tables(conn_info: dict) -> list[str]:
|
||||||
|
"""列出数据库中的所有表名(多数据库适配)。"""
|
||||||
|
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
if db_type == "mysql":
|
||||||
|
result = conn.execute(text("SHOW TABLES"))
|
||||||
|
return [row[0] for row in result]
|
||||||
|
elif db_type == "postgresql":
|
||||||
|
result = conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT tablename FROM pg_tables "
|
||||||
|
"WHERE schemaname = 'public' ORDER BY tablename"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return [row[0] for row in result]
|
||||||
|
else: # sqlite
|
||||||
|
result = conn.execute(
|
||||||
|
text("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||||
|
)
|
||||||
|
return [row[0] for row in result]
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("列出表失败:%s", exc)
|
||||||
|
return []
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def get_table_structure(conn_info: dict, table_name: str) -> dict:
|
||||||
|
"""
|
||||||
|
查询表结构(列名、类型、可空、主键、默认值、注释)。
|
||||||
|
|
||||||
|
【多数据库适配】
|
||||||
|
- MySQL:SHOW FULL COLUMNS FROM {table}
|
||||||
|
- PostgreSQL:information_schema.columns
|
||||||
|
- SQLite:PRAGMA table_info({table})
|
||||||
|
"""
|
||||||
|
_validate_identifier(table_name, "表名")
|
||||||
|
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
if db_type == "mysql":
|
||||||
|
result = conn.execute(text(f"SHOW FULL COLUMNS FROM {table_name}"))
|
||||||
|
columns = []
|
||||||
|
for row in result.mappings():
|
||||||
|
columns.append({
|
||||||
|
"name": row.get("Field", ""),
|
||||||
|
"type": row.get("Type", ""),
|
||||||
|
"nullable": row.get("Null", "") == "YES",
|
||||||
|
"key": row.get("Key", ""),
|
||||||
|
"default": row.get("Default", ""),
|
||||||
|
"comment": row.get("Comment", ""),
|
||||||
|
})
|
||||||
|
elif db_type == "postgresql":
|
||||||
|
result = conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT column_name, data_type, is_nullable, column_default "
|
||||||
|
"FROM information_schema.columns WHERE table_name = :tname "
|
||||||
|
"ORDER BY ordinal_position"
|
||||||
|
),
|
||||||
|
{"tname": table_name},
|
||||||
|
)
|
||||||
|
columns = [
|
||||||
|
{
|
||||||
|
"name": r["column_name"],
|
||||||
|
"type": r["data_type"],
|
||||||
|
"nullable": r["is_nullable"] == "YES",
|
||||||
|
"key": "",
|
||||||
|
"default": r["column_default"] or "",
|
||||||
|
"comment": "",
|
||||||
|
}
|
||||||
|
for r in result.mappings()
|
||||||
|
]
|
||||||
|
else: # sqlite
|
||||||
|
result = conn.execute(text(f"PRAGMA table_info({table_name})"))
|
||||||
|
columns = [
|
||||||
|
{
|
||||||
|
"name": r["name"],
|
||||||
|
"type": r["type"],
|
||||||
|
"nullable": not r["notnull"],
|
||||||
|
"key": "PRI" if r["pk"] else "",
|
||||||
|
"default": r["dflt_value"] or "",
|
||||||
|
"comment": "",
|
||||||
|
}
|
||||||
|
for r in result.mappings()
|
||||||
|
]
|
||||||
|
|
||||||
|
return {"success": True, "table": table_name, "columns": columns}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"查询表结构失败:{exc}", "columns": []}
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def alter_table(
|
||||||
|
conn_info: dict,
|
||||||
|
table_name: str,
|
||||||
|
action: str,
|
||||||
|
column_name: str,
|
||||||
|
column_type: str = "",
|
||||||
|
nullable: bool = True,
|
||||||
|
default: str = "",
|
||||||
|
comment: str = "",
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
修改表结构(加列/改列/删列)。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
action: add / modify / drop
|
||||||
|
column_name: 列名
|
||||||
|
column_type: 列类型(如 VARCHAR(255))
|
||||||
|
nullable: 是否可空
|
||||||
|
default: 默认值
|
||||||
|
comment: 注释
|
||||||
|
"""
|
||||||
|
_validate_identifier(table_name, "表名")
|
||||||
|
_validate_identifier(column_name, "列名")
|
||||||
|
|
||||||
|
# 校验列类型(只允许合法 SQL 类型表达式)
|
||||||
|
if action in ("add", "modify") and column_type:
|
||||||
|
if not re.match(r"^[a-zA-Z][a-zA-Z0-9_()]*$", column_type):
|
||||||
|
return {"success": False, "message": f"非法列类型:{column_type}"}
|
||||||
|
|
||||||
|
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with engine.begin() as conn:
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
if action == "add":
|
||||||
|
if db_type == "mysql":
|
||||||
|
null_str = "NULL" if nullable else "NOT NULL"
|
||||||
|
default_str = f" DEFAULT {default}" if default else ""
|
||||||
|
comment_str = f" COMMENT '{comment}'" if comment else ""
|
||||||
|
sql = (
|
||||||
|
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} "
|
||||||
|
f"{null_str}{default_str}{comment_str}"
|
||||||
|
)
|
||||||
|
elif db_type == "postgresql":
|
||||||
|
null_str = "NULL" if nullable else "NOT NULL"
|
||||||
|
default_str = f" DEFAULT {default}" if default else ""
|
||||||
|
sql = (
|
||||||
|
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} "
|
||||||
|
f"{null_str}{default_str}"
|
||||||
|
)
|
||||||
|
else: # sqlite
|
||||||
|
null_str = "" if nullable else " NOT NULL"
|
||||||
|
default_str = f" DEFAULT {default}" if default else ""
|
||||||
|
sql = (
|
||||||
|
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}"
|
||||||
|
f"{null_str}{default_str}"
|
||||||
|
)
|
||||||
|
|
||||||
|
elif action == "modify":
|
||||||
|
if db_type == "mysql":
|
||||||
|
null_str = "NULL" if nullable else "NOT NULL"
|
||||||
|
default_str = f" DEFAULT {default}" if default else ""
|
||||||
|
comment_str = f" COMMENT '{comment}'" if comment else ""
|
||||||
|
sql = (
|
||||||
|
f"ALTER TABLE {table_name} MODIFY COLUMN {column_name} {column_type} "
|
||||||
|
f"{null_str}{default_str}{comment_str}"
|
||||||
|
)
|
||||||
|
elif db_type == "postgresql":
|
||||||
|
# PG 需要拆成多条
|
||||||
|
conn.execute(text(
|
||||||
|
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {column_type}"
|
||||||
|
))
|
||||||
|
null_str = "DROP NOT NULL" if nullable else "SET NOT NULL"
|
||||||
|
conn.execute(text(
|
||||||
|
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} {null_str}"
|
||||||
|
))
|
||||||
|
if default:
|
||||||
|
conn.execute(text(
|
||||||
|
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} SET DEFAULT {default}"
|
||||||
|
))
|
||||||
|
return {"success": True, "message": f"列 {column_name} 修改成功"}
|
||||||
|
else: # sqlite
|
||||||
|
return {"success": False, "message": "SQLite 不支持 MODIFY COLUMN,请通过重建表修改"}
|
||||||
|
|
||||||
|
elif action == "drop":
|
||||||
|
sql = f"ALTER TABLE {table_name} DROP COLUMN {column_name}"
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": f"不支持的操作:{action}"}
|
||||||
|
|
||||||
|
conn.execute(text(sql))
|
||||||
|
return {"success": True, "message": f"列 {column_name} {action} 成功"}
|
||||||
|
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"修改表结构失败:{exc}"}
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection(conn_info: dict) -> dict:
|
||||||
|
"""测试数据库连接是否成功。"""
|
||||||
|
engine = None
|
||||||
|
try:
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
with engine.connect() as conn:
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
result = conn.execute(text("SELECT 1"))
|
||||||
|
result.fetchone()
|
||||||
|
return {"success": True, "message": "连接成功"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"连接失败:{exc}"}
|
||||||
|
finally:
|
||||||
|
if engine is not None:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_sql(sql: str) -> str:
|
||||||
|
"""
|
||||||
|
规范化 SQL:去掉尾部空白与分号。
|
||||||
|
|
||||||
|
【踩坑】用户习惯写 `SELECT * FROM t;` 带分号,但分页查询会包
|
||||||
|
`SELECT COUNT(*) FROM (sql) AS _sub`,分号嵌在括号里导致语法错误。
|
||||||
|
"""
|
||||||
|
return sql.strip().rstrip(";").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def execute_sql(
|
||||||
|
conn_info: dict,
|
||||||
|
sql: str,
|
||||||
|
params: list | dict | None = None,
|
||||||
|
) -> SqlExecuteResult:
|
||||||
|
"""
|
||||||
|
执行 SQL(INSERT/UPDATE/DELETE/SELECT 通用)。
|
||||||
|
|
||||||
|
【安全】强制参数化查询,防 SQL 注入。
|
||||||
|
"""
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
|
||||||
|
sql = _normalize_sql(sql)
|
||||||
|
if not sql:
|
||||||
|
return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0)
|
||||||
|
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
try:
|
||||||
|
with engine.begin() as conn:
|
||||||
|
if params:
|
||||||
|
result = conn.execute(text(sql), params)
|
||||||
|
else:
|
||||||
|
result = conn.execute(text(sql))
|
||||||
|
|
||||||
|
# SELECT:返回数据
|
||||||
|
if result.returns_rows:
|
||||||
|
columns = list(result.keys()) if result.keys() else []
|
||||||
|
rows = [dict(row) for row in result.mappings().all()]
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=True,
|
||||||
|
message=f"查询返回 {len(rows)} 条记录",
|
||||||
|
affected_rows=len(rows),
|
||||||
|
data=rows,
|
||||||
|
columns=columns,
|
||||||
|
total=len(rows),
|
||||||
|
)
|
||||||
|
|
||||||
|
# INSERT/UPDATE/DELETE:返回影响行数
|
||||||
|
affected = result.rowcount if result.rowcount >= 0 else 0
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=True,
|
||||||
|
message=f"操作成功,影响 {affected} 行",
|
||||||
|
affected_rows=affected,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("SQL 执行失败:%s | %s", sql[:200], exc)
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=False, message=f"SQL 执行失败:{exc}", affected_rows=0
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def query_with_pagination(
|
||||||
|
conn_info: dict,
|
||||||
|
sql: str,
|
||||||
|
params: list | dict | None = None,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> SqlExecuteResult:
|
||||||
|
"""
|
||||||
|
SELECT 分页查询。
|
||||||
|
|
||||||
|
【实现】在原始 SQL 外包一层 LIMIT/OFFSET,自动补 COUNT 总数。
|
||||||
|
【修复】
|
||||||
|
1. list 参数转为 dict(SQLAlchemy text() 不支持位置参数);
|
||||||
|
2. 内部参数名加 __ 前缀,防止与用户 SQL 参数冲突;
|
||||||
|
3. 非 SELECT 语句自动走 execute_sql(不包 COUNT/LIMIT)。
|
||||||
|
"""
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
|
||||||
|
sql = _normalize_sql(sql)
|
||||||
|
if not sql:
|
||||||
|
return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0)
|
||||||
|
|
||||||
|
# 非 SELECT 语句走通用执行(不包分页)
|
||||||
|
first_word = sql.split()[0].upper() if sql.split() else ""
|
||||||
|
if first_word not in ("SELECT", "WITH"):
|
||||||
|
return execute_sql(conn_info, sql, params)
|
||||||
|
|
||||||
|
engine = _build_engine(conn_info)
|
||||||
|
try:
|
||||||
|
offset = (page - 1) * page_size
|
||||||
|
|
||||||
|
# 统一参数为 dict(SQLAlchemy text() 只支持命名参数)
|
||||||
|
if params and isinstance(params, list):
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=False,
|
||||||
|
message="分页查询暂不支持位置参数(list),请使用命名参数(dict)",
|
||||||
|
affected_rows=0,
|
||||||
|
)
|
||||||
|
base_params: dict[str, Any] = dict(params) if isinstance(params, dict) else {}
|
||||||
|
|
||||||
|
# 内部参数名加 __ 前缀,防止与用户参数冲突
|
||||||
|
paged_sql = f"SELECT * FROM ({sql}) AS _sub LIMIT :__limit OFFSET :__offset"
|
||||||
|
count_sql = f"SELECT COUNT(*) as cnt FROM ({sql}) AS _sub"
|
||||||
|
paged_params = {**base_params, "__limit": page_size, "__offset": offset}
|
||||||
|
|
||||||
|
with engine.connect() as conn:
|
||||||
|
# 查总数
|
||||||
|
total_row = conn.execute(text(count_sql), base_params).fetchone()
|
||||||
|
total = total_row[0] if total_row else 0
|
||||||
|
|
||||||
|
# 查分页数据
|
||||||
|
result = conn.execute(text(paged_sql), paged_params)
|
||||||
|
columns = list(result.keys()) if result.keys() else []
|
||||||
|
rows = [dict(row) for row in result.mappings().all()]
|
||||||
|
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=True,
|
||||||
|
message=f"查询返回 {len(rows)} 条(共 {total} 条)",
|
||||||
|
affected_rows=len(rows),
|
||||||
|
data=rows,
|
||||||
|
columns=columns,
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("分页查询失败:%s | %s", sql[:200], exc)
|
||||||
|
return SqlExecuteResult(
|
||||||
|
success=False, message=f"查询失败:{exc}", affected_rows=0
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
@@ -0,0 +1,440 @@
|
|||||||
|
"""
|
||||||
|
文档问答服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
基于指定目录下的文档提供多轮对话式问答。
|
||||||
|
支持两种模式:
|
||||||
|
1. 文本模式(默认):解析文档到内存,直接用原文回答(无需向量化,快);
|
||||||
|
2. 向量模式(可选):手动触发向量化,用向量检索回答(大文档/高频问答时用)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 文本模式优先:小文档量直接塞 LLM 上下文即可,省向量化时间;
|
||||||
|
2. 向量化可选:用户按需触发,不强制;
|
||||||
|
3. 复用已有 document_loader / vector_store 组件。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- load_directory():只解析文档存内存(快);
|
||||||
|
- chat():文本模式直接用原文;有向量索引时用检索增强;
|
||||||
|
- vectorize():手动触发向量化(按钮)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.doc_qa")
|
||||||
|
|
||||||
|
# 会话存储
|
||||||
|
_conversations: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
# 持久化文件(对话历史跨重启保留)
|
||||||
|
_PERSIST_FILE = Path(r"D:\Agent\agent\data\docqa_conversations.json")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_persisted() -> None:
|
||||||
|
"""启动时从文件恢复对话历史。"""
|
||||||
|
if not _PERSIST_FILE.exists():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
data = json.loads(_PERSIST_FILE.read_text(encoding="utf-8"))
|
||||||
|
for cid, conv in data.items():
|
||||||
|
# 只恢复元数据和历史,documents 可能太大
|
||||||
|
_conversations[cid] = {
|
||||||
|
"directory": conv.get("directory", ""),
|
||||||
|
"documents": conv.get("documents", []),
|
||||||
|
"vectorized": conv.get("vectorized", False),
|
||||||
|
"collection_name": conv.get("collection_name"),
|
||||||
|
"history": conv.get("history", []),
|
||||||
|
"total_chars": conv.get("total_chars", 0),
|
||||||
|
"total_chunks": conv.get("total_chunks", 0),
|
||||||
|
"title": conv.get("title", "未命名对话"),
|
||||||
|
"created_at": conv.get("created_at", ""),
|
||||||
|
"updated_at": conv.get("updated_at", ""),
|
||||||
|
}
|
||||||
|
logger.info("已恢复 %d 个对话历史", len(_conversations))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("恢复对话历史失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _save_persisted() -> None:
|
||||||
|
"""持久化对话历史到文件。"""
|
||||||
|
try:
|
||||||
|
_PERSIST_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
# 只存必要字段,documents 可能很大
|
||||||
|
data = {}
|
||||||
|
for cid, conv in _conversations.items():
|
||||||
|
data[cid] = {
|
||||||
|
"directory": conv.get("directory", ""),
|
||||||
|
"documents": conv.get("documents", [])[:50], # 最多存 50 个文档元数据
|
||||||
|
"vectorized": conv.get("vectorized", False),
|
||||||
|
"collection_name": conv.get("collection_name"),
|
||||||
|
"history": conv.get("history", [])[-20:], # 最多存最近 20 轮
|
||||||
|
"total_chars": conv.get("total_chars", 0),
|
||||||
|
"total_chunks": conv.get("total_chunks", 0),
|
||||||
|
"title": conv.get("title", "未命名对话"),
|
||||||
|
"created_at": conv.get("created_at", ""),
|
||||||
|
"updated_at": conv.get("updated_at", ""),
|
||||||
|
}
|
||||||
|
_PERSIST_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("保存对话历史失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
# 启动时恢复
|
||||||
|
_load_persisted()
|
||||||
|
|
||||||
|
|
||||||
|
def load_directory(
|
||||||
|
directory: Path | None = None,
|
||||||
|
conversation_id: str | None = None,
|
||||||
|
file_paths: list[str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
解析文档并存入内存(**不做向量化**,快)。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
directory:目录路径(加载目录下全部文档)
|
||||||
|
file_paths:文件路径列表(加载指定文件,与 directory 二选一)
|
||||||
|
【返回】{conversation_id, total_chars, file_count, vectorized: False}
|
||||||
|
"""
|
||||||
|
from app.knowledge.document_loader import load_directory as _load, load_file
|
||||||
|
|
||||||
|
if conversation_id is None:
|
||||||
|
conversation_id = f"conv_{uuid.uuid4().hex[:12]}"
|
||||||
|
|
||||||
|
docs = []
|
||||||
|
warnings = []
|
||||||
|
target_label = ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if file_paths:
|
||||||
|
# 加载指定文件
|
||||||
|
target_label = f"{len(file_paths)} 个文件"
|
||||||
|
for fp in file_paths:
|
||||||
|
try:
|
||||||
|
docs.extend(load_file(Path(fp)))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
warnings.append(f"解析失败:{Path(fp).name},{exc}")
|
||||||
|
elif directory:
|
||||||
|
# 加载目录下全部文档
|
||||||
|
directory = Path(directory)
|
||||||
|
if not directory.exists():
|
||||||
|
return {"success": False, "message": f"目录不存在:{directory}"}
|
||||||
|
target_label = str(directory)
|
||||||
|
docs, warnings = _load(directory)
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": "directory 或 file_paths 必须提供其一"}
|
||||||
|
|
||||||
|
if not docs:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"无可用文档(跳过 {len(warnings)} 个文件)",
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
# 存入内存(不做向量化)
|
||||||
|
documents = [
|
||||||
|
{
|
||||||
|
"filename": d.metadata.get("filename", "未知"),
|
||||||
|
"text": d.page_content,
|
||||||
|
"chars": len(d.page_content),
|
||||||
|
}
|
||||||
|
for d in docs
|
||||||
|
]
|
||||||
|
total_chars = sum(d["chars"] for d in documents)
|
||||||
|
|
||||||
|
_conversations[conversation_id] = {
|
||||||
|
"directory": target_label,
|
||||||
|
"documents": documents,
|
||||||
|
"vectorized": False,
|
||||||
|
"collection_name": None,
|
||||||
|
"history": [],
|
||||||
|
"total_chars": total_chars,
|
||||||
|
"title": Path(target_label).name if target_label else "新对话",
|
||||||
|
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
}
|
||||||
|
_save_persisted()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"directory": target_label,
|
||||||
|
"file_count": len(documents),
|
||||||
|
"total_chars": total_chars,
|
||||||
|
"vectorized": False,
|
||||||
|
"files": documents,
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("文档解析失败")
|
||||||
|
return {"success": False, "message": f"解析失败:{exc}", "conversation_id": conversation_id}
|
||||||
|
|
||||||
|
|
||||||
|
def vectorize(conversation_id: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
手动触发向量化(按钮)。
|
||||||
|
|
||||||
|
【返回】{success, total_chunks, collection_name}
|
||||||
|
"""
|
||||||
|
from app.knowledge.embeddings import get_embedding_provider
|
||||||
|
from app.knowledge.text_splitter import split_documents
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
from app.knowledge.document_loader import LoadedDocument
|
||||||
|
|
||||||
|
conv = _conversations.get(conversation_id)
|
||||||
|
if conv is None:
|
||||||
|
return {"success": False, "message": "会话不存在,请先加载目录"}
|
||||||
|
|
||||||
|
if conv.get("vectorized"):
|
||||||
|
return {"success": True, "message": "已向量化,无需重复操作", "total_chunks": conv.get("total_chunks", 0)}
|
||||||
|
|
||||||
|
try:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
provider = get_embedding_provider(
|
||||||
|
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||||
|
)
|
||||||
|
collection_name = f"docqa_{conversation_id}"
|
||||||
|
vs = KnowledgeVectorStore(
|
||||||
|
persist_dir=settings.chroma_dir,
|
||||||
|
collection_name=collection_name,
|
||||||
|
embedding_provider=provider,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 内存文档 → LoadedDocument → 切分 → 入库
|
||||||
|
docs = [
|
||||||
|
LoadedDocument(page_content=d["text"], metadata={"filename": d["filename"], "source": ""})
|
||||||
|
for d in conv["documents"]
|
||||||
|
]
|
||||||
|
chunks = split_documents(docs)
|
||||||
|
|
||||||
|
import uuid as uuid_mod
|
||||||
|
|
||||||
|
ids = [f"chunk_{uuid_mod.uuid4().hex[:12]}" for _ in chunks]
|
||||||
|
vs.add_documents(
|
||||||
|
[c.page_content for c in chunks],
|
||||||
|
[c.metadata for c in chunks],
|
||||||
|
ids,
|
||||||
|
)
|
||||||
|
|
||||||
|
conv["vectorized"] = True
|
||||||
|
conv["collection_name"] = collection_name
|
||||||
|
conv["total_chunks"] = len(chunks)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"向量化完成:{len(chunks)} 个文本块",
|
||||||
|
"total_chunks": len(chunks),
|
||||||
|
"collection_name": collection_name,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("向量化失败")
|
||||||
|
return {"success": False, "message": f"向量化失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def chat(
|
||||||
|
conversation_id: str,
|
||||||
|
question: str,
|
||||||
|
model_preference: str = "auto",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
多轮对话问答。
|
||||||
|
|
||||||
|
【模式】
|
||||||
|
无文档:纯 LLM 对话(无 RAG,直接回答);
|
||||||
|
有文档未向量化:文档原文直接进 LLM 上下文;
|
||||||
|
有文档已向量化:向量检索 top-k 相关片段 + LLM 回答。
|
||||||
|
"""
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
|
||||||
|
conv = _conversations.get(conversation_id)
|
||||||
|
if conv is None:
|
||||||
|
return {"success": False, "message": "会话不存在,请先创建对话或加载文档"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
docs = conv.get("documents", [])
|
||||||
|
|
||||||
|
if not docs:
|
||||||
|
# ========== 无文档模式:纯 LLM 对话 ==========
|
||||||
|
context = "(本次对话无关联文档,请直接回答用户问题)"
|
||||||
|
sources = []
|
||||||
|
mode = "chat"
|
||||||
|
elif conv.get("vectorized") and conv.get("collection_name"):
|
||||||
|
# ========== 向量模式:检索 top-5 相关片段 ==========
|
||||||
|
from app.knowledge.embeddings import get_embedding_provider
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
provider = get_embedding_provider(
|
||||||
|
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||||
|
)
|
||||||
|
vs = KnowledgeVectorStore(
|
||||||
|
persist_dir=settings.chroma_dir,
|
||||||
|
collection_name=conv["collection_name"],
|
||||||
|
embedding_provider=provider,
|
||||||
|
)
|
||||||
|
hits = vs.search(question, top_k=5)
|
||||||
|
context = "\n\n".join(
|
||||||
|
f"【片段 {i + 1}】来源:{h.get('metadata', {}).get('filename', '未知')}\n{h.get('text', '')}"
|
||||||
|
for i, h in enumerate(hits)
|
||||||
|
)
|
||||||
|
sources = [
|
||||||
|
{
|
||||||
|
"filename": h.get("metadata", {}).get("filename", ""),
|
||||||
|
"score": h.get("score"),
|
||||||
|
"excerpt": h.get("text", "")[:150],
|
||||||
|
}
|
||||||
|
for h in hits[:3]
|
||||||
|
]
|
||||||
|
mode = "vector"
|
||||||
|
else:
|
||||||
|
# ========== 文本模式:文档原文进上下文 ==========
|
||||||
|
MAX_CONTEXT_CHARS = 500_000
|
||||||
|
total_chars = sum(d["chars"] for d in docs)
|
||||||
|
context_parts = []
|
||||||
|
if total_chars <= MAX_CONTEXT_CHARS:
|
||||||
|
for doc in docs:
|
||||||
|
context_parts.append(f"【文档:{doc['filename']}】\n{doc['text']}")
|
||||||
|
else:
|
||||||
|
MIN_CHARS_PER_DOC = 2000
|
||||||
|
for doc in docs:
|
||||||
|
quota = max(MIN_CHARS_PER_DOC, int(MAX_CONTEXT_CHARS * doc["chars"] / total_chars))
|
||||||
|
text = doc["text"][:quota]
|
||||||
|
context_parts.append(f"【文档:{doc['filename']}(共{doc['chars']}字符)】\n{text}")
|
||||||
|
if doc["chars"] > quota:
|
||||||
|
context_parts.append(f"…({doc['filename']} 内容过长已截断)")
|
||||||
|
context = "\n\n".join(context_parts)
|
||||||
|
sources = [
|
||||||
|
{"filename": d["filename"], "score": None, "excerpt": d["text"][:150]}
|
||||||
|
for d in docs[:3]
|
||||||
|
]
|
||||||
|
mode = "text"
|
||||||
|
|
||||||
|
# 多轮对话历史(超过 20 轮自动压缩摘要)
|
||||||
|
history = conv.get("history", [])
|
||||||
|
history_text = ""
|
||||||
|
if history:
|
||||||
|
if len(history) > 20:
|
||||||
|
# 上下文压缩:保留最近 8 轮 + 对前 12 轮做摘要
|
||||||
|
recent = history[-8:]
|
||||||
|
older = history[:-8]
|
||||||
|
try:
|
||||||
|
# 简单截断(避免每次调模型摘要),取前 200 字符每条
|
||||||
|
summary = "\n".join(
|
||||||
|
f"{m['role']}: {m['content'][:100]}" for m in older[:12]
|
||||||
|
)
|
||||||
|
history_text = f"【更早对话摘要】\n{summary}\n\n【近期对话】\n"
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
summary = ""
|
||||||
|
history_text = ""
|
||||||
|
history_text += "\n".join(
|
||||||
|
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
recent = history[-6:]
|
||||||
|
history_text = "\n".join(
|
||||||
|
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||||
|
)
|
||||||
|
|
||||||
|
if docs:
|
||||||
|
prompt = f"""你是一个基于文档的问答助手。请严格根据以下文档内容回答用户问题。
|
||||||
|
|
||||||
|
【文档内容】
|
||||||
|
{context}
|
||||||
|
|
||||||
|
【对话历史】
|
||||||
|
{history_text or '(无历史)'}
|
||||||
|
|
||||||
|
【用户问题】
|
||||||
|
{question}
|
||||||
|
|
||||||
|
【回答要求】
|
||||||
|
1. 严格基于上述文档内容回答,禁止编造
|
||||||
|
2. 如果文档中没有相关内容,直接回答「根据已有文档,未找到相关答案」
|
||||||
|
3. 引用文档原文时用引号标注
|
||||||
|
4. 用中文回答,完整有条理"""
|
||||||
|
else:
|
||||||
|
prompt = f"""你是一个专业的问答助手。请回答用户的问题。
|
||||||
|
|
||||||
|
【对话历史】
|
||||||
|
{history_text or '(无历史)'}
|
||||||
|
|
||||||
|
【用户问题】
|
||||||
|
{question}
|
||||||
|
|
||||||
|
请用中文回答,完整有条理。"""
|
||||||
|
|
||||||
|
model = get_model_for_task(model_preference, "strong")
|
||||||
|
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||||||
|
resp = model.invoke(prompt)
|
||||||
|
answer = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
|
||||||
|
history.append({"role": "user", "content": question})
|
||||||
|
history.append({"role": "assistant", "content": answer})
|
||||||
|
conv["history"] = history
|
||||||
|
conv["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
# 首次提问时用问题做标题
|
||||||
|
if len(history) == 2 and conv.get("title") == conv.get("directory", "").split("\\")[-1]:
|
||||||
|
conv["title"] = question[:20] + ("…" if len(question) > 20 else "")
|
||||||
|
|
||||||
|
_save_persisted()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"answer": answer,
|
||||||
|
"model": model_name,
|
||||||
|
"sources": sources,
|
||||||
|
"history_count": len(history),
|
||||||
|
"mode": mode,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("问答失败")
|
||||||
|
return {"success": False, "message": f"问答失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def clear_conversation(conversation_id: str) -> bool:
|
||||||
|
"""清除会话历史。"""
|
||||||
|
if conversation_id in _conversations:
|
||||||
|
_conversations[conversation_id]["history"] = []
|
||||||
|
_save_persisted()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def delete_conversation(conversation_id: str) -> bool:
|
||||||
|
"""删除会话(彻底移除)。"""
|
||||||
|
if conversation_id in _conversations:
|
||||||
|
del _conversations[conversation_id]
|
||||||
|
_save_persisted()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def list_conversations() -> list[dict[str, Any]]:
|
||||||
|
"""列出所有活跃会话(含标题、时间、消息数)。"""
|
||||||
|
items = []
|
||||||
|
for cid, conv in _conversations.items():
|
||||||
|
items.append({
|
||||||
|
"conversation_id": cid,
|
||||||
|
"title": conv.get("title", "未命名对话"),
|
||||||
|
"directory": conv.get("directory", ""),
|
||||||
|
"total_chars": conv.get("total_chars", 0),
|
||||||
|
"file_count": len(conv.get("documents", [])),
|
||||||
|
"history_count": len(conv.get("history", [])),
|
||||||
|
"vectorized": conv.get("vectorized", False),
|
||||||
|
"created_at": conv.get("created_at", ""),
|
||||||
|
"updated_at": conv.get("updated_at", ""),
|
||||||
|
})
|
||||||
|
# 按更新时间倒序
|
||||||
|
items.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
|
||||||
|
return items
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""
|
||||||
|
Git 深度集成服务
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
Git 仓库深度操作:状态查看、diff 对比、分支管理、日志、blame、自动提交。
|
||||||
|
对应用户需求:Agent 改码后自动 commit + 可视化 diff。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 复用已有 git_tools(只读+写操作),统一入口;
|
||||||
|
2. 支持按任务分支隔离,改码自动 commit;
|
||||||
|
3. diff 对比供前端可视化展示。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.git_deep")
|
||||||
|
|
||||||
|
|
||||||
|
def git_status(repo_path: str) -> dict:
|
||||||
|
"""查看工作区状态。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git 操作")
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "status", "--short"],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout or "(工作区干净)"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def git_diff(repo_path: str, file_path: str = "") -> dict:
|
||||||
|
"""查看工作区 diff(相对 HEAD)。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git diff")
|
||||||
|
cmd = ["git", "diff", "HEAD"]
|
||||||
|
if file_path:
|
||||||
|
cmd.append(file_path)
|
||||||
|
result = subprocess.run(
|
||||||
|
cmd, cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||||
|
)
|
||||||
|
return {"success": True, "diff": result.stdout[:10000] or "(无差异)"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def git_commit(repo_path: str, message: str, task_id: str = "") -> dict:
|
||||||
|
"""提交工作区改动(自动 add -A + commit)。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git 提交")
|
||||||
|
subprocess.run(["git", "add", "-A"], cwd=str(root), capture_output=True, timeout=15)
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "commit", "-m", message],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||||
|
)
|
||||||
|
if result.returncode == 0:
|
||||||
|
commit_hash = subprocess.run(
|
||||||
|
["git", "rev-parse", "--short", "HEAD"],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
|
||||||
|
).stdout.strip()
|
||||||
|
return {"success": True, "commit_hash": commit_hash, "message": f"提交成功:{commit_hash}"}
|
||||||
|
return {"success": False, "message": result.stderr or "提交失败"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def git_log(repo_path: str, limit: int = 20) -> dict:
|
||||||
|
"""查看提交日志。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git log")
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "log", f"--max-count={limit}", "--oneline", "--graph"],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout or "(无提交记录)"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def git_branch(repo_path: str) -> dict:
|
||||||
|
"""查看分支列表。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git branch")
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "branch", "-a"],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout or "(无分支信息)"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def git_blame(repo_path: str, file_path: str) -> dict:
|
||||||
|
"""查看文件逐行变更记录(blame)。"""
|
||||||
|
try:
|
||||||
|
root = ensure_under_root(Path(repo_path), "Git blame")
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "blame", file_path],
|
||||||
|
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout[:5000] or "(无记录)"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""
|
||||||
|
Git 读取服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
封装对本地 Git 仓库的只读操作:读取分支列表、校验分支是否存在、
|
||||||
|
读取仓库当前状态摘要。供项目管理 API 展示「前端/后端仓库分支」下拉框使用。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 12/13 已锁定「本地 Git 管理 + 真实分支语义」——分支必须来自
|
||||||
|
真实 git 仓库,不能是自由文本标签,所以用 subprocess 调本机 git CLI。
|
||||||
|
2. 不用 GitPython / pygit2:多一层原生依赖与编译风险,subprocess 足够
|
||||||
|
且行为与你在 PyCharm/终端里看到的完全一致,便于教学对照。
|
||||||
|
3. 只做只读操作(分支列表/校验):写操作(checkout/commit)属于
|
||||||
|
代码修改链路(M4/M5),届时通过白名单执行器统一收口,本模块不越权。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- 所有命令用 list 参数传参(不经 shell 字符串拼接),杜绝命令注入;
|
||||||
|
- 强制 subprocess 工作目录为传入的仓库路径,不信任环境变量里的 cwd;
|
||||||
|
- 统一超时与输出截断,避免 git 卡死拖垮 API。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:目标路径不是 git 仓库(用户填错路径)。
|
||||||
|
应对:捕获 git 返回码非 0,转成结构化「不是 Git 仓库」业务错误,
|
||||||
|
绝不让 API 500。
|
||||||
|
风险2:git 命令不存在(未安装)。
|
||||||
|
应对:捕获 FileNotFoundError,返回「未检测到 git 命令,请先安装」。
|
||||||
|
风险3:仓库损坏 / 文件锁冲突导致 git 长时间阻塞。
|
||||||
|
应对:强制 timeout=15s,超时返回明确提示,不无限等待。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class GitError(RuntimeError):
|
||||||
|
"""Git 操作失败的统一业务异常(带中文可读信息)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "GitError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
class GitReadService:
|
||||||
|
"""Git 只读服务(一期:分支列表与校验)"""
|
||||||
|
|
||||||
|
def __init__(self, timeout_seconds: int = 15) -> None:
|
||||||
|
self._timeout = timeout_seconds
|
||||||
|
|
||||||
|
def _run_git(self, repo_path: Path, args: list[str]) -> str:
|
||||||
|
"""
|
||||||
|
在指定仓库目录执行 git 子命令,返回 stdout 文本。
|
||||||
|
|
||||||
|
【安全要点】args 用 list 传参,绝不拼接 shell 字符串,防命令注入。
|
||||||
|
"""
|
||||||
|
if not Path(repo_path).exists():
|
||||||
|
raise GitError(
|
||||||
|
f"代码路径不存在:{repo_path}", error_type="PathNotFound"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
completed = subprocess.run(
|
||||||
|
["git", *args],
|
||||||
|
cwd=str(repo_path),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=self._timeout,
|
||||||
|
shell=False,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
)
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise GitError(
|
||||||
|
"未检测到 git 命令,请先安装 Git 并加入 PATH", error_type="GitNotFound"
|
||||||
|
) from exc
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
raise GitError(
|
||||||
|
f"git 命令执行超时(>{self._timeout}秒):git {' '.join(args)}",
|
||||||
|
error_type="GitTimeout",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
if completed.returncode != 0:
|
||||||
|
stderr = (completed.stderr or "").strip()
|
||||||
|
raise GitError(
|
||||||
|
f"git 命令执行失败(退出码 {completed.returncode}):{stderr[:500]}",
|
||||||
|
error_type="GitCommandFailed",
|
||||||
|
)
|
||||||
|
return completed.stdout or ""
|
||||||
|
|
||||||
|
def is_git_repo(self, repo_path: Path) -> bool:
|
||||||
|
"""判断指定路径是否是 git 仓库(含子目录)。"""
|
||||||
|
try:
|
||||||
|
out = self._run_git(repo_path, ["rev-parse", "--is-inside-work-tree"])
|
||||||
|
return out.strip().lower() == "true"
|
||||||
|
except GitError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def list_branches(self, repo_path: Path) -> list[str]:
|
||||||
|
"""
|
||||||
|
列出仓库全部本地分支名。
|
||||||
|
|
||||||
|
【返回】分支名列表(不含星号前缀),按字母序去重。
|
||||||
|
"""
|
||||||
|
out = self._run_git(repo_path, ["branch", "--format=%(refname:short)"])
|
||||||
|
branches = [line.strip() for line in out.splitlines() if line.strip()]
|
||||||
|
return sorted(set(branches))
|
||||||
|
|
||||||
|
def branch_exists(self, repo_path: Path, branch_name: str) -> bool:
|
||||||
|
"""校验指定分支是否存在(供前端下拉框与校验使用)。"""
|
||||||
|
try:
|
||||||
|
self._run_git(
|
||||||
|
repo_path,
|
||||||
|
["rev-parse", "--verify", "--quiet", f"refs/heads/{branch_name}"],
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
except GitError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def current_branch(self, repo_path: Path) -> str:
|
||||||
|
"""读取仓库当前所在分支名(HEAD 指向)。"""
|
||||||
|
out = self._run_git(repo_path, ["rev-parse", "--abbrev-ref", "HEAD"])
|
||||||
|
return out.strip() or "HEAD"
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
"""
|
||||||
|
健康检查服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
全链路健康探活:服务自身、模型连接、向量库、SQLite、Git、磁盘空间。
|
||||||
|
供运维监控、前端状态栏、外部监控系统调用。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 各组件独立探测,单项失败不影响整体(级联失败隔离);
|
||||||
|
2. 返回结构化结果:status / latency_ms / message,便于机器解析;
|
||||||
|
3. 缓存探测结果(30 秒),防止高频健康检查压垮依赖服务。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- check_all():并发探测全部组件 → 汇总健康状态;
|
||||||
|
- 各子检查独立 try/except,失败降级为 unhealthy 不抛异常。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.health")
|
||||||
|
|
||||||
|
|
||||||
|
def _check_service() -> dict:
|
||||||
|
"""检查服务自身状态。"""
|
||||||
|
return {
|
||||||
|
"name": "service",
|
||||||
|
"status": "healthy",
|
||||||
|
"message": "服务运行中",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_database() -> dict:
|
||||||
|
"""检查 SQLite 数据库连通性。"""
|
||||||
|
start = time.time()
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
db_path = settings.sqlite_db_path
|
||||||
|
if not db_path.exists():
|
||||||
|
return {
|
||||||
|
"name": "database",
|
||||||
|
"status": "degraded",
|
||||||
|
"message": f"数据库文件不存在:{db_path}",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
conn = sqlite3.connect(str(db_path), timeout=3)
|
||||||
|
try:
|
||||||
|
conn.execute("SELECT 1")
|
||||||
|
finally:
|
||||||
|
# 【修复】close 必须在 finally,否则 execute 抛异常时连接泄漏
|
||||||
|
conn.close()
|
||||||
|
return {
|
||||||
|
"name": "database",
|
||||||
|
"status": "healthy",
|
||||||
|
"message": "SQLite 连接正常",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"name": "database",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": f"数据库连接失败:{exc}",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_vectorstore() -> dict:
|
||||||
|
"""检查向量库(Chroma)状态。"""
|
||||||
|
start = time.time()
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
chroma_dir = settings.chroma_dir
|
||||||
|
if not chroma_dir.exists():
|
||||||
|
return {
|
||||||
|
"name": "vectorstore",
|
||||||
|
"status": "degraded",
|
||||||
|
"message": "向量库目录不存在",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
db_file = chroma_dir / "chroma.sqlite3"
|
||||||
|
if not db_file.exists():
|
||||||
|
return {
|
||||||
|
"name": "vectorstore",
|
||||||
|
"status": "degraded",
|
||||||
|
"message": "向量库尚未初始化",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"name": "vectorstore",
|
||||||
|
"status": "healthy",
|
||||||
|
"message": f"Chroma 就绪({db_file.stat().st_size // 1024}KB)",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"name": "vectorstore",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": f"向量库异常:{exc}",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_model_api() -> dict:
|
||||||
|
"""检查模型服务连通性(ccswitch 代理)。"""
|
||||||
|
start = time.time()
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
if not settings.ccswitch_api_key:
|
||||||
|
return {
|
||||||
|
"name": "model_api",
|
||||||
|
"status": "degraded",
|
||||||
|
"message": "未配置 ccswitch 代理密钥",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
# 轻量探测:GET /models(不消耗 token)
|
||||||
|
resp = httpx.get(
|
||||||
|
f"{settings.ccswitch_base_url}/models",
|
||||||
|
headers={"Authorization": f"Bearer {settings.ccswitch_api_key}"},
|
||||||
|
timeout=5.0,
|
||||||
|
)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
return {
|
||||||
|
"name": "model_api",
|
||||||
|
"status": "healthy",
|
||||||
|
"message": "模型服务连接正常(ccswitch)",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"name": "model_api",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": f"模型服务返回 {resp.status_code}",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"name": "model_api",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": f"模型服务连接失败:{exc}",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_git() -> dict:
|
||||||
|
"""检查 Git 可用性。"""
|
||||||
|
start = time.time()
|
||||||
|
git_path = shutil.which("git")
|
||||||
|
if not git_path:
|
||||||
|
return {
|
||||||
|
"name": "git",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": "git 命令未找到",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"name": "git",
|
||||||
|
"status": "healthy",
|
||||||
|
"message": f"Git 可用({git_path})",
|
||||||
|
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_disk() -> dict:
|
||||||
|
"""检查磁盘空间。"""
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
data_root = settings.data_root
|
||||||
|
usage = shutil.disk_usage(str(data_root))
|
||||||
|
free_gb = usage.free / (1024**3)
|
||||||
|
total_gb = usage.total / (1024**3)
|
||||||
|
pct = usage.used / usage.total * 100
|
||||||
|
|
||||||
|
if free_gb < 1:
|
||||||
|
status = "unhealthy"
|
||||||
|
msg = f"磁盘空间严重不足:剩余 {free_gb:.1f}GB"
|
||||||
|
elif pct > 90:
|
||||||
|
status = "degraded"
|
||||||
|
msg = f"磁盘使用率 {pct:.1f}%,建议清理"
|
||||||
|
else:
|
||||||
|
status = "healthy"
|
||||||
|
msg = f"磁盘 {usage.used / (1024**3):.1f}GB / {total_gb:.1f}GB({pct:.1f}%)"
|
||||||
|
|
||||||
|
return {"name": "disk", "status": status, "message": msg, "latency_ms": 0}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {
|
||||||
|
"name": "disk",
|
||||||
|
"status": "unhealthy",
|
||||||
|
"message": f"磁盘检查失败:{exc}",
|
||||||
|
"latency_ms": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def check_all() -> dict:
|
||||||
|
"""
|
||||||
|
全链路健康检查。
|
||||||
|
|
||||||
|
【返回】{status, checks: [{name, status, message, latency_ms}], timestamp}
|
||||||
|
"""
|
||||||
|
checks = [
|
||||||
|
_check_service(),
|
||||||
|
_check_database(),
|
||||||
|
_check_vectorstore(),
|
||||||
|
_check_model_api(),
|
||||||
|
_check_git(),
|
||||||
|
_check_disk(),
|
||||||
|
]
|
||||||
|
|
||||||
|
# 汇总状态:任一 unhealthy → unhealthy;任一 degraded → degraded
|
||||||
|
statuses = [c["status"] for c in checks]
|
||||||
|
if "unhealthy" in statuses:
|
||||||
|
overall = "unhealthy"
|
||||||
|
elif "degraded" in statuses:
|
||||||
|
overall = "degraded"
|
||||||
|
else:
|
||||||
|
overall = "healthy"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": overall,
|
||||||
|
"checks": checks,
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"healthy_count": sum(1 for c in checks if c["status"] == "healthy"),
|
||||||
|
"total_count": len(checks),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
from datetime import datetime # noqa: E402
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""
|
||||||
|
知识库自动更新服务
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
监控素材目录变化,自动重新解析和向量化变更的文档。
|
||||||
|
对应功能 21:知识库保持与文档同步。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选文件哈希对比(MD5)检测变更:比 mtime 可靠,比轮询高效;
|
||||||
|
2. 增量更新:只重新处理变更的文件,不全量重建;
|
||||||
|
3. 支持手动触发和定时检查。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- check_and_update():对比文件哈希,变更的重新入库;
|
||||||
|
- 定时循环每 N 分钟检查一次;
|
||||||
|
- 维护文件哈希表(JSON 文件持久化)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge.auto_update")
|
||||||
|
|
||||||
|
# 文件哈希表(检测变更用)
|
||||||
|
HASH_FILE = Path(r"D:\Agent\agent\data\knowledge_hashes.json")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_hashes() -> dict[str, str]:
|
||||||
|
if not HASH_FILE.exists():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
return json.loads(HASH_FILE.read_text(encoding="utf-8"))
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _save_hashes(hashes: dict[str, str]) -> None:
|
||||||
|
HASH_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
HASH_FILE.write_text(json.dumps(hashes, indent=2), encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _file_hash(path: Path) -> str:
|
||||||
|
"""计算文件 MD5 哈希。"""
|
||||||
|
try:
|
||||||
|
return hashlib.md5(path.read_bytes()).hexdigest()
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def check_and_update() -> dict:
|
||||||
|
"""
|
||||||
|
检查素材目录变更并自动更新知识库。
|
||||||
|
|
||||||
|
【返回】{changed: [文件名], total_files, message}
|
||||||
|
"""
|
||||||
|
settings = load_settings()
|
||||||
|
scan_dir = settings.project_root / "需向量化数据"
|
||||||
|
if not scan_dir.exists():
|
||||||
|
return {"changed": [], "total_files": 0, "message": f"目录不存在:{scan_dir}"}
|
||||||
|
|
||||||
|
from app.knowledge.document_loader import SUPPORTED_EXTENSIONS
|
||||||
|
|
||||||
|
current_hashes = _load_hashes()
|
||||||
|
new_hashes: dict[str, str] = {}
|
||||||
|
changed_files: list[str] = []
|
||||||
|
|
||||||
|
# 扫描目录
|
||||||
|
for f in scan_dir.rglob("*"):
|
||||||
|
if not f.is_file() or f.suffix.lower() not in SUPPORTED_EXTENSIONS:
|
||||||
|
continue
|
||||||
|
key = str(f)
|
||||||
|
h = _file_hash(f)
|
||||||
|
new_hashes[key] = h
|
||||||
|
if current_hashes.get(key) != h:
|
||||||
|
changed_files.append(f.name)
|
||||||
|
|
||||||
|
# 找删除的文件
|
||||||
|
deleted_keys = set(current_hashes) - set(new_hashes)
|
||||||
|
|
||||||
|
if not changed_files and not deleted_keys:
|
||||||
|
_save_hashes(new_hashes)
|
||||||
|
return {
|
||||||
|
"changed": [],
|
||||||
|
"total_files": len(new_hashes),
|
||||||
|
"message": "无变更",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 有变更:更新知识库
|
||||||
|
try:
|
||||||
|
from app.knowledge.embeddings import get_embedding_provider
|
||||||
|
from app.knowledge.knowledge_service import KnowledgeService
|
||||||
|
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||||
|
|
||||||
|
provider = get_embedding_provider(
|
||||||
|
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||||
|
)
|
||||||
|
vs = KnowledgeVectorStore(
|
||||||
|
persist_dir=settings.chroma_dir,
|
||||||
|
collection_name=settings.chroma_collection_name,
|
||||||
|
embedding_provider=provider,
|
||||||
|
)
|
||||||
|
service = KnowledgeService(vs, provider)
|
||||||
|
|
||||||
|
# 全量重建(简单可靠,增量替换后续优化)
|
||||||
|
result = service.ingest_directory(scan_dir)
|
||||||
|
|
||||||
|
_save_hashes(new_hashes)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"changed": changed_files,
|
||||||
|
"deleted": list(deleted_keys),
|
||||||
|
"total_files": len(new_hashes),
|
||||||
|
"ingested_chunks": result.get("ingested_chunks", 0),
|
||||||
|
"message": f"知识库已更新:{len(changed_files)} 个文件变更",
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("自动更新失败")
|
||||||
|
return {
|
||||||
|
"changed": changed_files,
|
||||||
|
"total_files": len(new_hashes),
|
||||||
|
"message": f"更新失败:{exc}",
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
"""
|
||||||
|
知识图谱服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
从文档中抽取实体与关系,构建轻量知识图谱,支持图查询。
|
||||||
|
对应功能 23:深度理解文档语义关系。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 轻量图存储(SQLite 三元组),免 Neo4j 等外部依赖;
|
||||||
|
2. LLM 驱动的实体关系抽取;
|
||||||
|
3. 支持实体查询、关系查询、路径查询。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.knowledge_graph")
|
||||||
|
|
||||||
|
|
||||||
|
class KnowledgeGraphStore:
|
||||||
|
"""知识图谱存储(三元组模型)"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS knowledge_triple (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
subject TEXT NOT NULL,
|
||||||
|
predicate TEXT NOT NULL,
|
||||||
|
object TEXT NOT NULL,
|
||||||
|
source TEXT DEFAULT '',
|
||||||
|
confidence REAL DEFAULT 1.0,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_kg_subject ON knowledge_triple(subject);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_kg_object ON knowledge_triple(object);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.executescript(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def add_triple(self, subject: str, predicate: str, obj: str, source: str = "", confidence: float = 1.0) -> str:
|
||||||
|
"""添加一个三元组。"""
|
||||||
|
triple_id = f"kg_{uuid.uuid4().hex[:8]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO knowledge_triple (id, subject, predicate, object, source, confidence, created_at) VALUES (?,?,?,?,?,?,?)",
|
||||||
|
(triple_id, subject, predicate, obj, source, confidence, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return triple_id
|
||||||
|
|
||||||
|
def query_by_subject(self, subject: str) -> list[dict]:
|
||||||
|
"""按主语查询关系。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM knowledge_triple WHERE subject = ? ORDER BY confidence DESC",
|
||||||
|
(subject,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def query_by_object(self, obj: str) -> list[dict]:
|
||||||
|
"""按宾语查询关系。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM knowledge_triple WHERE object = ? ORDER BY confidence DESC",
|
||||||
|
(obj,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def query_relation(self, predicate: str) -> list[dict]:
|
||||||
|
"""按关系查询。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM knowledge_triple WHERE predicate LIKE ? ORDER BY confidence DESC",
|
||||||
|
(f"%{predicate}%",),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def search_entities(self, keyword: str, limit: int = 20) -> list[dict]:
|
||||||
|
"""搜索实体(主语或宾语含关键词)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""SELECT DISTINCT subject AS entity FROM knowledge_triple WHERE subject LIKE ?
|
||||||
|
UNION
|
||||||
|
SELECT DISTINCT object AS entity FROM knowledge_triple WHERE object LIKE ? LIMIT ?""",
|
||||||
|
(f"%{keyword}%", f"%{keyword}%", limit),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get_graph_stats(self) -> dict:
|
||||||
|
"""获取图谱统计。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
triple_count = conn.execute("SELECT COUNT(*) FROM knowledge_triple").fetchone()[0]
|
||||||
|
subject_count = conn.execute("SELECT COUNT(DISTINCT subject) FROM knowledge_triple").fetchone()[0]
|
||||||
|
predicate_count = conn.execute("SELECT COUNT(DISTINCT predicate) FROM knowledge_triple").fetchone()[0]
|
||||||
|
return {
|
||||||
|
"triples": triple_count,
|
||||||
|
"entities": subject_count,
|
||||||
|
"relations": predicate_count,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def extract_triples(text: str, source: str = "", model_preference: str = "auto") -> dict:
|
||||||
|
"""
|
||||||
|
从文本中抽取实体关系三元组(LLM 驱动)。
|
||||||
|
|
||||||
|
【返回】{triples: [{subject, predicate, object}], count}
|
||||||
|
"""
|
||||||
|
prompt = f"""从下面的文本中抽取实体和关系,输出 JSON 三元组数组。
|
||||||
|
|
||||||
|
【文本】
|
||||||
|
{text[:3000]}
|
||||||
|
|
||||||
|
【输出格式】
|
||||||
|
只输出 JSON 数组,每个元素:
|
||||||
|
[{{"subject": "实体1", "predicate": "关系", "object": "实体2"}}]
|
||||||
|
|
||||||
|
示例:
|
||||||
|
[{{"subject": "网关", "predicate": "连接", "object": "MQTT服务器"}}]
|
||||||
|
|
||||||
|
只输出 JSON,不要解释。"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
model = get_model_for_task(model_preference, "strong")
|
||||||
|
resp = model.invoke(prompt)
|
||||||
|
content = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
json_match = re.search(r"\[.*\]", content, re.DOTALL)
|
||||||
|
if json_match:
|
||||||
|
triples = json.loads(json_match.group(0))
|
||||||
|
if isinstance(triples, list):
|
||||||
|
return {"triples": triples[:20], "count": len(triples), "source": source}
|
||||||
|
return {"triples": [], "count": 0, "source": source}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("三元组抽取失败:%s", exc)
|
||||||
|
return {"triples": [], "count": 0, "error": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: KnowledgeGraphStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_kg_store() -> KnowledgeGraphStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
_store = KnowledgeGraphStore(settings.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,482 @@
|
|||||||
|
"""
|
||||||
|
MCP 协议接入(框架预留)
|
||||||
|
========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
MCP(Model Context Protocol)标准工具协议接入框架。
|
||||||
|
对应功能 41:Agent 生态标准化对接。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. MCP 是 Agent 工具接入的标准协议(Anthropic 主导);
|
||||||
|
2. 框架化设计:支持注册/发现/调用 MCP Server 工具;
|
||||||
|
3. 预留 httpx 传输层,可对接任意 MCP Server。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- McpToolRegistry:注册/查询/调用 MCP 工具;
|
||||||
|
- 后续可接入 MCP Server(GitHub、数据库、浏览器等)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.mcp")
|
||||||
|
|
||||||
|
|
||||||
|
class McpTool:
|
||||||
|
"""MCP 工具定义"""
|
||||||
|
|
||||||
|
def __init__(self, name: str, description: str, input_schema: dict, server_url: str = ""):
|
||||||
|
self.name = name
|
||||||
|
self.description = description
|
||||||
|
self.input_schema = input_schema
|
||||||
|
self.server_url = server_url
|
||||||
|
|
||||||
|
|
||||||
|
class McpToolRegistry:
|
||||||
|
"""MCP 工具注册表"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._tools: dict[str, McpTool] = {}
|
||||||
|
|
||||||
|
def register(self, tool: McpTool) -> None:
|
||||||
|
self._tools[tool.name] = tool
|
||||||
|
logger.info("MCP 工具已注册:%s", tool.name)
|
||||||
|
|
||||||
|
def list_tools(self) -> list[dict]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": t.name,
|
||||||
|
"description": t.description,
|
||||||
|
"input_schema": t.input_schema,
|
||||||
|
"server_url": t.server_url,
|
||||||
|
}
|
||||||
|
for t in self._tools.values()
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_tool(self, name: str) -> McpTool | None:
|
||||||
|
return self._tools.get(name)
|
||||||
|
|
||||||
|
def call_tool(self, name: str, arguments: dict[str, Any]) -> dict:
|
||||||
|
"""调用 MCP 工具(优先本地实现,其次 httpx 传输)。"""
|
||||||
|
tool = self._tools.get(name)
|
||||||
|
if tool is None:
|
||||||
|
return {"success": False, "message": f"工具不存在:{name}"}
|
||||||
|
|
||||||
|
# 优先使用本地实现
|
||||||
|
local_impl = _TOOL_IMPLEMENTATIONS.get(name)
|
||||||
|
if local_impl:
|
||||||
|
try:
|
||||||
|
return local_impl(arguments)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"本地工具执行失败:{exc}"}
|
||||||
|
|
||||||
|
# 无本地实现:走远程 MCP Server
|
||||||
|
if not tool.server_url:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"工具 {name} 需要外部凭证配置(GITHUB_TOKEN/SLACK_TOKEN 等),当前未配置",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.post(
|
||||||
|
tool.server_url,
|
||||||
|
json={"tool": name, "arguments": arguments},
|
||||||
|
timeout=30.0,
|
||||||
|
)
|
||||||
|
return {"success": resp.status_code == 200, "data": resp.json() if resp.status_code == 200 else resp.text}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"调用失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
# 全局注册表
|
||||||
|
registry = McpToolRegistry()
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 本地工具实现(无需外部凭证)==========
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_filesystem(arguments: dict) -> dict:
|
||||||
|
"""MCP Filesystem 工具:文件读写、搜索、浏览。"""
|
||||||
|
action = arguments.get("action", "read")
|
||||||
|
path = arguments.get("path", "")
|
||||||
|
try:
|
||||||
|
p = Path(path)
|
||||||
|
if action == "read":
|
||||||
|
content = p.read_text(encoding="utf-8", errors="replace")[:50000]
|
||||||
|
return {"success": True, "content": content}
|
||||||
|
elif action == "write":
|
||||||
|
p.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
p.write_text(arguments.get("content", ""), encoding="utf-8")
|
||||||
|
return {"success": True, "message": f"已写入 {path}"}
|
||||||
|
elif action == "list":
|
||||||
|
items = [
|
||||||
|
{"name": x.name, "is_dir": x.is_dir(), "size": x.stat().st_size if x.is_file() else 0}
|
||||||
|
for x in p.iterdir()
|
||||||
|
]
|
||||||
|
return {"success": True, "items": items}
|
||||||
|
elif action == "search":
|
||||||
|
pattern = arguments.get("pattern", "*")
|
||||||
|
results = [
|
||||||
|
str(x) for x in p.rglob(pattern) if x.is_file()
|
||||||
|
][:50]
|
||||||
|
return {"success": True, "results": results}
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": f"不支持的操作:{action}"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_web_search(arguments: dict) -> dict:
|
||||||
|
"""MCP WebSearch 工具:网页搜索(DuckDuckGo)。"""
|
||||||
|
query = arguments.get("query", "")
|
||||||
|
if not query:
|
||||||
|
return {"success": False, "message": "query 必填"}
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.get(
|
||||||
|
f"https://html.duckduckgo.com/html/?q={query}",
|
||||||
|
headers={"User-Agent": "Mozilla/5.0"},
|
||||||
|
timeout=10.0,
|
||||||
|
)
|
||||||
|
return {"success": True, "results": resp.text[:5000], "source": "duckduckgo"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_web_fetch(arguments: dict) -> dict:
|
||||||
|
"""MCP WebFetch 工具:抓取网页内容。"""
|
||||||
|
url = arguments.get("url", "")
|
||||||
|
if not url:
|
||||||
|
return {"success": False, "message": "url 必填"}
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.get(url, timeout=15.0, follow_redirects=True)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"status_code": resp.status_code,
|
||||||
|
"content": resp.text[:20000],
|
||||||
|
"content_type": resp.headers.get("content-type", ""),
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_memory(arguments: dict) -> dict:
|
||||||
|
"""MCP Memory 工具:长期记忆存取。"""
|
||||||
|
action = arguments.get("action", "recall")
|
||||||
|
try:
|
||||||
|
from app.services.memory_service import get_memory_store
|
||||||
|
|
||||||
|
store = get_memory_store()
|
||||||
|
if action == "remember":
|
||||||
|
mem_id = store.remember(
|
||||||
|
content=arguments.get("content", ""),
|
||||||
|
project_id=arguments.get("project_id", ""),
|
||||||
|
category=arguments.get("category", "mcp"),
|
||||||
|
)
|
||||||
|
return {"success": True, "id": mem_id}
|
||||||
|
elif action == "recall":
|
||||||
|
items = store.recall(
|
||||||
|
query=arguments.get("query", ""),
|
||||||
|
project_id=arguments.get("project_id", ""),
|
||||||
|
top_k=int(arguments.get("top_k", 5)),
|
||||||
|
)
|
||||||
|
return {"success": True, "memories": items}
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": f"不支持:{action}"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_docker(arguments: dict) -> dict:
|
||||||
|
"""MCP Docker 工具:容器管理。"""
|
||||||
|
action = arguments.get("action", "ps")
|
||||||
|
try:
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
cmd_map = {
|
||||||
|
"ps": ["docker", "ps", "-a", "--format", "table {{.Names}}\t{{.Status}}\t{{.Image}}"],
|
||||||
|
"images": ["docker", "images", "--format", "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"],
|
||||||
|
"logs": ["docker", "logs", "--tail", "50", arguments.get("container", "")],
|
||||||
|
"stats": ["docker", "stats", "--no-stream"],
|
||||||
|
}
|
||||||
|
cmd = cmd_map.get(action)
|
||||||
|
if not cmd:
|
||||||
|
return {"success": False, "message": f"不支持:{action}"}
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
|
||||||
|
return {"success": result.returncode == 0, "output": result.stdout[:5000], "error": result.stderr[:500]}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_health(arguments: dict) -> dict:
|
||||||
|
"""MCP 健康检查工具:系统全链路探活。"""
|
||||||
|
try:
|
||||||
|
from app.services.health_service import check_all
|
||||||
|
|
||||||
|
return {"success": True, "health": check_all()}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_zentao(arguments: dict) -> dict:
|
||||||
|
"""禅道项目管理工具。"""
|
||||||
|
try:
|
||||||
|
from app.services.zentao_service import get_zentao_service
|
||||||
|
|
||||||
|
service = get_zentao_service()
|
||||||
|
action = arguments.get("action", "search")
|
||||||
|
|
||||||
|
if action == "create_bug":
|
||||||
|
result = service.create_bug(
|
||||||
|
title=arguments.get("title", ""),
|
||||||
|
description=arguments.get("description", ""),
|
||||||
|
project_id=arguments.get("project_id", ""),
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
elif action == "create_task":
|
||||||
|
result = service.create_task(
|
||||||
|
title=arguments.get("title", ""),
|
||||||
|
description=arguments.get("description", ""),
|
||||||
|
project_id=arguments.get("project_id", ""),
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
elif action == "search":
|
||||||
|
result = service.search(keyword=arguments.get("title", ""))
|
||||||
|
return result
|
||||||
|
elif action == "update_status":
|
||||||
|
result = service.update_status(
|
||||||
|
issue_id=arguments.get("issue_id", ""),
|
||||||
|
status=arguments.get("status", "done"),
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": f"不支持:{action}"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_git(arguments: dict) -> dict:
|
||||||
|
"""Git 深度集成工具。"""
|
||||||
|
try:
|
||||||
|
from app.tools.git_tools import get_diff, ensure_task_branch, commit_changes
|
||||||
|
|
||||||
|
action = arguments.get("action", "status")
|
||||||
|
repo_path = arguments.get("repo_path", "")
|
||||||
|
|
||||||
|
if action == "diff":
|
||||||
|
result = get_diff(repo_path)
|
||||||
|
return {"success": True, **result}
|
||||||
|
elif action == "status":
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "status", "--short"],
|
||||||
|
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout}
|
||||||
|
elif action == "commit":
|
||||||
|
result = commit_changes(
|
||||||
|
repo_path,
|
||||||
|
message=arguments.get("message", "自动提交"),
|
||||||
|
task_id=arguments.get("task_id", ""),
|
||||||
|
)
|
||||||
|
return {"success": True, **result}
|
||||||
|
elif action == "log":
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "log", "--oneline", "-20"],
|
||||||
|
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout}
|
||||||
|
elif action == "branch":
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "branch", "-a"],
|
||||||
|
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||||
|
)
|
||||||
|
return {"success": True, "output": result.stdout}
|
||||||
|
else:
|
||||||
|
return {"success": False, "message": f"不支持:{action}"}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 工具实现映射 ==========
|
||||||
|
_TOOL_IMPLEMENTATIONS = {
|
||||||
|
"filesystem": _tool_filesystem,
|
||||||
|
"web_search": _tool_web_search,
|
||||||
|
"web_fetch": _tool_web_fetch,
|
||||||
|
"memory": _tool_memory,
|
||||||
|
"docker": _tool_docker,
|
||||||
|
"health_check": _tool_health,
|
||||||
|
"zentao": _tool_zentao,
|
||||||
|
"git": _tool_git,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 注册全部工具 ==========
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="filesystem",
|
||||||
|
description="文件系统操作(读/写/列目录/搜索)",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["read", "write", "list", "search"]},
|
||||||
|
"path": {"type": "string"},
|
||||||
|
"content": {"type": "string"},
|
||||||
|
"pattern": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="web_search",
|
||||||
|
description="网页搜索(DuckDuckGo)",
|
||||||
|
input_schema={"type": "object", "properties": {"query": {"type": "string"}}},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="web_fetch",
|
||||||
|
description="抓取网页内容",
|
||||||
|
input_schema={"type": "object", "properties": {"url": {"type": "string"}}},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="memory",
|
||||||
|
description="长期记忆(存取项目约定、决策、规范)",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["remember", "recall"]},
|
||||||
|
"content": {"type": "string"},
|
||||||
|
"query": {"type": "string"},
|
||||||
|
"project_id": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="docker",
|
||||||
|
description="Docker 容器管理(ps/images/logs/stats)",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["ps", "images", "logs", "stats"]},
|
||||||
|
"container": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="health_check",
|
||||||
|
description="系统健康检查(全链路探活)",
|
||||||
|
input_schema={"type": "object", "properties": {}},
|
||||||
|
))
|
||||||
|
|
||||||
|
# ========== 需要凭证的工具(框架就绪)==========
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="github",
|
||||||
|
description="GitHub 操作(PR/Issue/仓库)— 需要 GITHUB_TOKEN",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["create_pr", "list_issues", "create_issue", "get_repo"]},
|
||||||
|
"repo": {"type": "string"},
|
||||||
|
"title": {"type": "string"},
|
||||||
|
"body": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server_url="", # 需配置
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="zentao",
|
||||||
|
description="禅道项目管理(创建/查询/更新 Bug 和任务)",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["create_bug", "create_task", "search", "update_status"]},
|
||||||
|
"title": {"type": "string"},
|
||||||
|
"description": {"type": "string"},
|
||||||
|
"project_id": {"type": "string"},
|
||||||
|
"issue_id": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="git",
|
||||||
|
description="Git 深度集成(commit/diff/branch/log/blame)",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["status", "diff", "commit", "log", "branch", "blame"]},
|
||||||
|
"repo_path": {"type": "string"},
|
||||||
|
"message": {"type": "string"},
|
||||||
|
"file_path": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="jira",
|
||||||
|
description="Jira 任务管理(创建/查询/更新)— 需要 JIRA_TOKEN",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["create_issue", "search", "update"]},
|
||||||
|
"project": {"type": "string"},
|
||||||
|
"summary": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="redis",
|
||||||
|
description="Redis 缓存操作(GET/SET/DEL)— 需要 Redis 连接",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {"type": "string", "enum": ["get", "set", "del", "keys"]},
|
||||||
|
"key": {"type": "string"},
|
||||||
|
"value": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="database",
|
||||||
|
description="通用数据库查询(SQL)— 需要数据库连接",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"connection_id": {"type": "string"},
|
||||||
|
"sql": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
registry.register(McpTool(
|
||||||
|
name="email",
|
||||||
|
description="邮件发送(SMTP)— 需要邮箱凭证",
|
||||||
|
input_schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"to": {"type": "string"},
|
||||||
|
"subject": {"type": "string"},
|
||||||
|
"body": {"type": "string"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""
|
||||||
|
长期记忆服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
记住项目约定、编码规范、历史决策,供 Agent 执行时智能召回。
|
||||||
|
对应功能 20:Agent 越用越准的关键。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 SQLite + 向量检索:结构化存储 + 语义召回,兼顾精确与模糊;
|
||||||
|
2. 按项目隔离记忆(namespace),多项目互不干扰;
|
||||||
|
3. 写入即向量化,下次执行时按相关性召回 top-k。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- remember():记录一条记忆(约定/规范/决策);
|
||||||
|
- recall():按任务描述召回相关记忆;
|
||||||
|
- list_memories():列出项目全部记忆。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.memory")
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryStore:
|
||||||
|
"""长期记忆存储"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS memory (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
project_id TEXT NOT NULL DEFAULT '',
|
||||||
|
category TEXT NOT NULL DEFAULT 'general',
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
source TEXT DEFAULT '',
|
||||||
|
tags TEXT DEFAULT '[]',
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def remember(
|
||||||
|
self,
|
||||||
|
content: str,
|
||||||
|
project_id: str = "",
|
||||||
|
category: str = "general",
|
||||||
|
source: str = "",
|
||||||
|
tags: list[str] | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""记录一条长期记忆。"""
|
||||||
|
mem_id = f"mem_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO memory (id, project_id, category, content, source, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(mem_id, project_id, category, content, source, json.dumps(tags or [], ensure_ascii=False), now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
logger.info("记忆已保存:%s(%s)", mem_id, category)
|
||||||
|
return mem_id
|
||||||
|
|
||||||
|
def recall(self, query: str, project_id: str = "", top_k: int = 5) -> list[dict]:
|
||||||
|
"""
|
||||||
|
按查询召回相关记忆。
|
||||||
|
|
||||||
|
【策略】先精确匹配关键词,再按时间倒序补充,确保相关记忆被召回。
|
||||||
|
"""
|
||||||
|
keywords = [w for w in query.split() if len(w) >= 2][:5]
|
||||||
|
results = []
|
||||||
|
|
||||||
|
with self._conn() as conn:
|
||||||
|
if keywords:
|
||||||
|
# 关键词匹配
|
||||||
|
conditions = " OR ".join(["content LIKE ?"] * len(keywords))
|
||||||
|
params = [f"%{k}%" for k in keywords]
|
||||||
|
sql = f"SELECT * FROM memory WHERE ({conditions})"
|
||||||
|
if project_id:
|
||||||
|
sql += " AND (project_id = ? OR project_id = '')"
|
||||||
|
params.append(project_id)
|
||||||
|
sql += " ORDER BY updated_at DESC LIMIT ?"
|
||||||
|
params.append(top_k)
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
results = [dict(r) for r in rows]
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
# 回退:取最近的记忆
|
||||||
|
sql = "SELECT * FROM memory"
|
||||||
|
params = []
|
||||||
|
if project_id:
|
||||||
|
sql += " WHERE project_id = ? OR project_id = ''"
|
||||||
|
params.append(project_id)
|
||||||
|
sql += " ORDER BY updated_at DESC LIMIT ?"
|
||||||
|
params.append(top_k)
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
results = [dict(r) for r in rows]
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def list_memories(self, project_id: str = "", category: str = "") -> list[dict]:
|
||||||
|
"""列出记忆(可按项目/分类筛选)。"""
|
||||||
|
sql = "SELECT * FROM memory"
|
||||||
|
conditions = []
|
||||||
|
params = []
|
||||||
|
if project_id:
|
||||||
|
conditions.append("project_id = ?")
|
||||||
|
params.append(project_id)
|
||||||
|
if category:
|
||||||
|
conditions.append("category = ?")
|
||||||
|
params.append(category)
|
||||||
|
if conditions:
|
||||||
|
sql += " WHERE " + " AND ".join(conditions)
|
||||||
|
sql += " ORDER BY updated_at DESC"
|
||||||
|
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def delete(self, mem_id: str) -> bool:
|
||||||
|
with self._conn() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM memory WHERE id = ?", (mem_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: MemoryStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_memory_store() -> MemoryStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
_store = MemoryStore(settings.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
"""
|
||||||
|
指标采集与统计服务
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
采集模型调用指标(token 消耗、延迟、成本)、任务执行指标、系统指标,
|
||||||
|
供监控仪表盘、成本统计、性能分析使用。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 轻量 JSON 文件存储(单机场景够用,免额外基础设施);
|
||||||
|
2. 调用方只需一行 record_model_call(),无侵入;
|
||||||
|
3. 统计接口支持按日期/模型/维度聚合。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- record_model_call():记录每次模型调用(token、延迟、模型名);
|
||||||
|
- record_task():记录任务执行(耗时、状态、步骤数);
|
||||||
|
- get_dashboard():聚合统计供仪表盘展示;
|
||||||
|
- 指标存 D:\\Agent\\agent\\data\\metrics.jsonl(追加式 JSONL)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.metrics")
|
||||||
|
|
||||||
|
# 指标文件
|
||||||
|
METRICS_FILE = Path(r"D:\Agent\agent\data\metrics.jsonl")
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
# 模型定价(每千 token,单位:元)—— 行业均价估算
|
||||||
|
MODEL_PRICING = {
|
||||||
|
"mimo-v2.6-pro": {"input": 0.002, "output": 0.008},
|
||||||
|
"mimo-v2.6-flash": {"input": 0.0005, "output": 0.002},
|
||||||
|
"glm-5.3": {"input": 0.002, "output": 0.008},
|
||||||
|
"glm-5.3-flash": {"input": 0.0005, "output": 0.002},
|
||||||
|
"default": {"input": 0.002, "output": 0.008},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _get_price(model_name: str) -> dict:
|
||||||
|
"""获取模型定价(未匹配则用默认价)。"""
|
||||||
|
for key, price in MODEL_PRICING.items():
|
||||||
|
if key != "default" and key.lower() in model_name.lower():
|
||||||
|
return price
|
||||||
|
return MODEL_PRICING["default"]
|
||||||
|
|
||||||
|
|
||||||
|
def record_model_call(
|
||||||
|
model_name: str,
|
||||||
|
provider: str = "",
|
||||||
|
input_tokens: int = 0,
|
||||||
|
output_tokens: int = 0,
|
||||||
|
latency_ms: float = 0,
|
||||||
|
success: bool = True,
|
||||||
|
task_id: str = "",
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
记录一次模型调用(异步追加,不阻塞主流程)。
|
||||||
|
|
||||||
|
【参数】provider:所属 Provider(如 ccswitch / zhipu),供按平台聚合用量。
|
||||||
|
【安全】写入失败只记日志,不影响业务。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
price = _get_price(model_name)
|
||||||
|
cost = (input_tokens / 1000 * price["input"]) + (output_tokens / 1000 * price["output"])
|
||||||
|
entry = {
|
||||||
|
"type": "model_call",
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"model": model_name,
|
||||||
|
"provider": provider,
|
||||||
|
"input_tokens": input_tokens,
|
||||||
|
"output_tokens": output_tokens,
|
||||||
|
"total_tokens": input_tokens + output_tokens,
|
||||||
|
"latency_ms": round(latency_ms, 1),
|
||||||
|
"success": success,
|
||||||
|
"cost": round(cost, 6),
|
||||||
|
"task_id": task_id,
|
||||||
|
}
|
||||||
|
with _lock:
|
||||||
|
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(METRICS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("指标写入失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def record_task(
|
||||||
|
task_id: str,
|
||||||
|
duration_s: float = 0,
|
||||||
|
status: str = "done",
|
||||||
|
steps: int = 0,
|
||||||
|
project_id: str = "",
|
||||||
|
) -> None:
|
||||||
|
"""记录任务执行指标。"""
|
||||||
|
try:
|
||||||
|
entry = {
|
||||||
|
"type": "task",
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"task_id": task_id,
|
||||||
|
"duration_s": round(duration_s, 1),
|
||||||
|
"status": status,
|
||||||
|
"steps": steps,
|
||||||
|
"project_id": project_id,
|
||||||
|
}
|
||||||
|
with _lock:
|
||||||
|
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(METRICS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("指标写入失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_metrics(hours: int = 24) -> list[dict]:
|
||||||
|
"""读取最近 N 小时的指标。"""
|
||||||
|
if not METRICS_FILE.exists():
|
||||||
|
return []
|
||||||
|
cutoff = datetime.now().astimezone() - timedelta(hours=hours)
|
||||||
|
results = []
|
||||||
|
try:
|
||||||
|
with open(METRICS_FILE, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
ts = entry.get("timestamp", "")
|
||||||
|
if ts and datetime.fromisoformat(ts) >= cutoff:
|
||||||
|
results.append(entry)
|
||||||
|
except (json.JSONDecodeError, ValueError):
|
||||||
|
continue
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("读取指标失败:%s", exc)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def get_dashboard(hours: int = 24) -> dict:
|
||||||
|
"""
|
||||||
|
获取监控仪表盘数据(最近 N 小时)。
|
||||||
|
|
||||||
|
【返回】
|
||||||
|
model_stats: 按模型聚合的 token/成本/延迟/调用次数
|
||||||
|
task_stats: 任务状态分布、平均耗时
|
||||||
|
totals: 总 token / 总成本 / 总调用次数
|
||||||
|
"""
|
||||||
|
entries = _read_metrics(hours)
|
||||||
|
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||||
|
task_calls = [e for e in entries if e.get("type") == "task"]
|
||||||
|
|
||||||
|
# 按模型聚合
|
||||||
|
model_stats: dict[str, dict] = {}
|
||||||
|
provider_stats: dict[str, dict] = {}
|
||||||
|
for e in model_calls:
|
||||||
|
name = e.get("model", "unknown")
|
||||||
|
provider = e.get("provider") or "unknown"
|
||||||
|
|
||||||
|
# 按模型聚合
|
||||||
|
if name not in model_stats:
|
||||||
|
model_stats[name] = {
|
||||||
|
"model": name,
|
||||||
|
"provider": provider,
|
||||||
|
"calls": 0,
|
||||||
|
"input_tokens": 0,
|
||||||
|
"output_tokens": 0,
|
||||||
|
"total_tokens": 0,
|
||||||
|
"cost": 0.0,
|
||||||
|
"total_latency_ms": 0.0,
|
||||||
|
"success_count": 0,
|
||||||
|
}
|
||||||
|
m = model_stats[name]
|
||||||
|
m["calls"] += 1
|
||||||
|
m["input_tokens"] += e.get("input_tokens", 0)
|
||||||
|
m["output_tokens"] += e.get("output_tokens", 0)
|
||||||
|
m["total_tokens"] += e.get("total_tokens", 0)
|
||||||
|
m["cost"] += e.get("cost", 0)
|
||||||
|
m["total_latency_ms"] += e.get("latency_ms", 0)
|
||||||
|
if e.get("success"):
|
||||||
|
m["success_count"] += 1
|
||||||
|
|
||||||
|
# 按 Provider 聚合(痛点 1:多平台用量统一查看)
|
||||||
|
if provider not in provider_stats:
|
||||||
|
provider_stats[provider] = {
|
||||||
|
"provider": provider,
|
||||||
|
"calls": 0,
|
||||||
|
"input_tokens": 0,
|
||||||
|
"output_tokens": 0,
|
||||||
|
"total_tokens": 0,
|
||||||
|
"cost": 0.0,
|
||||||
|
"total_latency_ms": 0.0,
|
||||||
|
"success_count": 0,
|
||||||
|
"models": set(),
|
||||||
|
}
|
||||||
|
p = provider_stats[provider]
|
||||||
|
p["calls"] += 1
|
||||||
|
p["input_tokens"] += e.get("input_tokens", 0)
|
||||||
|
p["output_tokens"] += e.get("output_tokens", 0)
|
||||||
|
p["total_tokens"] += e.get("total_tokens", 0)
|
||||||
|
p["cost"] += e.get("cost", 0)
|
||||||
|
p["total_latency_ms"] += e.get("latency_ms", 0)
|
||||||
|
p["models"].add(name)
|
||||||
|
if e.get("success"):
|
||||||
|
p["success_count"] += 1
|
||||||
|
|
||||||
|
# 计算平均延迟
|
||||||
|
for m in model_stats.values():
|
||||||
|
m["avg_latency_ms"] = round(m["total_latency_ms"] / m["calls"], 1) if m["calls"] > 0 else 0
|
||||||
|
m["success_rate"] = round(m["success_count"] / m["calls"] * 100, 1) if m["calls"] > 0 else 0
|
||||||
|
m["cost"] = round(m["cost"], 4)
|
||||||
|
|
||||||
|
for p in provider_stats.values():
|
||||||
|
p["avg_latency_ms"] = round(p["total_latency_ms"] / p["calls"], 1) if p["calls"] > 0 else 0
|
||||||
|
p["success_rate"] = round(p["success_count"] / p["calls"] * 100, 1) if p["calls"] > 0 else 0
|
||||||
|
p["cost"] = round(p["cost"], 4)
|
||||||
|
p["models"] = sorted(p["models"])
|
||||||
|
|
||||||
|
# 任务统计
|
||||||
|
status_dist: dict[str, int] = {}
|
||||||
|
total_duration = 0
|
||||||
|
for e in task_calls:
|
||||||
|
s = e.get("status", "unknown")
|
||||||
|
status_dist[s] = status_dist.get(s, 0) + 1
|
||||||
|
total_duration += e.get("duration_s", 0)
|
||||||
|
|
||||||
|
avg_duration = round(total_duration / len(task_calls), 1) if task_calls else 0
|
||||||
|
|
||||||
|
# 汇总
|
||||||
|
total_cost = sum(m["cost"] for m in model_stats.values())
|
||||||
|
total_tokens = sum(m["total_tokens"] for m in model_stats.values())
|
||||||
|
total_calls = sum(m["calls"] for m in model_stats.values())
|
||||||
|
|
||||||
|
return {
|
||||||
|
"period_hours": hours,
|
||||||
|
"model_stats": sorted(model_stats.values(), key=lambda x: x["cost"], reverse=True),
|
||||||
|
"provider_stats": sorted(provider_stats.values(), key=lambda x: x["cost"], reverse=True),
|
||||||
|
"task_stats": {
|
||||||
|
"total": len(task_calls),
|
||||||
|
"status_distribution": status_dist,
|
||||||
|
"avg_duration_s": avg_duration,
|
||||||
|
},
|
||||||
|
"totals": {
|
||||||
|
"model_calls": total_calls,
|
||||||
|
"total_tokens": total_tokens,
|
||||||
|
"total_cost": round(total_cost, 4),
|
||||||
|
"avg_latency_ms": round(
|
||||||
|
sum(m["total_latency_ms"] for m in model_stats.values()) / total_calls, 1
|
||||||
|
)
|
||||||
|
if total_calls > 0
|
||||||
|
else 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 趋势分析与成本预测(B2:用量深度分析)==========
|
||||||
|
|
||||||
|
|
||||||
|
def get_trend(days: int = 7) -> dict:
|
||||||
|
"""
|
||||||
|
按天聚合用量趋势(最近 N 天)。
|
||||||
|
|
||||||
|
【返回】
|
||||||
|
daily: [{date, calls, tokens, cost, avg_latency}]
|
||||||
|
providers: 按 Provider 的每日趋势
|
||||||
|
summary: 日均用量、峰值
|
||||||
|
"""
|
||||||
|
# 读取最近 N 天的数据(hours = days * 24)
|
||||||
|
entries = _read_metrics(days * 24)
|
||||||
|
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||||
|
|
||||||
|
# 按日期聚合
|
||||||
|
daily_map: dict[str, dict] = {}
|
||||||
|
provider_daily: dict[str, dict[str, dict]] = {}
|
||||||
|
|
||||||
|
for e in model_calls:
|
||||||
|
date = e.get("timestamp", "")[:10] # YYYY-MM-DD
|
||||||
|
if not date:
|
||||||
|
continue
|
||||||
|
provider = e.get("provider") or "unknown"
|
||||||
|
|
||||||
|
# 全局每日
|
||||||
|
if date not in daily_map:
|
||||||
|
daily_map[date] = {
|
||||||
|
"date": date,
|
||||||
|
"calls": 0,
|
||||||
|
"input_tokens": 0,
|
||||||
|
"output_tokens": 0,
|
||||||
|
"total_tokens": 0,
|
||||||
|
"cost": 0.0,
|
||||||
|
"total_latency_ms": 0.0,
|
||||||
|
}
|
||||||
|
d = daily_map[date]
|
||||||
|
d["calls"] += 1
|
||||||
|
d["input_tokens"] += e.get("input_tokens", 0)
|
||||||
|
d["output_tokens"] += e.get("output_tokens", 0)
|
||||||
|
d["total_tokens"] += e.get("total_tokens", 0)
|
||||||
|
d["cost"] += e.get("cost", 0)
|
||||||
|
d["total_latency_ms"] += e.get("latency_ms", 0)
|
||||||
|
|
||||||
|
# 按 Provider 每日
|
||||||
|
if provider not in provider_daily:
|
||||||
|
provider_daily[provider] = {}
|
||||||
|
if date not in provider_daily[provider]:
|
||||||
|
provider_daily[provider][date] = {
|
||||||
|
"date": date,
|
||||||
|
"calls": 0,
|
||||||
|
"tokens": 0,
|
||||||
|
"cost": 0.0,
|
||||||
|
}
|
||||||
|
pd = provider_daily[provider][date]
|
||||||
|
pd["calls"] += 1
|
||||||
|
pd["tokens"] += e.get("total_tokens", 0)
|
||||||
|
pd["cost"] += e.get("cost", 0)
|
||||||
|
|
||||||
|
# 转列表并排序
|
||||||
|
daily = sorted(daily_map.values(), key=lambda x: x["date"])
|
||||||
|
for d in daily:
|
||||||
|
d["cost"] = round(d["cost"], 4)
|
||||||
|
d["avg_latency_ms"] = round(d["total_latency_ms"] / d["calls"], 1) if d["calls"] else 0
|
||||||
|
|
||||||
|
# Provider 趋势
|
||||||
|
provider_trend = []
|
||||||
|
for prov, day_map in provider_daily.items():
|
||||||
|
days_list = sorted(day_map.values(), key=lambda x: x["date"])
|
||||||
|
for item in days_list:
|
||||||
|
item["cost"] = round(item["cost"], 4)
|
||||||
|
provider_trend.append({"provider": prov, "daily": days_list})
|
||||||
|
|
||||||
|
# 日均与峰值
|
||||||
|
if daily:
|
||||||
|
avg_cost = sum(d["cost"] for d in daily) / len(daily)
|
||||||
|
avg_calls = sum(d["calls"] for d in daily) / len(daily)
|
||||||
|
peak_day = max(daily, key=lambda x: x["cost"])
|
||||||
|
else:
|
||||||
|
avg_cost = avg_calls = 0
|
||||||
|
peak_day = None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"period_days": days,
|
||||||
|
"daily": daily,
|
||||||
|
"provider_trend": provider_trend,
|
||||||
|
"summary": {
|
||||||
|
"avg_daily_cost": round(avg_cost, 4),
|
||||||
|
"avg_daily_calls": round(avg_calls, 1),
|
||||||
|
"peak_day": peak_day,
|
||||||
|
"total_days": len(daily),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_cost_forecast(days: int = 7) -> dict:
|
||||||
|
"""
|
||||||
|
基于最近 N 天用量预测未来 30 天成本。
|
||||||
|
|
||||||
|
【算法】按日均成本线性外推 + 最近 3 天加权平均(近期趋势权重高)。
|
||||||
|
"""
|
||||||
|
entries = _read_metrics(days * 24)
|
||||||
|
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||||
|
|
||||||
|
daily_cost: dict[str, float] = {}
|
||||||
|
for e in model_calls:
|
||||||
|
date = e.get("timestamp", "")[:10]
|
||||||
|
if date:
|
||||||
|
daily_cost[date] = daily_cost.get(date, 0) + e.get("cost", 0)
|
||||||
|
|
||||||
|
if not daily_cost:
|
||||||
|
return {
|
||||||
|
"forecast_30d": 0,
|
||||||
|
"avg_daily_cost": 0,
|
||||||
|
"basis_days": 0,
|
||||||
|
"note": "暂无用量数据",
|
||||||
|
}
|
||||||
|
|
||||||
|
dates = sorted(daily_cost.keys())
|
||||||
|
total_cost = sum(daily_cost.values())
|
||||||
|
avg_daily = total_cost / len(dates)
|
||||||
|
|
||||||
|
# 最近 3 天加权平均(近期权重 0.6,历史 0.4)
|
||||||
|
recent_dates = dates[-3:]
|
||||||
|
recent_avg = sum(daily_cost[d] for d in recent_dates) / len(recent_dates)
|
||||||
|
weighted_daily = recent_avg * 0.6 + avg_daily * 0.4
|
||||||
|
|
||||||
|
forecast_30d = weighted_daily * 30
|
||||||
|
|
||||||
|
return {
|
||||||
|
"forecast_30d": round(forecast_30d, 2),
|
||||||
|
"avg_daily_cost": round(avg_daily, 4),
|
||||||
|
"recent_daily_cost": round(recent_avg, 4),
|
||||||
|
"weighted_daily_cost": round(weighted_daily, 4),
|
||||||
|
"basis_days": len(dates),
|
||||||
|
"date_range": {"start": dates[0], "end": dates[-1]},
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
平台用量定时抓取调度器
|
||||||
|
=====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
可配置的定时任务:按设定间隔自动抓取平台用量数据。
|
||||||
|
支持手动触发、停止、查看运行状态。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. asyncio 后台任务:无需外部调度器(APScheduler 等);
|
||||||
|
2. 配置存 SQLite:可持久化、可 API 修改;
|
||||||
|
3. 抓取用 asyncio.to_thread 包裹:Playwright 同步 API 不占用事件循环。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- PlatformScheduler 单例:启动时读配置,后台循环判断是否到点;
|
||||||
|
- 到点 → asyncio.to_thread(scrape_all_accounts) → 记录结果;
|
||||||
|
- 配置变更 → 即时生效(重启循环)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:同步抓取阻塞事件循环。
|
||||||
|
应对:asyncio.to_thread 在线程池执行同步抓取。
|
||||||
|
风险2:服务器重启后定时任务丢失。
|
||||||
|
应对:应用启动时自动恢复调度器(若配置为 enabled)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.platform_scheduler")
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformScheduler:
|
||||||
|
"""平台用量定时抓取调度器"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._task: asyncio.Task | None = None
|
||||||
|
self._running = False
|
||||||
|
self._last_trigger: float = 0.0
|
||||||
|
|
||||||
|
def is_running(self) -> bool:
|
||||||
|
"""调度器是否正在运行。"""
|
||||||
|
return self._running and self._task is not None and not self._task.done()
|
||||||
|
|
||||||
|
async def start(self) -> dict:
|
||||||
|
"""启动调度器(后台循环)。"""
|
||||||
|
if self.is_running():
|
||||||
|
return {"success": True, "message": "调度器已在运行"}
|
||||||
|
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
config = store.get_schedule()
|
||||||
|
if not config.get("enabled"):
|
||||||
|
return {"success": False, "message": "定时抓取未启用,请先在配置中开启"}
|
||||||
|
|
||||||
|
self._running = True
|
||||||
|
self._task = asyncio.create_task(self._loop())
|
||||||
|
logger.info("定时抓取调度器已启动(间隔 %d 分钟)", config.get("interval_minutes", 360))
|
||||||
|
return {"success": True, "message": "调度器已启动"}
|
||||||
|
|
||||||
|
async def stop(self) -> dict:
|
||||||
|
"""停止调度器。"""
|
||||||
|
self._running = False
|
||||||
|
if self._task and not self._task.done():
|
||||||
|
self._task.cancel()
|
||||||
|
try:
|
||||||
|
await self._task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
self._task = None
|
||||||
|
logger.info("定时抓取调度器已停止")
|
||||||
|
return {"success": True, "message": "调度器已停止"}
|
||||||
|
|
||||||
|
async def trigger_now(self) -> dict:
|
||||||
|
"""立即触发一次抓取(不等定时)。"""
|
||||||
|
if self._last_trigger and (
|
||||||
|
datetime.now().timestamp() - self._last_trigger < 30
|
||||||
|
):
|
||||||
|
return {"success": False, "message": "30 秒内已触发过,请稍后再试"}
|
||||||
|
|
||||||
|
self._last_trigger = datetime.now().timestamp()
|
||||||
|
logger.info("手动触发定时抓取")
|
||||||
|
result = await asyncio.to_thread(self._scrape_once)
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def _loop(self) -> None:
|
||||||
|
"""后台循环:按间隔判断是否到点并执行抓取。"""
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
last_run = datetime.now().timestamp()
|
||||||
|
|
||||||
|
while self._running:
|
||||||
|
try:
|
||||||
|
config = store.get_schedule()
|
||||||
|
if not config.get("enabled"):
|
||||||
|
logger.info("定时抓取已停用,调度器退出")
|
||||||
|
break
|
||||||
|
|
||||||
|
interval_seconds = max(
|
||||||
|
60, int(config.get("interval_minutes", 360)) * 60
|
||||||
|
)
|
||||||
|
now = datetime.now().timestamp()
|
||||||
|
|
||||||
|
if now - last_run >= interval_seconds:
|
||||||
|
logger.info("定时抓取触发(间隔 %d 分钟)", config["interval_minutes"])
|
||||||
|
result = await asyncio.to_thread(self._scrape_once)
|
||||||
|
store.record_schedule_run(result.get("message", ""))
|
||||||
|
last_run = now
|
||||||
|
|
||||||
|
await asyncio.sleep(30) # 每 30 秒检查一次是否到点
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
break
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("调度器循环异常:%s", exc)
|
||||||
|
await asyncio.sleep(60)
|
||||||
|
|
||||||
|
def _scrape_once(self) -> dict:
|
||||||
|
"""执行一次抓取(同步,在线程池中运行)。"""
|
||||||
|
from app.services.platform_scraper import scrape_all_accounts
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
config = store.get_schedule()
|
||||||
|
account_ids = config.get("account_ids", [])
|
||||||
|
|
||||||
|
try:
|
||||||
|
if account_ids:
|
||||||
|
# 只抓指定账号
|
||||||
|
results = []
|
||||||
|
for aid in account_ids:
|
||||||
|
from app.services.platform_scraper import scrape_usage
|
||||||
|
|
||||||
|
r = scrape_usage(aid)
|
||||||
|
results.append({"account_id": aid, **r})
|
||||||
|
else:
|
||||||
|
# 抓所有激活账号
|
||||||
|
results = scrape_all_accounts()
|
||||||
|
|
||||||
|
success = sum(1 for r in results if r.get("success"))
|
||||||
|
message = f"定时抓取完成:成功 {success}/{len(results)}"
|
||||||
|
logger.info(message)
|
||||||
|
return {"success": True, "message": message, "results": results}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
message = f"定时抓取失败:{exc}"
|
||||||
|
logger.warning(message)
|
||||||
|
return {"success": False, "message": message}
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_scheduler: PlatformScheduler | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_scheduler() -> PlatformScheduler:
|
||||||
|
global _scheduler
|
||||||
|
if _scheduler is None:
|
||||||
|
_scheduler = PlatformScheduler()
|
||||||
|
return _scheduler
|
||||||
@@ -0,0 +1,590 @@
|
|||||||
|
"""
|
||||||
|
平台用量抓取服务(Playwright 自动化)
|
||||||
|
====================================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
用 Playwright 内置浏览器打开平台控制台,登录后保存 Cookie,
|
||||||
|
之后用 Cookie 自动抓取用量数据(多账号多套餐并行)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. Playwright:能渲染 JS SPA(小米/火山控制台都是 React/Vue);
|
||||||
|
2. Cookie 持久化:登录一次,之后自动复用;
|
||||||
|
3. 无头模式:正式抓取用 headless,登录时用有头模式。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- login_and_save_cookies():打开浏览器让你登录,登录后保存 Cookie;
|
||||||
|
- scrape_usage():用 Cookie 后台抓取用量页面并解析;
|
||||||
|
- 多账号串行执行(避免并发浏览器吃内存)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:平台改版导致 CSS 选择器失效。
|
||||||
|
应对:解析失败时截图保存 + 返回页面文本供人工分析;
|
||||||
|
风险2:Cookie 过期。
|
||||||
|
应对:抓取时检测登录态,失效则提示重新登录;
|
||||||
|
风险3:页面加载慢。
|
||||||
|
应对:等待 networkidle + 显式等待关键元素,超时 30s。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.platform_scraper")
|
||||||
|
|
||||||
|
# 浏览器内核路径(已下载到 D 盘)
|
||||||
|
BROWSERS_PATH = Path(r"D:\Agent\agent\data\pw-browsers")
|
||||||
|
SCREENSHOT_DIR = Path(r"D:\Agent\agent\data\platform_screenshots")
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_browsers_env() -> None:
|
||||||
|
"""确保 Playwright 浏览器路径指向 D 盘。"""
|
||||||
|
os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", str(BROWSERS_PATH))
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 登录会话管理(两步式:打开浏览器 → 用户点完成 → 保存)==========
|
||||||
|
|
||||||
|
# 登录会话:account_id → {playwright, browser, context, page, initial_url, started_at}
|
||||||
|
_login_sessions: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def start_login(account_id: str, console_url: str) -> dict:
|
||||||
|
"""
|
||||||
|
第一步:打开浏览器(保持存活,等用户点「登录完成」)。
|
||||||
|
|
||||||
|
【改进】不再等待超时,浏览器一直开着,直到 finish_login 被调用。
|
||||||
|
"""
|
||||||
|
_ensure_browsers_env()
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
# 如果该账号已有活跃会话,先关闭
|
||||||
|
if account_id in _login_sessions:
|
||||||
|
finish_login(account_id, save=False)
|
||||||
|
|
||||||
|
try:
|
||||||
|
pw = sync_playwright().start()
|
||||||
|
browser = pw.chromium.launch(headless=False)
|
||||||
|
context = browser.new_context(
|
||||||
|
viewport={"width": 1400, "height": 900},
|
||||||
|
locale="zh-CN",
|
||||||
|
)
|
||||||
|
page = context.new_page()
|
||||||
|
page.goto(console_url, timeout=30000)
|
||||||
|
|
||||||
|
_login_sessions[account_id] = {
|
||||||
|
"pw": pw,
|
||||||
|
"browser": browser,
|
||||||
|
"context": context,
|
||||||
|
"page": page,
|
||||||
|
"initial_url": page.url,
|
||||||
|
"started_at": datetime.now().astimezone().isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("登录浏览器已打开(account=%s),等待用户完成登录", account_id)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": "浏览器已打开,请在浏览器中完成登录,完成后点击「登录完成」",
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"打开浏览器失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def finish_login(account_id: str, save: bool = True) -> dict:
|
||||||
|
"""
|
||||||
|
第二步:保存 Cookie + localStorage,关闭浏览器。
|
||||||
|
|
||||||
|
【参数】save=True 正常保存;False 表示取消登录(不保存)。
|
||||||
|
"""
|
||||||
|
session = _login_sessions.pop(account_id, None)
|
||||||
|
if session is None:
|
||||||
|
return {"success": False, "message": "没有进行中的登录会话"}
|
||||||
|
|
||||||
|
cookies: list = []
|
||||||
|
local_storage: dict = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
cookies = session["context"].cookies()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
cookies = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw = session["page"].evaluate("() => JSON.stringify(localStorage)")
|
||||||
|
local_storage = json.loads(raw) if raw else {}
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 关闭浏览器
|
||||||
|
try:
|
||||||
|
session["browser"].close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
session["pw"].stop()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not save:
|
||||||
|
return {"success": True, "message": "登录会话已取消"}
|
||||||
|
|
||||||
|
if not cookies and not local_storage:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "未获取到登录态,请确认已在浏览器中完成登录",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 保存到数据库
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
session_data = {"cookies": cookies, "local_storage": local_storage}
|
||||||
|
store.save_cookies(account_id, json.dumps(session_data, ensure_ascii=False))
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"登录态已保存(account=%s,Cookie %d 个 + localStorage %d 项)",
|
||||||
|
account_id,
|
||||||
|
len(cookies),
|
||||||
|
len(local_storage),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"登录态已保存(Cookie {len(cookies)} 个)",
|
||||||
|
"cookie_count": len(cookies),
|
||||||
|
"local_storage_count": len(local_storage),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def login_and_save_cookies(
|
||||||
|
console_url: str,
|
||||||
|
account_id: str,
|
||||||
|
timeout_seconds: int = 180,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
兼容旧接口:一步式登录(内部调用两步式)。
|
||||||
|
"""
|
||||||
|
start_result = start_login(account_id, console_url)
|
||||||
|
if not start_result.get("success"):
|
||||||
|
return start_result
|
||||||
|
|
||||||
|
# 等待一段时间后自动保存(兼容旧调用方)
|
||||||
|
import time
|
||||||
|
|
||||||
|
time.sleep(min(timeout_seconds, 30))
|
||||||
|
return finish_login(account_id)
|
||||||
|
|
||||||
|
|
||||||
|
def scrape_usage(account_id: str, timeout_seconds: int = 30) -> dict:
|
||||||
|
"""
|
||||||
|
用已保存的 Cookie 后台抓取用量数据。
|
||||||
|
|
||||||
|
【策略】
|
||||||
|
1. 加载 Cookie → 打开控制台 URL;
|
||||||
|
2. 等待页面渲染完成(含 JS 动态内容)→ 截图保存;
|
||||||
|
3. 多策略提取页面文本 → 解析用量数据;
|
||||||
|
4. 保存用量快照 + 原始文本(供调试)。
|
||||||
|
"""
|
||||||
|
_ensure_browsers_env()
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
account = store.get_with_cookies(account_id)
|
||||||
|
if not account:
|
||||||
|
return {"success": False, "message": f"账号不存在:{account_id}"}
|
||||||
|
if not account.get("cookies"):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "该账号尚未登录,请先执行「登录」保存 Cookie",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = json.loads(account["cookies"])
|
||||||
|
# 兼容旧格式(纯 Cookie 数组)与新格式({cookies, local_storage})
|
||||||
|
if isinstance(session, list):
|
||||||
|
cookies = session
|
||||||
|
local_storage = {}
|
||||||
|
else:
|
||||||
|
cookies = session.get("cookies", [])
|
||||||
|
local_storage = session.get("local_storage", {})
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return {"success": False, "message": "Cookie 格式损坏,请重新登录"}
|
||||||
|
|
||||||
|
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
screenshot_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.png"
|
||||||
|
|
||||||
|
with sync_playwright() as p:
|
||||||
|
browser = p.chromium.launch(headless=True)
|
||||||
|
context = browser.new_context(
|
||||||
|
viewport={"width": 1400, "height": 900},
|
||||||
|
locale="zh-CN",
|
||||||
|
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
|
)
|
||||||
|
context.add_cookies(cookies)
|
||||||
|
page = context.new_page()
|
||||||
|
|
||||||
|
# 恢复 localStorage(有些站点用 token 存在这里)
|
||||||
|
if local_storage:
|
||||||
|
try:
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
storage_script = (
|
||||||
|
"localStorage.clear();"
|
||||||
|
+ "".join(
|
||||||
|
f"localStorage.setItem({json.dumps(k)}, {json.dumps(v)});"
|
||||||
|
for k, v in local_storage.items()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
page.add_init_script(storage_script)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
page.goto(account["console_url"], timeout=30000)
|
||||||
|
|
||||||
|
# 关键改进:等待 JS 渲染完成(SPA 需要额外时间)
|
||||||
|
try:
|
||||||
|
page.wait_for_load_state("networkidle", timeout=timeout_seconds * 1000)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
# 额外等待 3 秒让动态内容渲染
|
||||||
|
page.wait_for_timeout(3000)
|
||||||
|
|
||||||
|
# 尝试等待页面出现文本内容
|
||||||
|
try:
|
||||||
|
page.wait_for_function(
|
||||||
|
"document.body.innerText.length > 100",
|
||||||
|
timeout=10000,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 截图
|
||||||
|
page.screenshot(path=str(screenshot_path), full_page=True)
|
||||||
|
|
||||||
|
# 多策略提取文本
|
||||||
|
page_text = ""
|
||||||
|
try:
|
||||||
|
page_text = page.inner_text("body")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
if not page_text or len(page_text) < 50:
|
||||||
|
# 降级:从 HTML 提取
|
||||||
|
try:
|
||||||
|
html = page.content()
|
||||||
|
import re as _re
|
||||||
|
|
||||||
|
clean = _re.sub(r"<(script|style)[^>]*>.*?</\1>", "", html, flags=_re.DOTALL)
|
||||||
|
clean = _re.sub(r"<[^>]+>", " ", clean)
|
||||||
|
page_text = _re.sub(r"\s+", " ", clean)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 保存原始文本(供调试)
|
||||||
|
text_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.txt"
|
||||||
|
try:
|
||||||
|
text_path.write_text(page_text[:20000], encoding="utf-8")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
# 关键改进:检测是否在登录页(Cookie 失效)
|
||||||
|
login_keywords = ["登录", "注册", "忘记密码", "立即登录", "请登录", "未登录", "Login"]
|
||||||
|
is_login_page = any(kw in page_text[:500] for kw in login_keywords)
|
||||||
|
if is_login_page and not any(
|
||||||
|
kw in page_text for kw in ["退出登录", "个人中心", "用户中心"]
|
||||||
|
):
|
||||||
|
# 记录登录过期(供前端右上角提示)
|
||||||
|
_record_login_expired(
|
||||||
|
account_id,
|
||||||
|
account.get("brand", ""),
|
||||||
|
account.get("account_name", ""),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "Cookie 已过期或未登录,请重新执行「登录」",
|
||||||
|
"screenshot": str(screenshot_path),
|
||||||
|
"page_text_preview": page_text[:300],
|
||||||
|
}
|
||||||
|
|
||||||
|
# 解析用量数据
|
||||||
|
usage_data = _parse_usage_text(page_text, account["brand"])
|
||||||
|
usage_data["raw_text_preview"] = page_text[:300]
|
||||||
|
|
||||||
|
# 保存快照
|
||||||
|
snapshot = store.save_snapshot(account_id, usage_data)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"抓取完成({account['brand']}-{account['account_name']})",
|
||||||
|
"usage": usage_data,
|
||||||
|
"screenshot": str(screenshot_path),
|
||||||
|
"snapshot_id": snapshot["id"],
|
||||||
|
"page_text_length": len(page_text),
|
||||||
|
"page_text_preview": page_text[:500],
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
try:
|
||||||
|
browser.close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return {"success": False, "message": f"抓取失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_usage_text(text: str, brand: str) -> dict:
|
||||||
|
"""
|
||||||
|
从页面文本中解析用量数据(按指标名精确提取)。
|
||||||
|
|
||||||
|
【火山引擎式布局】指标名 → 重置信息 → 数值独占一行 → % → 坐标轴标签
|
||||||
|
【小米式布局】直接用文字描述(如「已用 45%」)
|
||||||
|
|
||||||
|
【提取指标】
|
||||||
|
- 剩余时间(如「25天」)
|
||||||
|
- 近5小时用量
|
||||||
|
- 近一周用量
|
||||||
|
- 近一月用量
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
|
||||||
|
usage_percent = 0.0
|
||||||
|
used_amount = ""
|
||||||
|
total_amount = ""
|
||||||
|
remain_amount = ""
|
||||||
|
expire_date = ""
|
||||||
|
usage_5h = ""
|
||||||
|
usage_1w = ""
|
||||||
|
usage_1m = ""
|
||||||
|
|
||||||
|
lines = text.splitlines()
|
||||||
|
lines_stripped = [l.strip() for l in lines]
|
||||||
|
|
||||||
|
def _find_value_after_label(label: str, max_lookahead: int = 6) -> str:
|
||||||
|
"""
|
||||||
|
在文本行中找标签,然后往后扫描找数值(跳过「重置」等中间行)。
|
||||||
|
【布局】标签 → [重置信息] → 数值 → % → 坐标轴标签
|
||||||
|
"""
|
||||||
|
for i, line in enumerate(lines_stripped):
|
||||||
|
if label in line:
|
||||||
|
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
|
||||||
|
candidate = lines_stripped[j]
|
||||||
|
if not candidate:
|
||||||
|
continue
|
||||||
|
if any(kw in candidate for kw in ["重置", "即将", "后重置"]):
|
||||||
|
continue
|
||||||
|
if candidate == "%":
|
||||||
|
continue
|
||||||
|
if candidate in ("0%", "50%", "100%"):
|
||||||
|
continue
|
||||||
|
if re.match(r"^[\d,\.]+\s*(%|天|日|月|小时|个)?$", candidate):
|
||||||
|
return candidate
|
||||||
|
if re.match(r"^[\d,\.]+", candidate):
|
||||||
|
return candidate
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def _find_reset_after_label(label: str, max_lookahead: int = 6) -> str:
|
||||||
|
"""
|
||||||
|
找标签后的「重置时间」信息(如「即将重置」「5天9小时后重置」)。
|
||||||
|
"""
|
||||||
|
for i, line in enumerate(lines_stripped):
|
||||||
|
if label in line:
|
||||||
|
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
|
||||||
|
candidate = lines_stripped[j]
|
||||||
|
if not candidate:
|
||||||
|
continue
|
||||||
|
# 匹配重置时间模式
|
||||||
|
if "重置" in candidate:
|
||||||
|
return candidate
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# 提取「剩余时间」
|
||||||
|
remain_time = _find_value_after_label("剩余时间")
|
||||||
|
if remain_time:
|
||||||
|
remain_amount = remain_time
|
||||||
|
|
||||||
|
# 提取「近5小时用量」及其重置时间
|
||||||
|
usage_5h = _find_value_after_label("近5小时用量")
|
||||||
|
reset_5h = _find_reset_after_label("近5小时用量")
|
||||||
|
|
||||||
|
# 提取「近一周用量」及其重置时间
|
||||||
|
usage_1w = _find_value_after_label("近一周用量")
|
||||||
|
reset_1w = _find_reset_after_label("近一周用量")
|
||||||
|
|
||||||
|
# 提取「近一月用量」及其重置时间
|
||||||
|
usage_1m = _find_value_after_label("近一月用量")
|
||||||
|
reset_1m = _find_reset_after_label("近一月用量")
|
||||||
|
|
||||||
|
# 主用量百分比:优先取近一月 > 近一周 > 近5小时
|
||||||
|
for val in [usage_1m, usage_1w, usage_5h]:
|
||||||
|
m = re.match(r"([\d\.]+)", val or "")
|
||||||
|
if m:
|
||||||
|
usage_percent = float(m.group(1))
|
||||||
|
break
|
||||||
|
|
||||||
|
# 通用模式补充(兼容小米等其他平台)
|
||||||
|
if not any([usage_5h, usage_1w, usage_1m]):
|
||||||
|
# 小米式:「已用 45%」
|
||||||
|
pct_with_label = re.search(
|
||||||
|
r"(?:已用|使用|已消耗|用量|used)[^%\n]{0,20}?(\d+(?:\.\d+)?)\s*%", text, re.IGNORECASE
|
||||||
|
)
|
||||||
|
if pct_with_label:
|
||||||
|
usage_percent = float(pct_with_label.group(1))
|
||||||
|
else:
|
||||||
|
pct_matches = re.findall(r"(\d+(?:\.\d+)?)\s*%", text)
|
||||||
|
real_pcts = [float(p) for p in pct_matches if float(p) not in (0, 50, 100)]
|
||||||
|
if real_pcts:
|
||||||
|
usage_percent = real_pcts[0]
|
||||||
|
|
||||||
|
# 小米式:「当前套餐用量」后的「X / Y」分数(已用/总量)
|
||||||
|
xiaomi_fraction = re.search(
|
||||||
|
r"当前套餐用量\s*\n\s*([\d,]+)\s*/\s*([\d,]+)", text
|
||||||
|
)
|
||||||
|
if xiaomi_fraction:
|
||||||
|
used_amount = xiaomi_fraction.group(1).strip()
|
||||||
|
total_amount = xiaomi_fraction.group(2).strip()
|
||||||
|
# 计算剩余
|
||||||
|
try:
|
||||||
|
used_val = int(used_amount.replace(",", ""))
|
||||||
|
total_val = int(total_amount.replace(",", ""))
|
||||||
|
remain_val = total_val - used_val
|
||||||
|
remain_amount = f"{remain_val:,}"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 小米式:「Token 总消耗」后的数量
|
||||||
|
if not used_amount:
|
||||||
|
token_total = re.search(
|
||||||
|
r"Token\s*总消耗\s*\n\s*([\d,]+)\s*(?:Tokens?)?", text
|
||||||
|
)
|
||||||
|
if token_total:
|
||||||
|
used_amount = token_total.group(1).strip() + " Tokens"
|
||||||
|
|
||||||
|
# 分数形式(通用)
|
||||||
|
if not used_amount:
|
||||||
|
fraction = re.search(r"([\d,\.]+)\s*/\s*([\d,\.]+)", text)
|
||||||
|
if fraction:
|
||||||
|
used_amount = fraction.group(1)
|
||||||
|
total_amount = fraction.group(2)
|
||||||
|
|
||||||
|
# Token 数量(通用)
|
||||||
|
if not used_amount:
|
||||||
|
token_match = re.search(r"([\d,\.]+)\s*(?:tokens?|tok)", text, re.IGNORECASE)
|
||||||
|
if token_match:
|
||||||
|
used_amount = token_match.group(1)
|
||||||
|
|
||||||
|
# 小米式:「有效期至」日期(如「有效期至 2026-11-13 23:59:59 (UTC)」)
|
||||||
|
valid_until_match = re.search(r"有效期至\s*(\d{4}-\d{2}-\d{2})", text)
|
||||||
|
valid_until = valid_until_match.group(1) if valid_until_match else ""
|
||||||
|
|
||||||
|
# 到期日期(优先取「结束时间」后的日期)
|
||||||
|
expire_match = re.search(
|
||||||
|
r"(?:结束时间|到期|截止|expire|end)[:\s]*(\d{4}-\d{2}-\d{2})", text, re.IGNORECASE
|
||||||
|
)
|
||||||
|
if expire_match:
|
||||||
|
expire_date = expire_match.group(1)
|
||||||
|
elif valid_until:
|
||||||
|
expire_date = valid_until
|
||||||
|
else:
|
||||||
|
all_dates = re.findall(r"(\d{4}-\d{2}-\d{2})", text)
|
||||||
|
if all_dates:
|
||||||
|
expire_date = all_dates[-1]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"usage_percent": usage_percent,
|
||||||
|
"used_amount": used_amount,
|
||||||
|
"total_amount": total_amount,
|
||||||
|
"remain_amount": remain_amount,
|
||||||
|
"expire_date": expire_date,
|
||||||
|
"valid_until": valid_until,
|
||||||
|
"usage_5h": usage_5h,
|
||||||
|
"usage_1w": usage_1w,
|
||||||
|
"usage_1m": usage_1m,
|
||||||
|
"reset_5h": reset_5h,
|
||||||
|
"reset_1w": reset_1w,
|
||||||
|
"reset_1m": reset_1m,
|
||||||
|
"brand": brand,
|
||||||
|
"raw_data": {
|
||||||
|
"text_length": len(text),
|
||||||
|
"text_preview": text[:500],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 抓取进度追踪 ==========
|
||||||
|
|
||||||
|
# 全局进度:{running, total, completed, current_account, results, started_at}
|
||||||
|
_scrape_progress: dict[str, Any] = {
|
||||||
|
"running": False,
|
||||||
|
"total": 0,
|
||||||
|
"completed": 0,
|
||||||
|
"current_account": "",
|
||||||
|
"results": [],
|
||||||
|
"started_at": "",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 登录过期追踪:account_id → {brand, account_name, detected_at}
|
||||||
|
_login_expired: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def get_scrape_progress() -> dict:
|
||||||
|
"""获取当前抓取进度(供前端轮询)。"""
|
||||||
|
return dict(_scrape_progress)
|
||||||
|
|
||||||
|
|
||||||
|
def get_login_expired() -> list[dict]:
|
||||||
|
"""获取登录过期的账号列表(供前端右上角提示)。"""
|
||||||
|
return [
|
||||||
|
{"account_id": aid, **info} for aid, info in _login_expired.items()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def clear_login_expired(account_id: str) -> None:
|
||||||
|
"""清除某账号的登录过期标记(重新登录后调用)。"""
|
||||||
|
_login_expired.pop(account_id, None)
|
||||||
|
|
||||||
|
|
||||||
|
def _record_login_expired(account_id: str, brand: str, account_name: str) -> None:
|
||||||
|
"""记录登录过期。"""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
_login_expired[account_id] = {
|
||||||
|
"brand": brand,
|
||||||
|
"account_name": account_name,
|
||||||
|
"detected_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
}
|
||||||
|
logger.warning("检测到登录过期:%s-%s", brand, account_name)
|
||||||
|
|
||||||
|
|
||||||
|
def scrape_all_accounts() -> list[dict]:
|
||||||
|
"""抓取所有已激活账号的用量(串行执行,带进度追踪)。"""
|
||||||
|
from app.store.platform_account_store import get_platform_store
|
||||||
|
|
||||||
|
store = get_platform_store()
|
||||||
|
accounts = [a for a in store.list_all() if a.get("is_active")]
|
||||||
|
total = len(accounts)
|
||||||
|
|
||||||
|
# 重置进度
|
||||||
|
_scrape_progress.update({
|
||||||
|
"running": True,
|
||||||
|
"total": total,
|
||||||
|
"completed": 0,
|
||||||
|
"current_account": "",
|
||||||
|
"results": [],
|
||||||
|
"started_at": datetime.now().astimezone().isoformat(),
|
||||||
|
})
|
||||||
|
|
||||||
|
results = []
|
||||||
|
try:
|
||||||
|
for account in accounts:
|
||||||
|
_scrape_progress["current_account"] = f"{account['brand']}-{account['account_name']}"
|
||||||
|
result = scrape_usage(account["id"])
|
||||||
|
results.append({"account_id": account["id"], "brand": account["brand"], **result})
|
||||||
|
_scrape_progress["results"] = list(results)
|
||||||
|
_scrape_progress["completed"] = len(results)
|
||||||
|
finally:
|
||||||
|
_scrape_progress["running"] = False
|
||||||
|
|
||||||
|
return results
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""
|
||||||
|
提示词优化服务
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
基于 prompt-polisher Skill 定义,把用户的粗糙/口语化/不完整想法
|
||||||
|
润色成结构清晰、无歧义、可直接发给 AI 执行的高质量提示词。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 直接读取 SKILL.md 作为 System Prompt,规则统一维护、可迭代;
|
||||||
|
2. 调用强模型执行润色,结果结构化返回(润色后 + 改动说明 + 待定问题)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- load_skill_prompt():读取 SKILL.md 内容;
|
||||||
|
- polish():组装 Prompt → 调模型 → 解析输出结构;
|
||||||
|
- 结果分为 polish_result / changes / questions 三部分。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:模型输出格式不符合预期。
|
||||||
|
应对:宽松解析(提取【润色后】【改了什么】【还需要你定】三个区块)。
|
||||||
|
风险2:SKILL.md 文件丢失或编码异常。
|
||||||
|
应对:启动时缓存,文件不存在时用内置简化规则兜底。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.prompt_polisher")
|
||||||
|
|
||||||
|
# Skill 文件路径
|
||||||
|
SKILL_PATH = Path(r"D:\Agent\SKILLS\prompt-polisher\SKILL.md")
|
||||||
|
|
||||||
|
# 内置兜底规则(SKILL.md 缺失时使用)
|
||||||
|
FALLBACK_RULES = """你是一个提示词润色专家。把用户的粗糙想法润色成高质量提示词。
|
||||||
|
|
||||||
|
铁律:只润色提示词本身,不执行任务。不分析项目、不写代码、不查文件。
|
||||||
|
|
||||||
|
输出格式:
|
||||||
|
【润色后】
|
||||||
|
(可直接复制的提示词)
|
||||||
|
|
||||||
|
【改了什么】
|
||||||
|
- 补了什么
|
||||||
|
- 去掉了什么歧义
|
||||||
|
|
||||||
|
【还需要你定】(如有)
|
||||||
|
- 问题 1:选项 A / 选项 B"""
|
||||||
|
|
||||||
|
|
||||||
|
def _load_skill_prompt() -> str:
|
||||||
|
"""读取 SKILL.md 作为系统提示词(缓存结果)。"""
|
||||||
|
try:
|
||||||
|
if SKILL_PATH.exists():
|
||||||
|
return SKILL_PATH.read_text(encoding="utf-8")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("读取 SKILL.md 失败:%s,使用内置规则", exc)
|
||||||
|
return FALLBACK_RULES
|
||||||
|
|
||||||
|
|
||||||
|
# 缓存(模块加载时读一次)
|
||||||
|
_SKILL_PROMPT: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_skill_prompt() -> str:
|
||||||
|
global _SKILL_PROMPT
|
||||||
|
if _SKILL_PROMPT is None:
|
||||||
|
_SKILL_PROMPT = _load_skill_prompt()
|
||||||
|
return _SKILL_PROMPT
|
||||||
|
|
||||||
|
|
||||||
|
def polish(text: str, model_preference: str = "auto") -> dict:
|
||||||
|
"""
|
||||||
|
优化用户输入的提示词。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
text:用户原始输入(粗糙/口语化的想法)
|
||||||
|
model_preference:模型偏好(auto=智能选)
|
||||||
|
【返回】{polish_result, changes, questions, model}
|
||||||
|
"""
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
|
||||||
|
if not text or not text.strip():
|
||||||
|
return {"success": False, "message": "请输入要优化的内容"}
|
||||||
|
|
||||||
|
system_prompt = _get_skill_prompt()
|
||||||
|
|
||||||
|
user_prompt = f"""请润色下面这段提示词:
|
||||||
|
|
||||||
|
{text}"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
model = get_model_for_task(model_preference, "strong")
|
||||||
|
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||||||
|
|
||||||
|
# 组装消息:System = Skill 规则,User = 用户原始输入
|
||||||
|
from langchain_core.messages import HumanMessage, SystemMessage
|
||||||
|
|
||||||
|
resp = model.invoke(
|
||||||
|
[
|
||||||
|
SystemMessage(content=system_prompt),
|
||||||
|
HumanMessage(content=user_prompt),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
output = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
|
||||||
|
# 宽松解析输出结构
|
||||||
|
polished, changes, questions = _parse_output(output)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"polish_result": polished or output,
|
||||||
|
"changes": changes,
|
||||||
|
"questions": questions,
|
||||||
|
"model": model_name,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("提示词优化失败")
|
||||||
|
return {"success": False, "message": f"优化失败:{exc}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_output(output: str) -> tuple[str, list[str], list[str]]:
|
||||||
|
"""
|
||||||
|
宽松解析润色输出:提取【润色后】【改了什么】【还需要你定】三个区块。
|
||||||
|
|
||||||
|
【容错】区块标题可能有轻微变体,用正则宽松匹配。
|
||||||
|
"""
|
||||||
|
polished = ""
|
||||||
|
changes: list[str] = []
|
||||||
|
questions: list[str] = []
|
||||||
|
|
||||||
|
# 提取【润色后】区块
|
||||||
|
m_polish = re.search(
|
||||||
|
r"【润色后】\s*\n(.*?)(?=【改了什么】|【还需要你定】|$)",
|
||||||
|
output,
|
||||||
|
re.DOTALL,
|
||||||
|
)
|
||||||
|
if m_polish:
|
||||||
|
polished = m_polish.group(1).strip()
|
||||||
|
# 去掉代码块包裹标记
|
||||||
|
polished = re.sub(r"^```[a-z]*\n?|```$", "", polished.strip(), flags=re.MULTILINE).strip()
|
||||||
|
|
||||||
|
# 提取【改了什么】
|
||||||
|
m_changes = re.search(
|
||||||
|
r"【改了什么】\s*\n(.*?)(?=【还需要你定】|【润色后】|$)",
|
||||||
|
output,
|
||||||
|
re.DOTALL,
|
||||||
|
)
|
||||||
|
if m_changes:
|
||||||
|
raw = m_changes.group(1).strip()
|
||||||
|
changes = [
|
||||||
|
re.sub(r"^[-•*]\s*", "", line.strip())
|
||||||
|
for line in raw.splitlines()
|
||||||
|
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||||||
|
]
|
||||||
|
|
||||||
|
# 提取【还需要你定】
|
||||||
|
m_questions = re.search(
|
||||||
|
r"【还需要你定】\s*\n(.*?)(?=【润色后】|【改了什么】|$)",
|
||||||
|
output,
|
||||||
|
re.DOTALL,
|
||||||
|
)
|
||||||
|
if m_questions:
|
||||||
|
raw = m_questions.group(1).strip()
|
||||||
|
questions = [
|
||||||
|
re.sub(r"^[-•*]\s*", "", line.strip())
|
||||||
|
for line in raw.splitlines()
|
||||||
|
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||||||
|
]
|
||||||
|
|
||||||
|
return polished, changes, questions
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
"""
|
||||||
|
任务模板服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】常用开发/修复模板管理,一键复用到任务提交。
|
||||||
|
【实现思路】模板存 SQLite,支持 CRUD + 分类 + 标签。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.template")
|
||||||
|
|
||||||
|
|
||||||
|
class TaskTemplate:
|
||||||
|
"""任务模板"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
id: str,
|
||||||
|
name: str,
|
||||||
|
category: str,
|
||||||
|
content: str,
|
||||||
|
description: str,
|
||||||
|
tags: list[str],
|
||||||
|
created_at: str,
|
||||||
|
updated_at: str,
|
||||||
|
):
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
self.category = category
|
||||||
|
self.content = content
|
||||||
|
self.description = description
|
||||||
|
self.tags = tags
|
||||||
|
self.created_at = created_at
|
||||||
|
self.updated_at = updated_at
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateStore:
|
||||||
|
"""任务模板存储"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
self._seed_defaults()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS task_template (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
category TEXT NOT NULL DEFAULT '通用',
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
tags TEXT DEFAULT '[]',
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def _seed_defaults(self) -> None:
|
||||||
|
"""首次初始化默认模板。"""
|
||||||
|
defaults = [
|
||||||
|
{
|
||||||
|
"name": "修复空指针异常",
|
||||||
|
"category": "Bug修复",
|
||||||
|
"content": "修复 {文件名} 中的空指针异常:当 {变量/参数} 为 null 时,应抛出 IllegalArgumentException 并给出明确错误信息,而不是 NPE。",
|
||||||
|
"description": "Java NPE 修复模板",
|
||||||
|
"tags": ["Java", "NPE", "异常处理"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "新增 REST API 接口",
|
||||||
|
"category": "功能开发",
|
||||||
|
"content": "在 {Controller} 中新增 {接口名} 接口:路径 /api/{path},方法 {GET/POST/PUT/DELETE},入参 {参数说明},返回 {返回结构}。遵循项目现有编码规范,添加中文注释。",
|
||||||
|
"description": "RESTful 接口开发模板",
|
||||||
|
"tags": ["API", "REST", "Controller"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "数据库表结构变更",
|
||||||
|
"category": "数据库",
|
||||||
|
"content": "在表 {表名} 中新增字段 {字段名}({类型},{约束}),并更新对应的 Entity/DTO/Mapper/Service 各层代码。确保兼容现有数据,添加默认值。",
|
||||||
|
"description": "数据库变更模板",
|
||||||
|
"tags": ["数据库", "DDL", "MyBatis"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "单元测试生成",
|
||||||
|
"category": "测试",
|
||||||
|
"content": "为 {类名/方法名} 生成完整的单元测试,覆盖正常场景、边界条件、异常场景。使用 JUnit 5 + Mockito,测试方法命名遵循 test_{方法名}_{场景} 规范。",
|
||||||
|
"description": "单元测试生成模板",
|
||||||
|
"tags": ["测试", "JUnit", "Mockito"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "代码重构优化",
|
||||||
|
"category": "重构",
|
||||||
|
"content": "重构 {类名/模块}:识别重复代码、过长方法、过大类,提取公共方法、应用设计模式(如策略/工厂),保持功能不变、测试通过。",
|
||||||
|
"description": "代码重构模板",
|
||||||
|
"tags": ["重构", "设计模式", "代码质量"],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
with self._conn() as conn:
|
||||||
|
count = conn.execute("SELECT COUNT(*) FROM task_template").fetchone()[0]
|
||||||
|
if count == 0:
|
||||||
|
for item in defaults:
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(f"tpl_{uuid.uuid4().hex[:12]}", item["name"], item["category"], item["content"], item["description"], str(item["tags"]), now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def _row_to_obj(self, row: sqlite3.Row) -> TaskTemplate:
|
||||||
|
import json as json_mod
|
||||||
|
tags = []
|
||||||
|
try:
|
||||||
|
tags = json_mod.loads(row["tags"] or "[]")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return TaskTemplate(
|
||||||
|
id=row["id"],
|
||||||
|
name=row["name"],
|
||||||
|
category=row["category"],
|
||||||
|
content=row["content"],
|
||||||
|
description=row["description"] or "",
|
||||||
|
tags=tags,
|
||||||
|
created_at=row["created_at"],
|
||||||
|
updated_at=row["updated_at"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_all(self, category: str = "") -> list[TaskTemplate]:
|
||||||
|
sql = "SELECT * FROM task_template"
|
||||||
|
params = []
|
||||||
|
if category:
|
||||||
|
sql += " WHERE category = ?"
|
||||||
|
params.append(category)
|
||||||
|
sql += " ORDER BY updated_at DESC"
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
return [self._row_to_obj(r) for r in rows]
|
||||||
|
|
||||||
|
def get(self, tpl_id: str) -> Optional[TaskTemplate]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM task_template WHERE id = ?", (tpl_id,)).fetchone()
|
||||||
|
return self._row_to_obj(row) if row else None
|
||||||
|
|
||||||
|
def create(self, name: str, category: str, content: str, description: str = "", tags: list[str] | None = None) -> TaskTemplate:
|
||||||
|
import json as json_mod
|
||||||
|
|
||||||
|
tpl_id = f"tpl_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(tpl_id, name, category, content, description, json_mod.dumps(tags or [], ensure_ascii=False), now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(tpl_id)
|
||||||
|
|
||||||
|
def update(self, tpl_id: str, **kwargs) -> Optional[TaskTemplate]:
|
||||||
|
import json as json_mod
|
||||||
|
|
||||||
|
allowed = {"name", "category", "content", "description", "tags"}
|
||||||
|
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||||
|
if not updates:
|
||||||
|
return self.get(tpl_id)
|
||||||
|
if "tags" in updates:
|
||||||
|
updates["tags"] = json_mod.dumps(updates["tags"], ensure_ascii=False)
|
||||||
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values()) + [tpl_id]
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(f"UPDATE task_template SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(tpl_id)
|
||||||
|
|
||||||
|
def delete(self, tpl_id: str) -> bool:
|
||||||
|
with self._conn() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM task_template WHERE id = ?", (tpl_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: TemplateStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_template_store() -> TemplateStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
settings = __import__("app.config.settings", fromlist=["load_settings"]).load_settings()
|
||||||
|
_store = TemplateStore(settings.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""
|
||||||
|
测试生成服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】为指定代码文件/类/方法自动生成单元测试。
|
||||||
|
对应功能 25:改码后自动补测试。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 强模型 + 代码上下文 → 生成 JUnit/Mockito 测试;
|
||||||
|
2. 可指定测试框架和覆盖场景。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.models.model_router import get_model_for_task
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.testgen")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_tests(
|
||||||
|
source_code: str,
|
||||||
|
file_name: str = "",
|
||||||
|
test_framework: str = "junit5",
|
||||||
|
model_preference: str = "auto",
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
为指定代码生成单元测试。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
source_code:Java 源代码
|
||||||
|
file_name:文件名(供生成测试类名)
|
||||||
|
test_framework:junit5 / mockito / spring
|
||||||
|
model_preference:模型偏好
|
||||||
|
"""
|
||||||
|
if not source_code.strip():
|
||||||
|
return {"success": False, "message": "请提供源代码"}
|
||||||
|
|
||||||
|
prompt = f"""你是资深 Java 测试工程师。请为下面的代码生成完整的单元测试。
|
||||||
|
|
||||||
|
【源文件】{file_name or '未命名'}
|
||||||
|
【测试框架】{test_framework}
|
||||||
|
|
||||||
|
【源代码】
|
||||||
|
```
|
||||||
|
{source_code[:8000]}
|
||||||
|
```
|
||||||
|
|
||||||
|
【要求】
|
||||||
|
1. 使用 {test_framework} 框架,测试类命名为 `{{原类名}}Test`
|
||||||
|
2. 覆盖:正常场景、边界条件、异常场景
|
||||||
|
3. 外部依赖用 Mockito mock
|
||||||
|
4. 每个测试方法命名:test_{{方法名}}_{{场景}}
|
||||||
|
5. 添加中文注释说明每个测试的意图
|
||||||
|
6. 直接输出完整测试代码,用 ```java 包裹"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
model = get_model_for_task(model_preference, "strong")
|
||||||
|
model_name = getattr(model, "model_name", None) or getattr(model, "model", "")
|
||||||
|
resp = model.invoke(prompt)
|
||||||
|
output = resp.content if hasattr(resp, "content") else str(resp)
|
||||||
|
|
||||||
|
# 提取代码块
|
||||||
|
import re
|
||||||
|
|
||||||
|
code_match = re.search(r"```java\s*\n(.*?)\n```", output, re.DOTALL)
|
||||||
|
test_code = code_match.group(1) if code_match else output
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"test_code": test_code,
|
||||||
|
"model": model_name,
|
||||||
|
"file_name": file_name,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("测试生成失败")
|
||||||
|
return {"success": False, "message": f"测试生成失败:{exc}"}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""
|
||||||
|
图片识别服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】调用智谱 GLM-4V-Flash 识别图片内容(Bug 截图、UI 稿、日志截图等),
|
||||||
|
供任务提交时自动分析图片附件,把图片内容附加到需求描述。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选智谱 GLM-4V-Flash:完全免费、中文效果好、OpenAI 兼容口;
|
||||||
|
2. 不依赖 langchain-openai:智谱走自己的 OpenAI 兼容协议,直接 httpx 调用更轻量。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- analyze_image():base64 编码图片 → 调 GLM-4V-Flash → 返回文字描述;
|
||||||
|
- analyze_images():批量分析多张图片,合并结果。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:图片过大/格式不支持。
|
||||||
|
应对:前端限 10MB + 格式校验;后端 base64 编码前检查大小。
|
||||||
|
风险2:API 超时/限流。
|
||||||
|
应对:超时 30 秒 + 失败返回空字符串(不阻塞任务提交)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.vision")
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_image(image_path: str | Path, prompt: str = "") -> str:
|
||||||
|
"""
|
||||||
|
识别图片内容。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
image_path:图片文件路径(需在 D 盘可访问范围内)
|
||||||
|
prompt:可选自定义提示词(默认让模型描述图片内容)
|
||||||
|
【返回】图片内容的文字描述(失败返回空字符串,不抛异常)
|
||||||
|
"""
|
||||||
|
path = Path(image_path)
|
||||||
|
if not path.exists():
|
||||||
|
logger.warning("图片文件不存在:%s", path)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# 检查大小(20MB 限制,base64 后更大)
|
||||||
|
if path.stat().st_size > 20 * 1024 * 1024:
|
||||||
|
logger.warning("图片过大:%s(%.1fMB)", path, path.stat().st_size / 1024 / 1024)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
image_b64 = base64.b64encode(path.read_bytes()).decode("utf-8")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("图片读取失败:%s %s", path, exc)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# 根据扩展名确定 MIME 类型
|
||||||
|
ext = path.suffix.lower()
|
||||||
|
mime_map = {
|
||||||
|
".png": "image/png",
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".gif": "image/gif",
|
||||||
|
".bmp": "image/bmp",
|
||||||
|
".webp": "image/webp",
|
||||||
|
}
|
||||||
|
mime = mime_map.get(ext, "image/png")
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
api_key = settings.zhipu_api_key
|
||||||
|
base_url = settings.zhipu_base_url
|
||||||
|
model = settings.zhipu_vision_model or "glm-4v-flash"
|
||||||
|
|
||||||
|
if not api_key:
|
||||||
|
logger.warning("未配置智谱 API Key,跳过图片识别")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
user_prompt = prompt or (
|
||||||
|
"请完整识别并提取图片中的所有文字内容,逐字逐句转录,不要遗漏、不要总结、不要改写。"
|
||||||
|
"如果是报错截图,提取完整错误信息和堆栈;"
|
||||||
|
"如果是代码截图,逐行提取代码;"
|
||||||
|
"如果是表格/文档截图,按原格式完整转录;"
|
||||||
|
"如果是UI界面,提取所有可见的文字、标签、按钮文本。"
|
||||||
|
"保持原文,不做任何概括或省略。"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = httpx.post(
|
||||||
|
f"{base_url}/chat/completions",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
json={
|
||||||
|
"model": model,
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": user_prompt},
|
||||||
|
{
|
||||||
|
"type": "image_url",
|
||||||
|
"image_url": {
|
||||||
|
"url": f"data:{mime};base64,{image_b64}"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"max_tokens": 800,
|
||||||
|
},
|
||||||
|
timeout=30.0,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||||
|
logger.info("图片识别成功:%s(返回 %d 字符)", path.name, len(content))
|
||||||
|
return content.strip()
|
||||||
|
except httpx.HTTPStatusError as exc:
|
||||||
|
logger.warning("图片识别 HTTP 错误:%s %s", exc.response.status_code, exc.response.text[:200])
|
||||||
|
return ""
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("图片识别失败:%s %s", path.name, exc)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_images(image_paths: list[str], prompt: str = "") -> str:
|
||||||
|
"""
|
||||||
|
批量识别图片内容并合并结果。
|
||||||
|
|
||||||
|
【返回】合并后的文字描述(空行分隔各图),失败的跳过。
|
||||||
|
"""
|
||||||
|
results = []
|
||||||
|
for p in image_paths:
|
||||||
|
desc = analyze_image(p, prompt)
|
||||||
|
if desc:
|
||||||
|
path = Path(p)
|
||||||
|
results.append(f"【图片:{path.name}】\n{desc}")
|
||||||
|
|
||||||
|
return "\n\n".join(results)
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""
|
||||||
|
多租户工作空间服务
|
||||||
|
==================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
实现工作空间隔离:项目/知识库/任务/记忆按空间隔离。
|
||||||
|
对应功能 7:多团队共存。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 轻量方案:所有实体加 workspace_id 字段,查询时过滤;
|
||||||
|
2. 空间数据独立,互不可见(数据级隔离);
|
||||||
|
3. 支持默认空间(个人)+ 团队空间。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.workspace")
|
||||||
|
|
||||||
|
|
||||||
|
class WorkspaceStore:
|
||||||
|
"""工作空间存储"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
self._seed_default()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS workspace (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
is_default INTEGER DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def _seed_default(self) -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
count = conn.execute("SELECT COUNT(*) FROM workspace").fetchone()[0]
|
||||||
|
if count == 0:
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO workspace (id, name, description, is_default, created_at, updated_at) VALUES (?,?,?,?,?,?)",
|
||||||
|
("ws_default", "默认空间", "个人工作空间", 1, now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def list_all(self) -> list[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM workspace ORDER BY is_default DESC, created_at").fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get(self, ws_id: str) -> Optional[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM workspace WHERE id = ?", (ws_id,)).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def create(self, name: str, description: str = "") -> dict:
|
||||||
|
ws_id = f"ws_{uuid.uuid4().hex[:8]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO workspace (id, name, description, is_default, created_at, updated_at) VALUES (?,?,?,0,?,?)",
|
||||||
|
(ws_id, name, description, now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(ws_id)
|
||||||
|
|
||||||
|
def delete(self, ws_id: str) -> bool:
|
||||||
|
if ws_id == "ws_default":
|
||||||
|
return False # 禁止删除默认空间
|
||||||
|
with self._conn() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM workspace WHERE id = ?", (ws_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: WorkspaceStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_workspace_store() -> WorkspaceStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
_store = WorkspaceStore(settings.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
"""
|
||||||
|
禅道项目管理服务
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】对接禅道项目管理平台(开源版 16.5+ / 18.x),支持创建/查询/更新 Bug 和任务。
|
||||||
|
对应用户需求:Agent 任务与禅道 Issue 双向同步。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 禅道 18.x 开源版提供 REST v1 API(/api.php/v1/*),鉴权用 Bearer Token;
|
||||||
|
2. Token 通过 POST /api.php/v1/tokens 用账号密码换取,有效期有限(默认约 7 天);
|
||||||
|
3. 为避免 Token 过期导致调用失败,本模块做「自动登录 + 内存/落盘缓存 + 到期前主动续期 + 401 强制重登」;
|
||||||
|
4. 未配置凭证时降级为本地记录,不影响主流程。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- ZentaoService 统一封装鉴权与业务接口;
|
||||||
|
- _ensure_token():命中缓存直接用;缺失或临期则登录换新 Token 并落盘到 data_root;
|
||||||
|
- _request():带 Bearer 头请求;401/403 时强制刷新并重试一次;
|
||||||
|
- create_bug / create_task / search / update_status:对应 v1 的 bugs / tasks 资源;
|
||||||
|
- 全程不打印密码与完整 Token(日志只打前 6 位做定位)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:接口返回的 expireTime 格式不统一(时间戳 / 秒数 / 日期字符串)。
|
||||||
|
应对:_parse_expire_time 兼容多种格式;解析不出时按 zentao_token_ttl_seconds 兜底,
|
||||||
|
并在「剩余不足 5 分钟」时主动续期,宁可早换不突然过期。
|
||||||
|
风险2:多线程并发首次调用会重复登录。
|
||||||
|
应对:刷新动作用 threading.Lock 保护,拿到锁后再二次检查缓存。
|
||||||
|
风险3:账号密码改了导致登录失败。
|
||||||
|
应对:返回明确报错文案,不抛裸异常;同时保留 ZENTAO_TOKEN 手工令牌兜底。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.zentao")
|
||||||
|
|
||||||
|
# 剩余有效期低于该阈值(秒)即主动续期,避免长请求撞上过期点
|
||||||
|
REFRESH_MARGIN_SECONDS = 300
|
||||||
|
# 登录/业务请求超时
|
||||||
|
LOGIN_TIMEOUT = 20.0
|
||||||
|
REQUEST_TIMEOUT = 20.0
|
||||||
|
|
||||||
|
|
||||||
|
def _mask(token: str) -> str:
|
||||||
|
"""日志用的 Token 脱敏,只露前 6 位。"""
|
||||||
|
return f"{token[:6]}..." if token else "<empty>"
|
||||||
|
|
||||||
|
|
||||||
|
# 报错信息里需要脱敏的敏感字段(token / 口令);结尾引号可选,兼容被截断的 JSON 片段
|
||||||
|
_SENSITIVE_KEY_RE = re.compile(
|
||||||
|
r'("(?:token|apiToken|apikey|access_token|accessToken|password|passwd)"\s*:\s*")([^"]+)("?)',
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _redact_body(text: str, limit: int = 300) -> str:
|
||||||
|
"""错误信息里的响应体脱敏,避免把完整 Token / 口令打进日志。"""
|
||||||
|
snippet = (text or "")[:limit]
|
||||||
|
return _SENSITIVE_KEY_RE.sub(lambda m: f"{m.group(1)}{_mask(m.group(2) or '')}{m.group(3)}", snippet)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_expire_time(raw: Any, default_ttl: int) -> float:
|
||||||
|
"""
|
||||||
|
把禅道返回的 expireTime 归一成「过期时刻的 unix 时间戳」。
|
||||||
|
|
||||||
|
兼容:
|
||||||
|
1730000000 → unix 秒
|
||||||
|
1730000000000 → unix 毫秒
|
||||||
|
604800 → 从现在起 N 秒
|
||||||
|
"2026-10-30 12:00:00" → 日期字符串
|
||||||
|
缺失/解析失败 → 现在 + default_ttl
|
||||||
|
"""
|
||||||
|
now = time.time()
|
||||||
|
if raw is None or raw == "":
|
||||||
|
return now + default_ttl
|
||||||
|
|
||||||
|
if isinstance(raw, (int, float)):
|
||||||
|
val = float(raw)
|
||||||
|
if val > 1e12: # 毫秒
|
||||||
|
return val / 1000.0
|
||||||
|
if val > 1e9: # unix 秒
|
||||||
|
return val
|
||||||
|
if val > 0: # 从现在起的秒数
|
||||||
|
return now + val
|
||||||
|
return now + default_ttl
|
||||||
|
|
||||||
|
if isinstance(raw, str):
|
||||||
|
s = raw.strip()
|
||||||
|
if s.isdigit():
|
||||||
|
return _parse_expire_time(int(s), default_ttl)
|
||||||
|
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||||
|
try:
|
||||||
|
import datetime as _dt
|
||||||
|
|
||||||
|
return _dt.datetime.strptime(s, fmt).timestamp()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return now + default_ttl
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_token(payload: Any) -> tuple[str, float | None]:
|
||||||
|
"""
|
||||||
|
从登录响应里挖出 (token, expireTime)。
|
||||||
|
兼容裸对象 / status+data 包裹 / token 嵌套等情况。
|
||||||
|
"""
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return "", None
|
||||||
|
|
||||||
|
token = ""
|
||||||
|
expire_raw: Any = None
|
||||||
|
|
||||||
|
for key in ("token", "apiToken", "apikey", "access_token", "accessToken"):
|
||||||
|
if isinstance(payload.get(key), str) and payload.get(key):
|
||||||
|
token = payload[key]
|
||||||
|
break
|
||||||
|
|
||||||
|
for key in ("expireTime", "expire", "expiresAt", "expires_at", "expiry", "expires_in", "expiresIn"):
|
||||||
|
if key in payload and payload[key] not in (None, ""):
|
||||||
|
expire_raw = payload[key]
|
||||||
|
break
|
||||||
|
|
||||||
|
if not token:
|
||||||
|
data = payload.get("data")
|
||||||
|
if isinstance(data, dict):
|
||||||
|
token, expire_inner = _extract_token(data)
|
||||||
|
if expire_raw is None:
|
||||||
|
expire_raw = expire_inner
|
||||||
|
elif isinstance(data, str) and data:
|
||||||
|
token = data
|
||||||
|
|
||||||
|
return token, expire_raw
|
||||||
|
|
||||||
|
|
||||||
|
class ZentaoService:
|
||||||
|
"""禅道项目管理服务(自动管理 Token 生命周期)"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._base_url = ""
|
||||||
|
self._account = ""
|
||||||
|
self._password = ""
|
||||||
|
self._static_token = ""
|
||||||
|
self._token_ttl = 6 * 24 * 3600
|
||||||
|
self._cache_path: Path | None = None
|
||||||
|
|
||||||
|
self._token = ""
|
||||||
|
self._expire_at = 0.0
|
||||||
|
|
||||||
|
self._load_config()
|
||||||
|
self._load_token_cache()
|
||||||
|
|
||||||
|
# ========== 配置与缓存 ==========
|
||||||
|
|
||||||
|
def _load_config(self) -> None:
|
||||||
|
"""从 .env 加载禅道配置。"""
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
self._base_url = str(getattr(settings, "zentao_url", "") or "").rstrip("/")
|
||||||
|
self._account = getattr(settings, "zentao_account", "") or ""
|
||||||
|
self._password = getattr(settings, "zentao_password", "") or ""
|
||||||
|
self._static_token = getattr(settings, "zentao_token", "") or ""
|
||||||
|
self._token_ttl = int(getattr(settings, "zentao_token_ttl_seconds", 6 * 24 * 3600) or 6 * 24 * 3600)
|
||||||
|
self._cache_path = Path(settings.data_root) / "zentao_token.json"
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
self._base_url = ""
|
||||||
|
self._account = ""
|
||||||
|
self._password = ""
|
||||||
|
self._static_token = ""
|
||||||
|
self._cache_path = None
|
||||||
|
|
||||||
|
def _load_token_cache(self) -> None:
|
||||||
|
"""从磁盘恢复上次的 Token,服务重启不必重新登录。"""
|
||||||
|
path = self._cache_path
|
||||||
|
if path is None or not path.exists():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
if data.get("account") not in (None, self._account):
|
||||||
|
return # 换账号了,旧缓存作废
|
||||||
|
token = data.get("token") or ""
|
||||||
|
expire_at = float(data.get("expire_at") or 0)
|
||||||
|
if token and expire_at > time.time():
|
||||||
|
self._token = token
|
||||||
|
self._expire_at = expire_at
|
||||||
|
logger.info("禅道 Token 已从缓存恢复,到期时间:%s", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(expire_at)))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("禅道 Token 缓存读取失败:%s", exc)
|
||||||
|
|
||||||
|
def _save_token_cache(self) -> None:
|
||||||
|
path = self._cache_path
|
||||||
|
if path is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"account": self._account,
|
||||||
|
"token": self._token,
|
||||||
|
"expire_at": self._expire_at,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("禅道 Token 缓存写入失败:%s", exc)
|
||||||
|
|
||||||
|
# ========== 对外属性 ==========
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_configured(self) -> bool:
|
||||||
|
"""是否具备可用凭证(账号密码 或 手工 Token)。"""
|
||||||
|
return bool(self._base_url) and bool(
|
||||||
|
(self._account and self._password) or self._static_token or self._token
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_login_credential(self) -> bool:
|
||||||
|
return bool(self._account and self._password)
|
||||||
|
|
||||||
|
def token_status(self) -> dict:
|
||||||
|
"""给外部(健康检查/调试)看的 Token 状态,不含明文 Token。"""
|
||||||
|
now = time.time()
|
||||||
|
return {
|
||||||
|
"base_url": self._base_url,
|
||||||
|
"mode": "account_password" if self.has_login_credential else ("static_token" if self._static_token else "none"),
|
||||||
|
"token_masked": _mask(self._token or self._static_token),
|
||||||
|
"expire_at": self._expire_at or None,
|
||||||
|
"expire_at_text": (
|
||||||
|
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)) if self._expire_at else None
|
||||||
|
),
|
||||||
|
"seconds_left": max(0, int(self._expire_at - now)) if self._expire_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ========== Token 生命周期 ==========
|
||||||
|
|
||||||
|
def refresh_token(self, force: bool = False) -> dict:
|
||||||
|
"""
|
||||||
|
刷新 Token。默认只在缺失/临期时刷新;force=True 则无条件重新登录。
|
||||||
|
返回 {"success": bool, "message": str, ...}
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
if not force and self._token and self._expire_at - time.time() > REFRESH_MARGIN_SECONDS:
|
||||||
|
return {"success": True, "message": "Token 仍有效,无需刷新"}
|
||||||
|
|
||||||
|
# 手工 Token 兜底:没有账号密码就只能用它,不存在续期
|
||||||
|
if not self.has_login_credential:
|
||||||
|
if self._static_token:
|
||||||
|
self._token = self._static_token
|
||||||
|
self._expire_at = time.time() + self._token_ttl
|
||||||
|
return {"success": True, "message": "使用手工配置的 ZENTAO_TOKEN"}
|
||||||
|
return {"success": False, "message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD 或 ZENTAO_TOKEN)"}
|
||||||
|
|
||||||
|
result = self._login()
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _login(self) -> dict:
|
||||||
|
"""调 REST v1 tokens 接口换新 Token。调用方需已持有 self._lock。"""
|
||||||
|
if not self._base_url:
|
||||||
|
return {"success": False, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
||||||
|
|
||||||
|
url = f"{self._base_url}/api.php/v1/tokens"
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.post(
|
||||||
|
url,
|
||||||
|
json={"account": self._account, "password": self._password},
|
||||||
|
timeout=LOGIN_TIMEOUT,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"禅道登录请求失败:{exc}"}
|
||||||
|
|
||||||
|
# 禅道创建 Token 成功时返回 201 Created(REST 资源创建语义),与 _request() 判定保持一致
|
||||||
|
if resp.status_code not in (200, 201):
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": f"禅道登录失败 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = resp.json()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return {"success": False, "message": f"禅道登录响应非 JSON:{_redact_body(resp.text)}"}
|
||||||
|
|
||||||
|
token, expire_raw = _extract_token(payload)
|
||||||
|
if not token:
|
||||||
|
return {"success": False, "message": f"禅道登录响应缺少 token:{_redact_body(resp.text)}"}
|
||||||
|
|
||||||
|
self._token = token
|
||||||
|
self._expire_at = _parse_expire_time(expire_raw, self._token_ttl)
|
||||||
|
self._save_token_cache()
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"禅道 Token 已刷新(%s),到期时间:%s",
|
||||||
|
_mask(token),
|
||||||
|
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": "Token 已刷新",
|
||||||
|
"token_masked": _mask(token),
|
||||||
|
"expire_at_text": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _ensure_token(self) -> str:
|
||||||
|
"""返回可用 Token;缺失或临期则刷新。拿不到返回空串。"""
|
||||||
|
now = time.time()
|
||||||
|
if self._token and self._expire_at - now > REFRESH_MARGIN_SECONDS:
|
||||||
|
return self._token
|
||||||
|
|
||||||
|
# 手工 Token 且无账号密码:直接用,不走登录
|
||||||
|
if self._static_token and not self.has_login_credential:
|
||||||
|
self._token = self._static_token
|
||||||
|
if not self._expire_at:
|
||||||
|
self._expire_at = now + self._token_ttl
|
||||||
|
return self._token
|
||||||
|
|
||||||
|
self.refresh_token()
|
||||||
|
return self._token
|
||||||
|
|
||||||
|
# ========== HTTP 封装 ==========
|
||||||
|
|
||||||
|
def _request(
|
||||||
|
self,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
params: dict | None = None,
|
||||||
|
json_body: dict | None = None,
|
||||||
|
retry_on_auth_fail: bool = True,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
带鉴权的禅道 REST 请求。
|
||||||
|
|
||||||
|
path 以 / 开头,拼在 {base_url}/api.php/v1 之后,
|
||||||
|
例如 path="/bugs" → {base_url}/api.php/v1/bugs。
|
||||||
|
"""
|
||||||
|
if not self._base_url:
|
||||||
|
return {"success": False, "status_code": 0, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
||||||
|
|
||||||
|
token = self._ensure_token()
|
||||||
|
if not token:
|
||||||
|
return {"success": False, "status_code": 0, "message": "禅道 Token 获取失败,请检查 ZENTAO_ACCOUNT/ZENTAO_PASSWORD"}
|
||||||
|
|
||||||
|
url = f"{self._base_url}/api.php/v1{path}"
|
||||||
|
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
resp = httpx.request(
|
||||||
|
method.upper(),
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
json=json_body,
|
||||||
|
headers=headers,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "status_code": 0, "message": f"禅道调用失败:{exc}"}
|
||||||
|
|
||||||
|
# Token 失效:强制重登后重试一次
|
||||||
|
if resp.status_code in (401, 403) and retry_on_auth_fail and self.has_login_credential:
|
||||||
|
logger.info("禅道返回 %s,强制刷新 Token 后重试", resp.status_code)
|
||||||
|
self.refresh_token(force=True)
|
||||||
|
if self._token:
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
headers["Authorization"] = f"Bearer {self._token}"
|
||||||
|
resp = httpx.request(
|
||||||
|
method.upper(),
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
json=json_body,
|
||||||
|
headers=headers,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"success": False, "status_code": 0, "message": f"禅道重试失败:{exc}"}
|
||||||
|
|
||||||
|
ok = resp.status_code in (200, 201)
|
||||||
|
try:
|
||||||
|
data: Any = resp.json()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
data = None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": ok,
|
||||||
|
"status_code": resp.status_code,
|
||||||
|
"data": data,
|
||||||
|
# data 解析失败时 raw 会作为错误载荷回传给调用方(可能进日志/接口响应),必须脱敏
|
||||||
|
"raw": _redact_body(resp.text) if data is None else None,
|
||||||
|
"message": "" if ok else f"禅道返回 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
||||||
|
}
|
||||||
|
|
||||||
|
# ========== 业务接口 ==========
|
||||||
|
|
||||||
|
def create_bug(self, title: str, description: str = "", project_id: str = "") -> dict:
|
||||||
|
"""创建禅道 Bug。"""
|
||||||
|
if not self.is_configured:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD)",
|
||||||
|
"local_record": {"title": title, "description": description, "type": "bug"},
|
||||||
|
}
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"title": title,
|
||||||
|
"steps": description or title,
|
||||||
|
}
|
||||||
|
if project_id not in ("", None):
|
||||||
|
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
||||||
|
|
||||||
|
result = self._request("POST", "/bugs", json_body=body)
|
||||||
|
return {
|
||||||
|
"success": result["success"],
|
||||||
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||||
|
"message": result.get("message", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
def create_task(self, title: str, description: str = "", project_id: str = "") -> dict:
|
||||||
|
"""创建禅道任务。"""
|
||||||
|
if not self.is_configured:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": "禅道未配置",
|
||||||
|
"local_record": {"title": title, "description": description, "type": "task"},
|
||||||
|
}
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"name": title,
|
||||||
|
"desc": description or title,
|
||||||
|
}
|
||||||
|
if project_id not in ("", None):
|
||||||
|
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
||||||
|
|
||||||
|
result = self._request("POST", "/tasks", json_body=body)
|
||||||
|
return {
|
||||||
|
"success": result["success"],
|
||||||
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||||
|
"message": result.get("message", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
def search(self, keyword: str = "") -> dict:
|
||||||
|
"""搜索禅道 Issue(Bug 列表,支持关键字过滤)。"""
|
||||||
|
if not self.is_configured:
|
||||||
|
return {"success": False, "message": "禅道未配置", "results": []}
|
||||||
|
|
||||||
|
params: dict[str, Any] = {"page": 1, "limit": 20}
|
||||||
|
if keyword:
|
||||||
|
params["keywords"] = keyword
|
||||||
|
|
||||||
|
result = self._request("GET", "/bugs", params=params)
|
||||||
|
if not result["success"]:
|
||||||
|
return {"success": False, "message": result.get("message", ""), "results": []}
|
||||||
|
|
||||||
|
data = result.get("data")
|
||||||
|
# v1 常见返回:{"bugs": [...]} 或 [...]
|
||||||
|
if isinstance(data, dict):
|
||||||
|
items = data.get("bugs") or data.get("data") or data.get("items") or []
|
||||||
|
elif isinstance(data, list):
|
||||||
|
items = data
|
||||||
|
else:
|
||||||
|
items = []
|
||||||
|
return {"success": True, "results": items}
|
||||||
|
|
||||||
|
def update_status(self, issue_id: str, status: str = "done") -> dict:
|
||||||
|
"""更新禅道 Issue(Bug)状态。"""
|
||||||
|
if not self.is_configured:
|
||||||
|
return {"success": False, "message": "禅道未配置"}
|
||||||
|
|
||||||
|
result = self._request("PUT", f"/bugs/{issue_id}", json_body={"status": status})
|
||||||
|
return {
|
||||||
|
"success": result["success"],
|
||||||
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||||
|
"message": result.get("message", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_service: ZentaoService | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_zentao_service() -> ZentaoService:
|
||||||
|
global _service
|
||||||
|
if _service is None:
|
||||||
|
_service = ZentaoService()
|
||||||
|
return _service
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""存储抽象层:ProjectStore 接口 + SQLite 一期实现(决策点 5:可平迁)"""
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
"""
|
||||||
|
数据库连接存储层
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】数据库连接配置的持久化(SQLite),支持增删改查。
|
||||||
|
【安全设计】密码用简单加密存储(XOR + base64),前端返回脱敏值。
|
||||||
|
【实现思路】DatabaseConnectionStore 抽象 + SqliteDatabaseConnectionStore 实现。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.schemas.database import (
|
||||||
|
DatabaseConnection,
|
||||||
|
DatabaseConnectionCreate,
|
||||||
|
DatabaseConnectionUpdate,
|
||||||
|
)
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
# 简易加密密钥(本地场景,够用;生产建议用密钥管理服务)
|
||||||
|
_XOR_KEY = b"agent_db_key_2026"
|
||||||
|
|
||||||
|
|
||||||
|
def _encrypt(text: str) -> str:
|
||||||
|
"""简易 XOR + base64 加密(本地场景防止明文存储)。"""
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||||
|
return base64.b64encode(encrypted).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def _decrypt(token: str) -> str:
|
||||||
|
"""解密。"""
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
encrypted = base64.b64decode(token.encode("ascii"))
|
||||||
|
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||||
|
return decrypted.decode("utf-8")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseConnectionStore(ABC):
|
||||||
|
"""数据库连接配置存储抽象"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get(self, config_id: str) -> Optional[DatabaseConnection]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_with_password(self, config_id: str) -> Optional[dict]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_all(self) -> list[DatabaseConnection]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update(
|
||||||
|
self, config_id: str, payload: DatabaseConnectionUpdate
|
||||||
|
) -> Optional[DatabaseConnection]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def delete(self, config_id: str) -> bool: ...
|
||||||
|
|
||||||
|
|
||||||
|
class SqliteDatabaseConnectionStore(DatabaseConnectionStore):
|
||||||
|
"""SQLite 实现"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||||
|
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS db_connection (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
db_type TEXT NOT NULL,
|
||||||
|
host TEXT DEFAULT 'localhost',
|
||||||
|
port INTEGER DEFAULT 3306,
|
||||||
|
database TEXT NOT NULL,
|
||||||
|
username TEXT DEFAULT '',
|
||||||
|
password TEXT DEFAULT '',
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row_to_entity(row: sqlite3.Row, mask_password: bool = True) -> DatabaseConnection:
|
||||||
|
pwd = "******" if mask_password else _decrypt(row["password"] or "")
|
||||||
|
return DatabaseConnection(
|
||||||
|
id=row["id"],
|
||||||
|
name=row["name"],
|
||||||
|
db_type=row["db_type"],
|
||||||
|
host=row["host"] or "localhost",
|
||||||
|
port=row["port"] or 3306,
|
||||||
|
database=row["database"],
|
||||||
|
username=row["username"] or "",
|
||||||
|
password=pwd,
|
||||||
|
description=row["description"] or "",
|
||||||
|
created_at=datetime.fromisoformat(row["created_at"]),
|
||||||
|
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection:
|
||||||
|
config_id = f"db_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO db_connection
|
||||||
|
(id, name, db_type, host, port, database, username, password, description, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
|
(
|
||||||
|
config_id,
|
||||||
|
payload.name,
|
||||||
|
payload.db_type,
|
||||||
|
payload.host,
|
||||||
|
payload.port,
|
||||||
|
payload.database,
|
||||||
|
payload.username,
|
||||||
|
_encrypt(payload.password),
|
||||||
|
payload.description,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
created = self.get(config_id)
|
||||||
|
if created is None:
|
||||||
|
raise RuntimeError(f"连接配置创建后回读失败:{config_id}")
|
||||||
|
return created
|
||||||
|
|
||||||
|
def get(self, config_id: str) -> Optional[DatabaseConnection]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
|
||||||
|
).fetchone()
|
||||||
|
return self._row_to_entity(row) if row else None
|
||||||
|
|
||||||
|
def get_with_password(self, config_id: str) -> Optional[dict]:
|
||||||
|
"""返回含真实密码的连接信息(供引擎使用,不暴露给前端)。"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"db_type": row["db_type"],
|
||||||
|
"host": row["host"] or "localhost",
|
||||||
|
"port": row["port"] or 3306,
|
||||||
|
"database": row["database"],
|
||||||
|
"username": row["username"] or "",
|
||||||
|
"password": _decrypt(row["password"] or ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_all(self) -> list[DatabaseConnection]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM db_connection ORDER BY created_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_entity(r) for r in rows]
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self, config_id: str, payload: DatabaseConnectionUpdate
|
||||||
|
) -> Optional[DatabaseConnection]:
|
||||||
|
existing = self.get(config_id)
|
||||||
|
if existing is None:
|
||||||
|
return None
|
||||||
|
changes = payload.model_dump(exclude_none=True)
|
||||||
|
if not changes:
|
||||||
|
return existing
|
||||||
|
if "password" in changes:
|
||||||
|
changes["password"] = _encrypt(changes["password"])
|
||||||
|
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in changes)
|
||||||
|
values = list(changes.values()) + [config_id]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(f"UPDATE db_connection SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(config_id)
|
||||||
|
|
||||||
|
def delete(self, config_id: str) -> bool:
|
||||||
|
with self._connect() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM db_connection WHERE id = ?", (config_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
"""
|
||||||
|
模型配置存储层
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】模型偏好配置的持久化(SQLite),支持增删改查。
|
||||||
|
【技术选型理由】与 ProjectStore/TaskStore 同库同哲学(决策点 5 接口抽象 + SQLite)。
|
||||||
|
【安全设计】API key 不入库,只存 provider_key 引用。
|
||||||
|
【实现思路】ModelConfigStore 抽象 + SqliteModelConfigStore 实现,含默认数据初始化。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.schemas.model_config import ModelConfig, ModelConfigCreate, ModelConfigUpdate
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
# 默认模型配置(首次启动自动初始化,用户可增删改)
|
||||||
|
DEFAULT_MODELS = [
|
||||||
|
{
|
||||||
|
"display_name": "GLM-5.3 — 强模型(代码/推理)",
|
||||||
|
"model_id": "glm-5.3",
|
||||||
|
"provider_key": "ccswitch",
|
||||||
|
"model_role": "strong",
|
||||||
|
"is_enabled": True,
|
||||||
|
"sort_order": 10,
|
||||||
|
"description": "via ccswitch,代码与推理能力强",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"display_name": "GLM-5.3-Flash — 轻量快速",
|
||||||
|
"model_id": "glm-5.3-flash",
|
||||||
|
"provider_key": "ccswitch",
|
||||||
|
"model_role": "weak",
|
||||||
|
"is_enabled": True,
|
||||||
|
"sort_order": 20,
|
||||||
|
"description": "via ccswitch,速度快、成本低",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"display_name": "Mimo-v2.6-Pro — 小米强模型",
|
||||||
|
"model_id": "mimo-v2.6-pro",
|
||||||
|
"provider_key": "ccswitch",
|
||||||
|
"model_role": "strong",
|
||||||
|
"is_enabled": True,
|
||||||
|
"sort_order": 30,
|
||||||
|
"description": "via ccswitch",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"display_name": "DeepSeek-v4-Pro",
|
||||||
|
"model_id": "deepseek-v4-pro",
|
||||||
|
"provider_key": "ccswitch",
|
||||||
|
"model_role": "strong",
|
||||||
|
"is_enabled": True,
|
||||||
|
"sort_order": 40,
|
||||||
|
"description": "via ccswitch",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"display_name": "MiniMax-Latest",
|
||||||
|
"model_id": "minimax-latest",
|
||||||
|
"provider_key": "ccswitch",
|
||||||
|
"model_role": "general",
|
||||||
|
"is_enabled": True,
|
||||||
|
"sort_order": 50,
|
||||||
|
"description": "via ccswitch",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ModelConfigStore(ABC):
|
||||||
|
"""模型配置存储抽象接口"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def create(self, payload: ModelConfigCreate) -> ModelConfig: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get(self, config_id: str) -> Optional[ModelConfig]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update(
|
||||||
|
self, config_id: str, payload: ModelConfigUpdate
|
||||||
|
) -> Optional[ModelConfig]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def delete(self, config_id: str) -> bool: ...
|
||||||
|
|
||||||
|
|
||||||
|
class SqliteModelConfigStore(ModelConfigStore):
|
||||||
|
"""ModelConfigStore 的 SQLite 实现"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._init_schema()
|
||||||
|
self._seed_defaults()
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||||
|
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS model_config (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
model_id TEXT NOT NULL,
|
||||||
|
provider_key TEXT NOT NULL DEFAULT 'ccswitch',
|
||||||
|
model_role TEXT NOT NULL DEFAULT 'general',
|
||||||
|
is_enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
fallback_order INTEGER NOT NULL DEFAULT 999,
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
# 兼容旧表:补 fallback_order 列(幂等)
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"ALTER TABLE model_config ADD COLUMN fallback_order INTEGER NOT NULL DEFAULT 999"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass # 列已存在
|
||||||
|
# 数据迁移:fallback_order 全为 999 的旧数据按 sort_order 重排为 1,2,3...
|
||||||
|
try:
|
||||||
|
all_999 = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM model_config WHERE fallback_order != 999"
|
||||||
|
).fetchone()[0]
|
||||||
|
total = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||||||
|
if total > 0 and all_999 == 0:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id FROM model_config ORDER BY sort_order ASC, created_at ASC"
|
||||||
|
).fetchall()
|
||||||
|
for i, row in enumerate(rows, start=1):
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE model_config SET fallback_order = ? WHERE id = ?",
|
||||||
|
(i, row["id"]),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _seed_defaults(self) -> None:
|
||||||
|
"""首次启动初始化默认模型配置(幂等:已有数据则跳过)。"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
count = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||||||
|
if count > 0:
|
||||||
|
return
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
for idx, item in enumerate(DEFAULT_MODELS):
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO model_config
|
||||||
|
(id, display_name, model_id, provider_key, model_role,
|
||||||
|
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
|
(
|
||||||
|
f"model_{uuid.uuid4().hex[:12]}",
|
||||||
|
item["display_name"],
|
||||||
|
item["model_id"],
|
||||||
|
item["provider_key"],
|
||||||
|
item["model_role"],
|
||||||
|
1 if item["is_enabled"] else 0,
|
||||||
|
item["sort_order"],
|
||||||
|
idx + 1, # 默认降级链顺序按初始化顺序
|
||||||
|
item["description"],
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row_to_entity(row: sqlite3.Row) -> ModelConfig:
|
||||||
|
return ModelConfig(
|
||||||
|
id=row["id"],
|
||||||
|
display_name=row["display_name"],
|
||||||
|
model_id=row["model_id"],
|
||||||
|
provider_key=row["provider_key"],
|
||||||
|
model_role=row["model_role"],
|
||||||
|
is_enabled=bool(row["is_enabled"]),
|
||||||
|
sort_order=row["sort_order"],
|
||||||
|
fallback_order=row["fallback_order"] if "fallback_order" in row.keys() else 999,
|
||||||
|
description=row["description"] or "",
|
||||||
|
created_at=datetime.fromisoformat(row["created_at"]),
|
||||||
|
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def create(self, payload: ModelConfigCreate) -> ModelConfig:
|
||||||
|
config_id = f"model_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO model_config
|
||||||
|
(id, display_name, model_id, provider_key, model_role,
|
||||||
|
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
|
(
|
||||||
|
config_id,
|
||||||
|
payload.display_name,
|
||||||
|
payload.model_id,
|
||||||
|
payload.provider_key,
|
||||||
|
payload.model_role,
|
||||||
|
1 if payload.is_enabled else 0,
|
||||||
|
payload.sort_order,
|
||||||
|
payload.fallback_order,
|
||||||
|
payload.description,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
created = self.get(config_id)
|
||||||
|
if created is None:
|
||||||
|
raise RuntimeError(f"模型配置创建后回读失败:{config_id}")
|
||||||
|
return created
|
||||||
|
|
||||||
|
def get(self, config_id: str) -> Optional[ModelConfig]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM model_config WHERE id = ?", (config_id,)
|
||||||
|
).fetchone()
|
||||||
|
return self._row_to_entity(row) if row else None
|
||||||
|
|
||||||
|
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]:
|
||||||
|
sql = "SELECT * FROM model_config"
|
||||||
|
if only_enabled:
|
||||||
|
sql += " WHERE is_enabled = 1"
|
||||||
|
sql += " ORDER BY sort_order ASC, created_at ASC"
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(sql).fetchall()
|
||||||
|
return [self._row_to_entity(r) for r in rows]
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self, config_id: str, payload: ModelConfigUpdate
|
||||||
|
) -> Optional[ModelConfig]:
|
||||||
|
existing = self.get(config_id)
|
||||||
|
if existing is None:
|
||||||
|
return None
|
||||||
|
changes = payload.model_dump(exclude_none=True)
|
||||||
|
if not changes:
|
||||||
|
return existing
|
||||||
|
# is_enabled 转 SQLite 整数
|
||||||
|
if "is_enabled" in changes:
|
||||||
|
changes["is_enabled"] = 1 if changes["is_enabled"] else 0
|
||||||
|
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in changes)
|
||||||
|
values = list(changes.values()) + [config_id]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(f"UPDATE model_config SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(config_id)
|
||||||
|
|
||||||
|
def delete(self, config_id: str) -> bool:
|
||||||
|
with self._connect() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM model_config WHERE id = ?", (config_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
"""
|
||||||
|
平台账号存储
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
管理多个 AI 平台账号(品牌/账号名/套餐/控制台 URL/Cookie/用量快照)。
|
||||||
|
同一品牌可有多个账号(多套餐并行)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. SQLite 存账号与 Cookie(JSON 序列化);
|
||||||
|
2. 用量快照表记录每次抓取结果,支撑趋势分析;
|
||||||
|
3. Cookie 加密存储(复用 Provider 的 XOR 加密)。
|
||||||
|
|
||||||
|
【安全设计】Cookie/凭证加密存储,前端脱敏展示。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.platform_store")
|
||||||
|
|
||||||
|
# 简易加密(与 provider_store 同款)
|
||||||
|
_XOR_KEY = b"agent_platform_key_2026"
|
||||||
|
|
||||||
|
|
||||||
|
def _encrypt(text: str) -> str:
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||||
|
return base64_encode(encrypted)
|
||||||
|
|
||||||
|
|
||||||
|
def _decrypt(token: str) -> str:
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
import base64
|
||||||
|
|
||||||
|
encrypted = base64.b64decode(token.encode("ascii"))
|
||||||
|
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||||
|
return decrypted.decode("utf-8")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def base64_encode(data: bytes) -> str:
|
||||||
|
import base64
|
||||||
|
|
||||||
|
return base64.b64encode(data).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformAccountStore:
|
||||||
|
"""平台账号存储(SQLite)"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
self._seed_defaults()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS platform_account (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
brand TEXT NOT NULL,
|
||||||
|
account_name TEXT NOT NULL,
|
||||||
|
plan_name TEXT DEFAULT '',
|
||||||
|
console_url TEXT NOT NULL,
|
||||||
|
cookies TEXT DEFAULT '',
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS usage_snapshot (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
captured_at TEXT NOT NULL,
|
||||||
|
usage_percent REAL DEFAULT 0,
|
||||||
|
used_amount TEXT DEFAULT '',
|
||||||
|
total_amount TEXT DEFAULT '',
|
||||||
|
remain_amount TEXT DEFAULT '',
|
||||||
|
expire_date TEXT DEFAULT '',
|
||||||
|
usage_5h TEXT DEFAULT '',
|
||||||
|
usage_1w TEXT DEFAULT '',
|
||||||
|
usage_1m TEXT DEFAULT '',
|
||||||
|
reset_5h TEXT DEFAULT '',
|
||||||
|
reset_1w TEXT DEFAULT '',
|
||||||
|
reset_1m TEXT DEFAULT '',
|
||||||
|
valid_until TEXT DEFAULT '',
|
||||||
|
raw_data TEXT DEFAULT '',
|
||||||
|
FOREIGN KEY (account_id) REFERENCES platform_account(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS scrape_schedule (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
enabled INTEGER DEFAULT 0,
|
||||||
|
interval_minutes INTEGER DEFAULT 360,
|
||||||
|
account_ids TEXT DEFAULT '[]',
|
||||||
|
last_run_at TEXT DEFAULT '',
|
||||||
|
last_run_result TEXT DEFAULT '',
|
||||||
|
login_detect_enabled INTEGER DEFAULT 1,
|
||||||
|
login_detect_interval INTEGER DEFAULT 60,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.executescript(ddl)
|
||||||
|
conn.commit()
|
||||||
|
for col_ddl in (
|
||||||
|
"ALTER TABLE scrape_schedule ADD COLUMN login_detect_enabled INTEGER DEFAULT 1",
|
||||||
|
"ALTER TABLE scrape_schedule ADD COLUMN login_detect_interval INTEGER DEFAULT 60",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
conn.execute(col_ddl)
|
||||||
|
conn.commit()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
# 兼容旧表:补新列(幂等)
|
||||||
|
for col_ddl in (
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN usage_5h TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN usage_1w TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN usage_1m TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN reset_5h TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN reset_1w TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN reset_1m TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE usage_snapshot ADD COLUMN valid_until TEXT DEFAULT ''",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
conn.execute(col_ddl)
|
||||||
|
conn.commit()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass # 列已存在
|
||||||
|
|
||||||
|
def _seed_defaults(self) -> None:
|
||||||
|
"""首次初始化:预置用户提到的两个平台控制台。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
count = conn.execute("SELECT COUNT(*) FROM platform_account").fetchone()[0]
|
||||||
|
if count > 0:
|
||||||
|
return
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
defaults = [
|
||||||
|
{
|
||||||
|
"brand": "小米",
|
||||||
|
"account_name": "主力账号",
|
||||||
|
"plan_name": "Coding 套餐",
|
||||||
|
"console_url": "https://platform.xiaomimimo.com/console/plan-manage",
|
||||||
|
"description": "小米 MiMo 平台用量页",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"brand": "火山引擎",
|
||||||
|
"account_name": "主力账号",
|
||||||
|
"plan_name": "Coding 套餐",
|
||||||
|
"console_url": "https://console.volcengine.com/ark/region:cn-beijing/subscription/coding-plan",
|
||||||
|
"description": "火山方舟 Coding Plan 用量页",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
for item in defaults:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO platform_account
|
||||||
|
(id, brand, account_name, plan_name, console_url, description, is_active, created_at, updated_at)
|
||||||
|
VALUES (?,?,?,?,?,?,1,?,?)""",
|
||||||
|
(
|
||||||
|
f"pa_{uuid.uuid4().hex[:8]}",
|
||||||
|
item["brand"],
|
||||||
|
item["account_name"],
|
||||||
|
item["plan_name"],
|
||||||
|
item["console_url"],
|
||||||
|
item["description"],
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
logger.info("已预置平台账号:%d 个", len(defaults))
|
||||||
|
|
||||||
|
def _row_to_dict(self, row: sqlite3.Row) -> dict:
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"brand": row["brand"],
|
||||||
|
"account_name": row["account_name"],
|
||||||
|
"plan_name": row["plan_name"],
|
||||||
|
"console_url": row["console_url"],
|
||||||
|
"description": row["description"] or "",
|
||||||
|
"is_active": bool(row["is_active"]),
|
||||||
|
"has_cookies": bool(row["cookies"]),
|
||||||
|
"created_at": row["created_at"],
|
||||||
|
"updated_at": row["updated_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_all(self) -> list[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM platform_account ORDER BY brand, account_name"
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get(self, account_id: str) -> Optional[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM platform_account WHERE id = ?", (account_id,)
|
||||||
|
).fetchone()
|
||||||
|
return self._row_to_dict(row) if row else None
|
||||||
|
|
||||||
|
def get_with_cookies(self, account_id: str) -> Optional[dict]:
|
||||||
|
"""获取含真实 Cookie 的账号信息(供抓取用)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM platform_account WHERE id = ?", (account_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"brand": row["brand"],
|
||||||
|
"account_name": row["account_name"],
|
||||||
|
"plan_name": row["plan_name"],
|
||||||
|
"console_url": row["console_url"],
|
||||||
|
"cookies": _decrypt(row["cookies"] or ""),
|
||||||
|
"is_active": bool(row["is_active"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
def create(self, brand: str, account_name: str, plan_name: str, console_url: str, description: str = "") -> dict:
|
||||||
|
aid = f"pa_{uuid.uuid4().hex[:8]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO platform_account
|
||||||
|
(id, brand, account_name, plan_name, console_url, description, is_active, created_at, updated_at)
|
||||||
|
VALUES (?,?,?,?,?,?,1,?,?)""",
|
||||||
|
(aid, brand, account_name, plan_name, console_url, description, now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(aid)
|
||||||
|
|
||||||
|
def update(self, account_id: str, **kwargs) -> Optional[dict]:
|
||||||
|
allowed = {"brand", "account_name", "plan_name", "console_url", "description", "is_active"}
|
||||||
|
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||||
|
if "is_active" in updates:
|
||||||
|
updates["is_enabled"] = 1 if updates["is_active"] else 0
|
||||||
|
if not updates:
|
||||||
|
return self.get(account_id)
|
||||||
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values()) + [account_id]
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(f"UPDATE platform_account SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(account_id)
|
||||||
|
|
||||||
|
def save_cookies(self, account_id: str, cookies_json: str) -> bool:
|
||||||
|
"""保存登录 Cookie(JSON 序列化)。"""
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
cursor = conn.execute(
|
||||||
|
"UPDATE platform_account SET cookies = ?, updated_at = ? WHERE id = ?",
|
||||||
|
(_encrypt(cookies_json), now, account_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
def delete(self, account_id: str) -> bool:
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute("DELETE FROM usage_snapshot WHERE account_id = ?", (account_id,))
|
||||||
|
cursor = conn.execute(
|
||||||
|
"DELETE FROM platform_account WHERE id = ?", (account_id,)
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
# ---------- 用量快照 ----------
|
||||||
|
|
||||||
|
def save_snapshot(self, account_id: str, data: dict) -> dict:
|
||||||
|
"""保存一次用量快照(含四指标 + 重置时间 + 有效期)。"""
|
||||||
|
sid = f"us_{uuid.uuid4().hex[:8]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO usage_snapshot
|
||||||
|
(id, account_id, captured_at, usage_percent, used_amount, total_amount,
|
||||||
|
remain_amount, expire_date, usage_5h, usage_1w, usage_1m,
|
||||||
|
reset_5h, reset_1w, reset_1m, valid_until, raw_data)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||||
|
(
|
||||||
|
sid,
|
||||||
|
account_id,
|
||||||
|
now,
|
||||||
|
data.get("usage_percent", 0),
|
||||||
|
data.get("used_amount", ""),
|
||||||
|
data.get("total_amount", ""),
|
||||||
|
data.get("remain_amount", ""),
|
||||||
|
data.get("expire_date", ""),
|
||||||
|
data.get("usage_5h", ""),
|
||||||
|
data.get("usage_1w", ""),
|
||||||
|
data.get("usage_1m", ""),
|
||||||
|
data.get("reset_5h", ""),
|
||||||
|
data.get("reset_1w", ""),
|
||||||
|
data.get("reset_1m", ""),
|
||||||
|
data.get("valid_until", ""),
|
||||||
|
json.dumps(data.get("raw_data", {}), ensure_ascii=False),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"id": sid, "captured_at": now}
|
||||||
|
|
||||||
|
def get_latest_snapshot(self, account_id: str) -> Optional[dict]:
|
||||||
|
"""获取最近一次用量快照。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM usage_snapshot WHERE account_id = ? ORDER BY captured_at DESC LIMIT 1",
|
||||||
|
(account_id,),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def get_snapshots(self, account_id: str, limit: int = 30) -> list[dict]:
|
||||||
|
"""获取用量快照历史(供趋势分析)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM usage_snapshot WHERE account_id = ? ORDER BY captured_at DESC LIMIT ?",
|
||||||
|
(account_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
# ---------- 定时任务配置 ----------
|
||||||
|
|
||||||
|
def get_schedule(self) -> dict:
|
||||||
|
"""获取定时抓取配置(不存在则创建默认)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM scrape_schedule LIMIT 1").fetchone()
|
||||||
|
if row is None:
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO scrape_schedule
|
||||||
|
(id, enabled, interval_minutes, account_ids,
|
||||||
|
login_detect_enabled, login_detect_interval,
|
||||||
|
created_at, updated_at)
|
||||||
|
VALUES ('default', 0, 360, '[]', 1, 60, ?, ?)""",
|
||||||
|
(now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
row = conn.execute("SELECT * FROM scrape_schedule WHERE id = 'default'").fetchone()
|
||||||
|
|
||||||
|
account_ids = []
|
||||||
|
try:
|
||||||
|
account_ids = json.loads(row["account_ids"] or "[]")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"enabled": bool(row["enabled"]),
|
||||||
|
"interval_minutes": row["interval_minutes"] or 360,
|
||||||
|
"account_ids": account_ids,
|
||||||
|
"last_run_at": row["last_run_at"] or "",
|
||||||
|
"last_run_result": row["last_run_result"] or "",
|
||||||
|
"login_detect_enabled": bool(row["login_detect_enabled"]) if "login_detect_enabled" in row.keys() else True,
|
||||||
|
"login_detect_interval": row["login_detect_interval"] or 60 if "login_detect_interval" in row.keys() else 60,
|
||||||
|
}
|
||||||
|
|
||||||
|
def update_schedule(
|
||||||
|
self,
|
||||||
|
enabled: bool | None = None,
|
||||||
|
interval_minutes: int | None = None,
|
||||||
|
account_ids: list[str] | None = None,
|
||||||
|
login_detect_enabled: bool | None = None,
|
||||||
|
login_detect_interval: int | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""更新定时抓取配置(含登录过期检测配置)。"""
|
||||||
|
updates: dict[str, Any] = {"updated_at": datetime.now().astimezone().isoformat(timespec="seconds")}
|
||||||
|
if enabled is not None:
|
||||||
|
updates["enabled"] = 1 if enabled else 0
|
||||||
|
if interval_minutes is not None:
|
||||||
|
updates["interval_minutes"] = interval_minutes
|
||||||
|
if account_ids is not None:
|
||||||
|
updates["account_ids"] = json.dumps(account_ids, ensure_ascii=False)
|
||||||
|
if login_detect_enabled is not None:
|
||||||
|
updates["login_detect_enabled"] = 1 if login_detect_enabled else 0
|
||||||
|
if login_detect_interval is not None:
|
||||||
|
updates["login_detect_interval"] = login_detect_interval
|
||||||
|
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values())
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(f"UPDATE scrape_schedule SET {set_clause} WHERE id = 'default'", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get_schedule()
|
||||||
|
|
||||||
|
def record_schedule_run(self, result_summary: str) -> None:
|
||||||
|
"""记录一次定时任务执行结果。"""
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE scrape_schedule SET last_run_at = ?, last_run_result = ? WHERE id = 'default'",
|
||||||
|
(now, result_summary[:500]),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: PlatformAccountStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_platform_store() -> PlatformAccountStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
s = load_settings()
|
||||||
|
_store = PlatformAccountStore(s.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
"""
|
||||||
|
项目元数据存储抽象层
|
||||||
|
====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
定义项目(Project)持久化的统一接口,并给出 SQLite 一期实现。
|
||||||
|
业务层只依赖 ProjectStore 抽象,不感知底层是 SQLite / PostgreSQL / 还是内存。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 5 选了「C:接口抽象 + 一期 SQLite,预留平迁 Postgres」——
|
||||||
|
本模块就是那个抽象边界,换实现时业务代码零改动。
|
||||||
|
2. 选 SQLite 而非直接上 Postgres:硬约束 6 要求全落 D 盘本地,
|
||||||
|
Windows 单机场景下 Docker 化 Postgres 是负资产。
|
||||||
|
3. 用标准库 sqlite3 而非 ORM:项目表结构简单,ORM 反而引入额外
|
||||||
|
学习成本与隐式行为;SQL 显式可读,便于教学与排错。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- ProjectStore(ABC):声明 CRUD + 查询接口;
|
||||||
|
- SqliteProjectStore:用 sqlite3 实现,连接串落 D:\\Agent\\agent\\data\\agent.db;
|
||||||
|
- 每次操作独立开连接(短连接),避免长连接在 Windows 下的文件锁问题;
|
||||||
|
- 表创建幂等(IF NOT EXISTS),支持进程重复启动。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:SQLite 并发写冲突(多任务同时写)。
|
||||||
|
应对:启用 WAL 模式 + busy_timeout=5000,短连接重试;一期单用户场景足够。
|
||||||
|
风险2:datetime 字段时区不一致。
|
||||||
|
应对:统一存 ISO8601 字符串(UTC+8 本地时区),读取时解析回 datetime。
|
||||||
|
风险3:项目删除后孤儿数据(任务记录仍指向该项目)。
|
||||||
|
应对:删除项目时级联清理关联任务(一期任务表后置,先预留注释与钩子)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.schemas.project import Project, ProjectCreate, ProjectUpdate
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectStore(ABC):
|
||||||
|
"""项目元数据存储抽象接口(决策点 5:存储可替换)"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def create(self, payload: ProjectCreate) -> Project:
|
||||||
|
"""创建项目,返回带 id/时间戳的完整实体。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get(self, project_id: str) -> Optional[Project]:
|
||||||
|
"""按 ID 查询项目,不存在返回 None。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_all(self) -> list[Project]:
|
||||||
|
"""查询全部项目(按创建时间倒序)。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update(self, project_id: str, payload: ProjectUpdate) -> Optional[Project]:
|
||||||
|
"""按需更新项目字段,返回更新后的实体;不存在返回 None。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def delete(self, project_id: str) -> bool:
|
||||||
|
"""删除项目,返回是否真正删除了记录。"""
|
||||||
|
|
||||||
|
|
||||||
|
class SqliteProjectStore(ProjectStore):
|
||||||
|
"""ProjectStore 的 SQLite 实现(一期默认实现)"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
# ---------- 内部工具 ----------
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【要点】
|
||||||
|
- check_same_thread=False:FastAPI 线程池下跨线程安全(单机单用户场景);
|
||||||
|
- WAL:读写并发更友好;busy_timeout:写锁冲突时等待而非直接报错。
|
||||||
|
|
||||||
|
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||||
|
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
"""建表(幂等)。"""
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS project (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
code_root_path TEXT NOT NULL,
|
||||||
|
backend_path TEXT NOT NULL DEFAULT 'backend',
|
||||||
|
frontend_path TEXT NOT NULL DEFAULT 'frontend',
|
||||||
|
backend_branch TEXT NOT NULL DEFAULT 'master',
|
||||||
|
frontend_branch TEXT NOT NULL DEFAULT 'master',
|
||||||
|
backends TEXT DEFAULT '[]',
|
||||||
|
frontends TEXT DEFAULT '[]',
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
for col_ddl in (
|
||||||
|
"ALTER TABLE project ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0",
|
||||||
|
"ALTER TABLE project ADD COLUMN backends TEXT DEFAULT '[]'",
|
||||||
|
"ALTER TABLE project ADD COLUMN frontends TEXT DEFAULT '[]'",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
conn.execute(col_ddl)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# 数据迁移:sort_order 全为 0 的旧数据按当前顺序重排为 1,2,3...
|
||||||
|
# (上移/下移靠交换 sort_order 实现,全 0 时交换无效)
|
||||||
|
try:
|
||||||
|
zero_count = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM project WHERE sort_order = 0"
|
||||||
|
).fetchone()[0]
|
||||||
|
total = conn.execute("SELECT COUNT(*) FROM project").fetchone()[0]
|
||||||
|
if total > 0 and zero_count == total:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id FROM project ORDER BY created_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
for i, row in enumerate(rows, start=1):
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE project SET sort_order = ? WHERE id = ?",
|
||||||
|
(i, row["id"]),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row_to_entity(row: sqlite3.Row) -> Project:
|
||||||
|
import json as json_mod
|
||||||
|
|
||||||
|
backends = []
|
||||||
|
frontends = []
|
||||||
|
try:
|
||||||
|
backends = json_mod.loads(row["backends"] or "[]") if "backends" in row.keys() else []
|
||||||
|
frontends = json_mod.loads(row["frontends"] or "[]") if "frontends" in row.keys() else []
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return Project(
|
||||||
|
id=row["id"],
|
||||||
|
name=row["name"],
|
||||||
|
code_root_path=row["code_root_path"],
|
||||||
|
backend_path=row["backend_path"],
|
||||||
|
frontend_path=row["frontend_path"],
|
||||||
|
backend_branch=row["backend_branch"],
|
||||||
|
frontend_branch=row["frontend_branch"],
|
||||||
|
backends=backends,
|
||||||
|
frontends=frontends,
|
||||||
|
description=row["description"],
|
||||||
|
sort_order=row["sort_order"] if "sort_order" in row.keys() else 0,
|
||||||
|
created_at=datetime.fromisoformat(row["created_at"]),
|
||||||
|
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 接口实现 ----------
|
||||||
|
|
||||||
|
def create(self, payload: ProjectCreate) -> Project:
|
||||||
|
import json as json_mod
|
||||||
|
|
||||||
|
project_id = f"proj_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._connect() as conn:
|
||||||
|
# 新建项目排到第一位:现有项目 sort_order 整体 +1,新项目置 0
|
||||||
|
conn.execute("UPDATE project SET sort_order = sort_order + 1")
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO project (
|
||||||
|
id, name, code_root_path, backend_path, frontend_path,
|
||||||
|
backend_branch, frontend_branch, backends, frontends,
|
||||||
|
description, sort_order, created_at, updated_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
project_id,
|
||||||
|
payload.name,
|
||||||
|
payload.code_root_path,
|
||||||
|
payload.backend_path,
|
||||||
|
payload.frontend_path,
|
||||||
|
payload.backend_branch,
|
||||||
|
payload.frontend_branch,
|
||||||
|
json_mod.dumps([b.model_dump() for b in payload.backends], ensure_ascii=False),
|
||||||
|
json_mod.dumps([f.model_dump() for f in payload.frontends], ensure_ascii=False),
|
||||||
|
payload.description,
|
||||||
|
0,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
created = self.get(project_id)
|
||||||
|
if created is None: # 理论上不会发生,作为兜底防御
|
||||||
|
raise RuntimeError(f"项目创建后回读失败,project_id={project_id}")
|
||||||
|
return created
|
||||||
|
|
||||||
|
def get(self, project_id: str) -> Optional[Project]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM project WHERE id = ?", (project_id,)
|
||||||
|
).fetchone()
|
||||||
|
return self._row_to_entity(row) if row else None
|
||||||
|
|
||||||
|
def list_all(self) -> list[Project]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM project ORDER BY sort_order ASC, created_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_entity(r) for r in rows]
|
||||||
|
|
||||||
|
def update(self, project_id: str, payload: ProjectUpdate) -> Optional[Project]:
|
||||||
|
import json as json_mod
|
||||||
|
|
||||||
|
existing = self.get(project_id)
|
||||||
|
if existing is None:
|
||||||
|
return None
|
||||||
|
changes = payload.model_dump(exclude_none=True)
|
||||||
|
if not changes:
|
||||||
|
return existing
|
||||||
|
# JSON 字段序列化
|
||||||
|
if "backends" in changes:
|
||||||
|
changes["backends"] = json_mod.dumps(
|
||||||
|
[b if isinstance(b, dict) else b.model_dump() for b in changes["backends"]],
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
if "frontends" in changes:
|
||||||
|
changes["frontends"] = json_mod.dumps(
|
||||||
|
[f if isinstance(f, dict) else f.model_dump() for f in changes["frontends"]],
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in changes.keys())
|
||||||
|
values = list(changes.values()) + [project_id]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(f"UPDATE project SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(project_id)
|
||||||
|
|
||||||
|
def delete(self, project_id: str) -> bool:
|
||||||
|
with self._connect() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM project WHERE id = ?", (project_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
"""
|
||||||
|
Provider 服务通道存储
|
||||||
|
====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
管理多个 AI 模型服务通道(GLM/DeepSeek/Mimo 等平台)的地址与密钥。
|
||||||
|
实现 ccswitch 的核心能力:统一管理多平台、按 model_id 路由。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 每个 Provider = 一个平台(base_url + api_key);
|
||||||
|
2. 模型管理的 provider_key 引用 Provider 的 name;
|
||||||
|
3. 模型路由按 provider_key 查 Provider 连接配置 → 直连调用。
|
||||||
|
|
||||||
|
【安全设计】API key 加密存储,前端返回脱敏值。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.provider")
|
||||||
|
|
||||||
|
# 简易加密(与 db_connection_store 同款)
|
||||||
|
_XOR_KEY = b"agent_provider_key_2026"
|
||||||
|
|
||||||
|
|
||||||
|
def _encrypt(text: str) -> str:
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||||
|
return base64.b64encode(encrypted).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def _decrypt(token: str) -> str:
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
encrypted = base64.b64decode(token.encode("ascii"))
|
||||||
|
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||||
|
return decrypted.decode("utf-8")
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
class ProviderStore:
|
||||||
|
"""Provider 存储(SQLite)"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._init_schema()
|
||||||
|
self._seed_ccswitch()
|
||||||
|
|
||||||
|
def _conn(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||||
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||||
|
提交/回滚语义不变,额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS provider (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
base_url TEXT NOT NULL,
|
||||||
|
api_key TEXT NOT NULL DEFAULT '',
|
||||||
|
description TEXT DEFAULT '',
|
||||||
|
is_enabled INTEGER DEFAULT 1,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def _seed_ccswitch(self) -> None:
|
||||||
|
"""首次初始化:把 .env 里的 ccswitch 配置导入为默认 Provider(向后兼容)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
count = conn.execute("SELECT COUNT(*) FROM provider").fetchone()[0]
|
||||||
|
if count > 0:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
s = load_settings()
|
||||||
|
if s.ccswitch_api_key and s.ccswitch_base_url:
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
f"prov_{uuid.uuid4().hex[:8]}",
|
||||||
|
"ccswitch",
|
||||||
|
s.ccswitch_base_url,
|
||||||
|
_encrypt(s.ccswitch_api_key),
|
||||||
|
"ccswitch 本地代理(兼容旧配置)",
|
||||||
|
1,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
logger.info("已导入 ccswitch 为默认 Provider")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("导入 ccswitch 失败:%s", exc)
|
||||||
|
|
||||||
|
def _row_to_dict(self, row: sqlite3.Row, mask_key: bool = False) -> dict:
|
||||||
|
key = row["api_key"] or ""
|
||||||
|
# 本地工具不脱敏,直接返回解密后的真实密钥(便于用户查看/编辑)
|
||||||
|
display_key = _decrypt(key)
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"base_url": row["base_url"],
|
||||||
|
"api_key": display_key,
|
||||||
|
"description": row["description"] or "",
|
||||||
|
"is_enabled": bool(row["is_enabled"]),
|
||||||
|
"created_at": row["created_at"],
|
||||||
|
"updated_at": row["updated_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_all(self, only_enabled: bool = False) -> list[dict]:
|
||||||
|
sql = "SELECT * FROM provider"
|
||||||
|
if only_enabled:
|
||||||
|
sql += " WHERE is_enabled = 1"
|
||||||
|
sql += " ORDER BY created_at"
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(sql).fetchall()
|
||||||
|
return [self._row_to_dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get(self, provider_id: str) -> Optional[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
||||||
|
return self._row_to_dict(row) if row else None
|
||||||
|
|
||||||
|
def get_by_name(self, name: str) -> Optional[dict]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
||||||
|
return self._row_to_dict(row) if row else None
|
||||||
|
|
||||||
|
def get_with_key(self, name: str) -> Optional[dict]:
|
||||||
|
"""获取含真实 api_key 的连接信息(供模型路由用,不暴露给前端)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
||||||
|
return self._row_with_real_key(row) if row else None
|
||||||
|
|
||||||
|
def get_with_key_by_id(self, provider_id: str) -> Optional[dict]:
|
||||||
|
"""按 ID 获取含真实 api_key 的连接信息(供测试连接用)。"""
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
||||||
|
return self._row_with_real_key(row) if row else None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row_with_real_key(row: sqlite3.Row) -> dict:
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"base_url": row["base_url"],
|
||||||
|
"api_key": _decrypt(row["api_key"] or ""),
|
||||||
|
"is_enabled": bool(row["is_enabled"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
def create(self, name: str, base_url: str, api_key: str = "", description: str = "") -> dict:
|
||||||
|
pid = f"prov_{uuid.uuid4().hex[:8]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,1,?,?)",
|
||||||
|
(pid, name, base_url, _encrypt(api_key), description, now, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(pid)
|
||||||
|
|
||||||
|
def update(self, provider_id: str, **kwargs) -> Optional[dict]:
|
||||||
|
allowed = {"name", "base_url", "api_key", "description", "is_enabled"}
|
||||||
|
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||||
|
if not updates:
|
||||||
|
return self.get(provider_id)
|
||||||
|
if "api_key" in updates:
|
||||||
|
updates["api_key"] = _encrypt(updates["api_key"])
|
||||||
|
if "is_enabled" in updates:
|
||||||
|
updates["is_enabled"] = 1 if updates["is_enabled"] else 0
|
||||||
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values()) + [provider_id]
|
||||||
|
with self._conn() as conn:
|
||||||
|
conn.execute(f"UPDATE provider SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(provider_id)
|
||||||
|
|
||||||
|
def delete(self, provider_id: str) -> bool:
|
||||||
|
with self._conn() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM provider WHERE id = ?", (provider_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例
|
||||||
|
_store: ProviderStore | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_provider_store() -> ProviderStore:
|
||||||
|
global _store
|
||||||
|
if _store is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
s = load_settings()
|
||||||
|
_store = ProviderStore(s.sqlite_db_path)
|
||||||
|
return _store
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
SQLite 短连接上下文管理器
|
||||||
|
========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
统一「开连接 → 用完提交/回滚 → 关闭」的生命周期,杜绝连接泄漏。
|
||||||
|
|
||||||
|
【为什么需要】
|
||||||
|
Python 的 sqlite3.Connection 用在 with 里时:
|
||||||
|
with sqlite3.connect(...) as conn: # 退出时 commit/rollback,但**不 close**
|
||||||
|
...
|
||||||
|
连接对象要等 GC 才释放。后果:
|
||||||
|
- Windows:文件锁不释放 → PermissionError: [WinError 32]
|
||||||
|
- 服务端高频调用:连接数持续增长,最终耗尽句柄
|
||||||
|
测试 teardown 曾因此无法删除临时 db 文件。
|
||||||
|
|
||||||
|
【语义】与裸 `with sqlite3.connect()` **完全一致**,只多保证关闭:
|
||||||
|
- 正常退出 → commit(与 Connection.__exit__ 的成功语义相同)
|
||||||
|
- 异常退出 → rollback + 原样抛出
|
||||||
|
- 无论何种情况 → finally 中 close
|
||||||
|
|
||||||
|
【设计取舍】
|
||||||
|
用 @contextmanager 而不是包装类:调用点 `with self._connect() as conn`
|
||||||
|
的写法完全不用改,属于零侵入修复。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def open_connection(
|
||||||
|
db_path: Path | str, *, timeout: float = 5.0
|
||||||
|
) -> Iterator[sqlite3.Connection]:
|
||||||
|
"""
|
||||||
|
打开一个短连接,用完自动提交/回滚并关闭。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
db_path:SQLite 文件路径
|
||||||
|
timeout:写锁冲突等待秒数(busy_timeout 同值)
|
||||||
|
【返回】yield sqlite3.Connection(row_factory 已设为 sqlite3.Row)
|
||||||
|
"""
|
||||||
|
conn = sqlite3.connect(str(db_path), timeout=timeout, check_same_thread=False)
|
||||||
|
try:
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
# WAL:读写并发更友好;busy_timeout:写锁冲突时等待而非直接报错
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL;")
|
||||||
|
conn.execute("PRAGMA busy_timeout=5000;")
|
||||||
|
yield conn
|
||||||
|
# 与 sqlite3.Connection.__exit__ 的成功语义保持一致(提交)
|
||||||
|
conn.commit()
|
||||||
|
except BaseException:
|
||||||
|
# 与 sqlite3.Connection.__exit__ 的失败语义保持一致(回滚后抛出)
|
||||||
|
try:
|
||||||
|
conn.rollback()
|
||||||
|
except Exception: # noqa: BLE001 - 回滚失败不掩盖原始异常
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
# 【本模块存在的唯一理由】确保连接一定被关闭
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""任务模块包:任务生命周期管理(存储/执行/事件)"""
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"""
|
||||||
|
任务事件日志(落盘版事件总线)
|
||||||
|
=============================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
把任务执行事件写成 JSONL 文件,供 SSE 尾随推送。
|
||||||
|
一条任务 = 一个文件:data/task_events/{task_id}.jsonl
|
||||||
|
|
||||||
|
【为什么需要】
|
||||||
|
原实现是**进程内**的 asyncio.Queue 事件总线。任务改由独立 worker 进程执行后,
|
||||||
|
worker 与 API 不在同一进程,内存总线直接失效;且 API 一重启,内存里的事件全丢。
|
||||||
|
落盘到 JSONL 后:
|
||||||
|
- worker 无论在哪个进程写,API 都能读到;
|
||||||
|
- API 重启后 SSE 重连,能从文件续上,不丢历史事件;
|
||||||
|
- 前端可以只靠 SSE 就拿到完整流式输出,无需额外轮询。
|
||||||
|
|
||||||
|
【格式】每行一个 JSON:{"event": "...", "message": "...", "data": {...}, "timestamp": "..."}
|
||||||
|
追加写(append),不改写历史行。
|
||||||
|
|
||||||
|
【并发】worker 单进程写、API 多连接读;用 append 模式 + 逐行读,
|
||||||
|
平台保证 append 的原子性对小写入是安全的(这是本场景的合理假设)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Iterator
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.event_log")
|
||||||
|
|
||||||
|
# 同一任务的写入串行化(避免多线程交错写坏一行)
|
||||||
|
_write_locks: dict[str, threading.Lock] = {}
|
||||||
|
_locks_guard = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _lock_for(task_id: str) -> threading.Lock:
|
||||||
|
with _locks_guard:
|
||||||
|
lock = _write_locks.get(task_id)
|
||||||
|
if lock is None:
|
||||||
|
lock = threading.Lock()
|
||||||
|
_write_locks[task_id] = lock
|
||||||
|
return lock
|
||||||
|
|
||||||
|
|
||||||
|
class TaskEventLog:
|
||||||
|
"""任务事件日志:按 task_id 一个 JSONL 文件。"""
|
||||||
|
|
||||||
|
def __init__(self, base_dir: Path) -> None:
|
||||||
|
self._base_dir = Path(base_dir)
|
||||||
|
self._base_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
def path_of(self, task_id: str) -> Path:
|
||||||
|
"""事件文件路径。task_id 只用作文件名,需防路径穿越。"""
|
||||||
|
safe = "".join(c for c in task_id if c.isalnum() or c in "-_")
|
||||||
|
if not safe:
|
||||||
|
safe = "unknown"
|
||||||
|
return self._base_dir / f"{safe}.jsonl"
|
||||||
|
|
||||||
|
def append(self, task_id: str, event: dict[str, Any]) -> None:
|
||||||
|
"""追加一条事件(worker 侧调用)。"""
|
||||||
|
path = self.path_of(task_id)
|
||||||
|
line = json.dumps(event, ensure_ascii=False)
|
||||||
|
with _lock_for(task_id):
|
||||||
|
try:
|
||||||
|
# a=append, 不带缓冲地写完就落盘
|
||||||
|
with path.open("a", encoding="utf-8", newline="\n") as f:
|
||||||
|
f.write(line + "\n")
|
||||||
|
f.flush()
|
||||||
|
except Exception as exc: # noqa: BLE001 - 事件落盘失败不该打断任务
|
||||||
|
logger.warning("事件写入失败(task=%s):%s", task_id, exc)
|
||||||
|
|
||||||
|
def read_from(self, task_id: str, offset: int = 0) -> tuple[list[dict], int]:
|
||||||
|
"""
|
||||||
|
从指定字节偏移读取新增事件。
|
||||||
|
|
||||||
|
【返回】(事件列表, 新的字节偏移)
|
||||||
|
【设计】用字节偏移做游标,SSE 可以增量尾随,不必反复读全文件。
|
||||||
|
"""
|
||||||
|
path = self.path_of(task_id)
|
||||||
|
if not path.exists():
|
||||||
|
return [], offset
|
||||||
|
|
||||||
|
events: list[dict] = []
|
||||||
|
try:
|
||||||
|
with path.open("rb") as f:
|
||||||
|
f.seek(offset)
|
||||||
|
chunk = f.read()
|
||||||
|
new_offset = f.tell()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("事件读取失败(task=%s):%s", task_id, exc)
|
||||||
|
return [], offset
|
||||||
|
|
||||||
|
if not chunk:
|
||||||
|
return [], offset
|
||||||
|
|
||||||
|
for raw in chunk.split(b"\n"):
|
||||||
|
if not raw.strip():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
events.append(json.loads(raw.decode("utf-8")))
|
||||||
|
except Exception: # noqa: BLE001 - 半行/坏行跳过,不拖垮整批
|
||||||
|
continue
|
||||||
|
return events, new_offset
|
||||||
|
|
||||||
|
def clear(self, task_id: str) -> None:
|
||||||
|
"""删除事件文件(任务删除时调用)。"""
|
||||||
|
try:
|
||||||
|
self.path_of(task_id).unlink(missing_ok=True)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
def tail_until_terminal(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
offset: int = 0,
|
||||||
|
is_terminal=None,
|
||||||
|
max_idle_reads: int = 30,
|
||||||
|
poll_interval: float = 0.25,
|
||||||
|
) -> Iterator[tuple[list[dict], int]]:
|
||||||
|
"""
|
||||||
|
持续尾随事件文件,产出新增事件,直到终态或超时。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
is_terminal:fn() -> bool,返回 True 表示任务已结束,读完剩余事件就退出
|
||||||
|
max_idle_reads:连续无新增事件的轮询次数上限(防永久空转)
|
||||||
|
poll_interval:轮询间隔秒
|
||||||
|
【返回】yield (事件列表, 新偏移);事件为空也会 yield(供调用方发心跳)
|
||||||
|
"""
|
||||||
|
import time
|
||||||
|
|
||||||
|
idle = 0
|
||||||
|
while True:
|
||||||
|
events, offset = self.read_from(task_id, offset)
|
||||||
|
if events:
|
||||||
|
idle = 0
|
||||||
|
yield events, offset
|
||||||
|
else:
|
||||||
|
idle += 1
|
||||||
|
yield [], offset
|
||||||
|
|
||||||
|
if is_terminal is not None and is_terminal():
|
||||||
|
# 终态:再读一次,确保把写完的尾部事件吃干净
|
||||||
|
events, offset = self.read_from(task_id, offset)
|
||||||
|
if events:
|
||||||
|
yield events, offset
|
||||||
|
return
|
||||||
|
|
||||||
|
if idle >= max_idle_reads:
|
||||||
|
return
|
||||||
|
|
||||||
|
time.sleep(poll_interval)
|
||||||
|
|
||||||
|
|
||||||
|
# 全局单例(由 app 启动时注入真实目录)
|
||||||
|
_event_log: TaskEventLog | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_event_log() -> TaskEventLog:
|
||||||
|
"""获取全局事件日志实例(首次调用时按 settings 初始化)。"""
|
||||||
|
global _event_log
|
||||||
|
if _event_log is None:
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
|
||||||
|
_event_log = TaskEventLog(load_settings().data_root / "task_events")
|
||||||
|
return _event_log
|
||||||
|
|
||||||
|
|
||||||
|
def set_event_log(log: TaskEventLog) -> None:
|
||||||
|
"""注入自定义实例(测试用)。"""
|
||||||
|
global _event_log
|
||||||
|
_event_log = log
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""
|
||||||
|
热重载冲突守卫
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
在「跑任务」与「热重载」结构性互斥的前提下,把静默被杀变成明确拒绝。
|
||||||
|
|
||||||
|
【为什么需要】
|
||||||
|
Claude 干活会写文件(临时脚本、改源码)。若后端以 `--reload` 运行,
|
||||||
|
一旦 Claude 写到被监听目录,WatchFiles 就重启后端进程,正在执行的任务当场被杀:
|
||||||
|
WatchFiles detected changes → Reloading → ASGI callable returned without completing response
|
||||||
|
这不是调参能解决的,二者在结构上互斥。
|
||||||
|
|
||||||
|
【设计取舍】
|
||||||
|
宁可「发起时明确报错」,也不要「跑一半静默失败」。
|
||||||
|
报错信息直接告诉用户换哪个脚本启动,不让他猜。
|
||||||
|
|
||||||
|
【只拦会写文件的任务】
|
||||||
|
direct_claude / agent 都会调 Claude CLI(会写文件),必须拦;
|
||||||
|
纯查询类接口不经过这里,不受影响。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def is_reload_mode() -> bool:
|
||||||
|
"""检测当前进程是否运行在 uvicorn --reload 热重载模式下。"""
|
||||||
|
# 1. 命令行参数(最直接)
|
||||||
|
if any(a == "--reload" or a.startswith("--reload") for a in sys.argv):
|
||||||
|
return True
|
||||||
|
# 2. 环境变量兜底(部分启动方式会带上)
|
||||||
|
env = os.environ.get("UVICORN_RELOAD", "")
|
||||||
|
return env.lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
# 报错文案:直接给出替代命令,用户照抄即可
|
||||||
|
_RELOAD_CONFLICT_MESSAGE = (
|
||||||
|
"当前后端以 --reload 热重载模式运行,无法执行改码任务。\n"
|
||||||
|
"原因:Claude 执行时会写文件,触发 WatchFiles 自动重启后端,任务会被中途杀死。\n"
|
||||||
|
"解决:停止当前后端,改用无热重载方式启动后重试:\n"
|
||||||
|
" cd D:\\Agent\\agent\\backend\n"
|
||||||
|
" powershell -ExecutionPolicy Bypass -File .\\start_backend.ps1\n"
|
||||||
|
"(若确需边改代码边调试,请用 start_backend.dev.ps1,它只监听 app/ 目录)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ReloadConflictError(RuntimeError):
|
||||||
|
"""热重载与任务执行冲突"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(_RELOAD_CONFLICT_MESSAGE)
|
||||||
|
self.error_type = "ReloadConflict"
|
||||||
|
|
||||||
|
|
||||||
|
def assert_can_run_task() -> None:
|
||||||
|
"""
|
||||||
|
断言当前环境允许执行会写文件的任务。
|
||||||
|
|
||||||
|
【抛出】ReloadConflictError:热重载模式下禁止执行
|
||||||
|
【调用点】create_and_run / continue_chat —— 在任务真正启动前拦截
|
||||||
|
"""
|
||||||
|
if is_reload_mode():
|
||||||
|
raise ReloadConflictError()
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
"""
|
||||||
|
回滚服务
|
||||||
|
========
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
提供任务级代码回滚能力:从快照还原文件 / Git 分支回退。
|
||||||
|
是决策点 12「本地 Git + 快照」双安全网的落地,硬约束 5 的核心兜底。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 双通道设计:
|
||||||
|
- 快照还原:通用、不依赖 Git,能精确还原到「改码前一刻」;
|
||||||
|
- Git 回退:速度快、可整分支回退,适合大批量改动。
|
||||||
|
2. 优先 Git、快照兜底:Git 是行业标准(决策点 12/13 已确认),
|
||||||
|
快照是「Git 意外失效时的最后一道防线」。
|
||||||
|
3. 回滚操作本身也要审计 + 确认,不允许静默执行(安全闭环)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- RollbackService 统一入口 rollback_task(task_id, strategy);
|
||||||
|
- 快照索引:file_tools 写入时同步维护 index.jsonl 映射关系;
|
||||||
|
- Git 回退:在任务分支上 reset 到分支创建点。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:回滚后又有新改动被覆盖。
|
||||||
|
应对:回滚前对当前工作区做一次「紧急快照」,可反向恢复。
|
||||||
|
风险2:快照索引损坏。
|
||||||
|
应对:Git 通道兜底;两条路都失败时返回明确错误,提示人工介入。
|
||||||
|
风险3:回滚范围过大(误还原无关文件)。
|
||||||
|
应对:只还原该 task_id 名下的快照,不触碰其他任务的改动。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tasks.rollback")
|
||||||
|
|
||||||
|
# 快照目录与索引文件
|
||||||
|
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups")
|
||||||
|
INDEX_FILE = BACKUP_DIR / "index.jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
def record_backup(backup_path: str, original_path: str, task_id: str) -> None:
|
||||||
|
"""
|
||||||
|
记录一条快照映射(backup_path ↔ original_path)。
|
||||||
|
|
||||||
|
【用途】回滚时按 task_id 找到全部快照并还原。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
entry = {
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"backup_path": backup_path,
|
||||||
|
"original_path": original_path,
|
||||||
|
"task_id": task_id,
|
||||||
|
}
|
||||||
|
with open(INDEX_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("记录快照索引失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def list_backups(task_id: str) -> list[dict[str, Any]]:
|
||||||
|
"""列出指定任务的全部快照记录。"""
|
||||||
|
if not INDEX_FILE.exists():
|
||||||
|
return []
|
||||||
|
results = []
|
||||||
|
try:
|
||||||
|
with open(INDEX_FILE, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
entry = json.loads(line)
|
||||||
|
if entry.get("task_id") == task_id:
|
||||||
|
results.append(entry)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("读取快照索引失败:%s", exc)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
class RollbackService:
|
||||||
|
"""任务回滚服务(快照 + Git 双通道)"""
|
||||||
|
|
||||||
|
def rollback_task(
|
||||||
|
self, task_id: str, strategy: str = "auto"
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
回滚指定任务的代码改动。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
task_id:任务 ID
|
||||||
|
strategy:auto(Git 优先)| snapshot(仅快照)| git(仅 Git)
|
||||||
|
【返回】{success, strategy_used, restored_files, message}
|
||||||
|
"""
|
||||||
|
logger.info("开始回滚任务 %s(策略=%s)", task_id, strategy)
|
||||||
|
|
||||||
|
if strategy in ("auto", "snapshot"):
|
||||||
|
result = self._rollback_by_snapshots(task_id)
|
||||||
|
if result["success"] or strategy == "snapshot":
|
||||||
|
return result
|
||||||
|
|
||||||
|
if strategy in ("auto", "git"):
|
||||||
|
result = self._rollback_by_git(task_id)
|
||||||
|
return result
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"strategy_used": "none",
|
||||||
|
"restored_files": [],
|
||||||
|
"message": "未知回滚策略:" + strategy,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _rollback_by_snapshots(self, task_id: str) -> dict[str, Any]:
|
||||||
|
"""快照还原:把 task_id 名下的全部文件还原到改码前版本。"""
|
||||||
|
backups = list_backups(task_id)
|
||||||
|
if not backups:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"strategy_used": "snapshot",
|
||||||
|
"restored_files": [],
|
||||||
|
"message": f"未找到任务 {task_id} 的快照记录",
|
||||||
|
}
|
||||||
|
|
||||||
|
restored: list[str] = []
|
||||||
|
failed: list[str] = []
|
||||||
|
|
||||||
|
for entry in backups:
|
||||||
|
backup_path = Path(entry["backup_path"])
|
||||||
|
original_path = entry["original_path"]
|
||||||
|
if not backup_path.exists():
|
||||||
|
failed.append(f"快照缺失:{backup_path}")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
target = ensure_under_root(Path(original_path), action="回滚还原")
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(backup_path, target)
|
||||||
|
restored.append(str(target))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
failed.append(f"还原失败 {original_path}:{exc}")
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="rollback_task",
|
||||||
|
target=task_id,
|
||||||
|
result="success" if restored else "failure",
|
||||||
|
details={
|
||||||
|
"strategy": "snapshot",
|
||||||
|
"restored_count": len(restored),
|
||||||
|
"failed_count": len(failed),
|
||||||
|
"restored_files": restored[:10],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": len(restored) > 0,
|
||||||
|
"strategy_used": "snapshot",
|
||||||
|
"restored_files": restored,
|
||||||
|
"message": (
|
||||||
|
f"快照还原完成:成功 {len(restored)} 个,失败 {len(failed)} 个"
|
||||||
|
if restored
|
||||||
|
else f"快照还原失败:{failed[:3]}"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _rollback_by_git(self, task_id: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Git 回退:在任务分支上执行 reset 回分支创建点。
|
||||||
|
|
||||||
|
【说明】需要任务分支存在且有提交记录。
|
||||||
|
"""
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
from app.tools.proc_flags import hidden_popen_kwargs
|
||||||
|
|
||||||
|
branch = f"agent/task_{task_id}"
|
||||||
|
code_root = Path(r"D:\Agent\code")
|
||||||
|
|
||||||
|
# 在 code 下找含有该任务分支的仓库
|
||||||
|
target_repo: Path | None = None
|
||||||
|
for git_dir in code_root.rglob(".git"):
|
||||||
|
if not git_dir.is_dir():
|
||||||
|
continue
|
||||||
|
repo = git_dir.parent
|
||||||
|
try:
|
||||||
|
out = subprocess.run(
|
||||||
|
["git", "branch", "--list", branch],
|
||||||
|
cwd=str(repo),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=10,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
**hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
if out.stdout.strip():
|
||||||
|
target_repo = repo
|
||||||
|
break
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
|
||||||
|
if target_repo is None:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"strategy_used": "git",
|
||||||
|
"restored_files": [],
|
||||||
|
"message": f"未找到包含任务分支 {branch} 的 Git 仓库",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 切到任务分支并回退到分支创建点(分支的父提交)
|
||||||
|
subprocess.run(
|
||||||
|
["git", "checkout", branch],
|
||||||
|
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
|
||||||
|
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
# 用 reflog 找到分支创建前的位置;若无提交则跳过
|
||||||
|
out = subprocess.run(
|
||||||
|
["git", "rev-list", "--max-parents=0", "HEAD"],
|
||||||
|
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
|
||||||
|
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
root_commit = out.stdout.strip().splitlines()[0] if out.stdout.strip() else None
|
||||||
|
|
||||||
|
subprocess.run(
|
||||||
|
["git", "reset", "--hard", "master"],
|
||||||
|
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
|
||||||
|
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="rollback_task",
|
||||||
|
target=task_id,
|
||||||
|
result="success",
|
||||||
|
details={"strategy": "git", "repo": str(target_repo), "branch": branch},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"strategy_used": "git",
|
||||||
|
"restored_files": [str(target_repo)],
|
||||||
|
"message": f"Git 回退完成:仓库 {target_repo} 已从分支 {branch} 回退到 master",
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log_action(
|
||||||
|
action="rollback_task", target=task_id,
|
||||||
|
result="failure", details={"strategy": "git", "error": str(exc)},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"strategy_used": "git",
|
||||||
|
"restored_files": [],
|
||||||
|
"message": f"Git 回退失败:{exc}",
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_task_backups(self, task_id: str) -> list[dict[str, Any]]:
|
||||||
|
"""查询任务的全部快照(供前端展示可回滚范围)。"""
|
||||||
|
return list_backups(task_id)
|
||||||
@@ -0,0 +1,713 @@
|
|||||||
|
"""
|
||||||
|
任务执行服务
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
编排「任务创建 → 后台跑 LangGraph 主图 → 节点级事件推送 → 状态落库」
|
||||||
|
完整生命周期,并支撑 SSE 实时进度与 HITL 审批恢复。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 事件总线(asyncio.Queue):图在后台跑,SSE 端订阅事件流,
|
||||||
|
实现真正的节点级实时推送(而非轮询),对应决策点 10「SSE 推送」。
|
||||||
|
2. 后台执行用 asyncio.create_task:FastAPI 异步原生,
|
||||||
|
不阻塞请求线程;任务状态落库保证可追溯。
|
||||||
|
3. 中断恢复走 graph.astream + Command(resume=...):
|
||||||
|
LangGraph 标准 HITL 流程(基准文档第十三部分)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- TaskEventBus:task_id → 多个订阅者队列(支持多端同时观看);
|
||||||
|
- TaskService.run_task():后台协程,流式读取图执行事件并广播;
|
||||||
|
- 审批恢复:resume_task() 再次 astream,携带 Command(resume=...)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:事件队列积压(SSE 消费慢)。
|
||||||
|
应对:队列设上限 1000,超出丢弃最旧(进度类事件可丢,状态类不可丢)。
|
||||||
|
风险2:后台任务异常退出无人知晓。
|
||||||
|
应对:协程顶层 try/except,异常写入 error 通道并广播 error 事件。
|
||||||
|
风险3:同一任务并发启动两次。
|
||||||
|
应对:启动前检查 status==running 且未结束,重复启动拒绝。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from app.graph.orchestrator import get_orchestrator
|
||||||
|
from app.schemas.task import Task, TaskCreate
|
||||||
|
from app.tasks.reload_guard import assert_can_run_task
|
||||||
|
from app.tasks.task_store import TaskStore
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tasks.service")
|
||||||
|
|
||||||
|
# 事件队列上限(防止慢消费者拖垮内存)
|
||||||
|
MAX_QUEUE_SIZE = 1000
|
||||||
|
|
||||||
|
|
||||||
|
class TaskEventBus:
|
||||||
|
"""
|
||||||
|
任务事件总线:发布-订阅模式。
|
||||||
|
|
||||||
|
【用途】图执行事件 → SSE 推送给前端。
|
||||||
|
【设计】一个任务可有多个订阅者(多浏览器标签同时观看)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._subscribers: dict[str, list[asyncio.Queue]] = {}
|
||||||
|
self._event_buffer: dict[str, list[dict[str, Any]]] = {} # SSE 启动前的事件缓冲
|
||||||
|
|
||||||
|
def subscribe(self, task_id: str) -> asyncio.Queue:
|
||||||
|
"""订阅任务事件,返回独立队列(自动回放缓冲事件)。"""
|
||||||
|
queue: asyncio.Queue = asyncio.Queue(maxsize=MAX_QUEUE_SIZE)
|
||||||
|
# 【BUG-1 修复】回放 SSE 连接前的事件,防止启动竞态丢消息
|
||||||
|
buffered = self._event_buffer.pop(task_id, [])
|
||||||
|
for event in buffered:
|
||||||
|
try:
|
||||||
|
queue.put_nowait(event)
|
||||||
|
except asyncio.QueueFull:
|
||||||
|
break
|
||||||
|
self._subscribers.setdefault(task_id, []).append(queue)
|
||||||
|
logger.debug("任务 %s 新增订阅者(缓冲回放 %d 条)", task_id, len(buffered))
|
||||||
|
return queue
|
||||||
|
|
||||||
|
def unsubscribe(self, task_id: str, queue: asyncio.Queue) -> None:
|
||||||
|
"""取消订阅(SSE 断开时调用)。"""
|
||||||
|
queues = self._subscribers.get(task_id, [])
|
||||||
|
if queue in queues:
|
||||||
|
queues.remove(queue)
|
||||||
|
|
||||||
|
async def publish(self, task_id: str, event: dict[str, Any]) -> None:
|
||||||
|
"""广播事件给全部订阅者;无订阅者时缓冲,等连接后回放。"""
|
||||||
|
queues = self._subscribers.get(task_id, [])
|
||||||
|
if not queues:
|
||||||
|
# 【BUG-1 修复】无订阅者时缓冲事件(SSE 还没连上),最多存 100 条
|
||||||
|
buf = self._event_buffer.setdefault(task_id, [])
|
||||||
|
if len(buf) < 100:
|
||||||
|
buf.append(event)
|
||||||
|
return
|
||||||
|
for queue in list(queues):
|
||||||
|
try:
|
||||||
|
queue.put_nowait(event)
|
||||||
|
except asyncio.QueueFull:
|
||||||
|
try:
|
||||||
|
queue.get_nowait()
|
||||||
|
queue.put_nowait(event)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# 全局事件总线单例
|
||||||
|
_event_bus = TaskEventBus()
|
||||||
|
|
||||||
|
|
||||||
|
def _spawn_worker(task_id: str) -> int:
|
||||||
|
"""
|
||||||
|
以独立进程拉起任务执行 worker。
|
||||||
|
|
||||||
|
【L4】任务必须跑在 API 进程之外:API 重启(尤其 uvicorn --reload 检测到
|
||||||
|
Claude 写文件时)不再连带杀死正在执行的任务。
|
||||||
|
【返回】worker PID;拉起失败时抛出,由调用方决定如何降级。
|
||||||
|
"""
|
||||||
|
from app.worker.__main__ import spawn_worker
|
||||||
|
|
||||||
|
return spawn_worker(task_id)
|
||||||
|
|
||||||
|
|
||||||
|
class TaskService:
|
||||||
|
"""任务执行服务:创建/执行/审批/查询"""
|
||||||
|
|
||||||
|
def __init__(self, store: TaskStore, event_bus: TaskEventBus | None = None) -> None:
|
||||||
|
self._store = store
|
||||||
|
self._bus = event_bus or _event_bus
|
||||||
|
self._running_tasks: set[str] = set() # 内存锁:正在执行的任务 ID
|
||||||
|
|
||||||
|
# ---------- 事件工具 ----------
|
||||||
|
|
||||||
|
async def _emit(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
event: str,
|
||||||
|
node: str = "",
|
||||||
|
message: str = "",
|
||||||
|
data: dict | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
发布事件:写入进程内总线 + 落盘事件日志。
|
||||||
|
|
||||||
|
【为什么两路】
|
||||||
|
总线:同进程内 SSE 的低延迟通道(保留,兼容旧路径)。
|
||||||
|
事件日志:worker 在独立进程执行时,API 进程读不到内存总线,
|
||||||
|
必须靠落盘文件才能推送;同时它也是 API 重启后恢复流式的依据。
|
||||||
|
"""
|
||||||
|
payload = {
|
||||||
|
"event": event,
|
||||||
|
"node": node,
|
||||||
|
"message": message,
|
||||||
|
"data": data or {},
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
}
|
||||||
|
# 1) 进程内总线(尽力而为,失败不影响主流程)
|
||||||
|
try:
|
||||||
|
await self._bus.publish(task_id, payload)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
# 2) 落盘事件日志(跨进程 / 跨重启的关键通道)
|
||||||
|
try:
|
||||||
|
from app.tasks.event_log import get_event_log
|
||||||
|
|
||||||
|
get_event_log().append(task_id, payload)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.debug("事件落盘失败(task=%s)", task_id, exc_info=True)
|
||||||
|
|
||||||
|
# ---------- 任务创建与执行 ----------
|
||||||
|
|
||||||
|
async def create_and_run(self, payload: TaskCreate) -> Task:
|
||||||
|
"""
|
||||||
|
创建任务并异步启动图执行。
|
||||||
|
|
||||||
|
【返回】已落库的任务实体(status=running)。
|
||||||
|
"""
|
||||||
|
# 【L3】热重载与改码任务结构性互斥,发起前直接拒绝,避免跑一半被杀
|
||||||
|
assert_can_run_task()
|
||||||
|
|
||||||
|
thread_id = f"thread_{uuid.uuid4().hex[:12]}"
|
||||||
|
task = self._store.create(payload, thread_id=thread_id)
|
||||||
|
|
||||||
|
# 【13.8 修复】会话 ID 在**创建时**就落库,不等执行完补写。
|
||||||
|
# 原实现是 execute() 返回后才 update_session_id,而 Claude 干完活那一刻
|
||||||
|
# 恰好最容易触发 uvicorn reload → 进程被杀 → session_id 永远写不进去
|
||||||
|
# → 续聊读到空串 → 走 --session-id 新建 → ccswitch 里冒出第二个对话。
|
||||||
|
session_id = str(uuid.uuid4())
|
||||||
|
self._store.update_session_id(task.id, session_id)
|
||||||
|
|
||||||
|
# 保存用户消息到对话历史
|
||||||
|
self._store.append_chat_message(task.id, "user", payload.requirement_text)
|
||||||
|
|
||||||
|
# 【并发锁语义修正】_running_tasks 是**进程内**锁,只防同一 API 进程里的并发请求。
|
||||||
|
# L4 之后任务由独立 worker 执行,执行完成时的 discard 落在 worker 那边的内存副本上,
|
||||||
|
# API 这份会永不失效 → 二次提问被误判「正在执行中」。
|
||||||
|
# 故:API 调用结束即释放;跨进程的「是否在执行」以 DB 状态 + worker 存活为准。
|
||||||
|
self._running_tasks.add(task.id)
|
||||||
|
try:
|
||||||
|
# 【L4】任务改由独立 worker 进程执行,API 重启不再杀任务
|
||||||
|
try:
|
||||||
|
pid = _spawn_worker(task.id)
|
||||||
|
self._store.update_worker_pid(task.id, pid)
|
||||||
|
logger.info(
|
||||||
|
"任务已创建并启动(独立 worker pid=%s):%s(thread=%s)",
|
||||||
|
pid, task.id, thread_id,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 拉起失败要让任务有终态
|
||||||
|
self._store.update_status(
|
||||||
|
task.id, status="failed", error=f"启动执行进程失败:{exc}"
|
||||||
|
)
|
||||||
|
logger.exception("拉起任务 worker 失败:%s", task.id)
|
||||||
|
raise
|
||||||
|
return task
|
||||||
|
finally:
|
||||||
|
self._running_tasks.discard(task.id)
|
||||||
|
|
||||||
|
async def _run_direct_claude(self, task: Task) -> None:
|
||||||
|
"""
|
||||||
|
直调模式:零干预,直接把用户输入转发给 Claude CLI。
|
||||||
|
|
||||||
|
【原则】不做任何限制、不加模板包装、不限轮次、不限超时。
|
||||||
|
用户说什么就发什么,Claude 输出什么就展示什么。
|
||||||
|
如需人工介入,Claude 输出会写在报告里,用户直接看报告处理。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await self._emit(task.id, "status_change", message="直调 Claude 执行中…", node="direct_claude")
|
||||||
|
|
||||||
|
# 以存储层为准重读一次:create_and_run 刚写入的 session_id 等字段
|
||||||
|
# 在传入的 task 对象上可能还是旧值
|
||||||
|
task = self._store.get(task.id) or task
|
||||||
|
|
||||||
|
# 1. 定位项目根目录:code_root_path(父目录)+ 列出所有服务路径
|
||||||
|
# 例:code_root_path=D:\Project
|
||||||
|
# 后端 jetrun_iot → D:\Project\jetrun_iot
|
||||||
|
# 后端 jetrun_nms → D:\Project\jetrun_nms
|
||||||
|
# 前端 jetrun_things_front → D:\Project\front\jetrun_things_front
|
||||||
|
project_root = Path(r"D:\Agent\code")
|
||||||
|
project_label = task.project_id
|
||||||
|
service_lines: list[str] = []
|
||||||
|
try:
|
||||||
|
from app.api.project_api import get_store as get_project_store
|
||||||
|
|
||||||
|
project = get_project_store().get(task.project_id)
|
||||||
|
if project and project.code_root_path:
|
||||||
|
base = Path(project.code_root_path)
|
||||||
|
project_root = base # 用父目录,Claude 可访问所有子服务
|
||||||
|
project_label = project.name
|
||||||
|
|
||||||
|
for svc in list(project.backends or []):
|
||||||
|
svc_path = getattr(svc, "path", "") or ""
|
||||||
|
svc_label = getattr(svc, "label", "") or ""
|
||||||
|
svc_branch = getattr(svc, "branch", "") or ""
|
||||||
|
full_path = base / svc_path if svc_path else base
|
||||||
|
service_lines.append(
|
||||||
|
f"- 后端服务 {svc_label}:{full_path}(分支 {svc_branch})"
|
||||||
|
)
|
||||||
|
for svc in list(project.frontends or []):
|
||||||
|
svc_path = getattr(svc, "path", "") or ""
|
||||||
|
svc_label = getattr(svc, "label", "") or ""
|
||||||
|
svc_branch = getattr(svc, "branch", "") or ""
|
||||||
|
full_path = base / svc_path if svc_path else base
|
||||||
|
service_lines.append(
|
||||||
|
f"- 前端服务 {svc_label}:{full_path}(分支 {svc_branch})"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"直调模式项目根目录:%s(项目=%s,服务数=%d)",
|
||||||
|
project_root, project_label, len(service_lines),
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.warning("项目查找失败,回退默认目录:%s", project_root)
|
||||||
|
|
||||||
|
# 2. Prompt = 用户原话(Claude 通过 --resume 自己管上下文,不需要拼历史)
|
||||||
|
from app.tools.claude_engine import execute
|
||||||
|
|
||||||
|
services_desc = "\n".join(service_lines) if service_lines else "(未配置服务)"
|
||||||
|
project_context = (
|
||||||
|
f"【项目上下文】\n"
|
||||||
|
f"项目名称:{project_label}\n"
|
||||||
|
f"项目根目录:{project_root}\n"
|
||||||
|
f"项目包含以下服务:\n{services_desc}\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_history = self._store.get_chat_history(task.id)
|
||||||
|
|
||||||
|
# 会话 ID:创建任务时就已落库(见 create_and_run)
|
||||||
|
# --resume 的前提不是「有 session_id」,而是「会话真的建立过」,
|
||||||
|
# 即 CLI 已吐出 init 事件(session_ready=True)。
|
||||||
|
# 否则拿一个空会话去 --resume 必然 No conversation found。
|
||||||
|
session_id = getattr(task, "session_id", "") or ""
|
||||||
|
if not session_id:
|
||||||
|
# 兜底:旧任务没有 session_id,这里补一个并立刻落库
|
||||||
|
session_id = str(uuid.uuid4())
|
||||||
|
self._store.update_session_id(task.id, session_id)
|
||||||
|
is_continuation = bool(getattr(task, "session_ready", False))
|
||||||
|
|
||||||
|
# Prompt 路由:消息数 > 1 = 追问(发新消息),否则首轮(带项目上下文)
|
||||||
|
if len(chat_history) > 1:
|
||||||
|
prompt = chat_history[-1]["content"]
|
||||||
|
else:
|
||||||
|
prompt = project_context + task.requirement_text
|
||||||
|
|
||||||
|
# 3. 确定模型
|
||||||
|
model_pref = (getattr(task, "model_preference", "") or "").strip()
|
||||||
|
used_model = model_pref if model_pref and model_pref != "auto" else ""
|
||||||
|
|
||||||
|
# 5. 调用 Claude CLI(会话模式:首轮 --session-id,续聊 --resume)
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
|
||||||
|
def _on_output(text: str) -> None:
|
||||||
|
asyncio.run_coroutine_threadsafe(
|
||||||
|
self._emit(
|
||||||
|
task.id, "claude_output",
|
||||||
|
node="direct_claude",
|
||||||
|
message=text.rstrip("\n"),
|
||||||
|
),
|
||||||
|
loop,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_session(sid: str) -> None:
|
||||||
|
"""CLI 吐出 init 事件 → 会话已建立,立刻落库并标 ready。"""
|
||||||
|
try:
|
||||||
|
self._store.update_session_id(task.id, sid)
|
||||||
|
self._store.update_session_ready(task.id, True)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.warning("会话 ID 提前落库失败:%s", sid)
|
||||||
|
|
||||||
|
result = await asyncio.to_thread(
|
||||||
|
execute,
|
||||||
|
project_root=project_root,
|
||||||
|
prompt=prompt,
|
||||||
|
task_id=task.id,
|
||||||
|
timeout=0,
|
||||||
|
model=used_model or model_pref or "",
|
||||||
|
on_output=_on_output,
|
||||||
|
session_id=session_id,
|
||||||
|
resume=is_continuation,
|
||||||
|
skip_snapshot=True, # 对话续聊不需要快照代码
|
||||||
|
on_session=_on_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 保存 Claude 会话 ID(供下次 --resume);ready 标记跟着结果走
|
||||||
|
if result.get("session_id"):
|
||||||
|
self._store.update_session_id(task.id, result["session_id"])
|
||||||
|
self._store.update_session_ready(task.id, True)
|
||||||
|
elif not result.get("success"):
|
||||||
|
# 【BUG-1 修复 + 13.8】执行失败且没拿到 session_id → 会话可能没建立成功
|
||||||
|
# 只清 ready 标记,**保留 session_id**:下次用 --session-id 复用同一 ID
|
||||||
|
# 重建,而不是换一个新 UUID(换 UUID 又会造出第三个会话)。
|
||||||
|
self._store.update_session_ready(task.id, False)
|
||||||
|
|
||||||
|
# 5. 落库
|
||||||
|
# 【13.10 修复】output 必须在所有 return 分支之前赋值,
|
||||||
|
# 否则「手动停止」分支引用它会抛 UnboundLocalError(生产已命中)。
|
||||||
|
model_label = used_model or "CLI 默认"
|
||||||
|
output = result.get('output', '')
|
||||||
|
# 过滤 Claude SDK 的模型名校验噪音
|
||||||
|
output = "\n".join(
|
||||||
|
line for line in output.splitlines()
|
||||||
|
if "[claude-code:unrecognized_model]" not in line
|
||||||
|
)
|
||||||
|
|
||||||
|
# 检查是否被用户手动停止,避免覆盖 stopped 状态
|
||||||
|
current = self._store.get(task.id)
|
||||||
|
if current and current.status == "failed" and "手动停止" in (current.error or ""):
|
||||||
|
# 用户已停止,不覆盖状态,只保存对话记录
|
||||||
|
self._store.append_chat_message(task.id, "assistant", output)
|
||||||
|
return
|
||||||
|
|
||||||
|
report = (
|
||||||
|
f"【直调模式】使用模型:{model_label}\n\n"
|
||||||
|
f"{output}"
|
||||||
|
)
|
||||||
|
self._store.append_chat_message(task.id, "assistant", output)
|
||||||
|
status = "done" if result.get("success") else "failed"
|
||||||
|
self._store.update_status(
|
||||||
|
task.id,
|
||||||
|
status=status,
|
||||||
|
report=report,
|
||||||
|
error="" if result.get("success") else result.get("summary", "执行失败"),
|
||||||
|
)
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"done" if result.get("success") else "error",
|
||||||
|
node="direct_claude",
|
||||||
|
message="执行完成" if result.get("success") else "执行失败",
|
||||||
|
data={"duration": result.get("duration", 0)},
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("直调 Claude 模式执行失败")
|
||||||
|
# 【BUG-2 修复】异常时也写一条 assistant 消息,保持对话历史一致
|
||||||
|
error_msg = f"执行出错:{exc}"
|
||||||
|
try:
|
||||||
|
self._store.append_chat_message(task.id, "assistant", error_msg)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self._store.update_status(task.id, status="failed", error=str(exc))
|
||||||
|
except ValueError:
|
||||||
|
logger.warning("任务 %s 已在终态,跳过 failed 标记", task.id)
|
||||||
|
await self._emit(task.id, "error", node="direct_claude", message=str(exc))
|
||||||
|
finally:
|
||||||
|
self._running_tasks.discard(task.id) # 执行完毕,释放锁
|
||||||
|
self._bus._event_buffer.pop(task.id, None) # 清理事件缓冲(无订阅者时的残留)
|
||||||
|
|
||||||
|
async def continue_chat(self, task_id: str, user_message: str, model: str = "") -> Task:
|
||||||
|
"""
|
||||||
|
在已有任务上追加对话(一条任务 = 一个完整对话)。
|
||||||
|
|
||||||
|
【流程】并发守卫 → 追加 user 消息 → 更新模型偏好 → 重跑直调 Claude。
|
||||||
|
"""
|
||||||
|
# 【L3】续聊同样会跑 Claude(会写文件),热重载下一样拒绝
|
||||||
|
assert_can_run_task()
|
||||||
|
|
||||||
|
task = self._store.get(task_id)
|
||||||
|
if task is None:
|
||||||
|
raise ValueError(f"任务不存在:{task_id}")
|
||||||
|
|
||||||
|
# 【并发守卫语义修正】见 _is_task_busy 注释
|
||||||
|
if self._is_task_busy(task):
|
||||||
|
raise ValueError("任务正在执行中,请等待完成后再发送")
|
||||||
|
if task.status == "running":
|
||||||
|
# 僵尸状态:状态卡在 running 但 worker 已退出,放行续聊即可恢复
|
||||||
|
logger.warning(
|
||||||
|
"任务 %s 状态为 running 但 worker 已退出,按僵尸放行续聊", task_id
|
||||||
|
)
|
||||||
|
|
||||||
|
self._running_tasks.add(task_id)
|
||||||
|
try:
|
||||||
|
# 追加用户消息
|
||||||
|
self._store.append_chat_message(task_id, "user", user_message)
|
||||||
|
# 更新模型偏好(用户可在对话中切换模型)
|
||||||
|
if model and model != "auto":
|
||||||
|
self._store.update_model_preference(task_id, model)
|
||||||
|
# 重置状态为 running
|
||||||
|
self._store.update_status(task_id, status="running")
|
||||||
|
# 重新执行——同样交给独立 worker,避免续聊被 API 重启打断
|
||||||
|
try:
|
||||||
|
pid = _spawn_worker(task_id)
|
||||||
|
self._store.update_worker_pid(task_id, pid)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self._store.update_status(
|
||||||
|
task_id, status="failed", error=f"启动执行进程失败:{exc}"
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
return self._store.get(task_id)
|
||||||
|
finally:
|
||||||
|
# 【关键】API 调用结束即释放进程内锁,不等任务跑完
|
||||||
|
self._running_tasks.discard(task_id)
|
||||||
|
|
||||||
|
def _is_task_busy(self, task: Task) -> bool:
|
||||||
|
"""
|
||||||
|
判断任务是否正在执行(跨进程权威判据)。
|
||||||
|
|
||||||
|
【为什么不能只看 _running_tasks】
|
||||||
|
它是**进程内** set。L4 之后任务由独立 worker 执行,
|
||||||
|
worker 结束时的 discard 落在它自己的内存副本上,API 这份永不释放,
|
||||||
|
二次提问就会被永远误判「正在执行中」。
|
||||||
|
|
||||||
|
【判据优先级】
|
||||||
|
1. _running_tasks:同一 API 进程内的并发请求(短临界区,防 TOCTOU 双跑)
|
||||||
|
2. DB status != running:任务已终态 → 空闲
|
||||||
|
3. status == running 且 worker PID 存活 → 真在执行
|
||||||
|
4. status == running 但 worker 已死 → 僵尸,不算 busy(调用方放行并恢复)
|
||||||
|
"""
|
||||||
|
if task.id in self._running_tasks:
|
||||||
|
return True
|
||||||
|
if task.status != "running":
|
||||||
|
return False
|
||||||
|
from app.worker.__main__ import is_pid_alive
|
||||||
|
|
||||||
|
worker_pid = getattr(task, "worker_pid", 0) or 0
|
||||||
|
return bool(worker_pid) and is_pid_alive(worker_pid)
|
||||||
|
|
||||||
|
# ---------- 供独立 worker 进程调用的执行入口 ----------
|
||||||
|
|
||||||
|
def update_worker_pid(self, task_id: str, pid: int) -> None:
|
||||||
|
"""记录 worker PID(孤儿恢复判断存活用)。"""
|
||||||
|
self._store.update_worker_pid(task_id, pid)
|
||||||
|
|
||||||
|
async def run_direct_claude(self, task: Task) -> None:
|
||||||
|
"""公开入口:直调 Claude 执行(供 worker 进程调用)。"""
|
||||||
|
await self._run_direct_claude(task)
|
||||||
|
|
||||||
|
async def run_graph(self, task: Task) -> None:
|
||||||
|
"""公开入口:LangGraph 全流程执行(供 worker 进程调用)。"""
|
||||||
|
await self._run_graph(task)
|
||||||
|
|
||||||
|
async def _run_graph(self, task: Task) -> None:
|
||||||
|
"""
|
||||||
|
后台执行主图:流式读取事件 → 广播 → 更新状态。
|
||||||
|
|
||||||
|
【降级】任何异常写入 error 并把状态标 failed,不抛出。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await self._emit(task.id, "status_change", message="任务开始执行")
|
||||||
|
|
||||||
|
graph = get_orchestrator()
|
||||||
|
config = {"configurable": {"thread_id": task.thread_id}}
|
||||||
|
initial_state = {
|
||||||
|
"task_id": task.id,
|
||||||
|
"project_id": task.project_id,
|
||||||
|
"raw_requirement": task.requirement_text,
|
||||||
|
"model_preference": getattr(task, "model_preference", "auto") or "auto",
|
||||||
|
"use_vector_search": getattr(task, "use_vector_search", True),
|
||||||
|
"status": "running",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 流式执行:每个节点产出一个事件
|
||||||
|
async for chunk in graph.astream(initial_state, config=config):
|
||||||
|
# chunk 形如 {node_name: state_update}
|
||||||
|
if not isinstance(chunk, dict):
|
||||||
|
continue
|
||||||
|
for node_name, update in chunk.items():
|
||||||
|
if node_name == "__start__" or node_name == "__end__":
|
||||||
|
continue
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"node_end",
|
||||||
|
node=node_name,
|
||||||
|
message=f"节点 {node_name} 执行完成",
|
||||||
|
data=_summarize_update(update),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 检查是否停在中断点(HITL 审批)
|
||||||
|
snapshot = await graph.aget_state(config)
|
||||||
|
if snapshot and snapshot.next:
|
||||||
|
# 图停在 interrupt,等待人工审批
|
||||||
|
interrupt_payload = ""
|
||||||
|
try:
|
||||||
|
interrupts = snapshot.interrupts or []
|
||||||
|
if interrupts:
|
||||||
|
interrupt_payload = json.dumps(
|
||||||
|
interrupts[0].value if hasattr(interrupts[0], "value") else interrupts[0],
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
interrupt_payload = '{"message":"等待人工审批"}'
|
||||||
|
|
||||||
|
self._store.update_status(
|
||||||
|
task.id,
|
||||||
|
status="waiting_approval",
|
||||||
|
pending_approval=interrupt_payload,
|
||||||
|
)
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"status_change",
|
||||||
|
message="任务已暂停,等待人工审批",
|
||||||
|
data={"status": "waiting_approval"},
|
||||||
|
)
|
||||||
|
logger.info("任务停在中断点,等待审批:%s", task.id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 执行完毕,读取最终状态落库
|
||||||
|
final_values = snapshot.values if snapshot else {}
|
||||||
|
report = final_values.get("report", "")
|
||||||
|
error = final_values.get("error", "")
|
||||||
|
status = final_values.get("status", "done")
|
||||||
|
|
||||||
|
self._store.update_status(task.id, status=status, report=report, error=error)
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"done",
|
||||||
|
message=f"任务执行完毕,状态={status}",
|
||||||
|
data={"status": status, "has_report": bool(report)},
|
||||||
|
)
|
||||||
|
logger.info("任务执行完毕:%s → %s", task.id, status)
|
||||||
|
|
||||||
|
except Exception as exc: # noqa: BLE001 - 后台协程兜底
|
||||||
|
logger.exception("任务执行异常:%s", task.id)
|
||||||
|
try:
|
||||||
|
self._store.update_status(
|
||||||
|
task.id, status="failed", error=f"{type(exc).__name__}: {exc}"
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"error",
|
||||||
|
message=f"任务执行异常:{exc}",
|
||||||
|
data={"error_type": type(exc).__name__},
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
self._running_tasks.discard(task.id) # 【BUG-1 修复】agent 模式也要释放锁
|
||||||
|
self._bus._event_buffer.pop(task.id, None) # 清理事件缓冲
|
||||||
|
|
||||||
|
# ---------- HITL 审批恢复 ----------
|
||||||
|
|
||||||
|
async def resume_task(self, task_id: str, decision: dict[str, Any]) -> Optional[Task]:
|
||||||
|
"""
|
||||||
|
提交审批结果并从断点恢复执行。
|
||||||
|
|
||||||
|
【决策格式】{"decision": "approve"|"reject"|"edit", "comment": "..."}
|
||||||
|
【机制】Command(resume=decision) → 图从中断点继续。
|
||||||
|
"""
|
||||||
|
task = self._store.get(task_id)
|
||||||
|
if task is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
from langgraph.types import Command
|
||||||
|
|
||||||
|
graph = get_orchestrator()
|
||||||
|
config = {"configurable": {"thread_id": task.thread_id}}
|
||||||
|
|
||||||
|
self._store.update_status(task_id, status="running")
|
||||||
|
await self._emit(task.id, "status_change", message="收到审批结果,恢复执行")
|
||||||
|
|
||||||
|
async for chunk in graph.astream(Command(resume=decision), config=config):
|
||||||
|
if not isinstance(chunk, dict):
|
||||||
|
continue
|
||||||
|
for node_name, update in chunk.items():
|
||||||
|
if node_name in ("__start__", "__end__"):
|
||||||
|
continue
|
||||||
|
await self._emit(
|
||||||
|
task.id,
|
||||||
|
"node_end",
|
||||||
|
node=node_name,
|
||||||
|
message=f"节点 {node_name} 执行完成",
|
||||||
|
data=_summarize_update(update),
|
||||||
|
)
|
||||||
|
|
||||||
|
final = await graph.aget_state(config)
|
||||||
|
final_values = final.values if final else {}
|
||||||
|
self._store.update_status(
|
||||||
|
task_id,
|
||||||
|
status=final_values.get("status", "done"),
|
||||||
|
report=final_values.get("report", ""),
|
||||||
|
error=final_values.get("error", ""),
|
||||||
|
)
|
||||||
|
await self._emit(task.id, "done", message="审批恢复后执行完毕")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("审批恢复失败:%s", task_id)
|
||||||
|
try:
|
||||||
|
self._store.update_status(task_id, status="failed", error=str(exc))
|
||||||
|
except ValueError:
|
||||||
|
logger.warning("任务 %s 已在终态,跳过 failed 标记", task_id)
|
||||||
|
await self._emit(task.id, "error", message=f"审批恢复失败:{exc}")
|
||||||
|
|
||||||
|
return self._store.get(task_id)
|
||||||
|
|
||||||
|
# ---------- 查询 ----------
|
||||||
|
|
||||||
|
def get_task(self, task_id: str) -> Optional[Task]:
|
||||||
|
return self._store.get(task_id)
|
||||||
|
|
||||||
|
def list_tasks(self, project_id: str | None = None) -> list[Task]:
|
||||||
|
if project_id:
|
||||||
|
return self._store.list_by_project(project_id)
|
||||||
|
return self._store.list_all()
|
||||||
|
|
||||||
|
def delete_task(self, task_id: str) -> bool:
|
||||||
|
"""删除任务(含清理事件缓冲、并发锁、Claude 配置目录)。"""
|
||||||
|
self._bus._event_buffer.pop(task_id, None) # 清理缓冲,防内存泄漏
|
||||||
|
self._running_tasks.discard(task_id) # 清理并发锁
|
||||||
|
# 清理 Claude 配置目录(含会话文件)
|
||||||
|
try:
|
||||||
|
task = self._store.get(task_id)
|
||||||
|
if task and task.session_id:
|
||||||
|
import shutil as _shutil
|
||||||
|
cfg_dir = Path.home() / ".claude" / f"agent-{task.session_id[:12]}"
|
||||||
|
if cfg_dir.exists():
|
||||||
|
_shutil.rmtree(cfg_dir, ignore_errors=True)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
return self._store.delete(task_id)
|
||||||
|
|
||||||
|
def update_task_status(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
status: str,
|
||||||
|
error: str | None = None,
|
||||||
|
report: str | None = None,
|
||||||
|
) -> Optional[Task]:
|
||||||
|
"""更新任务状态(供手动停止等场景)。"""
|
||||||
|
return self._store.update_status(
|
||||||
|
task_id, status=status, error=error, report=report
|
||||||
|
)
|
||||||
|
|
||||||
|
def update_task_sort_order(self, task_id: str, sort_order: int) -> Optional[Task]:
|
||||||
|
"""更新任务排序值。"""
|
||||||
|
from app.tasks.task_store import ALLOWED_TRANSITIONS # noqa: F401
|
||||||
|
task = self._store.get(task_id)
|
||||||
|
if task is None:
|
||||||
|
return None
|
||||||
|
# 直接走底层 update(sort_order 不属于状态迁移,绕过状态机校验)
|
||||||
|
self._store._update_field(task_id, {"sort_order": sort_order})
|
||||||
|
return self._store.get(task_id)
|
||||||
|
|
||||||
|
def subscribe(self, task_id: str) -> asyncio.Queue:
|
||||||
|
"""订阅任务事件流(供 SSE 使用)。"""
|
||||||
|
return self._bus.subscribe(task_id)
|
||||||
|
|
||||||
|
def unsubscribe(self, task_id: str, queue: asyncio.Queue) -> None:
|
||||||
|
self._bus.unsubscribe(task_id, queue)
|
||||||
|
|
||||||
|
|
||||||
|
def _summarize_update(update: Any) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把节点状态更新压缩成小体积摘要(避免 SSE 报文过大)。
|
||||||
|
|
||||||
|
【规则】大文本截断到 200 字符;列表只留长度;嵌套 dict 只留顶层 key。
|
||||||
|
"""
|
||||||
|
if not isinstance(update, dict):
|
||||||
|
return {}
|
||||||
|
summary: dict[str, Any] = {}
|
||||||
|
for key, value in update.items():
|
||||||
|
if isinstance(value, str):
|
||||||
|
summary[key] = value[:200] + ("…" if len(value) > 200 else "")
|
||||||
|
elif isinstance(value, list):
|
||||||
|
summary[key] = f"[{len(value)} 项]"
|
||||||
|
elif isinstance(value, dict):
|
||||||
|
summary[key] = f"{{keys: {list(value.keys())[:5]}}}"
|
||||||
|
else:
|
||||||
|
summary[key] = value
|
||||||
|
return summary
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
"""
|
||||||
|
任务元数据存储
|
||||||
|
==============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
把任务(Task)落库到 SQLite,记录需求、状态、报告、检查点线程 ID。
|
||||||
|
与项目存储同库不同表,便于统一备份与事务管理。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 5 已锁定 SQLite(业务元数据),与 ProjectStore 同一哲学:
|
||||||
|
接口抽象 + 一期实现,可平迁 Postgres。
|
||||||
|
2. thread_id 字段关联 LangGraph 检查点线程,实现「任务 ↔ 图运行状态」
|
||||||
|
一对一绑定,支持断点续跑(决策点 12)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- TaskStore 抽象 + SqliteTaskStore 实现;
|
||||||
|
- 状态流转只允许合法迁移(running → waiting_approval → done/failed/degraded);
|
||||||
|
- 全表时间戳 ISO8601,便于排序与展示。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:状态非法跳变(如 done → running)。
|
||||||
|
应对:update_status 校验迁移合法性,非法迁移拒绝并返回 False。
|
||||||
|
风险2:任务与检查点线程不一致。
|
||||||
|
应对:thread_id 在创建时生成并落库,不再变更。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from app.schemas.task import Task, TaskCreate
|
||||||
|
from app.store.sqlite_util import open_connection
|
||||||
|
|
||||||
|
# 合法状态迁移表(禁止非法跳变)
|
||||||
|
# 【设计】done/failed/degraded 是终态,但允许后续翻盘:
|
||||||
|
# - failed → done / degraded:降级链重试成功后修正状态
|
||||||
|
# - degraded → done:降级后主链路成功可修正
|
||||||
|
# - done/failed/degraded → running:对话续聊时重新激活任务
|
||||||
|
ALLOWED_TRANSITIONS = {
|
||||||
|
"running": {"waiting_approval", "done", "failed", "degraded"},
|
||||||
|
"waiting_approval": {"running", "failed", "degraded"},
|
||||||
|
"done": {"degraded", "running"}, # 续聊可重新激活
|
||||||
|
"failed": {"done", "degraded", "running"}, # 续聊可重新激活
|
||||||
|
"degraded": {"done", "running"}, # 续聊可重新激活
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TaskStore(ABC):
|
||||||
|
"""任务存储抽象接口"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def create(self, payload: TaskCreate, thread_id: str) -> Task: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get(self, task_id: str) -> Optional[Task]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_by_project(self, project_id: str) -> list[Task]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_all(self) -> list[Task]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update_status(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
status: str,
|
||||||
|
report: str | None = None,
|
||||||
|
error: str | None = None,
|
||||||
|
) -> Optional[Task]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def append_chat_message(self, task_id: str, role: str, content: str) -> None: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_chat_history(self, task_id: str) -> list[dict]: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update_session_id(self, task_id: str, session_id: str) -> None: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update_session_ready(self, task_id: str, ready: bool) -> None: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def update_worker_pid(self, task_id: str, pid: int) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class SqliteTaskStore(TaskStore):
|
||||||
|
"""TaskStore 的 SQLite 实现"""
|
||||||
|
|
||||||
|
def __init__(self, db_path: Path) -> None:
|
||||||
|
self._db_path = Path(db_path)
|
||||||
|
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
"""
|
||||||
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||||
|
|
||||||
|
【13.x 修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||||
|
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||||
|
"""
|
||||||
|
return open_connection(self._db_path)
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS task (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
project_id TEXT NOT NULL,
|
||||||
|
requirement TEXT NOT NULL,
|
||||||
|
task_type TEXT NOT NULL DEFAULT 'feature',
|
||||||
|
status TEXT NOT NULL DEFAULT 'running',
|
||||||
|
thread_id TEXT NOT NULL,
|
||||||
|
model_preference TEXT NOT NULL DEFAULT 'auto',
|
||||||
|
use_vector_search INTEGER NOT NULL DEFAULT 1,
|
||||||
|
execution_mode TEXT NOT NULL DEFAULT 'agent',
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
report TEXT DEFAULT '',
|
||||||
|
error TEXT DEFAULT '',
|
||||||
|
pending_approval TEXT DEFAULT '',
|
||||||
|
chat_history TEXT DEFAULT '[]',
|
||||||
|
session_id TEXT DEFAULT '',
|
||||||
|
session_ready INTEGER NOT NULL DEFAULT 0,
|
||||||
|
worker_pid INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(ddl)
|
||||||
|
conn.commit()
|
||||||
|
# 兼容旧表:补新列(幂等)
|
||||||
|
for col_ddl in (
|
||||||
|
"ALTER TABLE task ADD COLUMN pending_approval TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE task ADD COLUMN model_preference TEXT NOT NULL DEFAULT 'auto'",
|
||||||
|
"ALTER TABLE task ADD COLUMN use_vector_search INTEGER NOT NULL DEFAULT 1",
|
||||||
|
"ALTER TABLE task ADD COLUMN execution_mode TEXT NOT NULL DEFAULT 'agent'",
|
||||||
|
"ALTER TABLE task ADD COLUMN chat_history TEXT DEFAULT '[]'",
|
||||||
|
"ALTER TABLE task ADD COLUMN session_id TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE task ADD COLUMN session_ready INTEGER NOT NULL DEFAULT 0",
|
||||||
|
"ALTER TABLE task ADD COLUMN worker_pid INTEGER NOT NULL DEFAULT 0",
|
||||||
|
"ALTER TABLE task ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
conn.execute(col_ddl)
|
||||||
|
conn.commit()
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
pass # 列已存在
|
||||||
|
# 数据迁移:sort_order 全为 0 的旧数据按当前顺序重排
|
||||||
|
try:
|
||||||
|
zero_count = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM task WHERE sort_order = 0"
|
||||||
|
).fetchone()[0]
|
||||||
|
total = conn.execute("SELECT COUNT(*) FROM task").fetchone()[0]
|
||||||
|
if total > 0 and zero_count == total:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id FROM task ORDER BY created_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
for i, row in enumerate(rows, start=1):
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE task SET sort_order = ? WHERE id = ?",
|
||||||
|
(i, row["id"]),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row_to_entity(row: sqlite3.Row) -> Task:
|
||||||
|
return Task(
|
||||||
|
id=row["id"],
|
||||||
|
project_id=row["project_id"],
|
||||||
|
requirement_text=row["requirement"],
|
||||||
|
task_type=row["task_type"],
|
||||||
|
status=row["status"],
|
||||||
|
thread_id=row["thread_id"],
|
||||||
|
model_preference=row["model_preference"] if "model_preference" in row.keys() else "auto",
|
||||||
|
use_vector_search=bool(row["use_vector_search"]) if "use_vector_search" in row.keys() else True,
|
||||||
|
execution_mode=row["execution_mode"] if "execution_mode" in row.keys() else "agent",
|
||||||
|
chat_history=row["chat_history"] if "chat_history" in row.keys() else "[]",
|
||||||
|
session_id=row["session_id"] if "session_id" in row.keys() else "",
|
||||||
|
session_ready=bool(row["session_ready"]) if "session_ready" in row.keys() else False,
|
||||||
|
worker_pid=int(row["worker_pid"]) if "worker_pid" in row.keys() else 0,
|
||||||
|
sort_order=row["sort_order"] if "sort_order" in row.keys() else 0,
|
||||||
|
report=row["report"] or "",
|
||||||
|
error=row["error"] or "",
|
||||||
|
pending_approval=row["pending_approval"] or "",
|
||||||
|
created_at=datetime.fromisoformat(row["created_at"]),
|
||||||
|
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def create(self, payload: TaskCreate, thread_id: str) -> Task:
|
||||||
|
task_id = f"task_{uuid.uuid4().hex[:12]}"
|
||||||
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
with self._connect() as conn:
|
||||||
|
max_sort = conn.execute("SELECT MAX(sort_order) FROM task").fetchone()[0]
|
||||||
|
if max_sort is None:
|
||||||
|
max_sort = 0
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO task
|
||||||
|
(id, project_id, requirement, task_type, status, thread_id,
|
||||||
|
model_preference, use_vector_search, execution_mode, sort_order, report, error, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, '', '', ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
task_id,
|
||||||
|
payload.project_id,
|
||||||
|
payload.requirement_text,
|
||||||
|
payload.task_type,
|
||||||
|
thread_id,
|
||||||
|
getattr(payload, "model_preference", "auto") or "auto",
|
||||||
|
1 if getattr(payload, "use_vector_search", True) else 0,
|
||||||
|
getattr(payload, "execution_mode", "agent") or "agent",
|
||||||
|
max_sort + 1,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
created = self.get(task_id)
|
||||||
|
if created is None:
|
||||||
|
raise RuntimeError(f"任务创建后回读失败:{task_id}")
|
||||||
|
return created
|
||||||
|
|
||||||
|
def get(self, task_id: str) -> Optional[Task]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM task WHERE id = ?", (task_id,)).fetchone()
|
||||||
|
return self._row_to_entity(row) if row else None
|
||||||
|
|
||||||
|
def list_by_project(self, project_id: str) -> list[Task]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM task WHERE project_id = ? ORDER BY created_at DESC",
|
||||||
|
(project_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_entity(r) for r in rows]
|
||||||
|
|
||||||
|
def list_all(self) -> list[Task]:
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM task ORDER BY sort_order ASC, created_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_entity(r) for r in rows]
|
||||||
|
|
||||||
|
def update_status(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
status: str,
|
||||||
|
report: str | None = None,
|
||||||
|
error: str | None = None,
|
||||||
|
pending_approval: str | None = None,
|
||||||
|
) -> Optional[Task]:
|
||||||
|
existing = self.get(task_id)
|
||||||
|
if existing is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 状态迁移合法性校验(禁止非法跳变)
|
||||||
|
allowed = ALLOWED_TRANSITIONS.get(existing.status, set())
|
||||||
|
if status != existing.status and status not in allowed:
|
||||||
|
raise ValueError(
|
||||||
|
f"非法状态迁移:{existing.status} → {status}(允许:{allowed or '无'})"
|
||||||
|
)
|
||||||
|
|
||||||
|
updates: dict[str, str] = {"status": status}
|
||||||
|
if report is not None:
|
||||||
|
updates["report"] = report
|
||||||
|
if error is not None:
|
||||||
|
updates["error"] = error
|
||||||
|
if pending_approval is not None:
|
||||||
|
updates["pending_approval"] = pending_approval
|
||||||
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values()) + [task_id]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(f"UPDATE task SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
return self.get(task_id)
|
||||||
|
|
||||||
|
def delete(self, task_id: str) -> bool:
|
||||||
|
"""删除任务(硬删除记录)。"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
cursor = conn.execute("DELETE FROM task WHERE id = ?", (task_id,))
|
||||||
|
conn.commit()
|
||||||
|
return cursor.rowcount > 0
|
||||||
|
|
||||||
|
def _update_field(self, task_id: str, updates: dict) -> None:
|
||||||
|
"""底层通用更新(绕过状态机校验,仅供非状态字段使用)。"""
|
||||||
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||||
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
values = list(updates.values()) + [task_id]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(f"UPDATE task SET {set_clause} WHERE id = ?", values)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# ---------- 对话历史管理 ----------
|
||||||
|
|
||||||
|
def append_chat_message(self, task_id: str, role: str, content: str) -> None:
|
||||||
|
"""追加一条对话消息到任务的 chat_history。"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
task = self.get(task_id)
|
||||||
|
if task is None:
|
||||||
|
return
|
||||||
|
history = _json.loads(task.chat_history or "[]")
|
||||||
|
history.append({"role": role, "content": content})
|
||||||
|
self._update_field(task_id, {"chat_history": _json.dumps(history, ensure_ascii=False)})
|
||||||
|
|
||||||
|
def get_chat_history(self, task_id: str) -> list[dict]:
|
||||||
|
"""获取任务的对话消息列表。"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
task = self.get(task_id)
|
||||||
|
if task is None:
|
||||||
|
return []
|
||||||
|
return _json.loads(task.chat_history or "[]")
|
||||||
|
|
||||||
|
def update_session_id(self, task_id: str, session_id: str) -> None:
|
||||||
|
"""更新 Claude 会话 ID(供 --resume 续聊用)。"""
|
||||||
|
self._update_field(task_id, {"session_id": session_id})
|
||||||
|
|
||||||
|
def update_session_ready(self, task_id: str, ready: bool) -> None:
|
||||||
|
"""
|
||||||
|
标记 Claude 会话是否已真实建立。
|
||||||
|
|
||||||
|
【为什么需要】session_id 在创建任务时就落库了,但那时 Claude 还没跑。
|
||||||
|
只有 CLI 吐出 init 事件(会话文件已生成)才敢标 ready,
|
||||||
|
否则续聊会拿一个不存在的会话去 --resume → No conversation found。
|
||||||
|
"""
|
||||||
|
self._update_field(task_id, {"session_ready": 1 if ready else 0})
|
||||||
|
|
||||||
|
def update_worker_pid(self, task_id: str, pid: int) -> None:
|
||||||
|
"""
|
||||||
|
记录执行该任务的 worker 进程 PID。
|
||||||
|
|
||||||
|
【用途】API 重启后的孤儿恢复不再「盲目标 failed」,而是先查这个 PID:
|
||||||
|
进程还活着 → 任务仍在跑,不要动;
|
||||||
|
进程已死 → 才标记失败。
|
||||||
|
"""
|
||||||
|
self._update_field(task_id, {"worker_pid": int(pid or 0)})
|
||||||
|
|
||||||
|
def update_model_preference(self, task_id: str, model_preference: str) -> None:
|
||||||
|
"""更新模型偏好(对话中切换模型用)。"""
|
||||||
|
self._update_field(task_id, {"model_preference": model_preference})
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""自研工具层包:路径守卫 / 文件读写 / 搜索定位 / 白名单执行 / Git 操作 / 审计"""
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""
|
||||||
|
审计日志
|
||||||
|
========
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
记录工具层的每一次敏感操作(文件写入、命令执行、git 提交),
|
||||||
|
落盘到 D:\\Agent\\agent\\data\\audit,支持事后追溯与合规审查。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 硬约束 5 要求「任何异常不能直接崩溃、要可排查」:
|
||||||
|
审计日志是排查 Agent 误操作的第一手证据。
|
||||||
|
2. 追加写 JSONL(每行一个 JSON):无需数据库、可 grep、可程序化分析。
|
||||||
|
3. 与工具层同步写入:不异步、不缓冲,保证操作与日志强一致。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- log_action() 记录 {时间, 操作, 目标, 结果, 详情};
|
||||||
|
- 按日期分文件:audit-YYYYMMDD.jsonl,便于按天归档;
|
||||||
|
- 敏感字段(如完整文件内容)只记摘要,不记全文(防止日志膨胀+泄密)。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:日志写入失败影响主流程。
|
||||||
|
应对:日志写入全程 try/except,失败只 warning 不抛出。
|
||||||
|
风险2:日志文件无限膨胀。
|
||||||
|
应对:按日期分文件;后续可加自动清理(保留 N 天)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.audit")
|
||||||
|
|
||||||
|
# 审计日志默认目录
|
||||||
|
DEFAULT_AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
|
||||||
|
|
||||||
|
|
||||||
|
def log_action(
|
||||||
|
action: str,
|
||||||
|
target: str,
|
||||||
|
result: str = "success",
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
audit_dir: Path | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
记录一次工具操作。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
action:操作类型(file_write / file_edit / exec_command / git_commit 等)
|
||||||
|
target:操作对象(文件路径/命令/git 仓库)
|
||||||
|
result:success / failure / denied
|
||||||
|
details:补充详情(会做摘要,不记全文)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
audit_dir = audit_dir or DEFAULT_AUDIT_DIR
|
||||||
|
audit_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
today = datetime.now().strftime("%Y%m%d")
|
||||||
|
log_file = audit_dir / f"audit-{today}.jsonl"
|
||||||
|
|
||||||
|
entry = {
|
||||||
|
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"action": action,
|
||||||
|
"target": target,
|
||||||
|
"result": result,
|
||||||
|
"details": _summarize_details(details or {}),
|
||||||
|
}
|
||||||
|
|
||||||
|
with open(log_file, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||||
|
|
||||||
|
except Exception as exc: # noqa: BLE001 - 审计失败不阻塞主流程
|
||||||
|
logger.warning("审计日志写入失败:%s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _summarize_details(details: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""摘要化详情:长文本截断,避免日志膨胀。"""
|
||||||
|
summary: dict[str, Any] = {}
|
||||||
|
for key, value in details.items():
|
||||||
|
if isinstance(value, str) and len(value) > 500:
|
||||||
|
summary[key] = value[:500] + f"…(共{len(value)}字符)"
|
||||||
|
elif isinstance(value, (int, float, bool)):
|
||||||
|
summary[key] = value
|
||||||
|
elif value is None:
|
||||||
|
summary[key] = None
|
||||||
|
else:
|
||||||
|
summary[key] = str(value)[:200]
|
||||||
|
return summary
|
||||||
@@ -0,0 +1,605 @@
|
|||||||
|
"""
|
||||||
|
Claude Code 改码引擎
|
||||||
|
====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
把 Claude Code CLI 作为「改码执行器」接入 Agent 系统。
|
||||||
|
当 CODING_ENGINE=claude_code 时,Worker 的 modify 节点调用
|
||||||
|
Claude Code 完成代码阅读、理解、修改,替代自研工具链。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 subprocess 调用 claude CLI 而非 Agent SDK:
|
||||||
|
CLI 成熟稳定、已配置好 ccswitch 模型路由、无需额外依赖。
|
||||||
|
2. 非交互模式(-p / --print):一次调用完成任务并输出结果,
|
||||||
|
适合编排集成。
|
||||||
|
3. 工作目录指向项目代码根目录:Claude Code 在该目录下读写文件。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- build_prompt():把任务描述、目标文件线索、上次失败原因组装成 Prompt;
|
||||||
|
- execute():subprocess 调用 claude CLI,捕获输出;
|
||||||
|
- 结果解析:提取 Claude Code 的改动摘要与执行结论。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:claude CLI 不可用(未安装/PATH 缺失)。
|
||||||
|
应对:启动时探测,失败则降级到 builtin 引擎并告警。
|
||||||
|
风险2:Claude Code 改码范围过大(改无关文件)。
|
||||||
|
应对:Prompt 中明确约束「只改指定文件的指定问题」,
|
||||||
|
执行前对目标目录做快照(复用 file_tools 的备份机制)。
|
||||||
|
风险3:执行时间长(Claude Code 自主循环改码)。
|
||||||
|
应对:超时默认 300 秒,超时后终止并降级。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.file_tools import _backup_file
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.claude_engine")
|
||||||
|
|
||||||
|
# 运行中的子进程注册表:task_id → Popen(供「停止」按钮 kill 用)
|
||||||
|
_running_processes: dict[str, subprocess.Popen] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def kill_process(task_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
强制终止指定任务的 Claude CLI 子进程。
|
||||||
|
|
||||||
|
【用途】用户点「停止」时调用,防止进程失控。
|
||||||
|
【返回】是否成功 kill
|
||||||
|
"""
|
||||||
|
proc = _running_processes.pop(task_id, None)
|
||||||
|
if proc is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
logger.info("已终止任务 %s 的 Claude 进程", task_id)
|
||||||
|
return True
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("终止进程失败:%s", exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class ClaudeCodeError(RuntimeError):
|
||||||
|
"""Claude Code 引擎异常"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "ClaudeCodeError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
def is_available() -> bool:
|
||||||
|
"""检测 claude CLI 是否可用。"""
|
||||||
|
return shutil.which("claude") is not None
|
||||||
|
|
||||||
|
|
||||||
|
def get_claude_path() -> str:
|
||||||
|
"""
|
||||||
|
获取 claude CLI 的完整可执行路径。
|
||||||
|
|
||||||
|
【Windows 坑】subprocess.run(["claude"], shell=False) 找不到 claude.CMD,
|
||||||
|
因为不走 PATHEXT 扩展名解析。必须用 shutil.which 拿到完整路径再调用。
|
||||||
|
"""
|
||||||
|
path = shutil.which("claude")
|
||||||
|
if not path:
|
||||||
|
raise ClaudeCodeError(
|
||||||
|
"claude CLI 不可用,请确认已安装 Claude Code 并加入 PATH",
|
||||||
|
error_type="ClaudeNotFound",
|
||||||
|
)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_session_id_from_line(line: str) -> str:
|
||||||
|
"""从单行 stream-json 中取 session_id(取不到返回空串)。"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
obj = _json.loads(line)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ""
|
||||||
|
if isinstance(obj, dict) and obj.get("session_id"):
|
||||||
|
return str(obj["session_id"])
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
class _StreamTextExtractor:
|
||||||
|
"""
|
||||||
|
从 Claude Code stream-json 逐行提取可展示文本(有状态)。
|
||||||
|
|
||||||
|
【为什么要状态】
|
||||||
|
`--include-partial-messages` 打开后,同一条回复会出现两遍:
|
||||||
|
① 增量:{"type":"stream_event","event":{"type":"content_block_delta",
|
||||||
|
"delta":{"type":"text_delta","text":"..."}}}
|
||||||
|
② 成块:{"type":"assistant","message":{"content":[{"type":"text","text":"..."}]}}
|
||||||
|
两者都推给前端,文本会翻倍。故:已推过增量就跳过成块文本。
|
||||||
|
|
||||||
|
【兼容的三种形状】
|
||||||
|
A. Claude Code CLI 增量(嵌在 event 里)
|
||||||
|
B. Messages API 增量(顶层 delta)—— 历史实现按此解析,保留兼容
|
||||||
|
C. 成块文本(assistant / message.content)—— 未开 partial 时的兜底
|
||||||
|
|
||||||
|
【刻意不推】
|
||||||
|
`result` 是最终汇总,前端已通过增量/成块累积过,再推必重复(沿用 BUG-2 原则)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._saw_delta = False
|
||||||
|
|
||||||
|
def feed(self, line: str) -> str:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
return ""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
try:
|
||||||
|
obj = _json.loads(line)
|
||||||
|
except Exception: # noqa: BLE001 - 非 JSON 行,原样透出
|
||||||
|
return line + "\n"
|
||||||
|
if not isinstance(obj, dict):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# ① 错误事件必须透出,用户要看到失败原因
|
||||||
|
if obj.get("type") == "error" and isinstance(obj.get("message"), str):
|
||||||
|
return f"\n[错误] {obj['message']}"
|
||||||
|
|
||||||
|
# ② 增量形状 A:CLI 的 stream_event 嵌套
|
||||||
|
event = obj.get("event")
|
||||||
|
if isinstance(event, dict):
|
||||||
|
delta = event.get("delta")
|
||||||
|
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||||||
|
self._saw_delta = True
|
||||||
|
return delta["text"]
|
||||||
|
|
||||||
|
# ③ 增量形状 B:Messages API 顶层 delta
|
||||||
|
delta = obj.get("delta")
|
||||||
|
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||||||
|
self._saw_delta = True
|
||||||
|
return delta["text"]
|
||||||
|
|
||||||
|
# ④ 成块文本(形状 C):已有增量就跳过,防重复
|
||||||
|
if self._saw_delta:
|
||||||
|
return ""
|
||||||
|
return self._block_text(obj)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _block_text(obj: dict) -> str:
|
||||||
|
"""取成块文本:只认 type=text 的 content block,跳过 tool_use / tool_result。"""
|
||||||
|
if isinstance(obj.get("result"), str):
|
||||||
|
return "" # 最终汇总不推流式,防重复
|
||||||
|
msg = obj.get("message")
|
||||||
|
source = msg if isinstance(msg, dict) else obj
|
||||||
|
content = source.get("content")
|
||||||
|
if isinstance(content, str):
|
||||||
|
return content
|
||||||
|
if isinstance(content, list):
|
||||||
|
parts = [
|
||||||
|
block.get("text", "")
|
||||||
|
for block in content
|
||||||
|
if isinstance(block, dict)
|
||||||
|
and block.get("type") == "text"
|
||||||
|
and isinstance(block.get("text"), str)
|
||||||
|
]
|
||||||
|
return "".join(parts)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_stream_text(line: str) -> str:
|
||||||
|
"""
|
||||||
|
无状态便捷入口:单行提取文本(不跨行去重)。
|
||||||
|
|
||||||
|
【注意】execute() 内部用有状态的 _StreamTextExtractor;
|
||||||
|
此函数仅供单行调试/兼容旧调用,跨行场景会失去 delta/成块去重能力。
|
||||||
|
"""
|
||||||
|
return _StreamTextExtractor().feed(line)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_final_text(stdout: str) -> str:
|
||||||
|
"""
|
||||||
|
从 stream-json 全量输出中提取最终完整文本。
|
||||||
|
|
||||||
|
优先取顶层 `result` 字段(Claude 的最终汇总,最权威);
|
||||||
|
没有 result 行时用 _StreamTextExtractor 累积(自动去重 delta 与成块文本)。
|
||||||
|
"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
obj = _json.loads(line)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
if isinstance(obj, dict) and isinstance(obj.get("result"), str):
|
||||||
|
return obj["result"]
|
||||||
|
|
||||||
|
extractor = _StreamTextExtractor()
|
||||||
|
parts = [text for text in (extractor.feed(line) for line in stdout.splitlines()) if text]
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_session_id(stdout: str) -> str:
|
||||||
|
"""
|
||||||
|
从 stream-json 输出中提取 Claude 会话 ID。
|
||||||
|
|
||||||
|
stream-json 开头会有:{"type":"system","subtype":"init","session_id":"xxx",...}
|
||||||
|
"""
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
sid = _extract_session_id_from_line(line)
|
||||||
|
if sid:
|
||||||
|
return sid
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_model_id(model: str) -> str:
|
||||||
|
"""
|
||||||
|
从模型注册表 key 中提取真实 model_id。
|
||||||
|
|
||||||
|
【背景】模型管理的注册表 key 格式是 "provider_key/model_id"(如 "小米6360/mimo-v2.6-pro"),
|
||||||
|
但 Claude CLI 只认 model_id(如 "mimo-v2.6-pro"),不认带前缀的 key。
|
||||||
|
【规则】含 "/" 时取最后一段作为 model_id;不含则原样返回。
|
||||||
|
"""
|
||||||
|
if not model:
|
||||||
|
return model
|
||||||
|
return model.rsplit("/", 1)[-1] if "/" in model else model
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_claude_config(model_id: str, session_id: str = "") -> Path:
|
||||||
|
"""
|
||||||
|
生成 Claude Code 独立配置目录(不动用户的 ~/.claude/settings.json)。
|
||||||
|
|
||||||
|
【方案】在 ~/.claude/agent-{session_id}/ 下写一份 settings.json,
|
||||||
|
连接信息(base_url + api_key)从 Provider 管理读,
|
||||||
|
模型名从用户提交时选的 model_id 取。
|
||||||
|
【关键】目录名用 session_id 做持久化——续聊时复用同一目录,
|
||||||
|
否则 --resume 找不到上一轮的会话!
|
||||||
|
【调用时】通过 CLAUDE_CONFIG_DIR 环境变量让 claude CLI 用这份配置。
|
||||||
|
"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
# 用 session_id 做目录名,确保续聊时复用同一目录(会话文件在里面)
|
||||||
|
dir_name = f"agent-{session_id[:12]}" if session_id else f"agent-{uuid.uuid4().hex[:12]}"
|
||||||
|
cfg_dir = Path.home() / ".claude" / dir_name
|
||||||
|
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# 1. 从模型配置找 provider_key → 从 Provider 管理拿 base_url + api_key
|
||||||
|
# 注意:model_id 可能是注册表 key("provider_key/model_id"),需要提取真实 model_id
|
||||||
|
real_model_id = _normalize_model_id(model_id)
|
||||||
|
base_url, api_key = "", ""
|
||||||
|
try:
|
||||||
|
from app.store.model_config_store import get_model_config_store
|
||||||
|
from app.store.provider_store import get_provider_store
|
||||||
|
|
||||||
|
# 按 model_id 找模型配置(取第一个匹配的)
|
||||||
|
mc_store = get_model_config_store()
|
||||||
|
all_models = mc_store.list_all()
|
||||||
|
target_model = next((m for m in all_models if m.model_id == real_model_id), None)
|
||||||
|
if target_model:
|
||||||
|
provider_key = target_model.provider_key
|
||||||
|
provider = get_provider_store().get_with_key(provider_key)
|
||||||
|
if provider:
|
||||||
|
base_url = provider.get("base_url", "")
|
||||||
|
api_key = provider.get("api_key", "")
|
||||||
|
except Exception: # noqa: BLE001 - 读不到就降级为空(走 CLI 默认)
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 2. 继承用户 settings.json 的非模型字段(如 AUTH_TOKEN),只替换核心的
|
||||||
|
user_cfg_path = Path.home() / ".claude" / "settings.json"
|
||||||
|
user_env: dict = {}
|
||||||
|
if user_cfg_path.exists():
|
||||||
|
try:
|
||||||
|
user_cfg = _json.loads(user_cfg_path.read_text(encoding="utf-8"))
|
||||||
|
user_env = dict(user_cfg.get("env", {}))
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 3. 组装独立配置:连接信息覆盖为 Provider 管理的值,模型覆盖为用户选的
|
||||||
|
env = {
|
||||||
|
**user_env,
|
||||||
|
"ANTHROPIC_MODEL": real_model_id,
|
||||||
|
"CLAUDE_CODE_SUBAGENT_MODEL": real_model_id,
|
||||||
|
}
|
||||||
|
if base_url:
|
||||||
|
env["ANTHROPIC_BASE_URL"] = base_url
|
||||||
|
if api_key:
|
||||||
|
env["ANTHROPIC_AUTH_TOKEN"] = api_key
|
||||||
|
|
||||||
|
clean_cfg = {"env": env, "model": real_model_id}
|
||||||
|
settings_file = cfg_dir / "settings.json"
|
||||||
|
settings_file.write_text(
|
||||||
|
_json.dumps(clean_cfg, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"已生成 Claude Code 独立配置:%s(模型=%s,provider_base_url=%s)",
|
||||||
|
settings_file, real_model_id, base_url or "继承",
|
||||||
|
)
|
||||||
|
return cfg_dir
|
||||||
|
|
||||||
|
|
||||||
|
def build_prompt(
|
||||||
|
step_description: str,
|
||||||
|
expected_output: str,
|
||||||
|
target_files: list[str],
|
||||||
|
prev_error: str = "",
|
||||||
|
retry: int = 0,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
构建 Claude Code 的改码 Prompt。
|
||||||
|
|
||||||
|
【要点】
|
||||||
|
- 明确任务范围(只改指定文件);
|
||||||
|
- 附带上次失败原因(修复循环);
|
||||||
|
- 要求代码注释(符合项目规范)。
|
||||||
|
"""
|
||||||
|
files_desc = "\n".join(f" - {f}" for f in target_files[:5]) if target_files else " - 请自行定位相关文件"
|
||||||
|
|
||||||
|
retry_hint = f"\n【上次修改失败原因,请修正】{prev_error}" if prev_error else ""
|
||||||
|
|
||||||
|
return f"""你是一个 Java 项目代码修复工程师。请完成以下修改任务。
|
||||||
|
|
||||||
|
【修改任务】{step_description}
|
||||||
|
【预期产出】{expected_output}
|
||||||
|
【重试次数】{retry}{retry_hint}
|
||||||
|
|
||||||
|
【候选文件】
|
||||||
|
{files_desc}
|
||||||
|
|
||||||
|
【硬性要求】
|
||||||
|
1. 只修改与本任务直接相关的代码,禁止改动无关文件;
|
||||||
|
2. 修改处必须加中文注释(说明功能、修改原因);
|
||||||
|
3. 修改完成后自行检查代码语法正确性;
|
||||||
|
4. 完成后在最后一行输出固定格式摘要:DONE: <一句话修改说明>。"""
|
||||||
|
|
||||||
|
|
||||||
|
def execute(
|
||||||
|
project_root: Path,
|
||||||
|
prompt: str,
|
||||||
|
task_id: str = "",
|
||||||
|
timeout: int = 0,
|
||||||
|
model: str = "",
|
||||||
|
on_output=None,
|
||||||
|
session_id: str = "",
|
||||||
|
resume: bool = False,
|
||||||
|
skip_snapshot: bool = False,
|
||||||
|
on_session=None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
调用 Claude Code CLI 执行任务(零限制,流式输出,会话续聊)。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
project_root:项目代码根目录
|
||||||
|
prompt:用户原话,不做任何包装
|
||||||
|
task_id:任务 ID(用于审计与快照)
|
||||||
|
timeout:0=不超时,跑完为止
|
||||||
|
model:模型名
|
||||||
|
on_output:流式回调 fn(text),每提取到一段可展示文本调用一次
|
||||||
|
session_id:Claude 会话 ID(首次传入 = 指定会话;resume 时 = 续接该会话)
|
||||||
|
resume:True = 用 --resume 续接已有会话(Claude 自己管上下文)
|
||||||
|
skip_snapshot:True = 跳过文件快照(对话续聊不需要快照代码)
|
||||||
|
on_session:会话就绪回调 fn(session_id),CLI 一吐出 init 事件立刻触发
|
||||||
|
—— 供调用方提前落库,避免执行完才补写时进程已死
|
||||||
|
"""
|
||||||
|
project_root = Path(project_root)
|
||||||
|
if not project_root.exists():
|
||||||
|
raise ClaudeCodeError(f"项目根目录不存在:{project_root}", error_type="PathNotFound")
|
||||||
|
claude_path = get_claude_path() # 拿完整路径,绕过 Windows PATHEXT 问题
|
||||||
|
|
||||||
|
# 执行前对项目做快照(对话续聊跳过,代码改码才需要)
|
||||||
|
if not skip_snapshot:
|
||||||
|
try:
|
||||||
|
snapshot_count = 0
|
||||||
|
for java_file in project_root.rglob("*.java"):
|
||||||
|
if _backup_file(java_file, task_id):
|
||||||
|
snapshot_count += 1
|
||||||
|
if snapshot_count >= 20:
|
||||||
|
break
|
||||||
|
logger.info("改码前快照完成:%d 个文件", snapshot_count)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("改码前快照失败(继续执行):%s", exc)
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
logger.info("调用 Claude Code 执行改码任务(cwd=%s)", project_root)
|
||||||
|
|
||||||
|
cfg_dir: Path | None = None # 临时配置目录,finally 中清理
|
||||||
|
try:
|
||||||
|
real_model = _normalize_model_id(model) if model else ""
|
||||||
|
cmd = [
|
||||||
|
claude_path,
|
||||||
|
"-p", # --print 模式,prompt 从 STDIN 读取
|
||||||
|
"--permission-mode", "acceptEdits",
|
||||||
|
"--output-format", "stream-json",
|
||||||
|
# 【13.7 修复】不加这个参数,stream-json 只吐成块消息,没有逐字增量,
|
||||||
|
# 前端只能在 done 时一把出。加了才会输出 stream_event/content_block_delta。
|
||||||
|
"--include-partial-messages",
|
||||||
|
"--verbose",
|
||||||
|
]
|
||||||
|
# 会话机制(终端同款):续聊用 --resume,首轮/无 session_id 时必须用 --session-id
|
||||||
|
# 【关键】session_id 为空也必须传 --session-id(随机 UUID),
|
||||||
|
# 否则 Claude CLI 默认续接 cwd 下的上一个会话 → 串台!
|
||||||
|
use_resume = bool(resume and session_id)
|
||||||
|
if use_resume:
|
||||||
|
cmd += ["--resume", session_id]
|
||||||
|
else:
|
||||||
|
if not session_id:
|
||||||
|
session_id = str(uuid.uuid4())
|
||||||
|
cmd += ["--session-id", session_id]
|
||||||
|
if real_model and real_model != "auto" and real_model.startswith("claude-"):
|
||||||
|
cmd += ["--model", real_model]
|
||||||
|
|
||||||
|
import os
|
||||||
|
env = os.environ.copy()
|
||||||
|
if real_model and real_model != "auto":
|
||||||
|
env["ANTHROPIC_MODEL"] = real_model
|
||||||
|
# 【关键】用 session_id 做目录名持久化,续聊时复用同一目录
|
||||||
|
cfg_dir = prepare_claude_config(real_model, session_id)
|
||||||
|
env["CLAUDE_CONFIG_DIR"] = str(cfg_dir)
|
||||||
|
else:
|
||||||
|
env.pop("ANTHROPIC_MODEL", None)
|
||||||
|
|
||||||
|
# 流式执行:prompt 从 STDIN 传入(避免命令行截断/乱码)
|
||||||
|
import subprocess as sp
|
||||||
|
|
||||||
|
from app.tools.proc_flags import hidden_popen_kwargs
|
||||||
|
|
||||||
|
process = sp.Popen(
|
||||||
|
cmd,
|
||||||
|
cwd=str(project_root),
|
||||||
|
stdin=sp.PIPE,
|
||||||
|
stdout=sp.PIPE,
|
||||||
|
stderr=sp.STDOUT,
|
||||||
|
text=True,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
env=env,
|
||||||
|
shell=False,
|
||||||
|
bufsize=1, # 行缓冲,逐行输出
|
||||||
|
# 【弹窗修复】claude 的入口是 claude.CMD(控制台程序),
|
||||||
|
# 直接拉起会分配可见控制台窗口。CREATE_NO_WINDOW 让它照常跑但不弹窗。
|
||||||
|
# 注意:不要用 DETACHED_PROCESS,它才是弹窗元凶(见 proc_flags 实测表)。
|
||||||
|
**hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
# 写入 prompt 到 STDIN 并关闭
|
||||||
|
process.stdin.write(prompt)
|
||||||
|
process.stdin.close()
|
||||||
|
# 注册进程,供外部「停止」按钮 kill
|
||||||
|
if task_id:
|
||||||
|
_running_processes[task_id] = process
|
||||||
|
try:
|
||||||
|
output_lines: list[str] = []
|
||||||
|
extractor = _StreamTextExtractor()
|
||||||
|
session_reported = False
|
||||||
|
# 逐行读取 stream-json,提取文本内容后回调
|
||||||
|
while True:
|
||||||
|
line = process.stdout.readline()
|
||||||
|
if not line and process.poll() is not None:
|
||||||
|
break
|
||||||
|
if line:
|
||||||
|
output_lines.append(line)
|
||||||
|
# 【13.8 修复】会话 ID 一拿到就立刻回调落库,
|
||||||
|
# 不等 execute() 返回——进程随时可能被 reload 杀掉。
|
||||||
|
if on_session and not session_reported:
|
||||||
|
sid = _extract_session_id_from_line(line)
|
||||||
|
if sid:
|
||||||
|
session_reported = True
|
||||||
|
try:
|
||||||
|
on_session(sid)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
if on_output:
|
||||||
|
try:
|
||||||
|
text = extractor.feed(line)
|
||||||
|
if text:
|
||||||
|
on_output(text)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
process.wait(timeout=timeout if timeout and timeout > 0 else None)
|
||||||
|
finally:
|
||||||
|
# 【BUG-3 修复】异常/退出时确保子进程被清理,防止僵尸进程
|
||||||
|
if process.poll() is None:
|
||||||
|
process.kill()
|
||||||
|
process.wait()
|
||||||
|
|
||||||
|
class _FakeCompleted:
|
||||||
|
"""模拟 subprocess.run 返回结构,统一后续处理"""
|
||||||
|
def __init__(self, rc: int) -> None:
|
||||||
|
self.returncode = rc
|
||||||
|
self.stdout = "".join(output_lines)
|
||||||
|
self.stderr = ""
|
||||||
|
|
||||||
|
completed = _FakeCompleted(process.returncode)
|
||||||
|
|
||||||
|
duration = round(time.time() - start, 1)
|
||||||
|
stdout = completed.stdout or ""
|
||||||
|
|
||||||
|
# 从 stream-json 提取完整文本输出(result 字段)
|
||||||
|
output = _extract_final_text(stdout)
|
||||||
|
if not output:
|
||||||
|
# 【BUG-3 修复】降级兜底时过滤 JSON 行,只保留纯文本
|
||||||
|
text_lines = []
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped.startswith("{") and stripped.endswith("}"):
|
||||||
|
continue # 跳过 stream-json 行
|
||||||
|
if stripped:
|
||||||
|
text_lines.append(stripped)
|
||||||
|
output = "\n".join(text_lines) if text_lines else stdout
|
||||||
|
|
||||||
|
# 提取 Claude 会话 ID(供 --resume 续聊用)
|
||||||
|
detected_session_id = _extract_session_id(stdout)
|
||||||
|
|
||||||
|
# 成功判定:returncode==0 即算成功
|
||||||
|
success = completed.returncode == 0
|
||||||
|
|
||||||
|
# 【13.8 兜底】--resume 找不到会话(配置目录丢失 / 会话被清理)时,
|
||||||
|
# 回退成 --session-id 重跑一次,避免整轮对话直接失败且上下文全丢。
|
||||||
|
if use_resume and not success and "No conversation found" in stdout:
|
||||||
|
logger.warning("会话 %s 已丢失,回退 --session-id 重跑一次", session_id)
|
||||||
|
return execute(
|
||||||
|
project_root=project_root,
|
||||||
|
prompt=prompt,
|
||||||
|
task_id=task_id,
|
||||||
|
timeout=timeout,
|
||||||
|
model=model,
|
||||||
|
on_output=on_output,
|
||||||
|
session_id=session_id,
|
||||||
|
resume=False,
|
||||||
|
skip_snapshot=True, # 首跑已快照过,重跑不再重复
|
||||||
|
on_session=on_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"success": success,
|
||||||
|
"output": output,
|
||||||
|
"summary": output.strip().splitlines()[-1][:200] if output.strip() else "(无输出)",
|
||||||
|
"duration": duration,
|
||||||
|
"returncode": completed.returncode,
|
||||||
|
"session_id": detected_session_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="claude_code_execute",
|
||||||
|
target=str(project_root),
|
||||||
|
result="success" if success else "failure",
|
||||||
|
details={
|
||||||
|
"summary": result["summary"][:200],
|
||||||
|
"duration": duration,
|
||||||
|
"returncode": completed.returncode,
|
||||||
|
"task_id": task_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logger.info("Claude Code 执行完成:success=%s, duration=%ss", success, duration)
|
||||||
|
return result
|
||||||
|
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise ClaudeCodeError(
|
||||||
|
f"claude CLI 未找到(路径:{claude_path}),请确认已安装 Claude Code",
|
||||||
|
error_type="ClaudeNotFound",
|
||||||
|
) from exc
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
log_action(
|
||||||
|
action="claude_code_execute",
|
||||||
|
target=str(project_root),
|
||||||
|
result="failure",
|
||||||
|
details={"error": "timeout", "timeout": timeout, "task_id": task_id},
|
||||||
|
)
|
||||||
|
raise ClaudeCodeError(
|
||||||
|
f"Claude Code 执行超时(>{timeout}秒)", error_type="Timeout"
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
# 注销进程
|
||||||
|
if task_id:
|
||||||
|
_running_processes.pop(task_id, None)
|
||||||
|
# 【注意】配置目录不能删!Claude 会话文件在里面,删了 --resume 就找不到了。
|
||||||
|
# 目录在任务删除时由 delete_task 统一清理。
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
"""
|
||||||
|
白名单命令执行器
|
||||||
|
================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
受限执行系统命令(编译、测试、git 等),带白名单校验、超时保护、
|
||||||
|
输出截断与审计日志。对应决策点 11「白名单受限执行」。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选白名单而非完整 Shell(决策点 11 已论证):
|
||||||
|
Agent 能跑编译验证假设,但不能 rm -rf /、不能改系统配置。
|
||||||
|
2. list 参数传参(shell=False):杜绝命令注入,`&&`、`|`、`;` 全部失效。
|
||||||
|
3. 超时 + 输出截断:防止编译卡死或日志刷爆上下文(硬约束 5 兜底)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- ALLOWED_COMMANDS 白名单:mvn/npm/npx/git/java/javac 等;
|
||||||
|
- 命令首段必须命中白名单,否则直接拒绝并审计;
|
||||||
|
- cwd 强制限定在允许根目录内;
|
||||||
|
- 执行结果统一返回 {stdout, stderr, returncode, truncated}。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:白名单命令带危险子参数(如 `git push --force`、`mvn clean` 误删)。
|
||||||
|
应对:一级黑名单子参数(push/force/reset --hard 等)直接拒绝。
|
||||||
|
风险2:命令执行卡死占用资源。
|
||||||
|
应对:强制 timeout(默认 60s,可配),超时 kill 进程组。
|
||||||
|
风险3:输出超大撑爆 Agent 上下文。
|
||||||
|
应对:stdout/stderr 各截断到 EXEC_OUTPUT_MAX_CHARS(默认 20000)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.config.settings import load_settings
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
from app.tools.proc_flags import hidden_popen_kwargs
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.executor")
|
||||||
|
|
||||||
|
# 允许执行的命令白名单(决策点 11)
|
||||||
|
ALLOWED_COMMANDS = {
|
||||||
|
"mvn", "npm", "npx", "git", "java", "javac", "python", "python3",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 禁止的子命令/参数(二级黑名单,防滥用)
|
||||||
|
FORBIDDEN_PATTERNS = [
|
||||||
|
"push", "--force", "-f ", "reset --hard", "clean --force",
|
||||||
|
"rm ", "del ", "format", "shutdown", "mkfs",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ExecutorError(RuntimeError):
|
||||||
|
"""执行器异常(中文可读)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "ExecutorError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_command(args: list[str]) -> None:
|
||||||
|
"""
|
||||||
|
校验命令是否在白名单内。
|
||||||
|
|
||||||
|
【规则】
|
||||||
|
1. args 非空且首段命中 ALLOWED_COMMANDS;
|
||||||
|
2. 整条命令不得命中 FORBIDDEN_PATTERNS。
|
||||||
|
"""
|
||||||
|
if not args:
|
||||||
|
raise ExecutorError("命令为空", error_type="EmptyCommand")
|
||||||
|
|
||||||
|
cmd_name = Path(args[0]).name.lower()
|
||||||
|
if cmd_name not in ALLOWED_COMMANDS:
|
||||||
|
raise ExecutorError(
|
||||||
|
f"命令 {cmd_name} 不在白名单内(允许:{sorted(ALLOWED_COMMANDS)})",
|
||||||
|
error_type="CommandNotAllowed",
|
||||||
|
)
|
||||||
|
|
||||||
|
full = " ".join(args).lower()
|
||||||
|
for pattern in FORBIDDEN_PATTERNS:
|
||||||
|
if pattern in full:
|
||||||
|
raise ExecutorError(
|
||||||
|
f"命令包含被禁止的子参数:{pattern}(安全策略拒绝)",
|
||||||
|
error_type="ForbiddenArgument",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_command(cmd_name: str) -> str:
|
||||||
|
"""
|
||||||
|
解析命令为完整可执行路径。
|
||||||
|
|
||||||
|
【Windows 坑】mvn 实际是 mvn.cmd,subprocess 无 shell 时找不到;
|
||||||
|
shutil.which 会自动解析 .cmd/.exe/.bat 后缀,必须先解析再执行。
|
||||||
|
"""
|
||||||
|
resolved = shutil.which(cmd_name)
|
||||||
|
if resolved:
|
||||||
|
return resolved
|
||||||
|
# 兜底:逐个尝试常见 Windows 后缀
|
||||||
|
for suffix in (".cmd", ".bat", ".exe"):
|
||||||
|
candidate = shutil.which(cmd_name + suffix)
|
||||||
|
if candidate:
|
||||||
|
return candidate
|
||||||
|
return cmd_name # 交给 FileNotFoundError 报错
|
||||||
|
|
||||||
|
|
||||||
|
def run_command(
|
||||||
|
args: list[str],
|
||||||
|
cwd: str | Path,
|
||||||
|
timeout: int | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
执行白名单命令。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
args:命令参数列表(如 ["mvn", "-q", "compile"])
|
||||||
|
cwd:工作目录(必须在允许范围内)
|
||||||
|
timeout:超时秒数(默认取配置 EXEC_TIMEOUT_SECONDS)
|
||||||
|
【返回】{stdout, stderr, returncode, truncated, command, cwd}
|
||||||
|
"""
|
||||||
|
settings = load_settings()
|
||||||
|
timeout = timeout or settings.exec_timeout_seconds
|
||||||
|
max_chars = settings.exec_output_max_chars
|
||||||
|
|
||||||
|
_validate_command(args)
|
||||||
|
work_dir = ensure_under_root(Path(cwd), action="执行命令")
|
||||||
|
|
||||||
|
if not work_dir.exists():
|
||||||
|
raise ExecutorError(f"工作目录不存在:{work_dir}", error_type="PathNotFound")
|
||||||
|
|
||||||
|
# Windows 下解析命令为完整路径(mvn → mvn.cmd)
|
||||||
|
resolved_args = [_resolve_command(args[0])] + list(args[1:])
|
||||||
|
command_str = " ".join(args)
|
||||||
|
logger.info("执行命令:%s(cwd=%s)", command_str, work_dir)
|
||||||
|
|
||||||
|
try:
|
||||||
|
completed = subprocess.run(
|
||||||
|
resolved_args,
|
||||||
|
cwd=str(work_dir),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout,
|
||||||
|
shell=False,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
**hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise ExecutorError(
|
||||||
|
f"命令不存在:{args[0]},请确认已安装并加入 PATH",
|
||||||
|
error_type="CommandNotFound",
|
||||||
|
) from exc
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
log_action(
|
||||||
|
action="exec_command",
|
||||||
|
target=command_str,
|
||||||
|
result="failure",
|
||||||
|
details={"error": "timeout", "timeout": timeout},
|
||||||
|
)
|
||||||
|
raise ExecutorError(
|
||||||
|
f"命令执行超时(>{timeout}秒):{command_str}",
|
||||||
|
error_type="Timeout",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
stdout = completed.stdout or ""
|
||||||
|
stderr = completed.stderr or ""
|
||||||
|
truncated = False
|
||||||
|
if len(stdout) > max_chars:
|
||||||
|
stdout = stdout[:max_chars] + f"\n…(输出截断,共 {len(completed.stdout)} 字符)"
|
||||||
|
truncated = True
|
||||||
|
if len(stderr) > max_chars:
|
||||||
|
stderr = stderr[:max_chars] + f"\n…(输出截断,共 {len(completed.stderr)} 字符)"
|
||||||
|
truncated = True
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="exec_command",
|
||||||
|
target=command_str,
|
||||||
|
result="success" if completed.returncode == 0 else "failure",
|
||||||
|
details={
|
||||||
|
"returncode": completed.returncode,
|
||||||
|
"cwd": str(work_dir),
|
||||||
|
"stdout_len": len(completed.stdout or ""),
|
||||||
|
"stderr_len": len(completed.stderr or ""),
|
||||||
|
"truncated": truncated,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"command": command_str,
|
||||||
|
"cwd": str(work_dir),
|
||||||
|
"stdout": stdout,
|
||||||
|
"stderr": stderr,
|
||||||
|
"returncode": completed.returncode,
|
||||||
|
"truncated": truncated,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 便捷封装:编译验证 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def run_compile_check(project_path: str | Path) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
对目标项目执行编译级验证(决策点 8)。
|
||||||
|
|
||||||
|
【自动识别】
|
||||||
|
- 有 pom.xml → Maven:mvn -q -DskipTests compile
|
||||||
|
- 有 package.json → npm:npm run build(或 tsc --noEmit)
|
||||||
|
【返回】{passed, command, stdout, stderr}
|
||||||
|
"""
|
||||||
|
root = ensure_under_root(Path(project_path), action="编译验证")
|
||||||
|
|
||||||
|
if (root / "pom.xml").exists():
|
||||||
|
result = run_command(["mvn", "-q", "-DskipTests", "compile"], cwd=root)
|
||||||
|
elif (root / "package.json").exists():
|
||||||
|
result = run_command(["npm", "run", "build"], cwd=root)
|
||||||
|
else:
|
||||||
|
return {
|
||||||
|
"passed": False,
|
||||||
|
"command": "",
|
||||||
|
"stdout": "",
|
||||||
|
"stderr": f"无法识别项目类型(未找到 pom.xml 或 package.json):{root}",
|
||||||
|
"returncode": -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"passed": result["returncode"] == 0,
|
||||||
|
"command": result["command"],
|
||||||
|
"stdout": result["stdout"],
|
||||||
|
"stderr": result["stderr"],
|
||||||
|
"returncode": result["returncode"],
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
"""
|
||||||
|
文件工具(读 / 写 / 编辑)
|
||||||
|
=========================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
自研工具链的文件操作能力:读取、写入、精确编辑(字符串替换)。
|
||||||
|
每次写盘前自动快照备份,支持一键还原(决策点 12「Git + 快照」双安全网)。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 2 选「纯自研工具链」:不引入 Aider 等外部编码引擎,
|
||||||
|
文件读写编辑自己实现,彻底掌握编码 Agent 的底层机制(教学价值)。
|
||||||
|
2. 编辑用「精确字符串替换」而非整文件覆盖:
|
||||||
|
最小化改动面、可预测、diff 可读,符合你 CLAUDE.md「最小必要改动」。
|
||||||
|
3. 写盘前快照到 D:\\Agent\\agent\\data\\backups:
|
||||||
|
即使没有 Git,也能还原到修改前(硬约束 5 兜底)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- read_file:支持按行号范围读取(大文件只读所需片段,省 token);
|
||||||
|
- write_file:写盘前备份原文件,新文件无需备份;
|
||||||
|
- edit_file:精确匹配 old_str → new_str,要求唯一匹配,避免误替换;
|
||||||
|
- 所有路径经 PathGuard 校验,越权直接拒绝。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:edit_file 的 old_str 在文件中多次出现 → 误替换。
|
||||||
|
应对:强制唯一匹配,多次出现时报错并提示用户给更多上下文。
|
||||||
|
风险2:写入半途断电/异常 → 文件损坏。
|
||||||
|
应对:先写临时文件再原子替换(Windows 下 os.replace)。
|
||||||
|
风险3:编码不一致(GBK/UTF-8)导致写坏文件。
|
||||||
|
应对:读取时探测编码,写入统一 UTF-8;无法确定时拒写并报错。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.file")
|
||||||
|
|
||||||
|
# 快照备份目录(决策点 12:Git 之外的二道保险)
|
||||||
|
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups")
|
||||||
|
|
||||||
|
|
||||||
|
class FileToolError(RuntimeError):
|
||||||
|
"""文件工具异常(中文可读)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "FileToolError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_encoding(path: Path) -> str:
|
||||||
|
"""探测文件编码:UTF-8 优先,回退 GBK。"""
|
||||||
|
raw = path.read_bytes()
|
||||||
|
for enc in ("utf-8", "gbk"):
|
||||||
|
try:
|
||||||
|
raw.decode(enc)
|
||||||
|
return enc
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
return "utf-8" # 兜底(读取时 errors=replace)
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_file(path: Path, task_id: str = "") -> Path | None:
|
||||||
|
"""
|
||||||
|
写盘前快照备份原文件。
|
||||||
|
|
||||||
|
【返回】备份文件路径;原文件不存在返回 None。
|
||||||
|
【联动】同时写入回滚索引,供 RollbackService 按任务还原。
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
return None
|
||||||
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
rel_name = str(path).replace("\\", "_").replace(":", "").replace("/", "_")
|
||||||
|
backup_name = f"{timestamp}_{task_id}_{rel_name}" if task_id else f"{timestamp}_{rel_name}"
|
||||||
|
backup_path = BACKUP_DIR / backup_name
|
||||||
|
backup_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(path, backup_path)
|
||||||
|
|
||||||
|
# 写入回滚索引(M5:一键回滚依赖此映射)
|
||||||
|
try:
|
||||||
|
from app.tasks.rollback_service import record_backup
|
||||||
|
|
||||||
|
record_backup(str(backup_path), str(path), task_id)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 索引失败不影响备份本身
|
||||||
|
logger.warning("写入回滚索引失败:%s", exc)
|
||||||
|
|
||||||
|
logger.info("已快照备份:%s → %s", path, backup_path)
|
||||||
|
return backup_path
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 读取 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def read_file(
|
||||||
|
path: str | Path,
|
||||||
|
start_line: int = 0,
|
||||||
|
end_line: int | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
读取文件内容(支持按行号范围)。
|
||||||
|
|
||||||
|
【返回】{path, content, total_lines, start_line, end_line}
|
||||||
|
【用途】Agent 读取源码以理解上下文(决策点 2 自研工具链)。
|
||||||
|
"""
|
||||||
|
file_path = ensure_under_root(Path(path), action="读取", readonly=True)
|
||||||
|
if not file_path.exists():
|
||||||
|
raise FileToolError(f"文件不存在:{file_path}", error_type="FileNotFound")
|
||||||
|
if not file_path.is_file():
|
||||||
|
raise FileToolError(f"路径不是文件:{file_path}", error_type="NotAFile")
|
||||||
|
|
||||||
|
encoding = _detect_encoding(file_path)
|
||||||
|
try:
|
||||||
|
text = file_path.read_text(encoding=encoding, errors="replace")
|
||||||
|
except Exception as exc:
|
||||||
|
raise FileToolError(f"读取失败:{file_path},原因:{exc}", error_type="ReadFailed")
|
||||||
|
|
||||||
|
lines = text.splitlines(keepends=True)
|
||||||
|
total = len(lines)
|
||||||
|
start = max(0, start_line)
|
||||||
|
end = total if end_line is None else min(end_line, total)
|
||||||
|
selected = "".join(lines[start:end])
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="file_read",
|
||||||
|
target=str(file_path),
|
||||||
|
result="success",
|
||||||
|
details={"start_line": start, "end_line": end, "total_lines": total},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"path": str(file_path),
|
||||||
|
"content": selected,
|
||||||
|
"total_lines": total,
|
||||||
|
"start_line": start,
|
||||||
|
"end_line": end,
|
||||||
|
"encoding": encoding,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 写入 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def write_file(
|
||||||
|
path: str | Path,
|
||||||
|
content: str,
|
||||||
|
task_id: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
写入文件(写盘前自动快照备份)。
|
||||||
|
|
||||||
|
【返回】{path, backup_path, bytes_written}
|
||||||
|
【安全】路径经守卫校验;原文件先备份;原子替换防写坏。
|
||||||
|
"""
|
||||||
|
file_path = ensure_under_root(Path(path), action="写入")
|
||||||
|
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
backup_path = _backup_file(file_path, task_id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 先写临时文件再原子替换,防止半途失败写坏原文件
|
||||||
|
tmp_path = file_path.with_suffix(file_path.suffix + ".tmp_write")
|
||||||
|
tmp_path.write_text(content, encoding="utf-8")
|
||||||
|
os.replace(tmp_path, file_path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise FileToolError(
|
||||||
|
f"写入失败:{file_path},原因:{exc}", error_type="WriteFailed"
|
||||||
|
)
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="file_write",
|
||||||
|
target=str(file_path),
|
||||||
|
result="success",
|
||||||
|
details={
|
||||||
|
"backup_path": str(backup_path) if backup_path else "新文件无备份",
|
||||||
|
"bytes": len(content.encode("utf-8")),
|
||||||
|
"task_id": task_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"path": str(file_path),
|
||||||
|
"backup_path": str(backup_path) if backup_path else None,
|
||||||
|
"bytes_written": len(content.encode("utf-8")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 精确编辑 ----------
|
||||||
|
|
||||||
|
|
||||||
|
def edit_file(
|
||||||
|
path: str | Path,
|
||||||
|
old_str: str,
|
||||||
|
new_str: str,
|
||||||
|
task_id: str = "",
|
||||||
|
replace_all: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
精确编辑:把 old_str 替换为 new_str(最小改动面)。
|
||||||
|
|
||||||
|
【约束】
|
||||||
|
- old_str 必须在文件中唯一出现(除非 replace_all=True);
|
||||||
|
- 匹配失败或多次匹配时抛错,不猜测、不误替换。
|
||||||
|
【返回】{path, replacements, backup_path}
|
||||||
|
"""
|
||||||
|
file_path = ensure_under_root(Path(path), action="编辑")
|
||||||
|
if not file_path.exists():
|
||||||
|
raise FileToolError(f"文件不存在:{file_path}", error_type="FileNotFound")
|
||||||
|
|
||||||
|
encoding = _detect_encoding(file_path)
|
||||||
|
text = file_path.read_text(encoding=encoding, errors="replace")
|
||||||
|
|
||||||
|
occurrences = text.count(old_str)
|
||||||
|
if occurrences == 0:
|
||||||
|
raise FileToolError(
|
||||||
|
f"编辑失败:在 {file_path} 中未找到匹配文本。"
|
||||||
|
f"请确认 old_str 与文件内容完全一致(含缩进与换行)",
|
||||||
|
error_type="StringNotFound",
|
||||||
|
)
|
||||||
|
if occurrences > 1 and not replace_all:
|
||||||
|
raise FileToolError(
|
||||||
|
f"编辑失败:匹配文本在文件中出现 {occurrences} 次,无法确定替换位置。"
|
||||||
|
f"请提供更多上下文使匹配唯一,或设置 replace_all=True",
|
||||||
|
error_type="AmbiguousMatch",
|
||||||
|
)
|
||||||
|
|
||||||
|
backup_path = _backup_file(file_path, task_id)
|
||||||
|
new_text = text.replace(old_str, new_str) if replace_all else text.replace(old_str, new_str, 1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
tmp_path = file_path.with_suffix(file_path.suffix + ".tmp_edit")
|
||||||
|
tmp_path.write_text(new_text, encoding="utf-8")
|
||||||
|
os.replace(tmp_path, file_path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise FileToolError(f"编辑写入失败:{exc}", error_type="WriteFailed")
|
||||||
|
|
||||||
|
replacements = occurrences if replace_all else 1
|
||||||
|
log_action(
|
||||||
|
action="file_edit",
|
||||||
|
target=str(file_path),
|
||||||
|
result="success",
|
||||||
|
details={
|
||||||
|
"old_str_preview": old_str[:100],
|
||||||
|
"new_str_preview": new_str[:100],
|
||||||
|
"replacements": replacements,
|
||||||
|
"backup_path": str(backup_path) if backup_path else None,
|
||||||
|
"task_id": task_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"path": str(file_path),
|
||||||
|
"replacements": replacements,
|
||||||
|
"backup_path": str(backup_path) if backup_path else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def restore_backup(backup_path: str | Path, target_path: str | Path) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
从快照还原文件(回滚能力)。
|
||||||
|
|
||||||
|
【用途】改错时一键还原到修改前状态(硬约束 5 兜底)。
|
||||||
|
"""
|
||||||
|
backup = Path(backup_path)
|
||||||
|
target = ensure_under_root(Path(target_path), action="还原")
|
||||||
|
if not backup.exists():
|
||||||
|
raise FileToolError(f"备份文件不存在:{backup}", error_type="BackupNotFound")
|
||||||
|
shutil.copy2(backup, target)
|
||||||
|
log_action(action="file_restore", target=str(target), result="success",
|
||||||
|
details={"backup": str(backup)})
|
||||||
|
return {"restored": str(target), "from_backup": str(backup)}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""
|
||||||
|
Git 操作工具
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
封装本地 Git 的常用写操作:状态查看、diff、建任务分支、提交。
|
||||||
|
对应决策点 12/13「本地 Git 管理 + 真实分支语义」。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 决策点 12 已锁定「本地 Git(无远程)」:改动可回滚、可审计、可并发隔离;
|
||||||
|
2. 任务分支策略:每个任务自动建 `agent/task_<id>` 分支,
|
||||||
|
改动隔离在任务分支上,master 不受污染(企业级标准做法);
|
||||||
|
3. 仍走 subprocess list 传参,防注入(与 GitReadService 同款)。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- ensure_task_branch:存在则切、不存在则建并切;
|
||||||
|
- commit_changes:add + commit(不 push,无远程);
|
||||||
|
- get_diff:工作区相对 HEAD 的 diff,供 Agent/人查看改动。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:工作区有未提交改动时切分支被拒。
|
||||||
|
应对:先自动 stash 或 commit 当前改动(决策:选 commit 留痕)。
|
||||||
|
风险2:git user.name/email 未配置导致 commit 失败。
|
||||||
|
应对:首次提交前自动设置仓库级 user(agent-bot)。
|
||||||
|
风险3:误提交大文件/敏感文件。
|
||||||
|
应对:.gitignore 已排除 .env 等;审计日志记录每次 commit 内容摘要。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
from app.tools.proc_flags import hidden_popen_kwargs
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.git")
|
||||||
|
|
||||||
|
|
||||||
|
class GitToolError(RuntimeError):
|
||||||
|
"""Git 工具异常(中文可读)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "GitToolError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
def _git(repo: Path, args: list[str], timeout: int = 30) -> str:
|
||||||
|
"""在指定仓库执行 git 命令,返回 stdout。"""
|
||||||
|
try:
|
||||||
|
completed = subprocess.run(
|
||||||
|
["git", *args],
|
||||||
|
cwd=str(repo),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout,
|
||||||
|
shell=False,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
**hidden_popen_kwargs(),
|
||||||
|
)
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise GitToolError("未检测到 git 命令", error_type="GitNotFound") from exc
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
raise GitToolError(f"git 命令超时:git {' '.join(args)}", error_type="Timeout") from exc
|
||||||
|
|
||||||
|
if completed.returncode != 0:
|
||||||
|
raise GitToolError(
|
||||||
|
f"git {' '.join(args)} 失败(退出码 {completed.returncode}):{(completed.stderr or '')[:500]}",
|
||||||
|
error_type="GitCommandFailed",
|
||||||
|
)
|
||||||
|
return completed.stdout or ""
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_task_branch(repo_path: str | Path, task_id: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
确保当前仓库位于任务分支上(存在则切、不存在则建并切)。
|
||||||
|
|
||||||
|
【分支命名】agent/task_<task_id>,隔离任务改动。
|
||||||
|
"""
|
||||||
|
repo = ensure_under_root(Path(repo_path), action="Git 操作")
|
||||||
|
branch = f"agent/task_{task_id}"
|
||||||
|
|
||||||
|
# 确保 user 配置存在(否则 commit 会失败)
|
||||||
|
try:
|
||||||
|
_git(repo, ["config", "user.email"], timeout=10)
|
||||||
|
except GitToolError:
|
||||||
|
_git(repo, ["config", "user.email", "agent-bot@local"], timeout=10)
|
||||||
|
_git(repo, ["config", "user.name", "agent-bot"], timeout=10)
|
||||||
|
|
||||||
|
try:
|
||||||
|
_git(repo, ["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], timeout=10)
|
||||||
|
# 分支已存在 → 切换
|
||||||
|
_git(repo, ["checkout", branch], timeout=15)
|
||||||
|
action = "switched"
|
||||||
|
except GitToolError:
|
||||||
|
# 分支不存在 → 创建并切换(若工作区脏,先建分支自带改动)
|
||||||
|
try:
|
||||||
|
_git(repo, ["checkout", "-b", branch], timeout=15)
|
||||||
|
action = "created"
|
||||||
|
except GitToolError as exc:
|
||||||
|
raise GitToolError(
|
||||||
|
f"创建任务分支失败:{exc}", error_type="BranchCreateFailed"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="git_branch",
|
||||||
|
target=str(repo),
|
||||||
|
result="success",
|
||||||
|
details={"branch": branch, "action": action, "task_id": task_id},
|
||||||
|
)
|
||||||
|
return {"repo": str(repo), "branch": branch, "action": action}
|
||||||
|
|
||||||
|
|
||||||
|
def commit_changes(repo_path: str | Path, message: str, task_id: str = "") -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
提交当前工作区改动(add + commit,不 push——决策点 12 无远程)。
|
||||||
|
|
||||||
|
【返回】{commit_hash, branch, files_changed}
|
||||||
|
"""
|
||||||
|
repo = ensure_under_root(Path(repo_path), action="Git 提交")
|
||||||
|
|
||||||
|
# add 全部改动(.gitignore 自动排除敏感文件)
|
||||||
|
_git(repo, ["add", "-A"], timeout=30)
|
||||||
|
|
||||||
|
# 若无可提交内容,返回空
|
||||||
|
status = _git(repo, ["status", "--porcelain"], timeout=15)
|
||||||
|
if not status.strip():
|
||||||
|
logger.info("无可提交内容:%s", repo)
|
||||||
|
return {"commit_hash": None, "branch": "", "files_changed": 0}
|
||||||
|
|
||||||
|
_git(repo, ["commit", "-m", message], timeout=30)
|
||||||
|
commit_hash = _git(repo, ["rev-parse", "--short", "HEAD"], timeout=10).strip()
|
||||||
|
branch = _git(repo, ["rev-parse", "--abbrev-ref", "HEAD"], timeout=10).strip()
|
||||||
|
files_changed = len([l for l in status.splitlines() if l.strip()])
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="git_commit",
|
||||||
|
target=str(repo),
|
||||||
|
result="success",
|
||||||
|
details={
|
||||||
|
"commit": commit_hash,
|
||||||
|
"branch": branch,
|
||||||
|
"files_changed": files_changed,
|
||||||
|
"message": message[:200],
|
||||||
|
"task_id": task_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"commit_hash": commit_hash,
|
||||||
|
"branch": branch,
|
||||||
|
"files_changed": files_changed,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_diff(repo_path: str | Path) -> dict[str, Any]:
|
||||||
|
"""获取工作区相对 HEAD 的 diff(供 Agent/人查看改动)。"""
|
||||||
|
repo = ensure_under_root(Path(repo_path), action="Git diff")
|
||||||
|
diff = _git(repo, ["diff", "HEAD"], timeout=20)
|
||||||
|
return {"repo": str(repo), "diff": diff[:5000], "truncated": len(diff) > 5000}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""
|
||||||
|
路径安全守卫
|
||||||
|
============
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
统一校验文件路径是否在允许的操作范围内,杜绝 Agent 越权读写系统文件。
|
||||||
|
是整个工具层的「安全第一道闸门」。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 白名单根目录(默认 D:\\Agent\\code):决策点 3 已定代码集中在该目录,
|
||||||
|
工具只允许在此范围内操作,硬约束 6「全落 D 盘」在路径层强制。
|
||||||
|
2. resolve() 后再比对:防 `..\\..\\Windows` 路径穿越攻击,
|
||||||
|
以及符号链接逃逸(Windows 下 junction/symlink 同理)。
|
||||||
|
3. 校验函数独立成模块:所有工具(file/executor/git)共用同一套规则,
|
||||||
|
避免各写一套校验导致漏网之鱼。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- PathGuard 持有 allowed_roots 列表;
|
||||||
|
- 校验时先 resolve() 为绝对路径,再判断是否位于任一根目录之下;
|
||||||
|
- 提供 ensure_under_root() 便捷函数,工具层一行调用。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:allowed_roots 配置过宽(如允许整个 D 盘)。
|
||||||
|
应对:默认只允许 D:\\Agent\\code 与 D:\\Agent\\agent\\data,
|
||||||
|
其他路径需在配置里显式追加。
|
||||||
|
风险2:符号链接指向根目录之外。
|
||||||
|
应对:resolve() 会解析符号链接到真实路径,再做前缀比对。
|
||||||
|
风险3:大小写差异导致比对失败(Windows 不区分大小写)。
|
||||||
|
应对:统一转小写后再比对。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.path_guard")
|
||||||
|
|
||||||
|
|
||||||
|
class PathSecurityError(PermissionError):
|
||||||
|
"""路径越权访问异常(中文可读)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
|
||||||
|
|
||||||
|
class PathGuard:
|
||||||
|
"""路径安全守卫:限定工具可操作的根目录范围"""
|
||||||
|
|
||||||
|
def __init__(self, allowed_roots: list[Path]) -> None:
|
||||||
|
# 统一 resolve 为真实绝对路径,比对时用小写规避大小写差异
|
||||||
|
self._roots = [Path(r).expanduser().resolve() for r in allowed_roots]
|
||||||
|
logger.info("路径守卫初始化,允许根目录:%s", self._roots)
|
||||||
|
|
||||||
|
def is_allowed(self, path: Path, *, readonly: bool = False) -> bool:
|
||||||
|
"""
|
||||||
|
判断路径是否在允许范围内。
|
||||||
|
|
||||||
|
【策略】
|
||||||
|
- readonly=True(读取/搜索):允许任意本地目录(用户要求);
|
||||||
|
- readonly=False(写入/删除/执行):仍限定白名单根目录。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
resolved = Path(path).expanduser().resolve()
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
# 拒绝 UNC 网络路径(防止误操作远程共享)
|
||||||
|
if str(resolved).startswith("\\\\"):
|
||||||
|
return False
|
||||||
|
if readonly:
|
||||||
|
return True
|
||||||
|
# 写入/删除:仍走白名单
|
||||||
|
resolved_lower = str(resolved).lower()
|
||||||
|
return any(
|
||||||
|
resolved_lower == str(root).lower()
|
||||||
|
or resolved_lower.startswith(str(root).lower() + "\\")
|
||||||
|
or resolved_lower.startswith(str(root).lower() + "/")
|
||||||
|
for root in self._roots
|
||||||
|
)
|
||||||
|
|
||||||
|
def ensure_allowed(self, path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
||||||
|
"""
|
||||||
|
校验路径合法性,不合法抛 PathSecurityError。
|
||||||
|
|
||||||
|
【返回】解析后的绝对路径(后续工具可直接使用)。
|
||||||
|
"""
|
||||||
|
resolved = Path(path).expanduser().resolve()
|
||||||
|
if not self.is_allowed(resolved, readonly=readonly):
|
||||||
|
raise PathSecurityError(
|
||||||
|
f"拒绝{action}:路径 {resolved} 不在允许的操作范围内 "
|
||||||
|
f"(允许根目录:{[str(r) for r in self._roots]})"
|
||||||
|
)
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 默认守卫(工具层统一使用)----------
|
||||||
|
|
||||||
|
_default_guard: PathGuard | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_guard() -> PathGuard:
|
||||||
|
"""
|
||||||
|
获取默认路径守卫。
|
||||||
|
|
||||||
|
【允许范围】全部 D 盘 + 常见项目目录(用户要求 Agent 可读取任意目录)。
|
||||||
|
"""
|
||||||
|
global _default_guard
|
||||||
|
if _default_guard is None:
|
||||||
|
_default_guard = PathGuard(
|
||||||
|
allowed_roots=[
|
||||||
|
Path(r"D:\Agent\code"),
|
||||||
|
Path(r"D:\Agent\agent\data"),
|
||||||
|
Path(r"D:\Agent\pytest_tmp"),
|
||||||
|
Path(r"D:\Project"),
|
||||||
|
Path(r"D:\Code"),
|
||||||
|
Path(r"D:\Workspace"),
|
||||||
|
Path(r"D:\Work"),
|
||||||
|
Path(r"D:\Git"),
|
||||||
|
Path("D:\\"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return _default_guard
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_under_root(path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
||||||
|
"""便捷函数:校验路径并返回解析后的绝对路径。"""
|
||||||
|
return get_default_guard().ensure_allowed(path, action, readonly=readonly)
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""
|
||||||
|
Windows 子进程窗口抑制
|
||||||
|
====================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
统一提供「子进程不弹出控制台窗口」的 Popen/run 参数。
|
||||||
|
|
||||||
|
【为什么需要】
|
||||||
|
claude CLI 的入口是 **claude.CMD 批处理脚本**(控制台程序),
|
||||||
|
直接拉起会分配一个可见控制台窗口 → 用户每次提问都弹出命令行。
|
||||||
|
|
||||||
|
【关键实测结论】(2026-10-23 探针验证,勿再改错)
|
||||||
|
|
||||||
|
标志组合 控制台窗口 父进程退出后存活
|
||||||
|
───────────────────────────────────────────── ───────── ────────────────
|
||||||
|
无标志 无 ?
|
||||||
|
CREATE_NO_WINDOW **无** **存活**
|
||||||
|
CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP **无** **存活**
|
||||||
|
DETACHED_PROCESS | CREATE_NO_WINDOW | GROUP **有!** 存活
|
||||||
|
|
||||||
|
→ **DETACHED_PROCESS 才是弹窗元凶**:它让控制台程序「无台可继承」时
|
||||||
|
**自己 AllocConsole 一个可见控制台**,并压过 CREATE_NO_WINDOW。
|
||||||
|
→ 只用 CREATE_NO_WINDOW 就同时拿到「不弹窗」和「独立存活」,
|
||||||
|
不要再加 DETACHED_PROCESS。
|
||||||
|
|
||||||
|
【教训】第一次修复往 DETACHED_PROCESS 上叠 CREATE_NO_WINDOW,等于没治病根。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
|
def hidden_popen_kwargs() -> dict:
|
||||||
|
"""
|
||||||
|
返回隐藏窗口所需的额外 Popen/run 参数。
|
||||||
|
|
||||||
|
【用法】
|
||||||
|
subprocess.Popen(cmd, **hidden_popen_kwargs())
|
||||||
|
subprocess.run(cmd, capture_output=True, **hidden_popen_kwargs())
|
||||||
|
|
||||||
|
【返回】Windows 下为 {"creationflags": CREATE_NO_WINDOW},其它平台为空 dict。
|
||||||
|
"""
|
||||||
|
if os.name != "nt":
|
||||||
|
return {}
|
||||||
|
return {"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||||
|
|
||||||
|
|
||||||
|
def worker_creation_flags() -> int:
|
||||||
|
"""
|
||||||
|
独立 worker 进程的创建标志。
|
||||||
|
|
||||||
|
【Windows】CREATE_NO_WINDOW 不弹出控制台窗口
|
||||||
|
CREATE_NEW_PROCESS_GROUP 不接收父进程 Ctrl+C
|
||||||
|
【绝不使用】DETACHED_PROCESS —— 会让控制台程序自建**可见**控制台,是弹窗元凶。
|
||||||
|
【独立性】Windows 上父进程退出不会连带杀死子进程(无 Job Object 时),
|
||||||
|
实测 CREATE_NO_WINDOW 下父退子活,足够支撑「API 重启不杀任务」。
|
||||||
|
【其它平台】返回 0(由调用方改用 start_new_session)
|
||||||
|
"""
|
||||||
|
if os.name != "nt":
|
||||||
|
return 0
|
||||||
|
return subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
"""
|
||||||
|
搜索定位工具(grep / 文件查找)
|
||||||
|
=============================
|
||||||
|
|
||||||
|
【功能说明】
|
||||||
|
自研工具链的代码定位能力:正则内容搜索(grep)与文件名模糊查找。
|
||||||
|
对应《核心诉求》「代码定位」环节,决策点 6 定为「代码走符号检索不进向量库」。
|
||||||
|
|
||||||
|
【技术选型理由】
|
||||||
|
1. 选 ripgrep 风格的纯 Python 实现(re + pathlib):
|
||||||
|
不依赖外部 rg 二进制,跨平台一致、可单测、可控。
|
||||||
|
2. grep 而非向量检索:代码定位要的是**精确符号匹配**,
|
||||||
|
向量检索在代码上召回不准(决策点 6 已论证)。
|
||||||
|
3. 输出结构化(文件+行号+内容片段):Agent 能直接定位到行级修改点。
|
||||||
|
|
||||||
|
【实现思路】
|
||||||
|
- grep_files:按正则搜索,支持 glob 过滤、大小写开关、结果上限;
|
||||||
|
- find_files:按文件名模式查找(支持 * 通配);
|
||||||
|
- 两者都经路径守卫校验,结果上限防止刷爆上下文。
|
||||||
|
|
||||||
|
【潜在风险与应对】
|
||||||
|
风险1:正则写错导致全库扫描耗时。
|
||||||
|
应对:结果上限 100 条 + 扫描文件数上限 5000,超时保护。
|
||||||
|
风险2:搜索到二进制文件产生乱码。
|
||||||
|
应对:跳过常见二进制扩展名(.png/.zip/.class/.jar 等)。
|
||||||
|
风险3:结果过多撑爆 Agent 上下文。
|
||||||
|
应对:每条结果截断到 200 字符,总数硬上限。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.tools.audit import log_action
|
||||||
|
from app.tools.path_guard import ensure_under_root
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent.tools.search")
|
||||||
|
|
||||||
|
# 结果上限(防止刷爆 Agent 上下文)
|
||||||
|
MAX_RESULTS = 100
|
||||||
|
MAX_SCAN_FILES = 5000
|
||||||
|
MAX_LINE_LENGTH = 200
|
||||||
|
|
||||||
|
# 跳过的二进制/无意义扩展名
|
||||||
|
SKIP_EXTENSIONS = {
|
||||||
|
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico",
|
||||||
|
".zip", ".jar", ".war", ".class", ".pyc", ".pyd",
|
||||||
|
".pdf", ".docx", ".xlsx", ".pptx",
|
||||||
|
".exe", ".dll", ".so", ".dylib",
|
||||||
|
".db", ".sqlite", ".sqlite3",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SearchToolError(RuntimeError):
|
||||||
|
"""搜索工具异常(中文可读)"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, error_type: str = "SearchToolError") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.error_type = error_type
|
||||||
|
|
||||||
|
|
||||||
|
def grep_files(
|
||||||
|
pattern: str,
|
||||||
|
search_path: str | Path,
|
||||||
|
glob_filter: str = "*",
|
||||||
|
case_sensitive: bool = False,
|
||||||
|
max_results: int = MAX_RESULTS,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
正则内容搜索(grep)。
|
||||||
|
|
||||||
|
【参数】
|
||||||
|
pattern:正则表达式
|
||||||
|
search_path:搜索根目录
|
||||||
|
glob_filter:文件名过滤(如 *.java)
|
||||||
|
case_sensitive:是否区分大小写
|
||||||
|
max_results:结果上限
|
||||||
|
【返回】{pattern, total_matches, results: [{file, line_no, line}]}
|
||||||
|
"""
|
||||||
|
root = ensure_under_root(Path(search_path), action="搜索", readonly=True)
|
||||||
|
if not root.exists():
|
||||||
|
raise SearchToolError(f"搜索路径不存在:{root}", error_type="PathNotFound")
|
||||||
|
|
||||||
|
try:
|
||||||
|
regex = re.compile(pattern, 0 if case_sensitive else re.IGNORECASE)
|
||||||
|
except re.error as exc:
|
||||||
|
raise SearchToolError(f"正则表达式无效:{pattern},原因:{exc}", error_type="InvalidRegex")
|
||||||
|
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
scanned = 0
|
||||||
|
|
||||||
|
for file_path in root.rglob(glob_filter):
|
||||||
|
if scanned >= MAX_SCAN_FILES:
|
||||||
|
logger.warning("扫描文件数超限 %d,提前终止", MAX_SCAN_FILES)
|
||||||
|
break
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
||||||
|
continue
|
||||||
|
scanned += 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
text = file_path.read_text(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for line_no, line in enumerate(text.splitlines(), start=1):
|
||||||
|
if regex.search(line):
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
"file": str(file_path),
|
||||||
|
"line_no": line_no,
|
||||||
|
"line": line[:MAX_LINE_LENGTH],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if len(results) >= max_results:
|
||||||
|
break
|
||||||
|
if len(results) >= max_results:
|
||||||
|
break
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="grep_files",
|
||||||
|
target=str(root),
|
||||||
|
result="success",
|
||||||
|
details={"pattern": pattern, "matches": len(results), "scanned": scanned},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"pattern": pattern,
|
||||||
|
"search_path": str(root),
|
||||||
|
"total_matches": len(results),
|
||||||
|
"scanned_files": scanned,
|
||||||
|
"results": results,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def find_files(
|
||||||
|
name_pattern: str,
|
||||||
|
search_path: str | Path,
|
||||||
|
max_results: int = MAX_RESULTS,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
按文件名模式查找文件。
|
||||||
|
|
||||||
|
【参数】name_pattern:支持 * 通配(如 *Controller.java)或纯名片段
|
||||||
|
【返回】{pattern, total, files: [...]}
|
||||||
|
"""
|
||||||
|
root = ensure_under_root(Path(search_path), action="查找", readonly=True)
|
||||||
|
if not root.exists():
|
||||||
|
raise SearchToolError(f"查找路径不存在:{root}", error_type="PathNotFound")
|
||||||
|
|
||||||
|
# 纯名片段转通配模式
|
||||||
|
pattern = name_pattern if "*" in name_pattern else f"*{name_pattern}*"
|
||||||
|
|
||||||
|
files: list[str] = []
|
||||||
|
scanned = 0
|
||||||
|
for file_path in root.rglob(pattern):
|
||||||
|
if scanned >= MAX_SCAN_FILES:
|
||||||
|
break
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
||||||
|
continue
|
||||||
|
scanned += 1
|
||||||
|
files.append(str(file_path))
|
||||||
|
if len(files) >= max_results:
|
||||||
|
break
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
action="find_files",
|
||||||
|
target=str(root),
|
||||||
|
result="success",
|
||||||
|
details={"pattern": pattern, "found": len(files)},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"pattern": pattern,
|
||||||
|
"search_path": str(root),
|
||||||
|
"total": len(files),
|
||||||
|
"files": files,
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""任务执行 Worker:在独立进程中执行任务,使任务生命周期与 API 进程解耦。"""
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user