226 lines
16 KiB
Markdown
226 lines
16 KiB
Markdown
# Fischer AgentKit — 项目上下文
|
||
|
||
## 规则
|
||
|
||
- Python >= 3.11,必须使用类型注解,所有数据模型使用 `pydantic>=2.0`
|
||
- 使用 Ruff 进行 lint 和格式化:`ruff check src/ && ruff format src/`(目标 py311,行宽 100)
|
||
- 测试:`pytest`(asyncio\_mode=auto),标记:`integration`、`redis`、`postgres`
|
||
- 禁止使用 `any` 类型 — 使用合适的 Pydantic 模型或 `Unknown`
|
||
- API Key 比较必须使用 `hmac.compare_digest`(恒定时间比较)
|
||
- 专家名称使用 `_EXPERT_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")` 校验
|
||
- HandoffTransport 队列有界(`maxsize=1024`),关闭使用 sentinel 模式
|
||
- 前端:Vue 3 + TypeScript + Ant Design Vue,Pinia stores,禁止 `require()` 调用
|
||
- **异步生成器安全**:在 `async def` 中禁止在第一个 `yield` 之前使用 `return` — 改用 `return; yield` 模式(见 `.trae/rules/project_rules.md`)
|
||
- 所有回复必须是中文
|
||
|
||
## 技术栈
|
||
|
||
- **后端**:Python 3.11+、FastAPI、Uvicorn、Pydantic v2、SQLAlchemy 2(async)
|
||
- **前端**:Vue 3、TypeScript、Vite 5、Ant Design Vue 4、Pinia、Vue Router 4
|
||
- **桌面端**:Tauri 2.x(Rust 外壳 + Python sidecar)
|
||
- **基础设施**:Redis(总线/缓存/状态)、PostgreSQL + pgvector(情景记忆)
|
||
- **CLI**:Typer + Rich
|
||
- **精确版本**:见 `pyproject.toml`(Python)、`package.json`(Node)
|
||
|
||
## 命令
|
||
|
||
```bash
|
||
# 后端
|
||
pip install -e ".[dev]" # 安装开发依赖
|
||
agentkit gui --port 8002 # Web GUI(前端 + API)
|
||
agentkit serve --port 8001 # 仅 API 服务
|
||
agentkit chat # CLI 交互式聊天
|
||
agentkit init # 生成 agentkit.yaml
|
||
agentkit version / doctor / usage # 工具命令
|
||
agentkit task submit/status/list/cancel # 任务管理
|
||
agentkit skill list/load/info # 技能管理
|
||
agentkit pair --name X # 为外部系统生成 API Key
|
||
pytest # 运行所有测试
|
||
pytest -m "not integration" # 仅单元测试
|
||
ruff check src/ && ruff format src/ # Lint + 格式化
|
||
|
||
# 前端
|
||
cd src/agentkit/server/frontend
|
||
npm install # 安装依赖
|
||
npm run dev # Vite 开发服务器(代理 /api -> :8000)
|
||
npm run build:frontend # 生产构建 -> ../static
|
||
npm run typecheck # TypeScript 检查
|
||
|
||
# 桌面端
|
||
cd src/agentkit/server/frontend
|
||
npm run tauri dev # Tauri 开发模式
|
||
npm run tauri build # Tauri 生产构建
|
||
|
||
# Docker
|
||
docker-compose up -d # AgentKit + Redis + PostgreSQL
|
||
```
|
||
|
||
## 架构
|
||
|
||
### 请求流程
|
||
|
||
```
|
||
用户输入
|
||
├─ @board 前缀 -> BoardRouter (experts/board_router.py) -> BoardOrchestrator(多轮讨论)
|
||
├─ @team 前缀 -> ExpertTeamRouter (experts/router.py) -> TeamOrchestrator(流水线协作)
|
||
└─ 其他 -> RequestPreprocessor (chat/request_preprocessor.py)
|
||
Layer 0: @skill:xxx 前缀 -> 显式技能选择(SKILL_REACT 或技能配置的模式)
|
||
Layer 1: 琐碎输入正则(~0ms,0 tokens)-> DIRECT_CHAT
|
||
(问候、身份、事实问答、数学、翻译;由 _TOOL_CONTEXT_RE 守护)
|
||
默认: -> REACT(LLM 在 agent 循环中自主决定工具使用)
|
||
-> ExecutionMode: DIRECT_CHAT / REACT / SKILL_REACT / REWOO / REFLEXION / PLAN_EXEC / TEAM_COLLAB
|
||
(chat handler 支持 DIRECT_CHAT、REACT、SKILL_REACT、PLAN_EXEC;
|
||
TEAM_COLLAB 通过 @team 前缀路由到 TeamOrchestrator(R7,不回退到 REACT);
|
||
ExecutionMode.TEAM_COLLAB 非前缀触发时向用户报错并提示使用 @team;
|
||
REWOO / REFLEXION-as-mode 暂时回退到 REACT(RV10 deferred))
|
||
```
|
||
|
||
**注意**:旧的 3 层 `CostAwareRouter`(含 `RegexRules` / `HeuristicClassifier` / `SemanticRouter` / `Vickrey Auction`)已被 `RequestPreprocessor` 替换。`IntentRouter`(`router/intent.py`)存在但未接入 chat 流程。`AuctionHouse`(Vickrey 拍卖)位于 `marketplace/auction.py`(属于 marketplace 子系统,非路由)。
|
||
|
||
### Agent 层级
|
||
|
||
```
|
||
BaseAgent (core/base.py) — 抽象基类,execute() 是 final 方法
|
||
+-- ConfigDrivenAgent (core/config_driven.py) — YAML 驱动,3 种任务模式
|
||
+-- ReActEngine (core/react.py) — Think->Act->Observe
|
||
+-- ReflexionAgent (core/reflexion.py) — 反思驱动
|
||
+-- ReWOOAgent (core/rewoo.py) — 无观察规划
|
||
+-- StandaloneAgent (core/standalone.py) — 独立运行器
|
||
```
|
||
|
||
### 专家团队模式(流水线)
|
||
|
||
```
|
||
ExpertConfig(继承 AgentConfig)-> Expert(通过 AgentPool 包装 ConfigDrivenAgent)
|
||
ExpertTeam:管理专家、共享工作区、团队状态(FORMING→PLANNING→EXECUTING→SYNTHESIZING→COMPLETED)
|
||
TeamOrchestrator:流水线执行 — Lead 将任务分解为带 depends_on 的 PlanPhase,拓扑排序,并行分层
|
||
PlanPhase:id、name、assigned_expert、task_description、depends_on、status(PENDING/RUNNING/COMPLETED/FAILED)
|
||
TeamPlan:带依赖的阶段,topological_sort() 返回执行层(Kahn 算法)
|
||
ExpertTeamRouter:@team 前缀路由、@team:dev_team 模板展开、名称校验、MAX_EXPERTS=10
|
||
HandoffTransport:InProcess(asyncio.Queue)+ Redis Pub/Sub — 仅用于事件广播
|
||
```
|
||
|
||
**流水线流程**:
|
||
|
||
1. `@team` 前缀触发团队模式(或 `@team:dev_team` 用模板,`@team:expert1,expert2` 显式指定)
|
||
2. `ExpertTeam.create_team()` 将状态置为 PLANNING
|
||
3. Lead Expert 通过 LLM 将任务分解为阶段(失败时回退为单阶段)
|
||
4. `topological_sort()` 将阶段排成层(同层并行,层间串行)
|
||
5. 每个阶段通过 `AgentPool.create_agent` 创建隔离的 `ConfigDrivenAgent`(上下文隔离,KTD3)
|
||
6. 阶段输出通过 `SharedWorkspace` 传递(`{plan_id}/phase/{phase_id}/output`)
|
||
7. Lead 综合结果(BEST 策略)
|
||
8. 所有阶段都失败时:回退到单 agent 模式
|
||
|
||
**事件序列**:`team_formed` → `plan_update` → `phase_started` → `expert_step` → `expert_result` → `phase_completed` → `team_synthesis` → `team_dissolved`
|
||
|
||
**团队模板**:`configs/experts/dev_team.yaml` 在 `bound_skills` 字段存储成员列表(tech\_lead、frontend\_engineer、backend\_engineer、qa\_engineer、code\_reviewer)
|
||
|
||
生命周期:FORMING -> PLANNING -> EXECUTING -> SYNTHESIZING -> COMPLETED -> DISSOLVED
|
||
失败时:回退到单 agent 模式(lead 或第一个活跃专家)。
|
||
|
||
### 模块映射
|
||
|
||
| 层级 | 模块 | 用途 |
|
||
| --- | ---------------------------------------------- | ------------------------------- |
|
||
| API | `server/`、`cli/` | FastAPI 路由 + Typer CLI |
|
||
| 认证 | `server/auth/` | JWT + RBAC + 终端安全(6 层白名单) |
|
||
| 服务 | `core/`、`chat/`、`skills/`、`experts/` | Agent 引擎、路由、技能、专家团队 |
|
||
| 数据 | `memory/`、`session/`、`bus/` | 持久化、会话、消息 |
|
||
| 工具 | `llm/`、`tools/`、`evolution/`、`quality/`、`mcp/` | LLM 网关、工具、自进化、质量、MCP |
|
||
| 客户端 | `client/` | ConfigSync、RemoteLLMProvider 集成 |
|
||
|
||
### 关键子系统
|
||
|
||
- **LLM 网关**(`llm/`):基于 LiteLLM 统一适配层(U15 迁移),保留原 6 个 provider 命名作为别名(OpenAI/Anthropic/Gemini/Doubao/Wenxin/Yuanbao),支持任意 OpenAI 兼容 API(如 DashScope/DeepSeek);含 fallback、语义缓存、用量追踪、RemoteLLMProvider(client→server 代理,带 401 刷新重试)
|
||
- **记忆**(`memory/`):4 层(SOUL/USER/MEMORY/DAILY)、WorkingMemory(Redis)、EpisodicMemory(PG+pgvector)、SemanticMemory(HTTP RAG)
|
||
- **进化**(`evolution/`):Reflector、PromptOptimizer(遗传算法)、PitfallDetector、ABTester
|
||
- **工具**(`tools/`):21 个内置 + MCP 扩展,组合(SequentialChain/ParallelFanOut/DynamicSelector)
|
||
- **流水线**(`orchestrator/`):PipelineEngine、SagaOrchestrator、DynamicPipeline、HandoffManager
|
||
- **总线**(`bus/`):MemoryBus(进程内)、RedisBus(分布式)
|
||
- **认证**(`server/auth/`):JWT(access 15min + refresh 7d,HS256)、API Key(恒定时间比较)、3 级 RBAC(member/operator/admin + 权限位)、6 层终端安全(blocklist→shell-ops→builtin→global→user→session→danger)、bcrypt 密码哈希(rounds=12)
|
||
|
||
### 服务端路由(28 个模块)
|
||
|
||
| 前缀 | 模块 | 用途 |
|
||
| ------------------------- | -------------------------------------- | ------------------------- |
|
||
| `/api/v1/agents` | agents.py | Agent CRUD |
|
||
| `/api/v1/tasks` | tasks.py | 任务提交/查询/取消 |
|
||
| `/api/v1/skills` | skills.py | 技能注册/列表 |
|
||
| `/api/v1/chat` | chat.py | Chat REST + WebSocket |
|
||
| `/api/v1/ws` | ws.py | WebSocket 通道 |
|
||
| `/api/v1/llm` | llm.py | LLM 用量 |
|
||
| `/api/v1/llm/chat` | llm\_gateway.py | LLM 网关代理(JWT 认证,SSE 流式) |
|
||
| `/api/v1/health` | health.py | 健康检查 |
|
||
| `/api/v1/metrics` | metrics.py | 指标 |
|
||
| `/api/v1/evolution` | evolution.py + evolution\_dashboard.py | 自进化 API |
|
||
| `/api/v1/memory` | memory.py | 记忆管理 |
|
||
| `/api/v1/portal` | portal.py | Portal |
|
||
| `/api/v1/kb` | kb\_management.py | 知识库 |
|
||
| `/api/v1/skill-mgmt` | skill\_management.py | 技能管理 |
|
||
| `/api/v1/workflows` | workflows.py | 工作流 |
|
||
| `/api/v1/terminal` | terminal.py | 本地终端(client sidecar PTY) |
|
||
| `/api/v1/terminal/server` | terminal\_server.py | 服务端终端(server PTY + 管理员审批) |
|
||
| `/api/v1/terminal` | terminal\_whitelist.py | 白名单/黑名单/审计日志管理 |
|
||
| `/api/v1/settings` | settings.py | 设置 |
|
||
| `/api/v1/auth` | auth.py | 登录/刷新/登出/me |
|
||
| `/api/v1/system` | system.py | 系统资源(需 SYSTEM\_CONFIG 权限) |
|
||
| `/api/v1/config` | config\_sync.py | 配置版本 + 同步(轮询) |
|
||
| `/api/v1/bitable` | bitable.py | 多维表格 companion 服务 |
|
||
| `/api/v1/calendar` | calendar.py | 日历服务(事件/提醒/同步) |
|
||
| `/api/v1/documents` | documents.py | 文档管理 |
|
||
| `/api/v1/admin` | admin.py | 管理员操作 |
|
||
| `/api/v1/experts` | experts.py | 专家团队管理 |
|
||
| `/api/v1/mcp` | mcp\_publish.py | MCP 发布 |
|
||
|
||
### WebSocket Chat 协议
|
||
|
||
Client -> Server:`message`、`reply`、`confirmation_reply`、`cancel`、`ping`
|
||
Server -> Client:`connected`、`token`、`thinking`、`step`、`final_answer`、`skill_match`、`confirmation_request`、`confirmation_result`、`ask_human`、`error`、`pong`
|
||
专家团队事件:
|
||
- 生命周期:`team_formed`、`plan_update`、`phase_started`、`phase_completed`、`phase_failed`、`team_dissolved`
|
||
- 专家执行(流式):`expert_step`(thinking/tool_call/tool_result 步骤,payload 携带 `expert_id`/`expert_name`/`expert_color`/`content`/`step`)、`expert_result_chunk`(token 增量)、`expert_result_chunk_reset`(重试前清空)、`expert_result`(终结,status=completed|error)
|
||
- 综合(流式):`team_synthesis_chunk`(增量 chunk,携带 `synthesis_id`)、`team_synthesis`(终结,携带 `synthesis_id` + status=completed|error|cancelled)
|
||
- PLAN_EXEC (U4):`phase_changed`、`phase_violation`
|
||
|
||
**`synthesis_id` 去重契约**:后端在 `team_synthesis_chunk` 和 `team_synthesis` 事件中注入稳定标识 `{plan_id}:synthesis`,前端用它精确匹配 streaming milestone,避免重试/并发时孤儿 milestone。
|
||
|
||
**`execute_stream()` 取消契约**:`ConfigDrivenAgent.execute_stream()` 注册 `CancellationToken` 到 `_active_tokens`(与 `BaseAgent.execute()` 一致),使 `cancel_task()` 能协作式取消流式任务。
|
||
|
||
### 前端页面
|
||
|
||
- `/agent/chat` — 专家团队聊天视图
|
||
- `/agent/code` — 代码/工作流
|
||
- `/agent/monitor` — 进化看板
|
||
- `/computer-use` — 桌面控制
|
||
- `/login` — 登录页(JWT 认证)
|
||
- 终端面板 — 本地 + 服务端终端,含白名单管理器
|
||
|
||
### 配置优先级
|
||
|
||
CLI 参数 > `agentkit.yaml` > 环境变量(`${VAR:-default}`)> `.env` > 硬编码默认值
|
||
|
||
配置查找:`--config` 路径 > `./agentkit.yaml` > `~/.agentkit/agentkit.yaml`(三个路径都不存在时使用硬编码默认值,CLI 仍可启动)
|
||
|
||
## 约定
|
||
|
||
- 技能配置:`configs/skills/*.yaml`(16 个预设,统一为 `SkillConfig`)
|
||
- 技能分类:`agent_template`(执行引擎:react/direct/rewoo/reflexion/plan\_exec/goal\_driven)vs `business_skill`(领域技能)。通过 `server/routes/skill_management.py` 中的 `_ENGINE_TEMPLATE_NAMES` 分类。前端按 `category` 字段分组 — `SkillsView` 双栏布局,`SkillCard`/`SkillsTab` 显示类型标签(引擎/技能)和基于分类的图标
|
||
- LLM 配置:`agentkit.yaml` llm 段(与服务端配置统一)
|
||
- 流水线配置:`configs/pipelines/*.yaml`
|
||
- 专家模板:`configs/experts/*.yaml`(15 个模板 — 5 编程专家 + 9 商业/思想领袖 + 1 团队模板 dev\_team),通过 `ExpertTemplateRegistry` 注册
|
||
- 团队模板:`bound_skills` 字段存储成员列表(如 `dev_team.yaml` 列出 tech\_lead、frontend\_engineer、backend\_engineer、qa\_engineer、code\_reviewer)
|
||
- 所有 Pydantic 模型使用 `model_config = ConfigDict(...)` 而非 `class Config`
|
||
- 测试文件:`tests/unit/` 和 `tests/integration/`
|
||
- 前端 stores:Pinia,每个领域一个(chat、team、settings)
|
||
- 前端组件:`src/agentkit/server/frontend/src/components/`
|
||
- 知识库:`docs/solutions/` — 已记录的问题解决方案(bug 修复、最佳实践、架构模式),按类别组织,YAML frontmatter 可搜索(`module`、`tags`、`problem_type`)。在已记录的领域内实现或调试时相关。
|
||
- 领域词汇:`CONCEPTS.md` — 项目共享领域词汇表(实体、命名流程、状态概念),在熟悉代码库或讨论领域概念时相关。
|
||
|
||
## 边界
|
||
|
||
- 未经明确请求不得修改 `pyproject.toml` 版本
|
||
- 禁止直接推送到 main — 使用 feature 分支
|
||
- 集成测试需要 Docker(Redis + PostgreSQL)
|
||
- 桌面端构建需要 Rust 工具链 + PyInstaller
|
||
|