Skip to content

8. 任务执行流程

8.1 完整执行流程

┌─────────────────────────────────────────────────────────────────────────────┐
│                         Manus Task Execution Flow                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   User Request                                                               │
│        │                                                                     │
│        ▼                                                                     │
│   ┌─────────────────┐                                                        │
│   │  1. Understand   │  Parse user intent, identify requirements             │
│   └────────┬────────┘                                                        │
│            │                                                                 │
│            ▼                                                                 │
│   ┌─────────────────┐                                                        │
│   │  2. Plan         │  Break down into steps, assign tools                  │
│   └────────┬────────┘                                                        │
│            │                                                                 │
│            ▼                                                                 │
│   ┌─────────────────┐     ┌─────────────────┐                               │
│   │  3. Execute      │────▶│  Tool Router    │                               │
│   │     Step N       │     │                 │                               │
│   └────────┬────────┘     │ browser_*       │                               │
│            │              │ file_*          │                               │
│            │              │ shell_*         │                               │
│            │              │ message_*       │                               │
│            │              └─────────────────┘                               │
│            ▼                                                                 │
│   ┌─────────────────┐                                                        │
│   │  4. Verify       │  Check if step succeeded                              │
│   └────────┬────────┘                                                        │
│            │                                                                 │
│      ┌─────┴─────┐                                                          │
│      │           │                                                          │
│   Success?    Failed                                                         │
│      │           │                                                          │
│      │     ┌─────┴─────┐                                                    │
│      │     │  5. Adapt  │  Try fallback or replan                           │
│      │     └─────┬─────┘                                                    │
│      │           │                                                          │
│      ▼           ▼                                                          │
│   ┌─────────────────┐                                                        │
│   │  More Steps?     │────Yes───▶ Loop back to Step 3                        │
│   └────────┬────────┘                                                        │
│            │ No                                                              │
│            ▼                                                                 │
│   ┌─────────────────┐                                                        │
│   │  6. Deliver      │  Package results, notify user                         │
│   └─────────────────┘                                                        │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

8.2 Agent 主循环实现

typescript
class ManusAgent {
  private planner: TaskPlanner;
  private executor: TaskExecutor;
  private browser: BrowserController;
  private filesystem: FileSystemController;
  private state: StateManager;
  private events: EventStreamManager;
  
  async run(userRequest: string): Promise<TaskResult> {
    const taskId = generateId();
    
    try {
      // 1. 创建沙盒环境
      const sandbox = await this.sandboxManager.createSandbox(taskId);
      this.events.taskStarted(taskId, userRequest);
      
      // 2. 规划任务
      const plan = await this.planner.plan(userRequest, this.state.getContext());
      this.state.update({ task: { plan, currentStep: 0 } });
      
      // 3. 执行计划
      for (let i = 0; i < plan.steps.length; i++) {
        const step = plan.steps[i];
        this.state.update({ task: { currentStep: i + 1 } });
        this.events.stepProgress(taskId, i + 1, plan.steps.length, step.description);
        
        // 执行步骤(带重试)
        const result = await this.executeStepWithRetry(step, 3);
        
        if (!result.success) {
          // 尝试重新规划
          const newPlan = await this.planner.replan(this.state.get(), result.error);
          if (newPlan) {
            plan.steps = [...plan.steps.slice(0, i), ...newPlan.steps];
            i--; // 重新执行当前步骤
            continue;
          }
          throw new Error(`Failed at step ${i + 1}: ${result.error}`);
        }
      }
      
      // 4. 验证任务完成
      const verification = await this.verifyTaskComplete(plan);
      
      // 5. 打包交付物
      const deliverables = await this.packageDeliverables();
      this.events.taskCompleted(taskId, deliverables);
      
      return {
        success: true,
        deliverables,
        summary: await this.generateSummary(plan)
      };
      
    } catch (error) {
      this.events.emit({
        type: 'task_failed',
        taskId,
        data: { error: error.message }
      });
      
      return {
        success: false,
        error: error.message
      };
    } finally {
      // 清理沙盒
      await this.sandboxManager.destroySandbox(taskId);
    }
  }
  
  private async executeStepWithRetry(step: TaskStep, maxRetries: number): Promise<StepResult> {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        // 决定使用哪个工具
        const toolCall = await this.decideToolCall(step);
        this.events.toolInvoked(this.state.get().task.id, toolCall.tool, toolCall.params);
        
        // 执行工具调用
        const result = await this.executor.execute(toolCall);
        this.events.toolResult(this.state.get().task.id, toolCall.tool, result);
        
        // 验证步骤结果
        const verified = await this.verifyStep(step, result);
        
        if (verified) {
          return { success: true, result };
        }
        
        // 验证失败,尝试备选方案
        if (step.fallback && attempt < maxRetries) {
          await this.executeFallback(step.fallback);
        }
        
      } catch (error) {
        if (attempt === maxRetries) {
          return { success: false, error: error.message };
        }
        // 等待后重试
        await sleep(1000 * attempt);
      }
    }
    
    return { success: false, error: 'Max retries exceeded' };
  }
  
  private async decideToolCall(step: TaskStep): Promise<ToolCall> {
    // 如果步骤已指定工具,直接使用
    if (step.tool) {
      return {
        tool: step.tool,
        params: step.params
      };
    }
    
    // 否则让 LLM 决定
    const screenshot = await this.browser.screenshot();
    
    const response = await this.llm.chat({
      messages: [{
        role: "system",
        content: "You are a tool selection agent. Choose the appropriate tool and parameters."
      }, {
        role: "user",
        content: [
          { type: "image", source: { type: "base64", data: screenshot.image } },
          { type: "text", text: `
Current step: ${step.description}

Context:
${this.state.getContextSummary()}

Available tools:
${this.getToolDescriptions()}

Choose a tool and provide parameters. Output JSON:
{
  "tool": "tool_name",
  "params": { ... },
  "reasoning": "why this tool"
}`
          }
        ]
      }]
    });
    
    return JSON.parse(response.content);
  }
}

前端面试知识库