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::Usage;
12use rig_core::tool::{Tool, ToolContext, ToolExecutionError};
13use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
14use serde::{Deserialize, Serialize};
15use serde_json::{Value, json};
16use tokio::sync::mpsc;
17use tracing::Instrument;
18
19use crate::BuildError;
20use crate::checkpoint::{CheckpointError, Checkpoints, Journal, Saving};
21use crate::events::{Emit, events, stream_agent};
22use crate::human::{Clock, Question, answer};
23use crate::node::{Meter, Node, NodeError, NodeIo, NodeOutput, in_conversation};
24
25pub const HANDOFF_TOOL: &str = "handoff_to_agent";
27
28pub const ASK_TOOL: &str = "ask_human";
31
32#[derive(Clone)]
43pub struct Swarm {
44 inner: Arc<Inner>,
45}
46
47struct Inner {
48 members: Vec<Arc<Member>>,
49 entry: Arc<Member>,
51 max_handoffs: usize,
52 execution_timeout: Duration,
53 agent_timeout: Duration,
54 repetition: Option<Repetition>,
55 questions: bool,
56 checkpoints: Option<Checkpoints>,
57}
58
59struct Member {
60 name: String,
61 description: Option<String>,
62 agent: Agent,
63}
64
65#[derive(Clone, Copy)]
66struct Repetition {
67 window: usize,
68 min_unique: usize,
69}
70
71#[must_use]
73pub struct SwarmBuilder {
74 agents: Vec<Agent>,
75 entry: Option<String>,
76 max_handoffs: usize,
77 execution_timeout: Duration,
78 agent_timeout: Duration,
79 repetition: Option<Repetition>,
80 questions: bool,
81 checkpoints: Option<Checkpoints>,
82}
83
84impl Swarm {
85 pub fn builder() -> SwarmBuilder {
87 SwarmBuilder {
88 agents: Vec::new(),
89 entry: None,
90 max_handoffs: 20,
91 execution_timeout: Duration::from_secs(15 * 60),
92 agent_timeout: Duration::from_secs(5 * 60),
93 repetition: None,
94 questions: false,
95 checkpoints: None,
96 }
97 }
98}
99
100impl SwarmBuilder {
101 pub fn agent(mut self, agent: Agent) -> Self {
107 self.agents.push(agent);
108 self
109 }
110
111 pub fn entry(mut self, name: impl Into<String>) -> Self {
113 self.entry = Some(name.into());
114 self
115 }
116
117 pub fn max_handoffs(mut self, max_handoffs: usize) -> Self {
119 self.max_handoffs = max_handoffs;
120 self
121 }
122
123 pub fn execution_timeout(mut self, timeout: Duration) -> Self {
125 self.execution_timeout = timeout;
126 self
127 }
128
129 pub fn agent_timeout(mut self, timeout: Duration) -> Self {
131 self.agent_timeout = timeout;
132 self
133 }
134
135 pub fn detect_repetition(mut self, window: usize, min_unique: usize) -> Self {
139 self.repetition = Some(Repetition { window, min_unique });
140 self
141 }
142
143 pub fn allow_questions(mut self) -> Self {
149 self.questions = true;
150 self
151 }
152
153 pub fn checkpoints(
157 mut self,
158 store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
159 ) -> Self {
160 self.checkpoints = Some(Checkpoints::new(store, "swarm"));
161 self
162 }
163
164 pub fn build(self) -> Result<Swarm, BuildError> {
166 if self.agents.is_empty() {
167 return Err(BuildError::Empty);
168 }
169 let mut members: Vec<Member> = Vec::with_capacity(self.agents.len());
170 for agent in self.agents {
171 let name = agent.name().ok_or(BuildError::UnnamedAgent)?.to_owned();
172 if members.iter().any(|member| member.name == name) {
173 return Err(BuildError::DuplicateName(name));
174 }
175 members.push(Member {
176 description: agent.description().map(str::to_owned),
177 name,
178 agent,
179 });
180 }
181 let members: Vec<Arc<Member>> = members.into_iter().map(Arc::new).collect();
182 let entry = match &self.entry {
183 None => members.first().ok_or(BuildError::Empty)?,
184 Some(name) => members
185 .iter()
186 .find(|member| &member.name == name)
187 .ok_or_else(|| BuildError::UnknownName(name.clone()))?,
188 }
189 .clone();
190 for member in &members {
191 if members.len() > 1 {
192 member.agent.tool_server_handle().add_tool(HandoffTool);
193 }
194 if self.questions {
195 member.agent.tool_server_handle().add_tool(AskTool);
196 }
197 }
198 Ok(Swarm {
199 inner: Arc::new(Inner {
200 members,
201 entry,
202 max_handoffs: self.max_handoffs,
203 execution_timeout: self.execution_timeout,
204 agent_timeout: self.agent_timeout,
205 repetition: self.repetition,
206 questions: self.questions,
207 checkpoints: self.checkpoints,
208 }),
209 })
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215pub struct Handoff {
216 pub from: String,
218 pub to: String,
220 pub message: String,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub context: Option<Value>,
225}
226
227#[derive(Debug, Clone)]
229#[non_exhaustive]
230pub struct SwarmRun {
231 pub answer: String,
233 pub agent: String,
235 pub agents: Vec<String>,
237 pub handoffs: Vec<Handoff>,
239 pub usage: Usage,
241 pub elapsed: Duration,
243}
244
245#[derive(Debug, thiserror::Error)]
247#[error("{reason}")]
248#[non_exhaustive]
249pub struct SwarmError {
250 pub reason: SwarmFailure,
252 pub agents: Vec<String>,
254 pub handoffs: Vec<Handoff>,
256 pub usage: Usage,
258}
259
260#[derive(Debug, thiserror::Error)]
262#[non_exhaustive]
263pub enum SwarmFailure {
264 #[error("agent {agent:?} failed: {source}")]
266 Agent {
267 agent: String,
269 #[source]
271 source: Box<PromptError>,
272 },
273 #[error("agent {agent:?} did not finish in time")]
275 Timeout {
276 agent: String,
278 },
279 #[error("the swarm reached its limit of {limit} handoffs")]
281 MaxHandoffs {
282 limit: usize,
284 },
285 #[error("checkpoint: {error}")]
287 Checkpoint {
288 #[source]
290 error: CheckpointError,
291 },
292 #[error("the last {window} turns went to only {unique} agents")]
295 Repetitive {
296 window: usize,
298 unique: usize,
300 },
301}
302
303#[derive(Debug)]
305#[non_exhaustive]
306pub enum SwarmEvent {
307 AgentStarted {
309 agent: String,
311 },
312 Text {
315 agent: String,
317 text: String,
319 },
320 Resumed {
323 agent: String,
325 handoffs: usize,
327 },
328 Handoff(Handoff),
330 Question(Question),
333 Finished(Box<Result<SwarmRun, SwarmError>>),
335}
336
337#[derive(Default, Clone, Serialize, Deserialize)]
339struct Trail {
340 agents: Vec<String>,
341 handoffs: Vec<Handoff>,
342 shared: Vec<(String, Value)>,
343 usage: Usage,
344}
345
346#[derive(Serialize, Deserialize)]
348struct Saved {
349 task: String,
350 finished: bool,
351 #[serde(default)]
353 answer: Option<String>,
354 current: String,
356 message: Option<String>,
357 trail: Trail,
358 active_ms: u64,
359 elapsed_ms: u64,
360}
361
362fn millis(duration: Duration) -> u64 {
363 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
364}
365
366impl Trail {
367 fn fail(self, reason: SwarmFailure) -> SwarmError {
368 SwarmError {
369 reason,
370 agents: self.agents,
371 handoffs: self.handoffs,
372 usage: self.usage,
373 }
374 }
375}
376
377fn run_span(entry: &str, run_id: Option<&str>) -> tracing::Span {
381 tracing::info_span!(
382 "swarm.run",
383 swarm.entry = %entry,
384 swarm.run_id = run_id,
385 swarm.agent = tracing::field::Empty,
386 swarm.handoffs = tracing::field::Empty,
387 swarm.usage.input_tokens = tracing::field::Empty,
388 swarm.usage.output_tokens = tracing::field::Empty,
389 otel.status_code = tracing::field::Empty,
390 error.type = tracing::field::Empty,
391 )
392}
393
394fn record_outcome(span: &tracing::Span, outcome: &Result<SwarmRun, SwarmError>) {
396 let (handoffs, usage) = match outcome {
397 Ok(run) => (run.handoffs.len(), run.usage),
398 Err(error) => (error.handoffs.len(), error.usage),
399 };
400 span.record("swarm.handoffs", handoffs);
401 if let Some(tokens) = usage.input_tokens {
402 span.record("swarm.usage.input_tokens", tokens);
403 }
404 if let Some(tokens) = usage.output_tokens {
405 span.record("swarm.usage.output_tokens", tokens);
406 }
407 match outcome {
408 Ok(run) => {
409 span.record("swarm.agent", run.agent.as_str());
410 }
411 Err(error) => {
412 span.record("otel.status_code", "ERROR");
413 span.record("error.type", error.reason.kind());
414 }
415 }
416}
417
418impl SwarmFailure {
419 fn kind(&self) -> &'static str {
421 match self {
422 Self::Agent { .. } => "agent_failed",
423 Self::Timeout { .. } => "timeout",
424 Self::MaxHandoffs { .. } => "max_handoffs",
425 Self::Repetitive { .. } => "repetitive_handoffs",
426 Self::Checkpoint { .. } => "checkpoint",
427 }
428 }
429}
430
431impl Swarm {
432 pub async fn run(&self, task: impl Into<String>) -> Result<SwarmRun, SwarmError> {
434 let span = run_span(&self.inner.entry.name, None);
435 let outcome = self
436 .run_task(task.into(), None, false, None)
437 .instrument(span.clone())
438 .await;
439 record_outcome(&span, &outcome);
440 outcome
441 }
442
443 pub async fn run_as(
454 &self,
455 run_id: &str,
456 task: impl Into<String>,
457 ) -> Result<SwarmRun, SwarmError> {
458 let span = run_span(&self.inner.entry.name, Some(run_id));
459 let outcome = self
460 .run_task(task.into(), self.saving(Some(run_id)), false, None)
461 .instrument(span.clone())
462 .await;
463 record_outcome(&span, &outcome);
464 outcome
465 }
466
467 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, SwarmEvent> {
491 self.stream_events(task.into(), None)
492 }
493
494 pub fn stream_as<'a>(
498 &'a self,
499 run_id: &'a str,
500 task: impl Into<String>,
501 ) -> WasmBoxedStream<'a, SwarmEvent> {
502 self.stream_events(task.into(), Some(run_id))
503 }
504
505 fn stream_events<'a>(
506 &'a self,
507 task: String,
508 run_id: Option<&'a str>,
509 ) -> WasmBoxedStream<'a, SwarmEvent> {
510 let span = run_span(&self.inner.entry.name, run_id);
511 events(
512 move |sender| async move {
513 let emit = move |event| {
514 let _ = sender.send(event);
515 };
516 let outcome = self
517 .run_task(task, self.saving(run_id), false, Some(&emit))
518 .instrument(span.clone())
519 .await;
520 record_outcome(&span, &outcome);
521 outcome
522 },
523 |outcome| SwarmEvent::Finished(Box::new(outcome)),
524 )
525 }
526
527 fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
529 run_id
530 .zip(self.inner.checkpoints.clone())
531 .map(|(id, checkpoints)| Saving::new(checkpoints, id))
532 }
533
534 async fn run_task(
538 &self,
539 task: String,
540 saving: Option<Saving>,
541 nested: bool,
542 emit: Option<Emit<'_, SwarmEvent>>,
543 ) -> Result<SwarmRun, SwarmError> {
544 let inner = &*self.inner;
545 let started = Instant::now();
546 let checkpoints = saving
547 .as_ref()
548 .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
549 let saved = match checkpoints {
550 Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
551 Ok(Some(Saved {
552 finished: true,
553 answer: Some(answer),
554 current,
555 trail,
556 elapsed_ms,
557 ..
558 })) if nested => {
559 return Ok(SwarmRun {
560 answer,
561 agent: current,
562 agents: trail.agents,
563 handoffs: trail.handoffs,
564 usage: trail.usage,
565 elapsed: Duration::from_millis(elapsed_ms),
566 });
567 }
568 Ok(saved) => saved.filter(|saved| !saved.finished),
569 Err(error) => {
570 return Err(Trail::default().fail(SwarmFailure::Checkpoint { error }));
571 }
572 },
573 None => None,
574 };
575 let (task, mut trail, mut current, mut message, clock, before) = match saved {
576 None => (
577 task,
578 Trail::default(),
579 Arc::clone(&inner.entry),
580 None,
581 Clock::resumed(Duration::ZERO),
582 Duration::ZERO,
583 ),
584 Some(saved) => {
585 let Some(current) = inner
586 .members
587 .iter()
588 .find(|member| member.name == saved.current)
589 .cloned()
590 else {
591 let error = CheckpointError::UnknownAgent(saved.current);
592 return Err(saved.trail.fail(SwarmFailure::Checkpoint { error }));
593 };
594 tracing::info!(agent = %saved.current, handoffs = saved.trail.handoffs.len(), "swarm run resumed");
595 if let Some(emit) = emit {
596 emit(SwarmEvent::Resumed {
597 agent: saved.current.clone(),
598 handoffs: saved.trail.handoffs.len(),
599 });
600 }
601 let clock = Clock::resumed(Duration::from_millis(saved.active_ms));
602 (
603 saved.task,
604 saved.trail,
605 current,
606 saved.message,
607 clock,
608 Duration::from_millis(saved.elapsed_ms),
609 )
610 }
611 };
612 let snapshot = |trail: &Trail,
613 current: &str,
614 message: &Option<String>,
615 answer: Option<String>| Saved {
616 task: task.clone(),
617 finished: answer.is_some(),
618 answer,
619 current: current.to_owned(),
620 message: message.clone(),
621 trail: trail.clone(),
622 active_ms: millis(clock.active()),
623 elapsed_ms: millis(before + started.elapsed()),
624 };
625 loop {
626 let member = Arc::clone(¤t);
627 if let Some((id, checkpoints)) = checkpoints {
628 let saved = snapshot(&trail, &member.name, &message, None);
629 if let Err(error) = checkpoints.save(id, &saved).await {
630 return Err(trail.fail(SwarmFailure::Checkpoint { error }));
631 }
632 }
633 trail.agents.push(member.name.clone());
634 if let Some(Repetition { window, min_unique }) = inner.repetition
635 && window > 0
636 && trail.agents.len() >= window
637 {
638 let recent = trail.agents.iter().rev().take(window);
639 let unique = recent.collect::<HashSet<_>>().len();
640 if unique < min_unique {
641 return Err(trail.fail(SwarmFailure::Repetitive { window, unique }));
642 }
643 }
644 let budget = inner
645 .agent_timeout
646 .min(inner.execution_timeout.saturating_sub(clock.active()));
647 let input = self.input(&member, &task, message.as_deref(), &trail);
648 let turn = Arc::new(Turn {
649 agent: member.name.clone(),
650 others: inner
651 .members
652 .iter()
653 .filter(|other| other.name != member.name)
654 .cloned()
655 .collect(),
656 handoff: Mutex::new(None),
657 questions: Mutex::new(None),
658 });
659 let meter = Meter::default();
660 let part = saving
663 .as_ref()
664 .map(|saving| saving.part("journal", "turn", trail.agents.len()));
665 let key = part.as_ref().map(|part| part.run_id.clone());
666 let mut runner = in_conversation(member.agent.prompt(input), &member.agent, key)
667 .tool_context(ToolContext::new().with_scope(turn.clone()))
668 .add_hook(meter.clone());
669 if let Some(journal) = part {
670 match Journal::open(journal).await {
673 Ok(journal) => runner = runner.add_hook(journal),
674 Err(error) => return Err(trail.fail(SwarmFailure::Checkpoint { error })),
675 }
676 }
677 let runner = runner.add_hook(StopOnHandoff(turn.clone()));
678 let run = async {
679 let Some(emit) = emit else {
680 return runner.run().await;
681 };
682 emit(SwarmEvent::AgentStarted {
683 agent: member.name.clone(),
684 });
685 let on_text = |text: &str| {
686 emit(SwarmEvent::Text {
687 agent: member.name.clone(),
688 text: text.to_owned(),
689 })
690 };
691 let (asks, mut asked) = mpsc::unbounded_channel();
694 if inner.questions {
695 *turn.asks() = Some(asks);
696 }
697 let mut agent = std::pin::pin!(stream_agent(runner, &on_text));
698 loop {
699 tokio::select! {
700 outcome = &mut agent => break outcome,
701 Some(question) = asked.recv() => {
702 tracing::info!(swarm.agent = %question.from(), "human.question");
705 emit(SwarmEvent::Question(question.pausing(&clock)));
706 }
707 }
708 }
709 }
710 .instrument(tracing::info_span!("swarm.agent", swarm.agent = %member.name));
711 let outcome = clock.within(budget, run).await;
712 trail.usage += meter.total();
713 let handoff = turn.take();
714 match (outcome, handoff) {
715 (None, _) => {
716 let agent = member.name.clone();
717 return Err(trail.fail(SwarmFailure::Timeout { agent }));
718 }
719 (Some(_), Some((handoff, next))) => {
720 if trail.handoffs.len() >= inner.max_handoffs {
721 let limit = inner.max_handoffs;
722 return Err(trail.fail(SwarmFailure::MaxHandoffs { limit }));
723 }
724 tracing::info!(
726 swarm.from = %handoff.from,
727 swarm.to = %handoff.to,
728 swarm.message = %handoff.message,
729 "swarm.handoff"
730 );
731 current = next;
732 if let Some(context) = &handoff.context {
733 trail.shared.push((handoff.from.clone(), context.clone()));
734 }
735 message = Some(handoff.message.clone());
736 if let Some(emit) = emit {
737 emit(SwarmEvent::Handoff(handoff.clone()));
738 }
739 trail.handoffs.push(handoff);
740 }
741 (Some(Ok(response)), None) => {
742 if let Some((id, checkpoints)) = checkpoints {
743 let saved =
746 snapshot(&trail, &member.name, &message, Some(response.output()));
747 if let Err(error) = checkpoints.save(id, &saved).await {
748 tracing::warn!(%error, "could not mark the swarm run finished");
749 }
750 }
751 return Ok(SwarmRun {
752 answer: response.output(),
753 agent: member.name.clone(),
754 agents: trail.agents,
755 handoffs: trail.handoffs,
756 usage: trail.usage,
757 elapsed: before + started.elapsed(),
758 });
759 }
760 (Some(Err(source)), None) => {
761 let agent = member.name.clone();
762 let source = Box::new(source);
763 return Err(trail.fail(SwarmFailure::Agent { agent, source }));
764 }
765 }
766 }
767 }
768
769 fn input(&self, current: &Member, task: &str, message: Option<&str>, trail: &Trail) -> String {
771 let members = &self.inner.members;
772 let mut text = String::new();
773 if let (Some(message), Some(last)) = (message, trail.handoffs.last()) {
774 let _ = write!(text, "Handoff from {}: {message}\n\n", last.from);
775 }
776 let _ = write!(text, "User request: {task}\n\n");
777 let before: &[String] = trail
778 .agents
779 .split_last()
780 .map(|(_, before)| before)
781 .unwrap_or_default();
782 if !before.is_empty() {
783 let _ = write!(
784 text,
785 "Agents who worked on this so far: {}\n\n",
786 before.join(" -> ")
787 );
788 }
789 if !trail.shared.is_empty() {
790 text.push_str("Shared by previous agents:\n");
791 for (agent, context) in &trail.shared {
792 let _ = writeln!(text, "- {agent}: {context}");
793 }
794 text.push('\n');
795 }
796 let others: Vec<&Member> = members
797 .iter()
798 .filter(|member| member.name != current.name)
799 .map(|member| &**member)
800 .collect();
801 if !others.is_empty() {
802 text.push_str("Other agents you can hand off to:\n");
803 for other in others {
804 match &other.description {
805 Some(description) => {
806 let _ = writeln!(text, "- {}: {description}", other.name);
807 }
808 None => {
809 let _ = writeln!(text, "- {}", other.name);
810 }
811 }
812 }
813 let _ = write!(
814 text,
815 "\nTo pass the work on, call {HANDOFF_TOOL} with the agent's name and a message \
816 saying what it should do; your turn ends there. If you answer instead, your \
817 answer is the final one."
818 );
819 }
820 if self.inner.questions {
821 let _ = write!(
822 text,
823 "\n\nIf you need a decision or a fact only the user has, call {ASK_TOOL} \
824 with your question and wait for the answer."
825 );
826 }
827 text.trim_end().to_owned()
828 }
829}
830
831impl Node for Swarm {
832 fn run<'a>(
837 &'a self,
838 input: String,
839 io: &'a NodeIo<'a>,
840 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
841 Box::pin(async move {
842 let saving = io.saving().map(|saving| {
843 let checkpoints = self.inner.checkpoints.clone();
844 let checkpoints =
845 checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("swarm"));
846 Saving::new(checkpoints, saving.run_id.clone())
847 });
848 let emit = |event| match event {
849 SwarmEvent::Text { text, .. } => io.text(&text),
850 SwarmEvent::Question(question) => io.forward(question),
851 _ => {}
852 };
853 let emit: Option<Emit<'_, SwarmEvent>> = io.is_streaming().then_some(&emit);
854 let run = self.run_task(input, saving, true, emit).await?;
855 Ok(NodeOutput::new(run.answer).with_usage(run.usage))
856 })
857 }
858}
859
860struct Turn {
862 agent: String,
863 others: Vec<Arc<Member>>,
865 handoff: Mutex<Option<(Handoff, Arc<Member>)>>,
867 questions: Mutex<Option<mpsc::UnboundedSender<Question>>>,
869}
870
871impl Turn {
872 fn asks(&self) -> std::sync::MutexGuard<'_, Option<mpsc::UnboundedSender<Question>>> {
873 self.questions
874 .lock()
875 .unwrap_or_else(PoisonError::into_inner)
876 }
877
878 fn slot(&self) -> std::sync::MutexGuard<'_, Option<(Handoff, Arc<Member>)>> {
879 self.handoff.lock().unwrap_or_else(PoisonError::into_inner)
880 }
881
882 fn take(&self) -> Option<(Handoff, Arc<Member>)> {
883 self.slot().take()
884 }
885}
886
887#[derive(Deserialize)]
888struct HandoffArgs {
889 agent_name: String,
890 message: String,
891 #[serde(default)]
892 context: Option<Value>,
893}
894
895#[derive(Debug, thiserror::Error)]
896enum HandoffError {
897 #[error("{HANDOFF_TOOL} works only during a swarm run")]
898 NotInSwarm,
899 #[error("you are {0}; hand off to another agent or answer yourself")]
900 ToSelf(String),
901 #[error("no agent is named {0:?}; you can hand off to: {1}")]
902 Unknown(String, String),
903 #[error("you already handed off to {0} this turn")]
904 Twice(String),
905}
906
907struct HandoffTool;
911
912impl Tool for HandoffTool {
913 const NAME: &'static str = HANDOFF_TOOL;
914 type Args = HandoffArgs;
915 type Output = String;
916 type Error = HandoffError;
917
918 fn description(&self) -> String {
919 "Pass the work to another agent of the swarm, with a message saying what it should do \
920 next and why, and optionally context to share with the agents after you. Your turn \
921 ends when you call this."
922 .into()
923 }
924
925 fn parameters(&self) -> Value {
926 json!({
927 "type": "object",
928 "properties": {
929 "agent_name": {"type": "string", "description": "The agent to hand off to."},
930 "message": {"type": "string", "description": "What the next agent should do, and why."},
931 "context": {"type": "object", "description": "Facts to share with the agents after you."}
932 },
933 "required": ["agent_name", "message"]
934 })
935 }
936
937 fn map_error(&self, error: HandoffError) -> ToolExecutionError {
939 let feedback = error.to_string();
940 ToolExecutionError::from_error(error).with_model_feedback(feedback)
941 }
942
943 async fn call(
944 &self,
945 context: &mut ToolContext,
946 args: HandoffArgs,
947 ) -> Result<String, HandoffError> {
948 let turn = context.scope::<Turn>().ok_or(HandoffError::NotInSwarm)?;
949 if args.agent_name == turn.agent {
950 return Err(HandoffError::ToSelf(turn.agent.clone()));
951 }
952 let Some(next) = turn
953 .others
954 .iter()
955 .find(|other| other.name == args.agent_name)
956 else {
957 let names: Vec<&str> = turn
958 .others
959 .iter()
960 .map(|other| other.name.as_str())
961 .collect();
962 return Err(HandoffError::Unknown(args.agent_name, names.join(", ")));
963 };
964 let mut slot = turn.slot();
965 if let Some((earlier, _)) = &*slot {
966 return Err(HandoffError::Twice(earlier.to.clone()));
967 }
968 let reply = format!("Handing off to {}.", args.agent_name);
969 let handoff = Handoff {
970 from: turn.agent.clone(),
971 to: args.agent_name,
972 message: args.message,
973 context: args.context.filter(|context| !context.is_null()),
974 };
975 *slot = Some((handoff, Arc::clone(next)));
976 Ok(reply)
977 }
978}
979
980#[derive(Deserialize)]
981struct AskArgs {
982 question: String,
983}
984
985#[derive(Debug, thiserror::Error)]
986enum AskError {
987 #[error("{ASK_TOOL} works only during a swarm run")]
988 NotInSwarm,
989 #[error("nobody can answer questions in this run; decide on your own")]
990 Nobody,
991 #[error("{0}; decide on your own")]
992 Unanswered(NodeError),
993}
994
995struct AskTool;
998
999impl Tool for AskTool {
1000 const NAME: &'static str = ASK_TOOL;
1001 type Args = AskArgs;
1002 type Output = String;
1003 type Error = AskError;
1004
1005 fn description(&self) -> String {
1006 "Ask the user a question (a decision, a missing fact, an approval) and wait for the \
1007 answer."
1008 .into()
1009 }
1010
1011 fn parameters(&self) -> Value {
1012 json!({
1013 "type": "object",
1014 "properties": {
1015 "question": {"type": "string", "description": "The question, standing on its own."}
1016 },
1017 "required": ["question"]
1018 })
1019 }
1020
1021 fn map_error(&self, error: AskError) -> ToolExecutionError {
1022 let feedback = error.to_string();
1023 ToolExecutionError::from_error(error).with_model_feedback(feedback)
1024 }
1025
1026 async fn call(&self, context: &mut ToolContext, args: AskArgs) -> Result<String, AskError> {
1027 let turn = context.scope::<Turn>().ok_or(AskError::NotInSwarm)?;
1028 let (question, reply) = Question::new(turn.agent.clone(), args.question, "");
1029 let sent = turn.asks().as_ref().map(|asks| asks.send(question));
1030 if !matches!(sent, Some(Ok(()))) {
1031 return Err(AskError::Nobody);
1032 }
1033 answer(reply).await.map_err(AskError::Unanswered)
1034 }
1035}
1036
1037struct StopOnHandoff(Arc<Turn>);
1040
1041impl AgentHook for StopOnHandoff {
1042 async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
1043 if event.tool_result().is_some() && self.0.slot().is_some() {
1044 OutcomeAction::stop("handed off")
1045 } else {
1046 OutcomeAction::proceed()
1047 }
1048 }
1049}