Skip to content

Commit ede4eb2

Browse files
committed
feat: implement background agents and async messaging system
This commit adds the complete background worker architecture and asynchronous messaging system for the CLI as specified in ORCHESTRATE/AGENT_1_BACKGROUND_AGENTS.md. ## New Features ### Background Agent Module (cortex-agents/src/background/) - **executor.rs**: BackgroundAgentManager for spawning and managing background tasks - Configurable max concurrent agents (default: 5) - Automatic timeout after 30 minutes - RAII cleanup with proper cancellation support - Event broadcasting for monitoring - **messaging.rs**: Inter-agent async messaging system - AgentMailbox for per-agent message queues - MessageRouter for routing messages between agents - Support for notifications, requests/responses, data sharing, and status updates - **events.rs**: Event system for background agents - AgentEvent enum for lifecycle events (Started, Progress, Completed, Failed, Cancelled) - NotificationManager for collecting and displaying notifications - Support for TodoUpdated events for progress tracking ### TUI Enhancements (cortex-tui/) - New /tasks command (aliases: /bg, /background) for viewing background tasks - TasksView component for displaying task status, duration, and progress - ModalType::Tasks for the background tasks modal ## Tests - 21 new unit tests covering: - Background agent spawning and cancellation - Max concurrent agent limits - Event subscription and notification - Inter-agent messaging - Notification management ## Implementation Details - Uses tokio for async runtime with mpsc/broadcast channels - Proper error handling with BackgroundAgentError enum - Isolated agent contexts (no shared credentials) - Grace period for cancellation (5 seconds)
1 parent 8008824 commit ede4eb2

10 files changed

Lines changed: 2487 additions & 0 deletions

File tree

cortex-agents/src/background/events.rs

Lines changed: 502 additions & 0 deletions
Large diffs are not rendered by default.

cortex-agents/src/background/executor.rs

Lines changed: 896 additions & 0 deletions
Large diffs are not rendered by default.

cortex-agents/src/background/messaging.rs

Lines changed: 523 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//! Background agent execution system.
2+
//!
3+
//! This module provides infrastructure for running agents in the background
4+
//! with async communication, event broadcasting, and lifecycle management.
5+
//!
6+
//! # Architecture
7+
//!
8+
//! ```text
9+
//! BackgroundAgentManager
10+
//! ├── BackgroundAgent (tokio task)
11+
//! │ ├── status channel (mpsc)
12+
//! │ ├── cancel channel (oneshot)
13+
//! │ └── mailbox (AgentMailbox)
14+
//! ├── Event broadcaster (broadcast)
15+
//! └── Agent registry (HashMap)
16+
//! ```
17+
//!
18+
//! # Example
19+
//!
20+
//! ```rust,ignore
21+
//! use cortex_agents::background::{
22+
//! BackgroundAgentManager, AgentConfig, AgentEvent
23+
//! };
24+
//!
25+
//! // Create manager
26+
//! let mut manager = BackgroundAgentManager::new(5);
27+
//!
28+
//! // Subscribe to events
29+
//! let mut events = manager.subscribe();
30+
//!
31+
//! // Spawn a background agent
32+
//! let id = manager.spawn(AgentConfig::new("Search for patterns")).await?;
33+
//!
34+
//! // Monitor events
35+
//! while let Ok(event) = events.recv().await {
36+
//! match event {
37+
//! AgentEvent::Progress { id, message } => println!("{}: {}", id, message),
38+
//! AgentEvent::Completed { id, result } => {
39+
//! println!("Agent {} completed: {:?}", id, result);
40+
//! break;
41+
//! }
42+
//! _ => {}
43+
//! }
44+
//! }
45+
//! ```
46+
//!
47+
//! # Safety & Limits
48+
//!
49+
//! - Maximum concurrent agents: configurable (default 5)
50+
//! - Automatic timeout: 30 minutes per agent
51+
//! - RAII cleanup: agents are cancelled when manager is dropped
52+
//! - Isolated contexts: agents don't share credentials
53+
54+
pub mod events;
55+
pub mod executor;
56+
pub mod messaging;
57+
58+
pub use events::{AgentEvent, Notification, NotificationLevel, NotificationManager};
59+
pub use executor::{
60+
AgentConfig, AgentResult, AgentStatus, BackgroundAgent, BackgroundAgentError,
61+
BackgroundAgentManager,
62+
};
63+
pub use messaging::{AgentMailbox, AgentMessage, MessageContent, MessageRouter};

