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 #[doc(alias = "node_timeout")]
160 pub fn agent_timeout(mut self, timeout: Duration) -> Self {
161 self.agent_timeout = timeout;
162 self
163 }
164
165 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 pub fn allow_questions(mut self) -> Self {
179 self.questions = true;
180 self
181 }
182
183 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
249pub struct Handoff {
250 pub from: String,
252 pub to: String,
254 pub message: String,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub context: Option<Value>,
259}
260
261#[derive(Debug, Clone)]
263#[non_exhaustive]
264pub struct SwarmRun {
265 pub answer: String,
267 pub agent: String,
269 pub agents: Vec<String>,
271 pub handoffs: Vec<Handoff>,
273 pub usage: Usage,
275 pub elapsed: Duration,
277}
278
279#[derive(Debug, thiserror::Error)]
281#[error("{reason}")]
282#[non_exhaustive]
283pub struct SwarmError {
284 pub reason: SwarmFailure,
286 pub agents: Vec<String>,
288 pub handoffs: Vec<Handoff>,
290 pub usage: Usage,
292}
293
294#[derive(Debug, thiserror::Error)]
296#[non_exhaustive]
297pub enum SwarmFailure {
298 #[error("agent {agent:?} failed: {source}")]
300 Agent {
301 agent: String,
303 #[source]
305 source: Box<PromptError>,
306 },
307 #[error("agent {agent:?} did not finish in time")]
309 Timeout {
310 agent: String,
312 },
313 #[error("the swarm reached its limit of {limit} handoffs")]
315 MaxHandoffs {
316 limit: usize,
318 },
319 #[error("checkpoint: {error}")]
321 Checkpoint {
322 #[source]
324 error: CheckpointError,
325 },
326 #[error("the last {window} turns went to only {unique} agents")]
329 Repetitive {
330 window: usize,
332 unique: usize,
334 },
335}
336
337#[derive(Debug)]
339#[non_exhaustive]
340pub enum SwarmEvent {
341 AgentStarted {
343 agent: String,
345 },
346 Text {
349 agent: String,
351 text: String,
353 },
354 Resumed {
357 agent: String,
359 handoffs: usize,
361 },
362 Handoff(Handoff),
364 Question(Question),
367 Finished(Box<Result<SwarmRun, SwarmError>>),
369}
370
371#[derive(Default, Clone, Serialize, Deserialize)]
373struct Trail {
374 agents: Vec<String>,
375 handoffs: Vec<Handoff>,
376 shared: Vec<(String, Value)>,
377 #[serde(default)]
379 work: Vec<(String, Vec<String>)>,
380 usage: Usage,
381}
382
383#[derive(Serialize, Deserialize)]
385struct Saved {
386 task: String,
387 finished: bool,
388 #[serde(default)]
390 answer: Option<String>,
391 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
414fn 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
431fn 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 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 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 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 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, SwarmEvent> {
528 self.stream_events(task.into(), None)
529 }
530
531 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 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 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(¤t);
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 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 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 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 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 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 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 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 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
919const WORK_LINE_BYTES: usize = 4 * 1024;
922
923const 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
941fn 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
955fn 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
978struct Turn {
980 agent: String,
981 others: Vec<Arc<Member>>,
983 handoff: Mutex<Option<(Handoff, Arc<Member>)>>,
985 work: Mutex<Vec<String>>,
988 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
1044struct 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 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
1134struct 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
1176struct 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 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}