Skip to main content

car_multi/patterns/
supervisor.rs

1//! Supervisor — one agent monitors and controls workers.
2//!
3//! Each round: workers execute in parallel → supervisor reviews → feedback or approve.
4//! Workers get the supervisor's feedback in the next round.
5//! Stops when supervisor says "APPROVED" or max rounds reached.
6
7use crate::error::MultiError;
8use crate::mailbox::Mailbox;
9use crate::patterns::swarm::{Swarm, SwarmMode};
10use crate::runner::AgentRunner;
11use crate::shared::SharedInfra;
12use crate::types::{AgentOutput, AgentSpec};
13use serde::{Deserialize, Serialize};
14use std::sync::Arc;
15use tracing::instrument;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct SupervisorResult {
19    pub task: String,
20    pub rounds: Vec<Vec<AgentOutput>>,
21    pub supervisor_feedback: Vec<String>,
22    pub final_answer: String,
23    pub approved: bool,
24}
25
26impl SupervisorResult {
27    pub fn total_rounds(&self) -> usize {
28        self.rounds.len()
29    }
30}
31
32pub struct Supervisor {
33    pub workers: Vec<AgentSpec>,
34    pub supervisor: AgentSpec,
35    pub max_rounds: u32,
36}
37
38impl Supervisor {
39    pub fn new(workers: Vec<AgentSpec>, supervisor: AgentSpec) -> Self {
40        Self {
41            workers,
42            supervisor,
43            max_rounds: 3,
44        }
45    }
46
47    pub fn with_max_rounds(mut self, max_rounds: u32) -> Self {
48        self.max_rounds = max_rounds;
49        self
50    }
51
52    #[instrument(name = "multi.supervisor", skip_all)]
53    pub async fn run(
54        &self,
55        task: &str,
56        runner: &Arc<dyn AgentRunner>,
57        infra: &SharedInfra,
58    ) -> Result<SupervisorResult, MultiError> {
59        let mut result = SupervisorResult {
60            task: task.to_string(),
61            rounds: Vec::new(),
62            supervisor_feedback: Vec::new(),
63            final_answer: String::new(),
64            approved: false,
65        };
66
67        let mut current_task = task.to_string();
68
69        for round_num in 0..self.max_rounds {
70            // Workers execute in parallel
71            let swarm = Swarm::new(self.workers.clone(), SwarmMode::Parallel);
72            let swarm_result = swarm.run(&current_task, runner, infra).await?;
73            result.rounds.push(swarm_result.outputs.clone());
74
75            // Supervisor reviews
76            let worker_summaries: Vec<String> = swarm_result
77                .outputs
78                .iter()
79                .filter(|o| o.succeeded())
80                .map(|o| format!("- {}: {}", o.name, truncate(&o.answer, 300)))
81                .collect();
82
83            let review_task = format!(
84                "Original task: {}\n\nRound {} results:\n{}\n\n\
85                 Review these results. If they are satisfactory, respond with \
86                 APPROVED followed by a final summary. Otherwise, provide specific \
87                 feedback for improvement.",
88                task,
89                round_num + 1,
90                worker_summaries.join("\n")
91            );
92
93            let mailbox = Mailbox::default();
94            let rt = infra.make_runtime();
95            let feedback_output = runner
96                .run(&self.supervisor, &review_task, &rt, &mailbox)
97                .await?;
98            let feedback = feedback_output.answer;
99            result.supervisor_feedback.push(feedback.clone());
100
101            if feedback.to_uppercase().contains("APPROVED") {
102                // Extract answer after APPROVED marker
103                let answer = strip_approved_prefix(&feedback);
104                result.final_answer = answer;
105                result.approved = true;
106                return Ok(result);
107            }
108
109            // Feed supervisor's feedback back to workers
110            current_task = format!(
111                "{}\n\nSupervisor feedback from round {}:\n{}",
112                task,
113                round_num + 1,
114                feedback
115            );
116        }
117
118        // Max rounds reached
119        result.final_answer = format!(
120            "[max supervision rounds reached] {}",
121            result.supervisor_feedback.last().unwrap_or(&String::new())
122        );
123        Ok(result)
124    }
125}
126
127fn strip_approved_prefix(s: &str) -> String {
128    let upper = s.to_uppercase();
129    for prefix in &["APPROVED:", "APPROVED.", "APPROVED\n", "APPROVED "] {
130        if upper.starts_with(prefix) {
131            return s[prefix.len()..].trim().to_string();
132        }
133    }
134    s.to_string()
135}
136
137fn truncate(s: &str, max_len: usize) -> &str {
138    if s.len() <= max_len {
139        return s;
140    }
141    let mut end = max_len;
142    while end > 0 && !s.is_char_boundary(end) {
143        end -= 1;
144    }
145    &s[..end]
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use crate::types::{AgentOutput, AgentSpec};
152    use car_engine::Runtime;
153    use std::sync::atomic::{AtomicU32, Ordering};
154
155    struct ApprovingRunner {
156        call_count: AtomicU32,
157    }
158
159    #[async_trait::async_trait]
160    impl AgentRunner for ApprovingRunner {
161        async fn run(
162            &self,
163            spec: &AgentSpec,
164            _task: &str,
165            _runtime: &Runtime,
166            _mailbox: &Mailbox,
167        ) -> Result<AgentOutput, MultiError> {
168            let _n = self.call_count.fetch_add(1, Ordering::SeqCst);
169            // Supervisor (runs after workers) approves on first review
170            let answer = if spec.name == "supervisor" {
171                "APPROVED: Everything looks good.".to_string()
172            } else {
173                format!("work from {}", spec.name)
174            };
175            Ok(AgentOutput {
176                name: spec.name.clone(),
177                answer,
178                turns: 1,
179                tool_calls: 0,
180                duration_ms: 5.0,
181                error: None,
182                outcome: None,
183                tokens: None,
184            })
185        }
186    }
187
188    #[tokio::test]
189    async fn test_supervisor_approves_round_1() {
190        let workers = vec![
191            AgentSpec::new("coder", "Write code"),
192            AgentSpec::new("tester", "Write tests"),
193        ];
194        let supervisor_spec = AgentSpec::new("supervisor", "Review and coordinate");
195
196        let runner: Arc<dyn AgentRunner> = Arc::new(ApprovingRunner {
197            call_count: AtomicU32::new(0),
198        });
199        let infra = SharedInfra::new();
200
201        let result = Supervisor::new(workers, supervisor_spec)
202            .run("build fibonacci", &runner, &infra)
203            .await
204            .unwrap();
205
206        assert!(result.approved);
207        assert_eq!(result.total_rounds(), 1);
208        assert_eq!(result.final_answer, "Everything looks good.");
209    }
210}