daimon 0.16.0

A Rust-native AI agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Handoff pattern: agents transfer control to each other mid-conversation.
//!
//! Inspired by OpenAI Swarm, a [`HandoffNetwork`] manages multiple agents that
//! can hand off the conversation to one another via synthetic `transfer_to_<name>`
//! tools. The network runs its own agent loop, detecting handoff signals and
//! switching the active agent while preserving conversation context.
//!
//! ```ignore
//! use daimon::agent::handoff::HandoffNetwork;
//!
//! let network = HandoffNetwork::builder()
//!     .entry("triage")
//!     .agent("triage", triage_agent)
//!     .agent("billing", billing_agent)
//!     .agent("support", support_agent)
//!     .build()?;
//!
//! let response = network.run("I need help with my bill").await?;
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use crate::agent::Agent;
use crate::error::{DaimonError, Result};
use crate::model::types::{ChatRequest, Message, ToolSpec, Usage};
use crate::tool::ToolOutput;

const HANDOFF_PREFIX: &str = "transfer_to_";

/// A network of agents that can hand off conversations to each other.
pub struct HandoffNetwork {
    agents: HashMap<String, Arc<Agent>>,
    entry: String,
    max_handoffs: usize,
    max_iterations_per_agent: usize,
}

impl HandoffNetwork {
    /// Returns a new builder.
    pub fn builder() -> HandoffBuilder {
        HandoffBuilder::new()
    }

    /// Runs the handoff network with the given user input.
    ///
    /// Starts with the entry agent, processes the conversation, and follows
    /// handoffs until an agent produces a final text response or limits are
    /// reached.
    #[tracing::instrument(skip_all, fields(entry = %self.entry))]
    pub async fn run(&self, input: &str) -> Result<HandoffResponse> {
        let mut current_agent_name = self.entry.clone();
        let mut handoffs = 0usize;
        let mut total_usage = Usage::default();
        let mut total_iterations = 0usize;

        let mut messages: Vec<Message> = Vec::new();

        let current_agent = self.agents.get(&current_agent_name).ok_or_else(|| {
            DaimonError::Orchestration(format!("entry agent '{}' not found", self.entry))
        })?;

        if let Some(system) = &current_agent.system_prompt {
            messages.push(Message::system(system));
        }
        messages.push(Message::user(input));

        loop {
            let agent = self.agents.get(&current_agent_name).ok_or_else(|| {
                DaimonError::Orchestration(format!("agent '{current_agent_name}' not found"))
            })?;

            let transfer_tools = self.build_transfer_tools(&current_agent_name);
            let mut agent_tool_specs: Vec<ToolSpec> = agent.tools.tool_specs().to_vec();
            agent_tool_specs.extend(transfer_tools);

            let mut agent_iterations = 0usize;

            loop {
                agent_iterations += 1;
                total_iterations += 1;

                if agent_iterations > self.max_iterations_per_agent {
                    return Err(DaimonError::MaxIterations(self.max_iterations_per_agent));
                }

                let request = ChatRequest {
                    messages: messages.clone(),
                    tools: agent_tool_specs.clone(),
                    temperature: agent.temperature,
                    max_tokens: agent.max_tokens,
                };

                let response = agent.model.generate_erased(&request).await?;

                if let Some(ref usage) = response.usage {
                    total_usage.accumulate(usage);
                }

                if !response.has_tool_calls() {
                    let final_text = response.text().to_string();
                    messages.push(response.message);

                    return Ok(HandoffResponse {
                        messages,
                        final_text,
                        final_agent: current_agent_name,
                        handoff_count: handoffs,
                        iterations: total_iterations,
                        usage: total_usage,
                    });
                }

                let tool_calls = response.tool_calls().to_vec();
                messages.push(Message::assistant_with_tool_calls(tool_calls.clone()));

                let mut handoff_target: Option<String> = None;

                for call in &tool_calls {
                    if let Some(target) = call.name.strip_prefix(HANDOFF_PREFIX) {
                        let reason = call
                            .arguments
                            .get("reason")
                            .and_then(|v| v.as_str())
                            .unwrap_or("transferring");

                        messages.push(Message::tool_result(
                            &call.id,
                            format!("Transferring to {target}. Reason: {reason}"),
                        ));
                        handoff_target = Some(target.to_string());
                    } else {
                        let output = match agent.tools.get(&call.name) {
                            Some(tool) => match tool.execute_erased(&call.arguments).await {
                                Ok(out) => out,
                                Err(e) => ToolOutput::error(e.to_string()),
                            },
                            None => {
                                ToolOutput::error(format!("tool '{}' not found", call.name))
                            }
                        };
                        messages.push(Message::tool_result(&call.id, &output.content));
                    }
                }

                if let Some(target) = handoff_target {
                    handoffs += 1;
                    if handoffs > self.max_handoffs {
                        return Err(DaimonError::Orchestration(format!(
                            "max handoffs ({}) exceeded",
                            self.max_handoffs
                        )));
                    }

                    if let Some(new_agent) = self.agents.get(&target) {
                        if let Some(system) = &new_agent.system_prompt {
                            messages.retain(|m| m.role != crate::model::types::Role::System);
                            messages.insert(0, Message::system(system));
                        }
                    }

                    tracing::info!(
                        from = %current_agent_name,
                        to = %target,
                        "agent handoff"
                    );
                    current_agent_name = target;
                    break;
                }
            }
        }
    }

