Execute 执行任务(同步)
(ctx context.Context, agentType, prompt string, opts *TaskExecuteOptions)
| 59 | |
| 60 | // Execute 执行任务(同步) |
| 61 | func (te *TaskExecutor) Execute(ctx context.Context, agentType, prompt string, opts *TaskExecuteOptions) (*TaskExecution, error) { |
| 62 | te.mu.RLock() |
| 63 | factory := te.executorFactory |
| 64 | te.mu.RUnlock() |
| 65 | |
| 66 | if factory == nil { |
| 67 | return nil, errors.New("executor factory not configured, subagent execution not available") |
| 68 | } |
| 69 | |
| 70 | // 创建执行器 |
| 71 | executor, err := factory.Create(agentType) |
| 72 | if err != nil { |
| 73 | return nil, fmt.Errorf("failed to create executor for %s: %w", agentType, err) |
| 74 | } |
| 75 | |
| 76 | // 构建请求 |
| 77 | req := &types.SubAgentRequest{ |
| 78 | AgentType: agentType, |
| 79 | Task: prompt, |
| 80 | Context: opts.Context, |
| 81 | } |
| 82 | |
| 83 | if opts.Timeout > 0 { |
| 84 | req.Timeout = opts.Timeout |
| 85 | } |
| 86 | |
| 87 | // 执行 |
| 88 | startTime := time.Now() |
| 89 | result, err := executor.Execute(ctx, req) |
| 90 | |
| 91 | execution := &TaskExecution{ |
| 92 | TaskID: fmt.Sprintf("task_%d", startTime.UnixNano()), |
| 93 | Subagent: agentType, |
| 94 | Model: opts.Model, |
| 95 | Status: "completed", |
| 96 | StartTime: startTime, |
| 97 | Duration: time.Since(startTime), |
| 98 | } |
| 99 | |
| 100 | if err != nil { |
| 101 | execution.Status = "failed" |
| 102 | execution.Error = err.Error() |
| 103 | return execution, nil |
| 104 | } |
| 105 | |
| 106 | if result != nil { |
| 107 | execution.Result = result.Output |
| 108 | if result.Success { |
| 109 | execution.Status = "completed" |
| 110 | } else { |
| 111 | execution.Status = "failed" |
| 112 | execution.Error = result.Error |
| 113 | } |
| 114 | execution.Metadata = map[string]any{ |
| 115 | "tokens_used": result.TokensUsed, |
| 116 | "step_count": result.StepCount, |
| 117 | "artifacts": result.Artifacts, |
| 118 | } |