# Phase 3：Agent 集成

日期：2026-04-04
状态：待实施

依赖：Phase 1 + Phase 2 完成

---

## 1. 本阶段目的

将代码指挥官接入 LangGraph：
- Graph 节点
- 边路由
- 任务模型

---

## 2. 详细任务

### 2.1 Graph 节点

**文件**: `backend/app/agents/graph.py`

```python
# 新增 code_commander_node
async def code_commander_node(state: AgentState) -> AgentState:
    """代码指挥官节点"""
    # 1. 获取用户需求和选择的 AI 提供商
    user_message = state.messages[-1].content
    ai_provider = state.get("ai_provider", "claude")
    
    # 2. 安全分级
    classifier = SecurityClassifier()
    risk_level = classifier.classify(user_message)
    
    # 3. 根据风险等级选择执行器
    adapter = get_adapter(ai_provider)
    if risk_level == RiskLevel.LOW:
        executor = DirectExecutor(adapter)
        result = await executor.execute(user_message)
    else:
        sandbox = await SandboxEnvironment.create()
        executor = SandboxExecutor(adapter)
        result = await executor.execute(user_message, sandbox.session_id)
        state["workspace_path"] = str(sandbox.workspace_path)
        state["execution_session_id"] = sandbox.session_id
    
    # 4. 更新状态
    state.messages.append(AIMessage(content=str(result)))
    state["next_step"] = None  # 任务完成
    
    return state

# 节点注册到 NODES
NODES: dict[str, NodeCallable] = {
    # ... 现有节点 ...
    "code_commander": code_commander_node,
}
```

### 2.2 边路由

**文件**: `backend/app/agents/graph.py`

```python
def _should_route_to_code_commander(state: AgentState) -> str:
    """判断是否路由到代码指挥官"""
    if state.current_agent == "code_commander":
        return "code_commander"
    # ... 其他条件
    return END

# 边注册
def _build_graph() -> CompiledGraph:
    # ... 现有边 ...
    
    # 新增代码指挥官相关边
    graph.add_conditional_edges(
        "master",
        _should_route_to_code_commander,
        {
            "code_commander": "code_commander",
            END: END,
        }
    )
    
    graph.add_edge("code_commander", END)
    
    return graph.compile()
```

### 2.3 任务模型

**文件**: `backend/app/agents/schemas/task.py`

```python
from pydantic import BaseModel, Field
from typing import Literal

class CodeProviderType(str, Enum):
    CLAUDE = "claude"
    GEMINI = "gemini"
    CODEX = "codex"
    OPENCODE = "opencode"

class RiskLevelType(str, Enum):
    LOW = "low"
    HIGH = "high"

class CodeTask(BaseModel):
    """代码任务"""
    id: str = Field(default_factory=lambda: f"code_{uuid.uuid4().hex[:8]}")
    provider: CodeProviderType
    prompt: str
    risk_level: RiskLevelType
    sandbox_mode: bool
    workspace_path: str | None = None
    session_id: str | None = None
    status: Literal["pending", "running", "completed", "failed"] = "pending"
    created_at: datetime = Field(default_factory=datetime.now)

class CodeExecutionResult(BaseModel):
    """代码执行结果"""
    task_id: str
    success: bool
    exit_code: int
    stdout: str
    stderr: str
    files_created: list[str] = Field(default_factory=list)
    workspace_path: str | None = None
    completed_at: datetime = Field(default_factory=datetime.now)
```

---

## 3. 核心文件清单

| 文件 | 操作 | 说明 |
|------|------|------|
| `graph.py` | 修改 | 新增 `code_commander_node` 和边路由 |
| `schemas/task.py` | 修改 | 新增 `CodeTask`, `CodeExecutionResult` 等模型 |

---

## 4. 验收标准

- [ ] `code_commander_node` 正确处理任务
- [ ] `SecurityClassifier` 被正确调用
- [ ] 高低风险任务路由到正确的执行器
- [ ] `CodeTask` 和 `CodeExecutionResult` 模型正确

---

## 5. 依赖关系

```
Phase 1 + Phase 2
       ↓
本阶段 → Phase 4（流式交互）
       → Phase 5（前端集成）
```
