第 6 / 8 节15 分钟
🎯
Agent 模式
高级让 AI 自主完成复杂的多步骤任务
🎬
视频教程即将上线
Agent 模式
学习如何使用 OpenCode 的 Agent 模式,让 AI 自主完成复杂的多步骤任务。
# 什么是 Agent 模式?#
Agent 模式让 OpenCode 能够:
- 🤔 规划 - 分析任务,制定执行计划
- 🔧 执行 - 自主调用工具完成任务
- 🔄 迭代 - 根据结果调整策略
- ✅ 验证 - 确保任务正确完成
# 启用 Agent 模式#
## 临时启用#
使用 /agent 命令:
❯ /agent 重构整个认证模块,添加 OAuth 支持
## 默认启用#
在配置中设置:
toml[agent] enabled = true auto_mode = true # 自动判断是否需要 agent 模式
# Agent 工作流程#
## 示例:重构任务#
❯ /agent 将所有类组件转换为函数组件
🤔 Planning...
Goal: Convert class components to functional components
Scope: Analyzing project structure...
Found: 15 class components
📋 Execution Plan:
1. Analyze each class component's state and lifecycle
2. Convert state to useState hooks
3. Convert lifecycle methods to useEffect
4. Update prop types
5. Run tests to verify
Proceed? [Y/n] y
🔧 Executing step 1/5: Analyzing components...
✓ Button.tsx - simple, no state
✓ Modal.tsx - has state, uses componentDidMount
✓ Form.tsx - complex state, multiple lifecycles
...
🔧 Executing step 2/5: Converting Button.tsx...
Converting class to function...
✓ Button.tsx converted
🔧 Executing step 3/5: Converting Modal.tsx...
Converting state to useState...
Converting componentDidMount to useEffect...
✓ Modal.tsx converted
...
✅ Task completed!
Converted: 15 components
Tests: All passing
Time: 3m 45s
# 任务类型#
## 代码重构#
❯ /agent 优化项目性能,找出并修复性能瓶颈
❯ /agent 统一错误处理方式
❯ /agent 添加 TypeScript 类型定义
## 功能实现#
❯ /agent 实现用户认证功能,包括登录、注册、忘记密码
❯ /agent 添加完整的 CRUD 操作到用户管理模块
❯ /agent 创建 REST API 端点和文档
## 测试与文档#
❯ /agent 为所有 utils 函数添加单元测试
❯ /agent 生成 API 文档
❯ /agent 更新 README,添加安装和使用说明
## 问题修复#
❯ /agent 修复所有 ESLint 警告
❯ /agent 找出并修复内存泄漏
❯ /agent 解决所有 TypeScript 类型错误
# 执行控制#
## 步骤确认#
默认情况下,每个关键步骤需要确认:
toml1[agent.confirmation] 2plan = true # 执行计划需要确认 3file_changes = true # 文件修改需要确认 4dangerous_ops = true # 危险操作需要确认
## 自动模式#
信任 Agent 自主执行:
❯ /agent --auto 修复所有 lint 错误
或在配置中:
toml[agent] auto_confirm = true max_auto_steps = 20 # 最多自动执行 20 步
## 暂停与继续#
# 暂停执行
❯ /agent pause
# 查看状态
❯ /agent status
# 继续执行
❯ /agent resume
# 取消任务
❯ /agent cancel
# 任务规划#
## 查看计划#
在执行前查看详细计划:
❯ /agent plan 重构数据库访问层
📋 Proposed Plan:
Phase 1: Analysis
- Scan current database access patterns
- Identify direct database calls
- Map data dependencies
Phase 2: Design
- Design repository pattern interfaces
- Plan migration strategy
- Define error handling
Phase 3: Implementation
- Create base repository class
- Implement specific repositories
- Update service layer
Phase 4: Testing
- Add unit tests for repositories
- Add integration tests
- Verify existing tests pass
Phase 5: Cleanup
- Remove old database calls
- Update documentation
Estimated steps: 45
Estimated time: 15-20 minutes
Execute this plan? [Y/n]
## 修改计划#
❯ /agent plan edit
Opening plan in editor...
# 修改后保存
Updated plan saved.
# 并行执行#
对于独立任务,Agent 可以并行执行:
❯ /agent 为所有组件添加测试
Planning...
Found 20 independent components
Parallel execution: 5 concurrent tasks
Executing in parallel:
[████░░░░░░] 8/20 components
- Button.test.tsx ✓
- Input.test.tsx ✓
- Modal.test.tsx (running)
- Form.test.tsx (running)
...
# 错误处理#
## 自动重试#
toml1[agent.error_handling] 2retry_count = 3 3retry_delay = 1000 # ms 4auto_fix = true # 尝试自动修复错误
## 回滚#
如果任务失败,可以回滚:
❯ /agent rollback
Rolling back changes...
✓ Restored: src/auth/login.tsx
✓ Restored: src/auth/register.tsx
✓ Restored: package.json
Rollback complete. 3 files restored.
## 手动介入#
❯ /agent 继续,跳过 Form.tsx 的转换
# 日志与报告#
## 执行日志#
❯ /agent log
Agent Execution Log:
[10:30:15] Task started: Convert class components
[10:30:16] Plan created: 5 phases, 15 steps
[10:30:20] Step 1: Analyzing components...
[10:30:45] Step 1 completed
[10:30:46] Step 2: Converting Button.tsx
...
## 任务报告#
❯ /agent report
Task Report: Convert class components
================================
Status: Completed
Duration: 3m 45s
Steps: 15/15
Changes Made:
- 15 files modified
- 450 lines added
- 620 lines removed
Quality Checks:
✓ All tests passing
✓ No lint errors
✓ Type checking passed
# 高级配置#
## 资源限制#
toml1[agent.limits] 2max_file_changes = 50 # 最多修改文件数 3max_duration = 600 # 最长执行时间(秒) 4max_tokens = 100000 # 最大 token 消耗
## 安全限制#
toml1[agent.security] 2allow_delete = false # 禁止删除文件 3allow_external_calls = false # 禁止外部调用 4protected_paths = [".env", "secrets/"]
# 下一步#
掌握 Agent 模式后,学习如何创建自动化工作流。