1use 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
25pub(crate) const DEFAULT_MAX_TURNS: usize = 8;
28
29pub const HANDOFF_TOOL: &str = "handoff_to_agent";
31
32pub const ASK_TOOL: &str = "ask_human";
35
36#[derive(Clone)]
51pub struct Swarm {
52 inner: Arc<Inner>,
53}
54
55struct Inner {
56 members: Vec<Arc<Member>>,
57 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#[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 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 pub fn agent(mut self, agent: Agent) -> Self {
125 self.agents.push(agent);
126 self
127 }
128
129 pub fn entry(mut self, name: impl Into<String>) -> Self {
131 self.entry = Some(name.into());
132 self
133 }
134
135 pub fn max_handoffs(mut self, max_handoffs: usize) -> Self {
137 self.max_handoffs = max_handoffs;
138 self
139 }
140
141 pub fn max_turns_per_agent(mut self, max_turns: usize) -> Self {
148 self.max_turns = max_turns;
149 self
150 }
151
152 pub fn execution_timeout(mut self, timeout: Duration) -> Self {
154 self.execution_timeout = timeout;
155 self
156 }
157
158 pub fn agent_timeout(mut self, timeout: Duration) -> Self {
160 self.agent_timeout = timeout;
161 self
162 }
163
164 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 pub fn allow_questions(mut self) -> Self {
178 self.questions = true;
179 self
180 }
181
182 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
248pub struct Handoff {
249 pub from: String,
251 pub to: String,
253 pub message: String,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub context: Option<Value>,
258}
259
260#[derive(Debug, Clone)]
262#[non_exhaustive]
263pub struct SwarmRun {
264 pub answer: String,
266 pub agent: String,
268 pub agents: Vec<String>,
270 pub handoffs: Vec<Handoff>,
272 pub usage: Usage,
274 pub elapsed: Duration,
276}
277
278#[derive(Debug, thiserror::Error)]
280#[error("{reason}")]
281#[non_exhaustive]
282pub struct SwarmError {
283 pub reason: SwarmFailure,
285 pub agents: Vec<String>,
287 pub handoffs: Vec<Handoff>,
289 pub usage: Usage,
291}
292
293#[derive(Debug, thiserror::Error)]
295#[non_exhaustive]
296pub enum SwarmFailure {
297 #[error("agent {agent:?} failed: {source}")]
299 Agent {
300 agent: String,
302 #[source]
304 source: Box<PromptError>,
305 },
306 #[error("agent {agent:?} did not finish in time")]
308 Timeout {
309 agent: String,
311 },
312 #[error("the swarm reached its limit of {limit} handoffs")]
314 MaxHandoffs {
315 limit: usize,
317 },
318 #[error("checkpoint: {error}")]
320 Checkpoint {
321 #[source]
323 error: CheckpointError,
324 },
325 #[error("the last {window} turns went to only {unique} agents")]
328 Repetitive {
329 window: usize,
331 unique: usize,
333 },
334}
335
336#[derive(Debug)]
338#[non_exhaustive]
339pub enum SwarmEvent {
340 AgentStarted {
342 agent: String,
344 },
345 Text {
348 agent: String,
350 text: String,
352 },
353 Resumed {
356 agent: String,
358 handoffs: usize,
360 },
361 Handoff(Handoff),
363 Question(Question),
366 Finished(Box<Result<SwarmRun, SwarmError>>),
368}
369
370#[derive(Default, Clone, Serialize, Deserialize)]
372struct Trail {
373 agents: Vec<String>,
374 handoffs: Vec<Handoff>,
375 shared: Vec<(String, Value)>,
376 #[serde(default)]
378 work: Vec<(String, Vec<String>)>,
379 usage: Usage,
380}
381
382#[derive(Serialize, Deserialize)]
384struct Saved {
385 task: String,
386 finished: bool,
387 #[serde(default)]
389 answer: Option<String>,
390 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
413fn 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
430fn 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 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 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 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 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, SwarmEvent> {
527 self.stream_events(task.into(), None)
528 }
529
530 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 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 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(¤t);
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 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 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 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 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 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 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 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 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
914const WORK_LINE_BYTES: usize = 4 * 1024;
917
918const 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
936fn 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
950fn 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
973struct Turn {
975 agent: String,
976 others: Vec<Arc<Member>>,
978 handoff: Mutex<Option<(Handoff, Arc<Member>)>>,
980 work: Mutex<Vec<String>>,
983 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
1039struct 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 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
1129struct 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
1171struct 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 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}