cortex-agents/src/lib.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,37 @@
112112
//! let decision = decide_routing(&tasks);
113113
//! assert_eq!(decision.mode, DispatchMode::Parallel);
114114
//! ```
115+
//!
116+
//! # Background Agents
117+
//!
118+
//! The background module provides infrastructure for running agents as background
119+
//! tokio tasks with async messaging:
120+
//!
121+
//! ```rust,ignore
122+
//! use cortex_agents::background::{BackgroundAgentManager, AgentConfig, AgentEvent};
123+
//!
124+
//! // Create manager
125+
//! let mut manager = BackgroundAgentManager::new(5);
126+
//!
127+
//! // Subscribe to events
128+
//! let mut events = manager.subscribe();
129+
//!
130+
//! // Spawn a background agent
131+
//! let id = manager.spawn(AgentConfig::new("Search for patterns")).await?;
132+
//!
133+
//! // Monitor events
134+
//! while let Ok(event) = events.recv().await {
135+
//! match event {
136+
//! AgentEvent::Completed { id, summary, .. } => {
137+
//! println!("Agent {} completed: {}", id, summary);
138+
//! break;
139+
//! }
140+
//! _ => {}
141+
//! }
142+
//! }
143+
//! ```
115144
145+
pub mod background;
116146
pub mod collab;
117147
pub mod control;
118148
pub mod custom;
@@ -176,6 +206,13 @@ pub use routing::{
176206
can_parallelize, decide_routing, estimate_duration, DispatchMode, RoutingDecision, TaskInfo,
177207
};
178208

209+
// Re-export background agent types
210+
pub use background::{
211+
AgentConfig, AgentEvent, AgentMailbox, AgentMessage, AgentResult, AgentStatus, BackgroundAgent,
212+
BackgroundAgentError, BackgroundAgentManager, MessageContent, MessageRouter, Notification,
213+
NotificationLevel, NotificationManager,
214+
};
215+
179216
use thiserror::Error;
180217

181218
#[derive(Error, Debug)]

cortex-tui/src/commands/executor.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ impl CommandExecutor {
8383
"init" => self.cmd_init(cmd),
8484
"commands" | "cmds" => CommandResult::Async("commands:list".to_string()),
8585
"agents" | "subagents" => CommandResult::OpenModal(ModalType::Agents),
86+
"tasks" | "bg" | "background" => CommandResult::OpenModal(ModalType::Tasks),
8687
"copy" | "cp" => CommandResult::Message(
8788
"To copy text from Cortex:\n\n\
8889
- Hold SHIFT while selecting text with mouse\n\

cortex-tui/src/commands/registry.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,15 @@ pub fn register_builtin_commands(registry: &mut CommandRegistry) {
279279
false,
280280
));
281281

282+
registry.register(CommandDef::new(
283+
"tasks",
284+
&["bg", "background"],
285+
"View and manage background tasks",
286+
"/tasks",
287+
CommandCategory::General,
288+
false,
289+
));
290+
282291
registry.register(CommandDef::new(
283292
"share",
284293
&[],

cortex-tui/src/commands/types.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ pub enum ModalType {
156156
Upgrade,
157157
/// Agents manager modal for listing and creating agents
158158
Agents,
159+
/// Background tasks view modal
160+
Tasks,
159161
}
160162

161163
impl ModalType {
@@ -181,6 +183,7 @@ impl ModalType {
181183
ModalType::Login => "Login",
182184
ModalType::Upgrade => "Upgrade",
183185
ModalType::Agents => "Agents",
186+
ModalType::Tasks => "Background Tasks",
184187
}
185188
}
186189
}

cortex-tui/src/views/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77
//! - [`MinimalSessionView`](minimal_session::MinimalSessionView) - Minimalist terminal-style chat
88
//! - [`ApprovalView`](approval::ApprovalView) - Tool approval modal
99
//! - [`QuestionPromptView`](question_prompt::QuestionPromptView) - Interactive question prompt
10+
//! - [`TasksView`](tasks::TasksView) - Background tasks monitoring view
1011
//! - [`tool_call`] - Tool call display types
1112
1213
pub mod approval;
1314
pub mod minimal_session;
1415
pub mod question_prompt;
16+
pub mod tasks;
1517
pub mod tool_call;
1618

1719
// Re-exports
1820
pub use approval::ApprovalView;
1921
pub use minimal_session::MinimalSessionView;
2022
pub use question_prompt::{QuestionClickZones, QuestionHit, QuestionPromptView};
23+
pub use tasks::{TaskDisplay, TaskStatus, TasksView};

0 commit comments

Comments
 (0)