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