|
| 1 | +# AGENT_1: Background Agents & Async Messaging |
| 2 | + |
| 3 | +## Mission |
| 4 | + |
| 5 | +Implémenter l'exécution véritablement parallèle d'agents en arrière-plan avec communication asynchrone entre agents. |
| 6 | + |
| 7 | +## Contexte |
| 8 | + |
| 9 | +**Priorité:** 🔴 Critique |
| 10 | +**Effort estimé:** 6-8 jours développeur |
| 11 | +**Présent dans:** Claude Code (v2.0.64+), Droid |
| 12 | + |
| 13 | +## État Actuel dans cortex-cli |
| 14 | + |
| 15 | +### Ce qui existe déjà ✅ |
| 16 | + |
| 17 | +- `cortex-agents/routing.rs`: |
| 18 | + - `DispatchMode::Background` enum variant |
| 19 | + - `DispatchMode::Parallel` enum variant |
| 20 | + - `TaskInfo` avec métadonnées de tâches |
| 21 | + - `RoutingDecision` pour décisions de dispatch |
| 22 | + - `decide_routing()` pour routing intelligent |
| 23 | + |
| 24 | +- `cortex-agents/agent.rs`: |
| 25 | + - `AgentMode::Background` enum variant |
| 26 | + - `AgentInfo` avec configuration complète |
| 27 | + |
| 28 | +### Ce qui manque ❌ |
| 29 | + |
| 30 | +- Exécution réelle des agents en background (tokio tasks) |
| 31 | +- Communication async entre agents (channels) |
| 32 | +- UI `/tasks` pour monitoring des agents |
| 33 | +- Ctrl+B pour lancer en arrière-plan |
| 34 | +- Notifications quand un agent termine |
| 35 | + |
| 36 | +## Objectifs Spécifiques |
| 37 | + |
| 38 | +### 1. Background Agent Executor |
| 39 | + |
| 40 | +```rust |
| 41 | +// cortex-agents/src/background/executor.rs |
| 42 | + |
| 43 | +use tokio::sync::{mpsc, oneshot, broadcast}; |
| 44 | +use std::collections::HashMap; |
| 45 | + |
| 46 | +/// Manager des agents en arrière-plan |
| 47 | +pub struct BackgroundAgentManager { |
| 48 | + agents: HashMap<String, BackgroundAgent>, |
| 49 | + event_tx: broadcast::Sender<AgentEvent>, |
| 50 | + max_concurrent: usize, |
| 51 | +} |
| 52 | + |
| 53 | +pub struct BackgroundAgent { |
| 54 | + id: String, |
| 55 | + handle: tokio::task::JoinHandle<AgentResult>, |
| 56 | + status_rx: mpsc::Receiver<AgentStatus>, |
| 57 | + cancel_tx: oneshot::Sender<()>, |
| 58 | + started_at: Instant, |
| 59 | +} |
| 60 | + |
| 61 | +#[derive(Clone, Debug)] |
| 62 | +pub enum AgentEvent { |
| 63 | + Started { id: String, task: String }, |
| 64 | + Progress { id: String, message: String }, |
| 65 | + Completed { id: String, result: AgentResult }, |
| 66 | + Failed { id: String, error: String }, |
| 67 | +} |
| 68 | + |
| 69 | +impl BackgroundAgentManager { |
| 70 | + pub fn new(max_concurrent: usize) -> Self { ... } |
| 71 | + |
| 72 | + /// Lance un agent en arrière-plan |
| 73 | + pub async fn spawn(&mut self, config: AgentConfig) -> Result<String, AgentError> { |
| 74 | + if self.agents.len() >= self.max_concurrent { |
| 75 | + return Err(AgentError::TooManyAgents); |
| 76 | + } |
| 77 | + |
| 78 | + let id = uuid::Uuid::new_v4().to_string(); |
| 79 | + let (status_tx, status_rx) = mpsc::channel(100); |
| 80 | + let (cancel_tx, cancel_rx) = oneshot::channel(); |
| 81 | + |
| 82 | + let event_tx = self.event_tx.clone(); |
| 83 | + let handle = tokio::spawn(async move { |
| 84 | + run_background_agent(config, status_tx, cancel_rx, event_tx).await |
| 85 | + }); |
| 86 | + |
| 87 | + self.agents.insert(id.clone(), BackgroundAgent { |
| 88 | + id: id.clone(), |
| 89 | + handle, |
| 90 | + status_rx, |
| 91 | + cancel_tx, |
| 92 | + started_at: Instant::now(), |
| 93 | + }); |
| 94 | + |
| 95 | + Ok(id) |
| 96 | + } |
| 97 | + |
| 98 | + /// Liste les agents actifs |
| 99 | + pub fn list(&self) -> Vec<AgentStatus> { ... } |
| 100 | + |
| 101 | + /// Attend qu'un agent termine |
| 102 | + pub async fn wait(&mut self, id: &str, timeout: Duration) -> Result<AgentResult> { ... } |
| 103 | + |
| 104 | + /// Annule un agent |
| 105 | + pub async fn cancel(&mut self, id: &str) -> Result<()> { ... } |
| 106 | + |
| 107 | + /// S'abonne aux événements |
| 108 | + pub fn subscribe(&self) -> broadcast::Receiver<AgentEvent> { |
| 109 | + self.event_tx.subscribe() |
| 110 | + } |
| 111 | +} |
| 112 | +``` |
| 113 | + |
| 114 | +### 2. Async Messaging Between Agents |
| 115 | + |
| 116 | +```rust |
| 117 | +// cortex-agents/src/background/messaging.rs |
| 118 | + |
| 119 | +use tokio::sync::mpsc; |
| 120 | + |
| 121 | +/// Channel pour communication inter-agents |
| 122 | +pub struct AgentMailbox { |
| 123 | + inbox: mpsc::Receiver<AgentMessage>, |
| 124 | + outbox: mpsc::Sender<AgentMessage>, |
| 125 | +} |
| 126 | + |
| 127 | +#[derive(Clone, Debug)] |
| 128 | +pub struct AgentMessage { |
| 129 | + pub from: String, |
| 130 | + pub to: String, |
| 131 | + pub content: MessageContent, |
| 132 | + pub timestamp: Instant, |
| 133 | +} |
| 134 | + |
| 135 | +#[derive(Clone, Debug)] |
| 136 | +pub enum MessageContent { |
| 137 | + /// Notification simple |
| 138 | + Notify(String), |
| 139 | + /// Demande avec réponse attendue |
| 140 | + Request { id: String, payload: String }, |
| 141 | + /// Réponse à une demande |
| 142 | + Response { request_id: String, payload: String }, |
| 143 | + /// Partage de données |
| 144 | + Data { key: String, value: serde_json::Value }, |
| 145 | +} |
| 146 | + |
| 147 | +impl AgentMailbox { |
| 148 | + /// Envoie un message à un autre agent |
| 149 | + pub async fn send(&self, to: &str, content: MessageContent) -> Result<()> { ... } |
| 150 | + |
| 151 | + /// Reçoit le prochain message (non-bloquant) |
| 152 | + pub fn try_recv(&mut self) -> Option<AgentMessage> { ... } |
| 153 | + |
| 154 | + /// Attend un message (avec timeout) |
| 155 | + pub async fn recv_timeout(&mut self, timeout: Duration) -> Option<AgentMessage> { ... } |
| 156 | +} |
| 157 | +``` |
| 158 | + |
| 159 | +### 3. TUI /tasks Command |
| 160 | + |
| 161 | +```rust |
| 162 | +// cortex-tui/src/views/tasks.rs |
| 163 | + |
| 164 | +use ratatui::widgets::{Table, Row, Cell}; |
| 165 | + |
| 166 | +pub struct TasksView { |
| 167 | + agents: Vec<AgentStatus>, |
| 168 | + selected: usize, |
| 169 | +} |
| 170 | + |
| 171 | +impl TasksView { |
| 172 | + pub fn render(&self, frame: &mut Frame, area: Rect) { |
| 173 | + let header = Row::new(vec!["ID", "Status", "Task", "Duration", "Tokens"]); |
| 174 | + |
| 175 | + let rows: Vec<Row> = self.agents.iter().map(|agent| { |
| 176 | + Row::new(vec![ |
| 177 | + Cell::from(agent.id.chars().take(8).collect::<String>()), |
| 178 | + Cell::from(status_badge(&agent.status)), |
| 179 | + Cell::from(truncate(&agent.task, 40)), |
| 180 | + Cell::from(format_duration(agent.duration)), |
| 181 | + Cell::from(format!("{}", agent.tokens_used)), |
| 182 | + ]) |
| 183 | + }).collect(); |
| 184 | + |
| 185 | + let table = Table::new(rows) |
| 186 | + .header(header) |
| 187 | + .widths(&[ |
| 188 | + Constraint::Length(10), |
| 189 | + Constraint::Length(12), |
| 190 | + Constraint::Percentage(40), |
| 191 | + Constraint::Length(10), |
| 192 | + Constraint::Length(10), |
| 193 | + ]); |
| 194 | + |
| 195 | + frame.render_widget(table, area); |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +fn status_badge(status: &AgentStatus) -> Span { |
| 200 | + match status { |
| 201 | + AgentStatus::Running => Span::styled("● Running", Style::default().fg(Color::Yellow)), |
| 202 | + AgentStatus::Completed => Span::styled("✓ Done", Style::default().fg(Color::Green)), |
| 203 | + AgentStatus::Failed => Span::styled("✗ Failed", Style::default().fg(Color::Red)), |
| 204 | + AgentStatus::Cancelled => Span::styled("○ Cancelled", Style::default().fg(Color::Gray)), |
| 205 | + } |
| 206 | +} |
| 207 | +``` |
| 208 | + |
| 209 | +### 4. Ctrl+B Handler |
| 210 | + |
| 211 | +```rust |
| 212 | +// cortex-tui/src/input/keybindings.rs |
| 213 | + |
| 214 | +// Ajouter dans le handler de touches |
| 215 | +KeyCode::Char('b') if modifiers.contains(KeyModifiers::CONTROL) => { |
| 216 | + // Lancer la tâche courante en arrière-plan |
| 217 | + if let Some(prompt) = self.get_current_prompt() { |
| 218 | + let agent_id = self.background_manager |
| 219 | + .spawn(AgentConfig::background(prompt)) |
| 220 | + .await?; |
| 221 | + self.show_notification(format!("Agent {} lancé en arrière-plan", &agent_id[..8])); |
| 222 | + } |
| 223 | + InputAction::Handled |
| 224 | +} |
| 225 | +``` |
| 226 | + |
| 227 | +### 5. Notification System |
| 228 | + |
| 229 | +```rust |
| 230 | +// cortex-tui/src/notifications.rs |
| 231 | + |
| 232 | +pub struct NotificationManager { |
| 233 | + event_rx: broadcast::Receiver<AgentEvent>, |
| 234 | + pending: VecDeque<Notification>, |
| 235 | +} |
| 236 | + |
| 237 | +impl NotificationManager { |
| 238 | + pub async fn poll(&mut self) { |
| 239 | + while let Ok(event) = self.event_rx.try_recv() { |
| 240 | + match event { |
| 241 | + AgentEvent::Completed { id, result } => { |
| 242 | + self.pending.push_back(Notification { |
| 243 | + title: format!("Agent {} terminé", &id[..8]), |
| 244 | + body: result.summary, |
| 245 | + level: NotificationLevel::Info, |
| 246 | + }); |
| 247 | + } |
| 248 | + AgentEvent::Failed { id, error } => { |
| 249 | + self.pending.push_back(Notification { |
| 250 | + title: format!("Agent {} échoué", &id[..8]), |
| 251 | + body: error, |
| 252 | + level: NotificationLevel::Error, |
| 253 | + }); |
| 254 | + } |
| 255 | + _ => {} |
| 256 | + } |
| 257 | + } |
| 258 | + } |
| 259 | +} |
| 260 | +``` |
| 261 | + |
| 262 | +## Fichiers à Créer |
| 263 | + |
| 264 | +``` |
| 265 | +cortex-agents/src/ |
| 266 | +├── background/ |
| 267 | +│ ├── mod.rs |
| 268 | +│ ├── executor.rs # BackgroundAgentManager |
| 269 | +│ ├── messaging.rs # AgentMailbox, inter-agent comm |
| 270 | +│ └── events.rs # AgentEvent, notifications |
| 271 | +
|
| 272 | +cortex-tui/src/ |
| 273 | +├── views/ |
| 274 | +│ └── tasks.rs # /tasks view |
| 275 | +├── notifications.rs # Notification system |
| 276 | +``` |
| 277 | + |
| 278 | +## Fichiers à Modifier |
| 279 | + |
| 280 | +1. `cortex-agents/src/lib.rs` - Export du module background |
| 281 | +2. `cortex-agents/Cargo.toml` - Ajouter tokio, uuid |
| 282 | +3. `cortex-tui/src/commands/registry.rs` - Ajouter /tasks |
| 283 | +4. `cortex-tui/src/commands/executor.rs` - Handler /tasks |
| 284 | +5. `cortex-tui/src/input/keybindings.rs` - Ctrl+B |
| 285 | +6. `cortex-tui/src/app.rs` - Intégrer NotificationManager |
| 286 | + |
| 287 | +## Tests Requis |
| 288 | + |
| 289 | +```rust |
| 290 | +#[cfg(test)] |
| 291 | +mod tests { |
| 292 | + #[tokio::test] |
| 293 | + async fn test_spawn_background_agent() { |
| 294 | + let mut manager = BackgroundAgentManager::new(5); |
| 295 | + let id = manager.spawn(AgentConfig::test()).await.unwrap(); |
| 296 | + assert!(!id.is_empty()); |
| 297 | + assert_eq!(manager.list().len(), 1); |
| 298 | + } |
| 299 | + |
| 300 | + #[tokio::test] |
| 301 | + async fn test_max_concurrent_limit() { |
| 302 | + let mut manager = BackgroundAgentManager::new(2); |
| 303 | + manager.spawn(AgentConfig::test()).await.unwrap(); |
| 304 | + manager.spawn(AgentConfig::test()).await.unwrap(); |
| 305 | + assert!(manager.spawn(AgentConfig::test()).await.is_err()); |
| 306 | + } |
| 307 | + |
| 308 | + #[tokio::test] |
| 309 | + async fn test_agent_cancellation() { |
| 310 | + let mut manager = BackgroundAgentManager::new(5); |
| 311 | + let id = manager.spawn(AgentConfig::long_running()).await.unwrap(); |
| 312 | + manager.cancel(&id).await.unwrap(); |
| 313 | + let status = manager.get_status(&id); |
| 314 | + assert!(matches!(status, AgentStatus::Cancelled)); |
| 315 | + } |
| 316 | + |
| 317 | + #[tokio::test] |
| 318 | + async fn test_inter_agent_messaging() { |
| 319 | + let (mailbox1, mailbox2) = create_connected_mailboxes(); |
| 320 | + mailbox1.send("agent2", MessageContent::Notify("hello".into())).await.unwrap(); |
| 321 | + let msg = mailbox2.recv_timeout(Duration::from_secs(1)).await.unwrap(); |
| 322 | + assert!(matches!(msg.content, MessageContent::Notify(_))); |
| 323 | + } |
| 324 | +} |
| 325 | +``` |
| 326 | + |
| 327 | +## Sécurité |
| 328 | + |
| 329 | +### Limites |
| 330 | + |
| 331 | +- Max 5 agents concurrent par défaut (configurable) |
| 332 | +- Timeout automatique après 30 minutes |
| 333 | +- Isolation de contexte entre agents |
| 334 | +- Pas d'accès aux credentials d'autres agents |
| 335 | + |
| 336 | +### Cleanup |
| 337 | + |
| 338 | +- RAII: agents cleanup automatique à la fin de session |
| 339 | +- Cancel propre avec timeout de grace (5s) |
| 340 | +- Pas de zombie processes |
| 341 | + |
| 342 | +## Critères de Succès |
| 343 | + |
| 344 | +- [ ] Agents s'exécutent vraiment en parallèle (tokio tasks) |
| 345 | +- [ ] Communication async fonctionne |
| 346 | +- [ ] /tasks affiche les agents actifs |
| 347 | +- [ ] Ctrl+B lance en arrière-plan |
| 348 | +- [ ] Notifications quand agents terminent |
| 349 | +- [ ] Tests passent |
| 350 | +- [ ] Pas de memory leaks |
| 351 | + |
| 352 | +## Estimation |
| 353 | + |
| 354 | +| Tâche | Durée | |
| 355 | +|-------|-------| |
| 356 | +| BackgroundAgentManager | 2 jours | |
| 357 | +| Inter-agent messaging | 1.5 jours | |
| 358 | +| TUI /tasks view | 1 jour | |
| 359 | +| Ctrl+B + notifications | 1 jour | |
| 360 | +| Tests et documentation | 1.5 jours | |
| 361 | +| **Total** | **7 jours** | |
| 362 | + |
| 363 | +--- |
| 364 | + |
| 365 | +*Agent autonome - Pas de dépendance externe* |
0 commit comments