    fn build_transfer_tools(&self, current: &str) -> Vec<ToolSpec> {
        self.agents
            .keys()
            .filter(|name| *name != current)
            .map(|name| ToolSpec {
                name: format!("{HANDOFF_PREFIX}{name}"),
                description: format!("Transfer the conversation to the '{name}' agent"),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "reason": {
                            "type": "string",
                            "description": "Why the conversation is being transferred"
                        }
                    },
                    "required": ["reason"]
                }),
            })
            .collect()
    }
}

/// Response from a handoff network run.
#[derive(Debug, Clone)]
pub struct HandoffResponse {
    /// Full message history.
    pub messages: Vec<Message>,
    /// Final text output.
    pub final_text: String,
    /// Name of the agent that produced the final response.
    pub final_agent: String,
    /// How many handoffs occurred.
    pub handoff_count: usize,
    /// Total model iterations across all agents.
    pub iterations: usize,
    /// Aggregated token usage.
    pub usage: Usage,
}

impl HandoffResponse {
    /// Get the final response text.
    pub fn text(&self) -> &str {
        &self.final_text
    }
}

/// Builder for constructing a [`HandoffNetwork`].
pub struct HandoffBuilder {
    agents: HashMap<String, Arc<Agent>>,
    entry: Option<String>,
    max_handoffs: usize,
    max_iterations_per_agent: usize,
}

impl HandoffBuilder {
    fn new() -> Self {
        Self {
            agents: HashMap::new(),
            entry: None,
            max_handoffs: 10,
            max_iterations_per_agent: 25,
        }
    }

    /// Registers an agent in the network.
    pub fn agent(mut self, name: impl Into<String>, agent: Arc<Agent>) -> Self {
        self.agents.insert(name.into(), agent);
        self
    }

    /// Sets the entry agent (the first to receive the user's input).
    pub fn entry(mut self, name: impl Into<String>) -> Self {
        self.entry = Some(name.into());
        self
    }

    /// Sets the maximum number of handoffs allowed. Default: 10.
    pub fn max_handoffs(mut self, max: usize) -> Self {
        self.max_handoffs = max;
        self
    }

    /// Sets the max iterations each agent gets before the loop aborts. Default: 25.
    pub fn max_iterations_per_agent(mut self, max: usize) -> Self {
        self.max_iterations_per_agent = max;
        self
    }

