Agent模式
Agent模式是我用Claude Code最喜欢的功能之一。它不再只是被动回答问题,而是能主动思考、探索项目、制定计划并逐步执行。
这篇文章详细介绍Agent模式的工作原理和使用场景。
什么是Agent模式
传统对话模式 vs Agent模式
先看传统AI助手怎么工作的:
传统模式:
你: 帮我找到处理用户认证的代码
AI: 你可以在auth.js文件中查看
你: 认证逻辑在哪个函数?
AI: 应该在verifyToken函数中
你: 帮我添加刷新token的功能
AI: [等待你提供更多信息]
这种模式下,AI只能被动回答,每次都需要你明确指示下一步。
Agent模式:
你: 帮我添加刷新token的功能
Agent: I'll help you add refresh token functionality. Let me first explore
your authentication setup.
[Agent自主工作流程]
1. 探索项目结构
✓ Found auth middleware in src/middleware/auth.js
✓ Found JWT config in src/config/jwt.js
✓ Found User model in src/models/User.js
2. 分析现有认证逻辑
✓ Using JWT for access tokens (15min expiry)
✓ No refresh token mechanism currently
✓ Token stored in Authorization header
3. 设计实现方案
✓ Add refreshToken field to User model
✓ Create /auth/refresh endpoint
✓ Update login to return both tokens
✓ Add token rotation mechanism
4. 执行实现
✓ Modified User model
✓ Created refresh token endpoint
✓ Updated authentication middleware
✓ Added token cleanup logic
✓ Refresh token functionality has been implemented!
Next steps you might want:
- Add tests for refresh token flow
- Update API documentation
- Configure token expiry times
看到区别了吗?Agent模式下,Claude Code会:
- 主动探索: 自己查找相关文件和代码
- 自主分析: 理解现有架构和实现
- 制定计划: 设计完整的实现方案
- 执行任务: 逐步完成所有必要的修改
- 提供建议: 主动提出后续优化方向
Agent的核心特征
1. 自主性(Autonomy)
Agent不需要你手把手指导每一步:
传统模式:
你: 创建一个API
AI: 好的,需要什么端点?
你: GET /users 和 POST /users
AI: 需要什么字段?
你: name, email, password
AI: 需要验证吗?
你: 是的
AI: 需要什么验证规则?
[...无穷无尽的来回...]
Agent模式:
你: 创建一个用户管理API,包含常见功能
Agent: I'll create a complete user management API for you.
[自主完成]
✓ RESTful endpoints (GET, POST, PUT, DELETE)
✓ Input validation with proper error messages
✓ Password hashing with bcrypt
✓ Email format validation
✓ Error handling middleware
✓ API documentation
2. 探索能力(Exploration)
Agent会主动探索项目环境:
- 自动发现项目结构
- 识别技术栈和框架
- 找到相关配置文件
- 理解代码依赖关系
- 发现潜在问题
3. 规划能力(Planning)
Agent会在执行前制定详细计划:
Task: 重构数据 库查询层
Agent Planning:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Execution Plan
Phase 1: Discovery & Analysis
├─ Scan all database queries in the project
├─ Identify duplicate query patterns
├─ Find N+1 query problems
└─ Map query-to-file relationships
Phase 2: Design
├─ Design unified query builder interface
├─ Plan migration strategy
├─ Define error handling approach
└─ Design caching layer
Phase 3: Implementation
├─ Create base QueryBuilder class
├─ Refactor user queries
├─ Refactor product queries
├─ Refactor order queries
└─ Add caching mechanism
Phase 4: Validation
├─ Run existing tests
├─ Add new tests for QueryBuilder
└─ Performance benchmarking
Estimated impact: ~15 files, ~500 lines modified
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Proceed with execution? (yes/no)
4. 执行能力(Execution)
Agent会逐步执行计划并实时报告进度:
🤖 Executing Phase 1: Discovery & Analysis
├─ [1/4] Scanning database queries... ✓ Found 23 queries
├─ [2/4] Identifying patterns... ✓ Found 5 duplicate patterns
├─ [3/4] Analyzing N+1 problems... ✓ Found 3 instances
└─ [4/4] Mapping relationships... ✓ 12 files affected
🤖 Executing Phase 2: Design
├─ [1/4] Designing QueryBuilder... ✓ Interface defined
├─ [2/4] Planning migration... ✓ Strategy documented
├─ [3/4] Defining error handling... ✓ ErrorHandler created
└─ [4/4] Designing caching... ✓ Cache layer planned
🤖 Executing Phase 3: Implementation
[Working on user queries...]
如何启动和使用Agent
启动Agent模式
Agent模式有多种启动方式:
方式1:通过Slash命令启动
# 在Claude Code中输入
/agent 帮我重构认证模块,使其支持多种登录方式
方式2:使用agent命令行参数
# 启动时直接进入Agent模式
claude --agent
# 或者带任务启动
claude --agent "优化数据库查询性能"
方式3:自然语言触发
对于复杂任务,Claude Code会自动建议使用Agent模式:
你: 我需要将整个项目从JavaScript迁移到TypeScript
Claude: This is a complex task that would benefit from Agent mode.
Agent can autonomously:
- Analyze your entire codebase
- Create migration plan
- Convert files systematically
- Fix type errors
- Update configurations
Switch to Agent mode? (yes/no)
Agent的工作界面
启动Agent后 ,你会看到专门的Agent界面:
╔═══════════════════════════════════════════════════════════╗
║ AGENT MODE ACTIVE ║
║ ║
║ Status: Idle ║
║ Task: None ║
║ Files Monitored: 0 ║
║ Context: 2.5K / 200K tokens ║
╚═══════════════════════════════════════════════════════════╝
Agent Controls:
/pause - Pause agent execution
/resume - Resume agent execution
/stop - Stop current task
/status - Show detailed status
/plan - Show execution plan
/exit - Exit agent mode
Ready for task. What should I work on?
给Agent分配任务
简单任务描述
添加用户头像上传功能
Agent会自动扩展理解:
- 需要文件上传API
- 需要图片处理(裁剪、压缩)
- 需要存储方案(本地/云存储)
- 需要数据库字段更新
- 需要前端上传组件
详细任务描述
我需要实现一个完整的评论系统:
1. 用户可以对文章发表评论
2. 支持评论回复(嵌套评论)
3. 支持点赞评论
4. 实时通知被回复的用户
5. 支持举报不当评论
6. 管理员可以审核和删除评论
问题导向型任务
用户反馈系统响应很慢,请帮我找出问题并优化
Agent会:
- 分析性能瓶颈
- 检查数据库查询
- 查看API响应时间
- 检查前端渲染
- 提出优化方案
- 实施改进
Agent的自主探索能力详解
项目结构探索
当你给Agent一个任务时,它首先会探索项目结构:
🔍 Exploring Project Structure...
📁 Project Analysis:
├─ Type: Node.js application
├─ Framework: Express.js
├─ Language: JavaScript (ES6+)
├─ Database: MongoDB with Mongoose
├─ Testing: Jest
└─ Package Manager: npm
📂 Directory Structure:
├─ src/
│ ├─ controllers/ (7 files)
│ ├─ models/ (5 files)
│ ├─ routes/ (8 files)
│ ├─ middleware/ (4 files)
│ ├─ utils/ (6 files)
│ └─ config/ (3 files)
├─ tests/ (12 files)
└─ public/ (static assets)
📊 Code Metrics:
├─ Total Files: 45
├─ Lines of Code: ~3,200
├─ Dependencies: 23
└─ Dev Dependencies: 15
🔗 Key Dependencies:
├─ express: ^4.18.0
├─ mongoose: ^7.0.0
├─ jsonwebtoken: ^9.0.0
└─ bcryptjs: ^2.4.3
智能文件发现
Agent会智能地找到相关文件:
Task: 添加邮件通知功能
🔍 Agent Discovery Process:
Step 1: Looking for existing email/notification code...
✓ No email service found
✓ Found notification mention in User model (line 45)
Step 2: Checking configuration files...
✓ Found config/index.js
✗ No email configuration present
Step 3: Analyzing dependencies...
✗ No email library installed
✓ Need to add nodemailer
Step 4: Identifying integration points...
✓ User registration (controllers/auth.js:56)
✓ Password reset (controllers/auth.js:123)
✓ Order creation (controllers/orders.js:78)
📋 Discovery Summary:
Files to create: 3 (email service, templates, config)
Files to modify: 4 (auth controller, orders, config, package.json)
Dependencies to add: 2 (nodemailer, email-templates)
代码依赖分析
Agent会分析代码之间的依赖关系:
🔍 Analyzing Dependencies for "refactor User authentication"
📊 Dependency Graph:
controllers/auth.js
├─ requires models/User.js
├─ requires middleware/validateInput.js
├─ requires utils/jwt.js
└─ requires utils/password.js
middleware/auth.js
├─ requires models/User.js
└─ requires utils/jwt.js
routes/auth.js
├─ requires controllers/auth.js
└─ requires middleware/auth.js
⚠️ Impact Analysis:
└─ Modifying utils/jwt.js will affect:
├─ controllers/auth.js (3 usage points)
├─ middleware/auth.js (2 usage points)
└─ controllers/admin.js (1 usage point)
💡 Recommendation:
Create new jwt.js with backward compatibility
Migrate usage points one by one
Remove old implementation last
问题识别
Agent会主动识别潜在问题:
🔍 Project Health Check...
⚠️ Issues Discovered:
Security Issues:
├─ [HIGH] Passwords stored in plain text (models/User.js:23)
├─ [HIGH] SQL injection risk (controllers/users.js:45)
└─ [MEDIUM] Missing rate limiting on auth routes
Performance Issues:
├─ [HIGH] N+1 query in getOrders (controllers/orders.js:67)
├─ [MEDIUM] No database indexing on email field
└─ [LOW] Large payload in /api/users response
Code Quality:
├─ [MEDIUM] Duplicate code in 3 controllers
├─ [LOW] Missing error handling in 5 async functions
└─ [LOW] Inconsistent naming conventions
Missing Features:
├─ No input validation on 4 routes
├─ No logging system
└─ No API documentation
Would you like me to address these issues?
Agent的规划和执行流程
任务分解
Agent会将复杂任务分解为可管理的子任务:
Task: 实现完整的博客系统
🎯 Task Breakdown:
EPIC: Blog System Implementation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Module 1: Data Layer ⏱️ ~30min
├─ Task 1.1: Create Post model
│ ├─ Define schema (title, content, author, tags, status)
│ ├─ Add timestamps and soft delete
│ └─ Create indexes
│
├─ Task 1.2: Create Comment model
│ ├─ Define schema with post reference
│ ├─ Support nested comments
│ └─ Add moderation status
│
└─ Task 1.3: Create Category model
├─ Define schema with hierarchy support
└─ Add slug generation
Module 2: API Layer ⏱️ ~45min
├─ Task 2.1: Post CRUD endpoints
│ ├─ GET /posts (with pagination, filtering)
│ ├─ GET /posts/:id
│ ├─ POST /posts (auth required)
│ ├─ PUT /posts/:id (auth + ownership check)
│ └─ DELETE /posts/:id (soft delete)
│
├─ Task 2.2: Comment endpoints
│ ├─ GET /posts/:id/comments
│ ├─ POST /posts/:id/comments
│ └─ DELETE /comments/:id
│
└─ Task 2.3: Category endpoints
├─ GET /categories
└─ POST /categories (admin only)
Module 3: Business Logic ⏱️ ~40min
├─ Task 3.1: Post publishing workflow
│ ├─ Draft/Published status
│ ├─ Scheduled publishing
│ └─ SEO optimization (meta tags, slug)
│
├─ Task 3.2: Search functionality
│ ├─ Full-text search
│ ├─ Tag-based filtering
│ └─ Category filtering
│
└─ Task 3.3: Analytics
├─ View counter
├─ Popular posts
└─ User activity tracking
Module 4: Testing ⏱️ ~35min
├─ Task 4.1: Model tests
├─ Task 4.2: API endpoint tests
└─ Task 4.3: Integration tests
Module 5: Documentation ⏱️ ~20min
├─ Task 5.1: API documentation
├─ Task 5.2: Setup guide
└─ Task 5.3: Architecture overview
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total Estimated Time: ~2h 50min
Total Tasks: 20
Files to Create: ~25
Files to Modify: ~8
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Start execution? (yes/no/customize)
智能执行顺序
Agent会选择最优的执行顺序:
🎯 Optimizing Execution Order...
Original Plan Order: Task 1.1 → 1.2 → 1.3 → 2.1 → 2.2 → 2.3...
⚡ Optimized Execution Order:
Parallel Batch 1 (Independent tasks):
├─ Task 1.1: Create Post model
├─ Task 1.2: Create Comment model
└─ Task 1.3: Create Category model
Sequential Batch 2 (Depends on Batch 1):
├─ Task 2.1: Post CRUD endpoints
├─ Task 2.2: Comment endpoints
└─ Task 2.3: Category endpoints
Parallel Batch 3 (Can run together):
├─ Task 3.1: Publishing workflow
├─ Task 3.2: Search functionality
└─ Task 3.3: Analytics
Sequential Batch 4 (Needs working code):
├─ Task 4.1: Model tests
├─ Task 4.2: API tests
└─ Task 4.3: Integration tests
Final Task:
└─ Task 5: Documentation
💡 Optimization Results:
Original estimated time: 2h 50min
Optimized time: 1h 45min (38% faster)
Parallel tasks: 9
Sequential tasks: 11
实时进度报告
Agent会实时 报告执行进度:
🚀 Executing Blog System Implementation
Overall Progress: ████████░░░░░░░░░░░░ 40% (8/20 tasks)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Module 1: Data Layer ✅ COMPLETED
├─ ✅ Task 1.1: Create Post model (2m 15s)
├─ ✅ Task 1.2: Create Comment model (1m 45s)
└─ ✅ Task 1.3: Create Category model (1m 30s)
Module 2: API Layer 🔄 IN PROGRESS
├─ ✅ Task 2.1: Post CRUD endpoints (4m 20s)
├─ ✅ Task 2.2: Comment endpoints (2m 55s)
└─ 🔄 Task 2.3: Category endpoints
Progress: [Step 3/5] Implementing GET /categories
✓ Created route file
✓ Implemented controller logic
⏳ Adding input validation...
⏺️ Pending: Error handling
⏺️ Pending: API documentation
Module 3: Business Logic ⏺️ PENDING
Module 4: Testing ⏺️ PENDING
Module 5: Documentation ⏺️ PENDING