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