    /// Builds the handoff network.
    pub fn build(self) -> Result<HandoffNetwork> {
        let entry = self
            .entry
            .ok_or_else(|| DaimonError::Builder("handoff network requires an entry agent".into()))?;

        if !self.agents.contains_key(&entry) {
            return Err(DaimonError::Builder(format!(
                "entry agent '{entry}' not found in registered agents"
            )));
        }

        if self.agents.len() < 2 {
            return Err(DaimonError::Builder(
                "handoff network requires at least two agents".into(),
            ));
        }

        Ok(HandoffNetwork {
            agents: self.agents,
            entry,
            max_handoffs: self.max_handoffs,
            max_iterations_per_agent: self.max_iterations_per_agent,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Model;
    use crate::model::types::*;
    use crate::stream::ResponseStream;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct DirectResponseModel {
        response: String,
    }

    impl DirectResponseModel {
        fn new(response: &str) -> Self {
            Self {
                response: response.to_string(),
            }
        }
    }

    impl Model for DirectResponseModel {
        async fn generate(&self, _request: &ChatRequest) -> Result<ChatResponse> {
            Ok(ChatResponse {
                message: Message::assistant(&self.response),
                stop_reason: StopReason::EndTurn,
                usage: Some(Usage::default()),
            })
        }

        async fn generate_stream(&self, _request: &ChatRequest) -> Result<ResponseStream> {
            Ok(Box::pin(futures::stream::empty()))
        }
    }

    struct HandoffModel {
        target: String,
        call_count: AtomicUsize,
    }

    impl HandoffModel {
        fn new(target: &str) -> Self {
            Self {
                target: target.to_string(),
                call_count: AtomicUsize::new(0),
            }
        }
    }

    impl Model for HandoffModel {
        async fn generate(&self, _request: &ChatRequest) -> Result<ChatResponse> {
            let count = self.call_count.fetch_add(1, Ordering::SeqCst);
            if count == 0 {
                Ok(ChatResponse {
                    message: Message::assistant_with_tool_calls(vec![crate::tool::ToolCall {
                        id: "transfer_1".into(),
                        name: format!("{HANDOFF_PREFIX}{}", self.target),
                        arguments: serde_json::json!({"reason": "user needs billing help"}),
                    }]),
                    stop_reason: StopReason::ToolUse,
                    usage: Some(Usage::default()),
                })
            } else {
                Ok(ChatResponse {
                    message: Message::assistant("Triage done but model called again"),
                    stop_reason: StopReason::EndTurn,
                    usage: Some(Usage::default()),
                })
            }
        }

        async fn generate_stream(&self, _request: &ChatRequest) -> Result<ResponseStream> {
            Ok(Box::pin(futures::stream::empty()))
        }
    }

    #[test]
    fn test_builder_requires_entry() {
        let a = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("a"))
                .build()
                .unwrap(),
        );
        let b = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("b"))
                .build()
                .unwrap(),
        );
        let result = HandoffNetwork::builder()
            .agent("a", a)
            .agent("b", b)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_requires_two_agents() {
        let a = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("a"))
                .build()
                .unwrap(),
        );
        let result = HandoffNetwork::builder()
            .entry("a")
            .agent("a", a)
            .build();
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_direct_response_no_handoff() {
        let a = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("I can help!"))
                .build()
                .unwrap(),
        );
        let b = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("billing help"))
                .build()
                .unwrap(),
        );

        let network = HandoffNetwork::builder()
            .entry("triage")
            .agent("triage", a)
            .agent("billing", b)
            .build()
            .unwrap();

        let response = network.run("hello").await.unwrap();
        assert_eq!(response.text(), "I can help!");
        assert_eq!(response.final_agent, "triage");
        assert_eq!(response.handoff_count, 0);
    }

    #[tokio::test]
    async fn test_handoff_transfers_to_target() {
        let triage = Arc::new(
            Agent::builder()
                .model(HandoffModel::new("billing"))
                .build()
                .unwrap(),
        );
        let billing = Arc::new(
            Agent::builder()
                .model(DirectResponseModel::new("Here is your bill info"))
                .build()
                .unwrap(),
        );

        let network = HandoffNetwork::builder()
            .entry("triage")
            .agent("triage", triage)
            .agent("billing", billing)
            .build()
            .unwrap();

        let response = network.run("billing question").await.unwrap();
        assert_eq!(response.text(), "Here is your bill info");
        assert_eq!(response.final_agent, "billing");
        assert_eq!(response.handoff_count, 1);
    }

    struct AlwaysHandoffModel {
        target: String,
    }

    impl AlwaysHandoffModel {
        fn new(target: &str) -> Self {
            Self {
                target: target.to_string(),
            }
        }
    }

    impl Model for AlwaysHandoffModel {
        async fn generate(&self, _request: &ChatRequest) -> Result<ChatResponse> {
            Ok(ChatResponse {
                message: Message::assistant_with_tool_calls(vec![crate::tool::ToolCall {
                    id: "t".into(),
                    name: format!("{HANDOFF_PREFIX}{}", self.target),
                    arguments: serde_json::json!({"reason": "bounce"}),
                }]),
                stop_reason: StopReason::ToolUse,
                usage: Some(Usage::default()),
            })
        }

        async fn generate_stream(&self, _request: &ChatRequest) -> Result<ResponseStream> {
            Ok(Box::pin(futures::stream::empty()))
        }
    }

    #[tokio::test]
    async fn test_max_handoffs_exceeded() {
        let a = Arc::new(
            Agent::builder()
                .model(AlwaysHandoffModel::new("b"))
                .build()
                .unwrap(),
        );
        let b = Arc::new(
            Agent::builder()
                .model(AlwaysHandoffModel::new("a"))
                .build()
                .unwrap(),
        );

        let network = HandoffNetwork::builder()
            .entry("a")
            .agent("a", a)
            .agent("b", b)
            .max_handoffs(3)
            .build()
            .unwrap();

        let result = network.run("ping pong").await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max handoffs"), "got: {err}");
    }
}