StartSubagent 启动子代理
(ctx context.Context, config *SubagentConfig)
| 107 | |
| 108 | // StartSubagent 启动子代理 |
| 109 | func (sm *FileSubagentManager) StartSubagent(ctx context.Context, config *SubagentConfig) (*SubagentInstance, error) { |
| 110 | sm.mu.Lock() |
| 111 | defer sm.mu.Unlock() |
| 112 | |
| 113 | // 生成子代理ID |
| 114 | if config.ID == "" { |
| 115 | config.ID = fmt.Sprintf("subagent_%d", time.Now().UnixNano()) |
| 116 | } |
| 117 | |
| 118 | // 检查是否已存在 |
| 119 | if _, exists := sm.agents[config.ID]; exists { |
| 120 | return nil, fmt.Errorf("subagent already exists: %s", config.ID) |
| 121 | } |
| 122 | |
| 123 | // 创建子代理实例 |
| 124 | instance := &SubagentInstance{ |
| 125 | ID: config.ID, |
| 126 | Type: config.Type, |
| 127 | Status: "starting", |
| 128 | Config: config, |
| 129 | StartTime: time.Now(), |
| 130 | Output: "", |
| 131 | Metadata: make(map[string]string), |
| 132 | LastUpdate: time.Now(), |
| 133 | } |
| 134 | |
| 135 | // 构建启动命令 |
| 136 | cmd, err := sm.buildSubagentCommand(config) |
| 137 | if err != nil { |
| 138 | return nil, fmt.Errorf("failed to build subagent command: %w", err) |
| 139 | } |
| 140 | |
| 141 | // 启动子代理进程 |
| 142 | cmdObj := exec.CommandContext(ctx, "bash", "-c", cmd) |
| 143 | cmdObj.Dir = config.WorkDir |
| 144 | |
| 145 | // 设置环境变量 |
| 146 | if len(config.Env) > 0 { |
| 147 | env := os.Environ() |
| 148 | for k, v := range config.Env { |
| 149 | env = append(env, fmt.Sprintf("%s=%s", k, v)) |
| 150 | } |
| 151 | cmdObj.Env = env |
| 152 | } |
| 153 | |
| 154 | // 创建输出文件 |
| 155 | outputFile := filepath.Join(sm.dataDir, config.ID+".output") |
| 156 | outFile, err := os.Create(outputFile) |
| 157 | if err != nil { |
| 158 | return nil, fmt.Errorf("failed to create output file: %w", err) |
| 159 | } |
| 160 | |
| 161 | cmdObj.Stdout = outFile |
| 162 | cmdObj.Stderr = outFile |
| 163 | |
| 164 | // 启动进程 |
| 165 | err = cmdObj.Start() |
| 166 | if err != nil { |
no test coverage detected