use std::collections::HashSet;
use std::fmt::Write as _;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use rig_agent::Agent;
use rig_agent::agent::{AgentHook, HookContext, OutcomeAction, OutcomeEvent};
use rig_agent::completion::PromptError;
use rig_core::completion::{AssistantContent, Usage};
use rig_core::tool::{Tool, ToolContext, ToolExecutionError};
use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tracing::Instrument;
use crate::BuildError;
use crate::checkpoint::{CheckpointError, Checkpoints, Journal, Saving};
use crate::events::{Emit, events, stream_agent};
use crate::human::{Clock, Question, answer};
use crate::node::{Meter, Node, NodeError, NodeIo, NodeOutput, in_conversation, turn_budget};
pub(crate) const DEFAULT_MAX_TURNS: usize = 8;
pub const HANDOFF_TOOL: &str = "handoff_to_agent";
pub const ASK_TOOL: &str = "ask_human";
#[derive(Clone)]
pub struct Swarm {
inner: Arc<Inner>,
}
struct Inner {
members: Vec<Arc<Member>>,
entry: Arc<Member>,
max_handoffs: usize,
max_turns: usize,
execution_timeout: Duration,
agent_timeout: Duration,
repetition: Option<Repetition>,
questions: bool,
checkpoints: Option<Checkpoints>,
}
struct Member {
name: String,
description: Option<String>,
agent: Agent,
}
#[derive(Clone, Copy)]
struct Repetition {
window: usize,
min_unique: usize,
}
#[must_use]
pub struct SwarmBuilder {
agents: Vec<Agent>,
entry: Option<String>,
max_handoffs: usize,
max_turns: usize,
execution_timeout: Duration,
agent_timeout: Duration,
repetition: Option<Repetition>,
questions: bool,
checkpoints: Option<Checkpoints>,
}
impl Swarm {
pub fn builder() -> SwarmBuilder {
SwarmBuilder {
agents: Vec::new(),
entry: None,
max_handoffs: 20,
max_turns: DEFAULT_MAX_TURNS,
execution_timeout: Duration::from_secs(15 * 60),
agent_timeout: Duration::from_secs(5 * 60),
repetition: None,
questions: false,
checkpoints: None,
}
}
}
impl SwarmBuilder {
pub fn agent(mut self, agent: Agent) -> Self {
self.agents.push(agent);
self
}
pub fn entry(mut self, name: impl Into<String>) -> Self {
self.entry = Some(name.into());
self
}
pub fn max_handoffs(mut self, max_handoffs: usize) -> Self {
self.max_handoffs = max_handoffs;
self
}
pub fn max_turns_per_agent(mut self, max_turns: usize) -> Self {
self.max_turns = max_turns;
self
}
pub fn execution_timeout(mut self, timeout: Duration) -> Self {
self.execution_timeout = timeout;
self
}
#[doc(alias = "node_timeout")]
pub fn agent_timeout(mut self, timeout: Duration) -> Self {
self.agent_timeout = timeout;
self
}
pub fn detect_repetition(mut self, window: usize, min_unique: usize) -> Self {
self.repetition = Some(Repetition { window, min_unique });
self
}
pub fn allow_questions(mut self) -> Self {
self.questions = true;
self
}
pub fn checkpoints(
mut self,
store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
) -> Self {
self.checkpoints = Some(Checkpoints::new(store, "swarm"));
self
}
pub fn build(self) -> Result<Swarm, BuildError> {
if self.agents.is_empty() {
return Err(BuildError::Empty);
}
if self.max_turns == 0 {
return Err(BuildError::ZeroTurns);
}
let mut members: Vec<Member> = Vec::with_capacity(self.agents.len());
for agent in self.agents {
let name = agent.name().ok_or(BuildError::UnnamedAgent)?.to_owned();
if members.iter().any(|member| member.name == name) {
return Err(BuildError::DuplicateName(name));
}
members.push(Member {
description: agent.description().map(str::to_owned),
name,
agent,
});
}
let members: Vec<Arc<Member>> = members.into_iter().map(Arc::new).collect();
let entry = match &self.entry {
None => members.first().ok_or(BuildError::Empty)?,
Some(name) => members
.iter()
.find(|member| &member.name == name)
.ok_or_else(|| BuildError::UnknownName(name.clone()))?,
}
.clone();
for member in &members {
if members.len() > 1 {
member.agent.tool_server_handle().add_tool(HandoffTool);
}
if self.questions {
member.agent.tool_server_handle().add_tool(AskTool);
}
}
Ok(Swarm {
inner: Arc::new(Inner {
members,
entry,
max_handoffs: self.max_handoffs,
max_turns: self.max_turns,
execution_timeout: self.execution_timeout,
agent_timeout: self.agent_timeout,
repetition: self.repetition,
questions: self.questions,
checkpoints: self.checkpoints,
}),
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Handoff {
pub from: String,
pub to: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<Value>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SwarmRun {
pub answer: String,
pub agent: String,
pub agents: Vec<String>,
pub handoffs: Vec<Handoff>,
pub usage: Usage,
pub elapsed: Duration,
}
#[derive(Debug, thiserror::Error)]
#[error("{reason}")]
#[non_exhaustive]
pub struct SwarmError {
pub reason: SwarmFailure,
pub agents: Vec<String>,
pub handoffs: Vec<Handoff>,
pub usage: Usage,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SwarmFailure {
#[error("agent {agent:?} failed: {source}")]
Agent {
agent: String,
#[source]
source: Box<PromptError>,
},
#[error("agent {agent:?} did not finish in time")]
Timeout {
agent: String,
},
#[error("the swarm reached its limit of {limit} handoffs")]
MaxHandoffs {
limit: usize,
},
#[error("checkpoint: {error}")]
Checkpoint {
#[source]
error: CheckpointError,
},
#[error("the last {window} turns went to only {unique} agents")]
Repetitive {
window: usize,
unique: usize,
},
}
#[derive(Debug)]
#[non_exhaustive]
pub enum SwarmEvent {
AgentStarted {
agent: String,
},
Text {
agent: String,
text: String,
},
Resumed {
agent: String,
handoffs: usize,
},
Handoff(Handoff),
Question(Question),
Finished(Box<Result<SwarmRun, SwarmError>>),
}
#[derive(Default, Clone, Serialize, Deserialize)]
struct Trail {
agents: Vec<String>,
handoffs: Vec<Handoff>,
shared: Vec<(String, Value)>,
#[serde(default)]
work: Vec<(String, Vec<String>)>,
usage: Usage,
}
#[derive(Serialize, Deserialize)]
struct Saved {
task: String,
finished: bool,
#[serde(default)]
answer: Option<String>,
current: String,
message: Option<String>,
trail: Trail,
active_ms: u64,
elapsed_ms: u64,
}
fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
impl Trail {
fn fail(self, reason: SwarmFailure) -> SwarmError {
SwarmError {
reason,
agents: self.agents,
handoffs: self.handoffs,
usage: self.usage,
}
}
}
fn run_span(entry: &str, run_id: Option<&str>) -> tracing::Span {
tracing::info_span!(
"swarm.run",
swarm.entry = %entry,
swarm.run_id = run_id,
swarm.agent = tracing::field::Empty,
swarm.handoffs = tracing::field::Empty,
swarm.usage.input_tokens = tracing::field::Empty,
swarm.usage.output_tokens = tracing::field::Empty,
otel.status_code = tracing::field::Empty,
error.type = tracing::field::Empty,
)
}
fn record_outcome(span: &tracing::Span, outcome: &Result<SwarmRun, SwarmError>) {
let (handoffs, usage) = match outcome {
Ok(run) => (run.handoffs.len(), run.usage),
Err(error) => (error.handoffs.len(), error.usage),
};
span.record("swarm.handoffs", handoffs);
if let Some(tokens) = usage.input_tokens {
span.record("swarm.usage.input_tokens", tokens);
}
if let Some(tokens) = usage.output_tokens {
span.record("swarm.usage.output_tokens", tokens);
}
match outcome {
Ok(run) => {
span.record("swarm.agent", run.agent.as_str());
}
Err(error) => {
span.record("otel.status_code", "ERROR");
span.record("error.type", error.reason.kind());
}
}
}
impl SwarmFailure {
fn kind(&self) -> &'static str {
match self {
Self::Agent { .. } => "agent_failed",
Self::Timeout { .. } => "timeout",
Self::MaxHandoffs { .. } => "max_handoffs",
Self::Repetitive { .. } => "repetitive_handoffs",
Self::Checkpoint { .. } => "checkpoint",
}
}
}
impl Swarm {
pub async fn run(&self, task: impl Into<String>) -> Result<SwarmRun, SwarmError> {
let span = run_span(&self.inner.entry.name, None);
let outcome = self
.run_task(task.into(), None, false, None)
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
}
pub async fn run_as(
&self,
run_id: &str,
task: impl Into<String>,
) -> Result<SwarmRun, SwarmError> {
let span = run_span(&self.inner.entry.name, Some(run_id));
let outcome = self
.run_task(task.into(), self.saving(Some(run_id)), false, None)
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
}
pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, SwarmEvent> {
self.stream_events(task.into(), None)
}
pub fn stream_as<'a>(
&'a self,
run_id: &'a str,
task: impl Into<String>,
) -> WasmBoxedStream<'a, SwarmEvent> {
self.stream_events(task.into(), Some(run_id))
}
fn stream_events<'a>(
&'a self,
task: String,
run_id: Option<&'a str>,
) -> WasmBoxedStream<'a, SwarmEvent> {
let span = run_span(&self.inner.entry.name, run_id);
events(
move |sender| async move {
let emit = move |event| {
let _ = sender.send(event);
};
let outcome = self
.run_task(task, self.saving(run_id), false, Some(&emit))
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
},
|outcome| SwarmEvent::Finished(Box::new(outcome)),
)
}
fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
run_id
.zip(self.inner.checkpoints.clone())
.map(|(id, checkpoints)| Saving::new(checkpoints, id))
}
async fn run_task(
&self,
task: String,
saving: Option<Saving>,
nested: bool,
emit: Option<Emit<'_, SwarmEvent>>,
) -> Result<SwarmRun, SwarmError> {
let inner = &*self.inner;
let started = Instant::now();
let checkpoints = saving
.as_ref()
.map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
let saved = match checkpoints {
Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
Ok(Some(Saved {
finished: true,
answer: Some(answer),
current,
trail,
elapsed_ms,
..
})) if nested => {
return Ok(SwarmRun {
answer,
agent: current,
agents: trail.agents,
handoffs: trail.handoffs,
usage: trail.usage,
elapsed: Duration::from_millis(elapsed_ms),
});
}
Ok(saved) => saved.filter(|saved| !saved.finished),
Err(error) => {
return Err(Trail::default().fail(SwarmFailure::Checkpoint { error }));
}
},
None => None,
};
let (task, mut trail, mut current, mut message, clock, before) = match saved {
None => (
task,
Trail::default(),
Arc::clone(&inner.entry),
None,
Clock::resumed(Duration::ZERO),
Duration::ZERO,
),
Some(saved) => {
let Some(current) = inner
.members
.iter()
.find(|member| member.name == saved.current)
.cloned()
else {
let error = CheckpointError::UnknownAgent(saved.current);
return Err(saved.trail.fail(SwarmFailure::Checkpoint { error }));
};
tracing::info!(agent = %saved.current, handoffs = saved.trail.handoffs.len(), "swarm run resumed");
if let Some(emit) = emit {
emit(SwarmEvent::Resumed {
agent: saved.current.clone(),
handoffs: saved.trail.handoffs.len(),
});
}
let clock = Clock::resumed(Duration::from_millis(saved.active_ms));
(
saved.task,
saved.trail,
current,
saved.message,
clock,
Duration::from_millis(saved.elapsed_ms),
)
}
};
let snapshot = |trail: &Trail,
current: &str,
message: &Option<String>,
answer: Option<String>| Saved {
task: task.clone(),
finished: answer.is_some(),
answer,
current: current.to_owned(),
message: message.clone(),
trail: trail.clone(),
active_ms: millis(clock.active()),
elapsed_ms: millis(before + started.elapsed()),
};
loop {
let member = Arc::clone(¤t);
if let Some((id, checkpoints)) = checkpoints {
let saved = snapshot(&trail, &member.name, &message, None);
if let Err(error) = checkpoints.save(id, &saved).await {
return Err(trail.fail(SwarmFailure::Checkpoint { error }));
}
}
trail.agents.push(member.name.clone());
if let Some(Repetition { window, min_unique }) = inner.repetition
&& window > 0
&& trail.agents.len() >= window
{
let recent = trail.agents.iter().rev().take(window);
let unique = recent.collect::<HashSet<_>>().len();
if unique < min_unique {
return Err(trail.fail(SwarmFailure::Repetitive { window, unique }));
}
}
let budget = inner
.agent_timeout
.min(inner.execution_timeout.saturating_sub(clock.active()));
let input = self.input(&member, &task, message.as_deref(), &trail);
let turn = Arc::new(Turn {
agent: member.name.clone(),
others: inner
.members
.iter()
.filter(|other| other.name != member.name)
.cloned()
.collect(),
handoff: Mutex::new(None),
work: Mutex::new(Vec::new()),
questions: Mutex::new(None),
});
let meter = Meter::default();
let part = saving
.as_ref()
.map(|saving| saving.part("journal", "turn", trail.agents.len()));
let key = part.as_ref().map(|part| part.run_id.clone());
let prompt = member
.agent
.prompt(input)
.max_turns(turn_budget(&member.agent, inner.max_turns));
let mut runner = in_conversation(prompt, &member.agent, key)
.tool_context(ToolContext::new().with_scope(turn.clone()))
.add_hook(meter.clone());
if let Some(journal) = part {
match Journal::open(journal).await {
Ok(journal) => runner = runner.add_hook(journal),
Err(error) => return Err(trail.fail(SwarmFailure::Checkpoint { error })),
}
}
let runner = runner.add_hook(StopOnHandoff(turn.clone()));
let run = async {
let Some(emit) = emit else {
return runner.run().await;
};
emit(SwarmEvent::AgentStarted {
agent: member.name.clone(),
});
let on_text = |text: &str| {
emit(SwarmEvent::Text {
agent: member.name.clone(),
text: text.to_owned(),
})
};
let (asks, mut asked) = mpsc::unbounded_channel();
if inner.questions {
*turn.asks() = Some(asks);
}
let mut agent = std::pin::pin!(stream_agent(runner, &on_text));
loop {
tokio::select! {
outcome = &mut agent => break outcome,
Some(question) = asked.recv() => {
tracing::info!(swarm.agent = %question.from(), "human.question");
emit(SwarmEvent::Question(question.pausing(&clock)));
}
}
}
}
.instrument(tracing::info_span!("swarm.agent", swarm.agent = %member.name));
let outcome = clock.within(budget, run).await;
trail.usage += meter.total();
let handoff = turn.take();
match (outcome, handoff) {
(None, _) => {
let agent = member.name.clone();
return Err(trail.fail(SwarmFailure::Timeout { agent }));
}
(Some(_), Some((handoff, next))) => {
if trail.handoffs.len() >= inner.max_handoffs {
let limit = inner.max_handoffs;
return Err(trail.fail(SwarmFailure::MaxHandoffs { limit }));
}
tracing::info!(
swarm.from = %handoff.from,
swarm.to = %handoff.to,
swarm.message_chars = handoff.message.chars().count(),
"swarm.handoff"
);
current = next;
if let Some(context) = &handoff.context {
trail.shared.push((handoff.from.clone(), context.clone()));
}
let work = turn.take_work();
if !work.is_empty() {
trail.work.push((handoff.from.clone(), work));
trim_trail_work(&mut trail.work);
}
message = Some(handoff.message.clone());
if let Some(emit) = emit {
emit(SwarmEvent::Handoff(handoff.clone()));
}
trail.handoffs.push(handoff);
}
(Some(Ok(response)), None) => {
if let Some((id, checkpoints)) = checkpoints {
let saved =
snapshot(&trail, &member.name, &message, Some(response.output()));
if checkpoints.save(id, &saved).await.is_err() {
tracing::warn!(
kind = "checkpoint",
"could not mark the swarm run finished"
);
}
}
return Ok(SwarmRun {
answer: response.output(),
agent: member.name.clone(),
agents: trail.agents,
handoffs: trail.handoffs,
usage: trail.usage,
elapsed: before + started.elapsed(),
});
}
(Some(Err(source)), None) => {
let agent = member.name.clone();
let source = Box::new(source);
return Err(trail.fail(SwarmFailure::Agent { agent, source }));
}
}
}
}
fn input(&self, current: &Member, task: &str, message: Option<&str>, trail: &Trail) -> String {
let members = &self.inner.members;
let mut text = String::new();
if let (Some(message), Some(last)) = (message, trail.handoffs.last()) {
let _ = write!(text, "Handoff from {}: {message}\n\n", last.from);
}
let _ = write!(text, "User request: {task}\n\n");
let before: &[String] = trail
.agents
.split_last()
.map(|(_, before)| before)
.unwrap_or_default();
if !before.is_empty() {
let _ = write!(
text,
"Agents who worked on this so far: {}\n\n",
before.join(" -> ")
);
}
if !trail.shared.is_empty() {
text.push_str("Shared by previous agents:\n");
for (agent, context) in &trail.shared {
let _ = writeln!(text, "- {agent}: {context}");
}
text.push('\n');
}
for (agent, work) in &trail.work {
let _ = writeln!(text, "What {agent} wrote and read before handing off:");
for line in work {
let _ = writeln!(text, "{line}");
}
text.push('\n');
}
let others: Vec<&Member> = members
.iter()
.filter(|member| member.name != current.name)
.map(|member| &**member)
.collect();
if !others.is_empty() {
text.push_str("Other agents you can hand off to:\n");
for other in others {
match &other.description {
Some(description) => {
let _ = writeln!(text, "- {}: {description}", other.name);
}
None => {
let _ = writeln!(text, "- {}", other.name);
}
}
}
let _ = write!(
text,
"\nIf you can complete the user request yourself, answer it: your answer is the \
final one. Hand off only when another agent must do something you cannot, by \
calling {HANDOFF_TOOL} with the agent's name and a message saying what it should \
do; your turn ends there."
);
}
if self.inner.questions {
let _ = write!(
text,
"\n\nIf you need a decision or a fact only the user has, call {ASK_TOOL} \
with your question and wait for the answer."
);
}
text.trim_end().to_owned()
}
}
impl Node for Swarm {
fn run<'a>(
&'a self,
input: String,
io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
Box::pin(async move {
let saving = io.saving().map(|saving| {
let checkpoints = self.inner.checkpoints.clone();
let checkpoints =
checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("swarm"));
Saving::new(checkpoints, saving.run_id.clone())
});
let emit = |event| match event {
SwarmEvent::Text { text, .. } => io.text(&text),
SwarmEvent::Question(question) => io.forward(question),
_ => {}
};
let emit: Option<Emit<'_, SwarmEvent>> = io.is_streaming().then_some(&emit);
let run = self.run_task(input, saving, true, emit).await?;
Ok(NodeOutput::new(run.answer).with_usage(run.usage))
})
}
}
const WORK_LINE_BYTES: usize = 4 * 1024;
const WORK_TOTAL_BYTES: usize = 32 * 1024;
fn bounded_line(line: String) -> String {
if line.len() <= WORK_LINE_BYTES {
return line;
}
let mut end = WORK_LINE_BYTES;
while !line.is_char_boundary(end) {
end -= 1;
}
let mut cut = line;
cut.truncate(end);
cut.push_str(" [truncated]");
cut
}
fn trim_oldest(work: &mut Vec<String>) {
let mut total: usize = work.iter().map(String::len).sum();
let dropped = work
.iter()
.take_while(|line| {
let over = total > WORK_TOTAL_BYTES;
total = total.saturating_sub(line.len());
over
})
.count();
work.drain(..dropped);
}
fn trim_trail_work(work: &mut Vec<(String, Vec<String>)>) {
let mut total: usize = work
.iter()
.flat_map(|(_, lines)| lines)
.map(String::len)
.sum();
while total > WORK_TOTAL_BYTES {
let Some((_, lines)) = work.first_mut() else {
break;
};
if lines.is_empty() {
work.remove(0);
continue;
}
total -= lines.remove(0).len();
if lines.is_empty() {
work.remove(0);
}
}
}
struct Turn {
agent: String,
others: Vec<Arc<Member>>,
handoff: Mutex<Option<(Handoff, Arc<Member>)>>,
work: Mutex<Vec<String>>,
questions: Mutex<Option<mpsc::UnboundedSender<Question>>>,
}
impl Turn {
fn asks(&self) -> std::sync::MutexGuard<'_, Option<mpsc::UnboundedSender<Question>>> {
self.questions
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn slot(&self) -> std::sync::MutexGuard<'_, Option<(Handoff, Arc<Member>)>> {
self.handoff.lock().unwrap_or_else(PoisonError::into_inner)
}
fn take(&self) -> Option<(Handoff, Arc<Member>)> {
self.slot().take()
}
fn note(&self, lines: impl IntoIterator<Item = String>) {
let mut work = self.work.lock().unwrap_or_else(PoisonError::into_inner);
work.extend(
lines
.into_iter()
.filter(|line| !line.trim().is_empty())
.map(bounded_line),
);
trim_oldest(&mut work);
}
fn take_work(&self) -> Vec<String> {
let mut work = self.work.lock().unwrap_or_else(PoisonError::into_inner);
std::mem::take(&mut *work)
}
}
#[derive(Deserialize)]
struct HandoffArgs {
agent_name: String,
message: String,
#[serde(default)]
context: Option<Value>,
}
#[derive(Debug, thiserror::Error)]
enum HandoffError {
#[error("{HANDOFF_TOOL} works only during a swarm run")]
NotInSwarm,
#[error("you are {0}; hand off to another agent or answer yourself")]
ToSelf(String),
#[error("no agent is named {0:?}; you can hand off to: {1}")]
Unknown(String, String),
#[error("you already handed off to {0} this turn")]
Twice(String),
}
struct HandoffTool;
impl Tool for HandoffTool {
const NAME: &'static str = HANDOFF_TOOL;
type Args = HandoffArgs;
type Output = String;
type Error = HandoffError;
fn description(&self) -> String {
"Pass the work to another agent of the swarm, with a message saying what it should do \
next and why, and optionally context to share with the agents after you. Your turn \
ends when you call this. Answer directly yourself when you can; hand off only work \
that another agent must do. Do not hand back to the agent that just handed the work \
to you unless you have new information for it."
.into()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"agent_name": {"type": "string", "description": "The agent to hand off to."},
"message": {"type": "string", "description": "What the next agent should do, and why."},
"context": {"type": "object", "description": "Facts to share with the agents after you."}
},
"required": ["agent_name", "message"]
})
}
fn map_error(&self, error: HandoffError) -> ToolExecutionError {
let feedback = error.to_string();
ToolExecutionError::from_error(error).with_model_feedback(feedback)
}
async fn call(
&self,
context: &mut ToolContext,
args: HandoffArgs,
) -> Result<String, HandoffError> {
let turn = context.scope::<Turn>().ok_or(HandoffError::NotInSwarm)?;
if args.agent_name == turn.agent {
return Err(HandoffError::ToSelf(turn.agent.clone()));
}
let Some(next) = turn
.others
.iter()
.find(|other| other.name == args.agent_name)
else {
let names: Vec<&str> = turn
.others
.iter()
.map(|other| other.name.as_str())
.collect();
return Err(HandoffError::Unknown(args.agent_name, names.join(", ")));
};
let mut slot = turn.slot();
if let Some((earlier, _)) = &*slot {
return Err(HandoffError::Twice(earlier.to.clone()));
}
let reply = format!("Handing off to {}.", args.agent_name);
let handoff = Handoff {
from: turn.agent.clone(),
to: args.agent_name,
message: args.message,
context: args.context.filter(|context| !context.is_null()),
};
*slot = Some((handoff, Arc::clone(next)));
Ok(reply)
}
}
#[derive(Deserialize)]
struct AskArgs {
question: String,
}
#[derive(Debug, thiserror::Error)]
enum AskError {
#[error("{ASK_TOOL} works only during a swarm run")]
NotInSwarm,
#[error("nobody can answer questions in this run; decide on your own")]
Nobody,
#[error("{0}; decide on your own")]
Unanswered(NodeError),
}
struct AskTool;
impl Tool for AskTool {
const NAME: &'static str = ASK_TOOL;
type Args = AskArgs;
type Output = String;
type Error = AskError;
fn description(&self) -> String {
"Ask the user a question (a decision, a missing fact, an approval) and wait for the \
answer."
.into()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"question": {"type": "string", "description": "The question, standing on its own."}
},
"required": ["question"]
})
}
fn map_error(&self, error: AskError) -> ToolExecutionError {
let feedback = error.to_string();
ToolExecutionError::from_error(error).with_model_feedback(feedback)
}
async fn call(&self, context: &mut ToolContext, args: AskArgs) -> Result<String, AskError> {
let turn = context.scope::<Turn>().ok_or(AskError::NotInSwarm)?;
let (question, reply) = Question::new(turn.agent.clone(), args.question, "");
let sent = turn.asks().as_ref().map(|asks| asks.send(question));
if !matches!(sent, Some(Ok(()))) {
return Err(AskError::Nobody);
}
answer(reply).await.map_err(AskError::Unanswered)
}
}
struct StopOnHandoff(Arc<Turn>);
impl AgentHook for StopOnHandoff {
async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
let handed_off = self.0.slot().is_some();
if let Some(response) = event.completion() {
self.0.note(
response
.choice
.iter()
.filter_map(AssistantContent::as_text)
.map(str::to_owned),
);
} else if let Some(result) = event.tool_result()
&& !handed_off
{
self.0.note([result.output().render()]);
}
if event.tool_result().is_some() && handed_off {
OutcomeAction::stop("handed off")
} else {
OutcomeAction::proceed()
}
}
}