Skip to main content

rig_multiagent/
swarm.rs

1//! Agents that pass the work to each other.
2
3use std::collections::HashSet;
4use std::fmt::Write as _;
5use std::sync::{Arc, Mutex, PoisonError};
6use std::time::{Duration, Instant};
7
8use rig_agent::Agent;
9use rig_agent::agent::{AgentHook, HookContext, OutcomeAction, OutcomeEvent};
10use rig_agent::completion::PromptError;
11use rig_core::completion::Usage;
12use rig_core::tool::{Tool, ToolContext, ToolExecutionError};
13use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
14use serde::{Deserialize, Serialize};
15use serde_json::{Value, json};
16use tokio::sync::mpsc;
17use tracing::Instrument;
18
19use crate::BuildError;
20use crate::checkpoint::{CheckpointError, Checkpoints, Journal, Saving};
21use crate::events::{Emit, events, stream_agent};
22use crate::human::{Clock, Question, answer};
23use crate::node::{Meter, Node, NodeError, NodeIo, NodeOutput, in_conversation};
24
25/// The name of the tool a swarm gives each of its agents.
26pub const HANDOFF_TOOL: &str = "handoff_to_agent";
27
28/// The name of the tool a swarm that [allows questions](SwarmBuilder::allow_questions)
29/// gives its agents.
30pub const ASK_TOOL: &str = "ask_human";
31
32/// A team of agents that pass the work to each other.
33///
34/// The run starts with the [entry](SwarmBuilder::entry) agent. Each agent
35/// sees the task, who worked on it before, what they shared, and the other
36/// agents it can hand off to; it either answers, which ends the run with
37/// that answer, or calls [`handoff_to_agent`](HANDOFF_TOOL), which ends its
38/// turn and starts the agent it named. Every agent run starts fresh: what
39/// one agent tells the next travels in the handoff message and context.
40///
41/// Cloning is cheap; clones share the agents.
42#[derive(Clone)]
43pub struct Swarm {
44    inner: Arc<Inner>,
45}
46
47struct Inner {
48    members: Vec<Arc<Member>>,
49    /// The member the run starts with, one of `members`.
50    entry: Arc<Member>,
51    max_handoffs: usize,
52    execution_timeout: Duration,
53    agent_timeout: Duration,
54    repetition: Option<Repetition>,
55    questions: bool,
56    checkpoints: Option<Checkpoints>,
57}
58
59struct Member {
60    name: String,
61    description: Option<String>,
62    agent: Agent,
63}
64
65#[derive(Clone, Copy)]
66struct Repetition {
67    window: usize,
68    min_unique: usize,
69}
70
71/// Builds a [`Swarm`].
72#[must_use]
73pub struct SwarmBuilder {
74    agents: Vec<Agent>,
75    entry: Option<String>,
76    max_handoffs: usize,
77    execution_timeout: Duration,
78    agent_timeout: Duration,
79    repetition: Option<Repetition>,
80    questions: bool,
81    checkpoints: Option<Checkpoints>,
82}
83
84impl Swarm {
85    /// Start building a swarm.
86    pub fn builder() -> SwarmBuilder {
87        SwarmBuilder {
88            agents: Vec::new(),
89            entry: None,
90            max_handoffs: 20,
91            execution_timeout: Duration::from_secs(15 * 60),
92            agent_timeout: Duration::from_secs(5 * 60),
93            repetition: None,
94            questions: false,
95            checkpoints: None,
96        }
97    }
98}
99
100impl SwarmBuilder {
101    /// Add an agent. It needs a [name](rig_agent::AgentBuilder::name), which
102    /// the others hand off to; its description tells them what it is for.
103    ///
104    /// The swarm adds the [`handoff_to_agent`](HANDOFF_TOOL) tool to the
105    /// agent's tool set, which clones of the agent share.
106    pub fn agent(mut self, agent: Agent) -> Self {
107        self.agents.push(agent);
108        self
109    }
110
111    /// The agent the run starts with. Defaults to the first one added.
112    pub fn entry(mut self, name: impl Into<String>) -> Self {
113        self.entry = Some(name.into());
114        self
115    }
116
117    /// How many handoffs a run may make before it fails. Defaults to 20.
118    pub fn max_handoffs(mut self, max_handoffs: usize) -> Self {
119        self.max_handoffs = max_handoffs;
120        self
121    }
122
123    /// How long a whole run may take. Defaults to 15 minutes.
124    pub fn execution_timeout(mut self, timeout: Duration) -> Self {
125        self.execution_timeout = timeout;
126        self
127    }
128
129    /// How long one agent's turn may take. Defaults to 5 minutes.
130    pub fn agent_timeout(mut self, timeout: Duration) -> Self {
131        self.agent_timeout = timeout;
132        self
133    }
134
135    /// Fail a run whose last `window` turns went to fewer than `min_unique`
136    /// distinct agents: two agents passing the work back and forth. Off by
137    /// default.
138    pub fn detect_repetition(mut self, window: usize, min_unique: usize) -> Self {
139        self.repetition = Some(Repetition { window, min_unique });
140        self
141    }
142
143    /// Give the agents an [`ask_human`](ASK_TOOL) tool, to ask the person
144    /// behind a [streamed](Swarm::stream) run for a decision or a fact. The
145    /// agent waits for the answer within its turn, and the run's timeouts
146    /// stop meanwhile. In a plain run nobody can answer, and the tool says
147    /// so to the agent.
148    pub fn allow_questions(mut self) -> Self {
149        self.questions = true;
150        self
151    }
152
153    /// Keep the progress of runs started with [`run_as`](Swarm::run_as) or
154    /// [`stream_as`](Swarm::stream_as) in `store` (any rig-memory store: a
155    /// `DirStore`, a database), so a run that stopped resumes where it was.
156    pub fn checkpoints(
157        mut self,
158        store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
159    ) -> Self {
160        self.checkpoints = Some(Checkpoints::new(store, "swarm"));
161        self
162    }
163
164    /// Check the agents and give each one the handoff tool.
165    pub fn build(self) -> Result<Swarm, BuildError> {
166        if self.agents.is_empty() {
167            return Err(BuildError::Empty);
168        }
169        let mut members: Vec<Member> = Vec::with_capacity(self.agents.len());
170        for agent in self.agents {
171            let name = agent.name().ok_or(BuildError::UnnamedAgent)?.to_owned();
172            if members.iter().any(|member| member.name == name) {
173                return Err(BuildError::DuplicateName(name));
174            }
175            members.push(Member {
176                description: agent.description().map(str::to_owned),
177                name,
178                agent,
179            });
180        }
181        let members: Vec<Arc<Member>> = members.into_iter().map(Arc::new).collect();
182        let entry = match &self.entry {
183            None => members.first().ok_or(BuildError::Empty)?,
184            Some(name) => members
185                .iter()
186                .find(|member| &member.name == name)
187                .ok_or_else(|| BuildError::UnknownName(name.clone()))?,
188        }
189        .clone();
190        for member in &members {
191            if members.len() > 1 {
192                member.agent.tool_server_handle().add_tool(HandoffTool);
193            }
194            if self.questions {
195                member.agent.tool_server_handle().add_tool(AskTool);
196            }
197        }
198        Ok(Swarm {
199            inner: Arc::new(Inner {
200                members,
201                entry,
202                max_handoffs: self.max_handoffs,
203                execution_timeout: self.execution_timeout,
204                agent_timeout: self.agent_timeout,
205                repetition: self.repetition,
206                questions: self.questions,
207                checkpoints: self.checkpoints,
208            }),
209        })
210    }
211}
212
213/// One agent passing the work to another.
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215pub struct Handoff {
216    /// The agent that handed off.
217    pub from: String,
218    /// The agent it handed off to.
219    pub to: String,
220    /// What it asked the next agent to do.
221    pub message: String,
222    /// What it shared with the agents after it.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub context: Option<Value>,
225}
226
227/// A swarm run that ended with an answer.
228#[derive(Debug, Clone)]
229#[non_exhaustive]
230pub struct SwarmRun {
231    /// The final answer.
232    pub answer: String,
233    /// The agent that gave it.
234    pub agent: String,
235    /// Every agent turn, in order, the last one included.
236    pub agents: Vec<String>,
237    /// Every handoff, in order.
238    pub handoffs: Vec<Handoff>,
239    /// The model tokens all the agents spent.
240    pub usage: Usage,
241    /// How long the run took.
242    pub elapsed: Duration,
243}
244
245/// A swarm run that ended without an answer, with what happened before.
246#[derive(Debug, thiserror::Error)]
247#[error("{reason}")]
248#[non_exhaustive]
249pub struct SwarmError {
250    /// Why the run stopped.
251    pub reason: SwarmFailure,
252    /// Every agent turn, in order, the failed one included.
253    pub agents: Vec<String>,
254    /// Every handoff, in order.
255    pub handoffs: Vec<Handoff>,
256    /// The model tokens all the agents spent.
257    pub usage: Usage,
258}
259
260/// Why a swarm run stopped without an answer.
261#[derive(Debug, thiserror::Error)]
262#[non_exhaustive]
263pub enum SwarmFailure {
264    /// An agent's run failed.
265    #[error("agent {agent:?} failed: {source}")]
266    Agent {
267        /// The agent.
268        agent: String,
269        /// Its run's error.
270        #[source]
271        source: Box<PromptError>,
272    },
273    /// An agent's turn, or the whole run, ran out of time.
274    #[error("agent {agent:?} did not finish in time")]
275    Timeout {
276        /// The agent whose turn was cut short.
277        agent: String,
278    },
279    /// The agents handed off more times than [`SwarmBuilder::max_handoffs`].
280    #[error("the swarm reached its limit of {limit} handoffs")]
281    MaxHandoffs {
282        /// The limit.
283        limit: usize,
284    },
285    /// The checkpoint could not be read or written.
286    #[error("checkpoint: {error}")]
287    Checkpoint {
288        /// What went wrong.
289        #[source]
290        error: CheckpointError,
291    },
292    /// The work kept bouncing among a few agents; see
293    /// [`SwarmBuilder::detect_repetition`].
294    #[error("the last {window} turns went to only {unique} agents")]
295    Repetitive {
296        /// How many recent turns were checked.
297        window: usize,
298        /// How many distinct agents they went to.
299        unique: usize,
300    },
301}
302
303/// What a [streamed](Swarm::stream) swarm run reports, as it happens.
304#[derive(Debug)]
305#[non_exhaustive]
306pub enum SwarmEvent {
307    /// An agent's turn started.
308    AgentStarted {
309        /// The agent.
310        agent: String,
311    },
312    /// Text an agent's model wrote. A turn that ends in a handoff may write
313    /// some before calling the tool; the final answer is the last turn's.
314    Text {
315        /// The agent.
316        agent: String,
317        /// The new text.
318        text: String,
319    },
320    /// The run resumed from its checkpoint: the first event of a resumed
321    /// [`stream_as`](Swarm::stream_as) run.
322    Resumed {
323        /// The agent whose turn starts the resumed run.
324        agent: String,
325        /// The handoffs made before the run stopped.
326        handoffs: usize,
327    },
328    /// An agent passed the work on.
329    Handoff(Handoff),
330    /// An agent asks a person; it waits for the [answer](Question::answer),
331    /// and the run's timeouts stop meanwhile. See [`SwarmBuilder::allow_questions`].
332    Question(Question),
333    /// The run ended: the last event. Boxed, so the many text events stay small.
334    Finished(Box<Result<SwarmRun, SwarmError>>),
335}
336
337/// What a run has done so far.
338#[derive(Default, Clone, Serialize, Deserialize)]
339struct Trail {
340    agents: Vec<String>,
341    handoffs: Vec<Handoff>,
342    shared: Vec<(String, Value)>,
343    usage: Usage,
344}
345
346/// A run's checkpoint: what it did, and whose turn is next.
347#[derive(Serialize, Deserialize)]
348struct Saved {
349    task: String,
350    finished: bool,
351    /// The answer, once finished.
352    #[serde(default)]
353    answer: Option<String>,
354    /// The agent whose turn comes next.
355    current: String,
356    message: Option<String>,
357    trail: Trail,
358    active_ms: u64,
359    elapsed_ms: u64,
360}
361
362fn millis(duration: Duration) -> u64 {
363    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
364}
365
366impl Trail {
367    fn fail(self, reason: SwarmFailure) -> SwarmError {
368        SwarmError {
369            reason,
370            agents: self.agents,
371            handoffs: self.handoffs,
372            usage: self.usage,
373        }
374    }
375}
376
377/// The span a swarm run is in. Its totals are recorded when the run ends:
378/// tokens under `swarm.usage.*` (not `gen_ai.usage.*`, which the model calls
379/// under it carry, so backends do not count them twice).
380fn run_span(entry: &str, run_id: Option<&str>) -> tracing::Span {
381    tracing::info_span!(
382        "swarm.run",
383        swarm.entry = %entry,
384        swarm.run_id = run_id,
385        swarm.agent = tracing::field::Empty,
386        swarm.handoffs = tracing::field::Empty,
387        swarm.usage.input_tokens = tracing::field::Empty,
388        swarm.usage.output_tokens = tracing::field::Empty,
389        otel.status_code = tracing::field::Empty,
390        error.type = tracing::field::Empty,
391    )
392}
393
394/// Record how a run ended on its span.
395fn record_outcome(span: &tracing::Span, outcome: &Result<SwarmRun, SwarmError>) {
396    let (handoffs, usage) = match outcome {
397        Ok(run) => (run.handoffs.len(), run.usage),
398        Err(error) => (error.handoffs.len(), error.usage),
399    };
400    span.record("swarm.handoffs", handoffs);
401    if let Some(tokens) = usage.input_tokens {
402        span.record("swarm.usage.input_tokens", tokens);
403    }
404    if let Some(tokens) = usage.output_tokens {
405        span.record("swarm.usage.output_tokens", tokens);
406    }
407    match outcome {
408        Ok(run) => {
409            span.record("swarm.agent", run.agent.as_str());
410        }
411        Err(error) => {
412            span.record("otel.status_code", "ERROR");
413            span.record("error.type", error.reason.kind());
414        }
415    }
416}
417
418impl SwarmFailure {
419    /// A short, stable name for the failure, for `error.type`.
420    fn kind(&self) -> &'static str {
421        match self {
422            Self::Agent { .. } => "agent_failed",
423            Self::Timeout { .. } => "timeout",
424            Self::MaxHandoffs { .. } => "max_handoffs",
425            Self::Repetitive { .. } => "repetitive_handoffs",
426            Self::Checkpoint { .. } => "checkpoint",
427        }
428    }
429}
430
431impl Swarm {
432    /// Run the swarm on `task` until an agent answers.
433    pub async fn run(&self, task: impl Into<String>) -> Result<SwarmRun, SwarmError> {
434        let span = run_span(&self.inner.entry.name, None);
435        let outcome = self
436            .run_task(task.into(), None, false, None)
437            .instrument(span.clone())
438            .await;
439        record_outcome(&span, &outcome);
440        outcome
441    }
442
443    /// Run the swarm as run `run_id`: resume it from its last checkpoint if
444    /// it has one and did not finish, or else start it on `task`. Progress
445    /// is saved before every turn, so a run that stopped (the process
446    /// restarted, an agent failed) carries on with the turn it was on. Each
447    /// turn keeps a journal of its tool results (answers to `ask_human`
448    /// included), so a turn run again replays them rather than running the
449    /// tools twice.
450    ///
451    /// Needs [`checkpoints`](SwarmBuilder::checkpoints); without them it is
452    /// [`run`](Self::run). A `run_id` is 1-128 of `[A-Za-z0-9_-]`.
453    pub async fn run_as(
454        &self,
455        run_id: &str,
456        task: impl Into<String>,
457    ) -> Result<SwarmRun, SwarmError> {
458        let span = run_span(&self.inner.entry.name, Some(run_id));
459        let outcome = self
460            .run_task(task.into(), self.saving(Some(run_id)), false, None)
461            .instrument(span.clone())
462            .await;
463        record_outcome(&span, &outcome);
464        outcome
465    }
466
467    /// Run the swarm on `task`, reporting each turn, the text its model
468    /// writes and each handoff as they happen, and the outcome last.
469    ///
470    /// The run makes progress only while the stream is polled, and stops
471    /// when the stream is dropped.
472    ///
473    /// ```no_run
474    /// # async fn show(swarm: rig_multiagent::Swarm) {
475    /// use futures::StreamExt;
476    /// use rig_multiagent::SwarmEvent;
477    ///
478    /// let mut events = swarm.stream("Fix the flaky test");
479    /// while let Some(event) = events.next().await {
480    ///     match event {
481    ///         SwarmEvent::AgentStarted { agent } => println!("\n[{agent}]"),
482    ///         SwarmEvent::Text { text, .. } => print!("{text}"),
483    ///         SwarmEvent::Handoff(handoff) => println!("\n-> {}", handoff.to),
484    ///         SwarmEvent::Finished(outcome) => println!("\n{outcome:?}"),
485    ///         _ => {}
486    ///     }
487    /// }
488    /// # }
489    /// ```
490    pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, SwarmEvent> {
491        self.stream_events(task.into(), None)
492    }
493
494    /// [`stream`](Self::stream) as run `run_id`, resuming it as
495    /// [`run_as`](Self::run_as) does. A resumed run starts with
496    /// [`SwarmEvent::Resumed`].
497    pub fn stream_as<'a>(
498        &'a self,
499        run_id: &'a str,
500        task: impl Into<String>,
501    ) -> WasmBoxedStream<'a, SwarmEvent> {
502        self.stream_events(task.into(), Some(run_id))
503    }
504
505    fn stream_events<'a>(
506        &'a self,
507        task: String,
508        run_id: Option<&'a str>,
509    ) -> WasmBoxedStream<'a, SwarmEvent> {
510        let span = run_span(&self.inner.entry.name, run_id);
511        events(
512            move |sender| async move {
513                let emit = move |event| {
514                    let _ = sender.send(event);
515                };
516                let outcome = self
517                    .run_task(task, self.saving(run_id), false, Some(&emit))
518                    .instrument(span.clone())
519                    .await;
520                record_outcome(&span, &outcome);
521                outcome
522            },
523            |outcome| SwarmEvent::Finished(Box::new(outcome)),
524        )
525    }
526
527    /// Where run `run_id` keeps its progress, if the swarm has a store.
528    fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
529        run_id
530            .zip(self.inner.checkpoints.clone())
531            .map(|(id, checkpoints)| Saving::new(checkpoints, id))
532    }
533
534    /// Run `task`, saving to `saving`. A `nested` run (a graph node) that
535    /// finished before answers as it did, rather than starting over: its
536    /// graph lost track of it.
537    async fn run_task(
538        &self,
539        task: String,
540        saving: Option<Saving>,
541        nested: bool,
542        emit: Option<Emit<'_, SwarmEvent>>,
543    ) -> Result<SwarmRun, SwarmError> {
544        let inner = &*self.inner;
545        let started = Instant::now();
546        let checkpoints = saving
547            .as_ref()
548            .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
549        let saved = match checkpoints {
550            Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
551                Ok(Some(Saved {
552                    finished: true,
553                    answer: Some(answer),
554                    current,
555                    trail,
556                    elapsed_ms,
557                    ..
558                })) if nested => {
559                    return Ok(SwarmRun {
560                        answer,
561                        agent: current,
562                        agents: trail.agents,
563                        handoffs: trail.handoffs,
564                        usage: trail.usage,
565                        elapsed: Duration::from_millis(elapsed_ms),
566                    });
567                }
568                Ok(saved) => saved.filter(|saved| !saved.finished),
569                Err(error) => {
570                    return Err(Trail::default().fail(SwarmFailure::Checkpoint { error }));
571                }
572            },
573            None => None,
574        };
575        let (task, mut trail, mut current, mut message, clock, before) = match saved {
576            None => (
577                task,
578                Trail::default(),
579                Arc::clone(&inner.entry),
580                None,
581                Clock::resumed(Duration::ZERO),
582                Duration::ZERO,
583            ),
584            Some(saved) => {
585                let Some(current) = inner
586                    .members
587                    .iter()
588                    .find(|member| member.name == saved.current)
589                    .cloned()
590                else {
591                    let error = CheckpointError::UnknownAgent(saved.current);
592                    return Err(saved.trail.fail(SwarmFailure::Checkpoint { error }));
593                };
594                tracing::info!(agent = %saved.current, handoffs = saved.trail.handoffs.len(), "swarm run resumed");
595                if let Some(emit) = emit {
596                    emit(SwarmEvent::Resumed {
597                        agent: saved.current.clone(),
598                        handoffs: saved.trail.handoffs.len(),
599                    });
600                }
601                let clock = Clock::resumed(Duration::from_millis(saved.active_ms));
602                (
603                    saved.task,
604                    saved.trail,
605                    current,
606                    saved.message,
607                    clock,
608                    Duration::from_millis(saved.elapsed_ms),
609                )
610            }
611        };
612        let snapshot = |trail: &Trail,
613                        current: &str,
614                        message: &Option<String>,
615                        answer: Option<String>| Saved {
616            task: task.clone(),
617            finished: answer.is_some(),
618            answer,
619            current: current.to_owned(),
620            message: message.clone(),
621            trail: trail.clone(),
622            active_ms: millis(clock.active()),
623            elapsed_ms: millis(before + started.elapsed()),
624        };
625        loop {
626            let member = Arc::clone(&current);
627            if let Some((id, checkpoints)) = checkpoints {
628                let saved = snapshot(&trail, &member.name, &message, None);
629                if let Err(error) = checkpoints.save(id, &saved).await {
630                    return Err(trail.fail(SwarmFailure::Checkpoint { error }));
631                }
632            }
633            trail.agents.push(member.name.clone());
634            if let Some(Repetition { window, min_unique }) = inner.repetition
635                && window > 0
636                && trail.agents.len() >= window
637            {
638                let recent = trail.agents.iter().rev().take(window);
639                let unique = recent.collect::<HashSet<_>>().len();
640                if unique < min_unique {
641                    return Err(trail.fail(SwarmFailure::Repetitive { window, unique }));
642                }
643            }
644            let budget = inner
645                .agent_timeout
646                .min(inner.execution_timeout.saturating_sub(clock.active()));
647            let input = self.input(&member, &task, message.as_deref(), &trail);
648            let turn = Arc::new(Turn {
649                agent: member.name.clone(),
650                others: inner
651                    .members
652                    .iter()
653                    .filter(|other| other.name != member.name)
654                    .cloned()
655                    .collect(),
656                handoff: Mutex::new(None),
657                questions: Mutex::new(None),
658            });
659            let meter = Meter::default();
660            // Each turn is a conversation of its own: one cache key for it,
661            // the same when a resumed run repeats the turn.
662            let part = saving
663                .as_ref()
664                .map(|saving| saving.part("journal", "turn", trail.agents.len()));
665            let key = part.as_ref().map(|part| part.run_id.clone());
666            let mut runner = in_conversation(member.agent.prompt(input), &member.agent, key)
667                .tool_context(ToolContext::new().with_scope(turn.clone()))
668                .add_hook(meter.clone());
669            if let Some(journal) = part {
670                // A resumed turn replays the tools it ran before, answers to
671                // ask_human included, rather than running them again.
672                match Journal::open(journal).await {
673                    Ok(journal) => runner = runner.add_hook(journal),
674                    Err(error) => return Err(trail.fail(SwarmFailure::Checkpoint { error })),
675                }
676            }
677            let runner = runner.add_hook(StopOnHandoff(turn.clone()));
678            let run = async {
679                let Some(emit) = emit else {
680                    return runner.run().await;
681                };
682                emit(SwarmEvent::AgentStarted {
683                    agent: member.name.clone(),
684                });
685                let on_text = |text: &str| {
686                    emit(SwarmEvent::Text {
687                        agent: member.name.clone(),
688                        text: text.to_owned(),
689                    })
690                };
691                // Questions the agent's tool asks reach the run's reader
692                // while the agent waits.
693                let (asks, mut asked) = mpsc::unbounded_channel();
694                if inner.questions {
695                    *turn.asks() = Some(asks);
696                }
697                let mut agent = std::pin::pin!(stream_agent(runner, &on_text));
698                loop {
699                    tokio::select! {
700                        outcome = &mut agent => break outcome,
701                        Some(question) = asked.recv() => {
702                            // The question's text stays out of telemetry, as Rig
703                            // keeps prompts out unless content recording is on.
704                            tracing::info!(swarm.agent = %question.from(), "human.question");
705                            emit(SwarmEvent::Question(question.pausing(&clock)));
706                        }
707                    }
708                }
709            }
710            .instrument(tracing::info_span!("swarm.agent", swarm.agent = %member.name));
711            let outcome = clock.within(budget, run).await;
712            trail.usage += meter.total();
713            let handoff = turn.take();
714            match (outcome, handoff) {
715                (None, _) => {
716                    let agent = member.name.clone();
717                    return Err(trail.fail(SwarmFailure::Timeout { agent }));
718                }
719                (Some(_), Some((handoff, next))) => {
720                    if trail.handoffs.len() >= inner.max_handoffs {
721                        let limit = inner.max_handoffs;
722                        return Err(trail.fail(SwarmFailure::MaxHandoffs { limit }));
723                    }
724                    // A span event of the run: where the work went, and why.
725                    tracing::info!(
726                        swarm.from = %handoff.from,
727                        swarm.to = %handoff.to,
728                        swarm.message = %handoff.message,
729                        "swarm.handoff"
730                    );
731                    current = next;
732                    if let Some(context) = &handoff.context {
733                        trail.shared.push((handoff.from.clone(), context.clone()));
734                    }
735                    message = Some(handoff.message.clone());
736                    if let Some(emit) = emit {
737                        emit(SwarmEvent::Handoff(handoff.clone()));
738                    }
739                    trail.handoffs.push(handoff);
740                }
741                (Some(Ok(response)), None) => {
742                    if let Some((id, checkpoints)) = checkpoints {
743                        // The answer stands even if the mark is lost; the
744                        // next run_as then repeats the last turn.
745                        let saved =
746                            snapshot(&trail, &member.name, &message, Some(response.output()));
747                        if let Err(error) = checkpoints.save(id, &saved).await {
748                            tracing::warn!(%error, "could not mark the swarm run finished");
749                        }
750                    }
751                    return Ok(SwarmRun {
752                        answer: response.output(),
753                        agent: member.name.clone(),
754                        agents: trail.agents,
755                        handoffs: trail.handoffs,
756                        usage: trail.usage,
757                        elapsed: before + started.elapsed(),
758                    });
759                }
760                (Some(Err(source)), None) => {
761                    let agent = member.name.clone();
762                    let source = Box::new(source);
763                    return Err(trail.fail(SwarmFailure::Agent { agent, source }));
764                }
765            }
766        }
767    }
768
769    /// The prompt an agent's turn starts with.
770    fn input(&self, current: &Member, task: &str, message: Option<&str>, trail: &Trail) -> String {
771        let members = &self.inner.members;
772        let mut text = String::new();
773        if let (Some(message), Some(last)) = (message, trail.handoffs.last()) {
774            let _ = write!(text, "Handoff from {}: {message}\n\n", last.from);
775        }
776        let _ = write!(text, "User request: {task}\n\n");
777        let before: &[String] = trail
778            .agents
779            .split_last()
780            .map(|(_, before)| before)
781            .unwrap_or_default();
782        if !before.is_empty() {
783            let _ = write!(
784                text,
785                "Agents who worked on this so far: {}\n\n",
786                before.join(" -> ")
787            );
788        }
789        if !trail.shared.is_empty() {
790            text.push_str("Shared by previous agents:\n");
791            for (agent, context) in &trail.shared {
792                let _ = writeln!(text, "- {agent}: {context}");
793            }
794            text.push('\n');
795        }
796        let others: Vec<&Member> = members
797            .iter()
798            .filter(|member| member.name != current.name)
799            .map(|member| &**member)
800            .collect();
801        if !others.is_empty() {
802            text.push_str("Other agents you can hand off to:\n");
803            for other in others {
804                match &other.description {
805                    Some(description) => {
806                        let _ = writeln!(text, "- {}: {description}", other.name);
807                    }
808                    None => {
809                        let _ = writeln!(text, "- {}", other.name);
810                    }
811                }
812            }
813            let _ = write!(
814                text,
815                "\nTo pass the work on, call {HANDOFF_TOOL} with the agent's name and a message \
816                 saying what it should do; your turn ends there. If you answer instead, your \
817                 answer is the final one."
818            );
819        }
820        if self.inner.questions {
821            let _ = write!(
822                text,
823                "\n\nIf you need a decision or a fact only the user has, call {ASK_TOOL} \
824                 with your question and wait for the answer."
825            );
826        }
827        text.trim_end().to_owned()
828    }
829}
830
831impl Node for Swarm {
832    /// Streams every agent's text, handing-off turns included, and passes on
833    /// their questions. In a checkpointed graph run, the swarm keeps its own
834    /// progress (in its store, or else the graph's), so a resumed graph
835    /// resumes the swarm inside the node too.
836    fn run<'a>(
837        &'a self,
838        input: String,
839        io: &'a NodeIo<'a>,
840    ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
841        Box::pin(async move {
842            let saving = io.saving().map(|saving| {
843                let checkpoints = self.inner.checkpoints.clone();
844                let checkpoints =
845                    checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("swarm"));
846                Saving::new(checkpoints, saving.run_id.clone())
847            });
848            let emit = |event| match event {
849                SwarmEvent::Text { text, .. } => io.text(&text),
850                SwarmEvent::Question(question) => io.forward(question),
851                _ => {}
852            };
853            let emit: Option<Emit<'_, SwarmEvent>> = io.is_streaming().then_some(&emit);
854            let run = self.run_task(input, saving, true, emit).await?;
855            Ok(NodeOutput::new(run.answer).with_usage(run.usage))
856        })
857    }
858}
859
860/// One agent's turn, as the handoff tool and hook see it.
861struct Turn {
862    agent: String,
863    /// The members it can hand off to.
864    others: Vec<Arc<Member>>,
865    /// The handoff it made, with the member it hands off to.
866    handoff: Mutex<Option<(Handoff, Arc<Member>)>>,
867    /// Where the ask tool sends questions; `None` when nobody can answer.
868    questions: Mutex<Option<mpsc::UnboundedSender<Question>>>,
869}
870
871impl Turn {
872    fn asks(&self) -> std::sync::MutexGuard<'_, Option<mpsc::UnboundedSender<Question>>> {
873        self.questions
874            .lock()
875            .unwrap_or_else(PoisonError::into_inner)
876    }
877
878    fn slot(&self) -> std::sync::MutexGuard<'_, Option<(Handoff, Arc<Member>)>> {
879        self.handoff.lock().unwrap_or_else(PoisonError::into_inner)
880    }
881
882    fn take(&self) -> Option<(Handoff, Arc<Member>)> {
883        self.slot().take()
884    }
885}
886
887#[derive(Deserialize)]
888struct HandoffArgs {
889    agent_name: String,
890    message: String,
891    #[serde(default)]
892    context: Option<Value>,
893}
894
895#[derive(Debug, thiserror::Error)]
896enum HandoffError {
897    #[error("{HANDOFF_TOOL} works only during a swarm run")]
898    NotInSwarm,
899    #[error("you are {0}; hand off to another agent or answer yourself")]
900    ToSelf(String),
901    #[error("no agent is named {0:?}; you can hand off to: {1}")]
902    Unknown(String, String),
903    #[error("you already handed off to {0} this turn")]
904    Twice(String),
905}
906
907/// The tool a swarm adds to its agents. It records the handoff for the turn
908/// it runs in (found through the tool context), and [`StopOnHandoff`] ends
909/// the turn.
910struct HandoffTool;
911
912impl Tool for HandoffTool {
913    const NAME: &'static str = HANDOFF_TOOL;
914    type Args = HandoffArgs;
915    type Output = String;
916    type Error = HandoffError;
917
918    fn description(&self) -> String {
919        "Pass the work to another agent of the swarm, with a message saying what it should do \
920         next and why, and optionally context to share with the agents after you. Your turn \
921         ends when you call this."
922            .into()
923    }
924
925    fn parameters(&self) -> Value {
926        json!({
927            "type": "object",
928            "properties": {
929                "agent_name": {"type": "string", "description": "The agent to hand off to."},
930                "message": {"type": "string", "description": "What the next agent should do, and why."},
931                "context": {"type": "object", "description": "Facts to share with the agents after you."}
932            },
933            "required": ["agent_name", "message"]
934        })
935    }
936
937    /// The messages name the agents to pick from, so the model sees them.
938    fn map_error(&self, error: HandoffError) -> ToolExecutionError {
939        let feedback = error.to_string();
940        ToolExecutionError::from_error(error).with_model_feedback(feedback)
941    }
942
943    async fn call(
944        &self,
945        context: &mut ToolContext,
946        args: HandoffArgs,
947    ) -> Result<String, HandoffError> {
948        let turn = context.scope::<Turn>().ok_or(HandoffError::NotInSwarm)?;
949        if args.agent_name == turn.agent {
950            return Err(HandoffError::ToSelf(turn.agent.clone()));
951        }
952        let Some(next) = turn
953            .others
954            .iter()
955            .find(|other| other.name == args.agent_name)
956        else {
957            let names: Vec<&str> = turn
958                .others
959                .iter()
960                .map(|other| other.name.as_str())
961                .collect();
962            return Err(HandoffError::Unknown(args.agent_name, names.join(", ")));
963        };
964        let mut slot = turn.slot();
965        if let Some((earlier, _)) = &*slot {
966            return Err(HandoffError::Twice(earlier.to.clone()));
967        }
968        let reply = format!("Handing off to {}.", args.agent_name);
969        let handoff = Handoff {
970            from: turn.agent.clone(),
971            to: args.agent_name,
972            message: args.message,
973            context: args.context.filter(|context| !context.is_null()),
974        };
975        *slot = Some((handoff, Arc::clone(next)));
976        Ok(reply)
977    }
978}
979
980#[derive(Deserialize)]
981struct AskArgs {
982    question: String,
983}
984
985#[derive(Debug, thiserror::Error)]
986enum AskError {
987    #[error("{ASK_TOOL} works only during a swarm run")]
988    NotInSwarm,
989    #[error("nobody can answer questions in this run; decide on your own")]
990    Nobody,
991    #[error("{0}; decide on your own")]
992    Unanswered(NodeError),
993}
994
995/// The tool a swarm that allows questions adds to its agents: it sends the
996/// question to the run's reader and waits for the answer, within the turn.
997struct AskTool;
998
999impl Tool for AskTool {
1000    const NAME: &'static str = ASK_TOOL;
1001    type Args = AskArgs;
1002    type Output = String;
1003    type Error = AskError;
1004
1005    fn description(&self) -> String {
1006        "Ask the user a question (a decision, a missing fact, an approval) and wait for the \
1007         answer."
1008            .into()
1009    }
1010
1011    fn parameters(&self) -> Value {
1012        json!({
1013            "type": "object",
1014            "properties": {
1015                "question": {"type": "string", "description": "The question, standing on its own."}
1016            },
1017            "required": ["question"]
1018        })
1019    }
1020
1021    fn map_error(&self, error: AskError) -> ToolExecutionError {
1022        let feedback = error.to_string();
1023        ToolExecutionError::from_error(error).with_model_feedback(feedback)
1024    }
1025
1026    async fn call(&self, context: &mut ToolContext, args: AskArgs) -> Result<String, AskError> {
1027        let turn = context.scope::<Turn>().ok_or(AskError::NotInSwarm)?;
1028        let (question, reply) = Question::new(turn.agent.clone(), args.question, "");
1029        let sent = turn.asks().as_ref().map(|asks| asks.send(question));
1030        if !matches!(sent, Some(Ok(()))) {
1031            return Err(AskError::Nobody);
1032        }
1033        answer(reply).await.map_err(AskError::Unanswered)
1034    }
1035}
1036
1037/// Ends an agent's turn once it has handed off, so it does not keep working
1038/// on what the next agent now owns.
1039struct StopOnHandoff(Arc<Turn>);
1040
1041impl AgentHook for StopOnHandoff {
1042    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
1043        if event.tool_result().is_some() && self.0.slot().is_some() {
1044            OutcomeAction::stop("handed off")
1045        } else {
1046            OutcomeAction::proceed()
1047        }
1048    }
1049}