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
//! Streaming distributed execution — stream agent events across process boundaries.
//!
//! While [`TaskWorker`](super::TaskWorker) returns only the final result,
//! [`StreamingTaskWorker`] uses `Agent::prompt_stream()` and publishes each
//! [`StreamEvent`] through a [`TaskEventBus`], allowing remote consumers to
//! observe the agent's progress in real time.
//!
//! ```ignore
//! use daimon::distributed::streaming::*;
//!
//! let bus = InProcessEventBus::new(64);
//! let worker = StreamingTaskWorker::new(broker, bus.clone(), || {
//!     Agent::builder().model(my_model).build().unwrap()
//! });
//!
//! // Subscribe before submitting
//! let mut rx = bus.subscribe();
//!
//! // Worker loop (background task)
//! tokio::spawn(async move { worker.run().await });
//!
//! // Receive live events
//! while let Ok(evt) = rx.recv().await {
//!     println!("{}: {:?}", evt.task_id, evt.event);
//! }
//! ```

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

use crate::agent::Agent;
use crate::error::{DaimonError, Result};
use crate::stream::StreamEvent;

use super::broker::ErasedTaskBroker;
use super::types::{AgentTask, TaskResult};
use super::worker::AgentFactory;

/// A serializable wrapper around [`StreamEvent`] tagged with a task ID.
///
/// This is the unit of data that flows through a [`TaskEventBus`],
/// allowing consumers to correlate events with their originating task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskStreamEvent {
    /// The task this event belongs to.
    pub task_id: String,
    /// The serializable event payload.
    pub event: SerializableStreamEvent,
}

/// Serializable version of [`StreamEvent`] for cross-process transport.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SerializableStreamEvent {
    TextDelta(String),
    ToolCallStart { id: String, name: String },
    ToolCallDelta { id: String, arguments_delta: String },
    ToolCallEnd { id: String },
    ToolResult { id: String, content: String, is_error: bool },
    Usage { iteration: usize, input_tokens: u32, output_tokens: u32, estimated_cost: f64 },
    Error(String),
    Done,
}

impl From<&StreamEvent> for SerializableStreamEvent {
    fn from(event: &StreamEvent) -> Self {
        match event {
            StreamEvent::TextDelta(t) => Self::TextDelta(t.clone()),
            StreamEvent::ToolCallStart { id, name } => Self::ToolCallStart {
                id: id.clone(),
                name: name.clone(),
            },
            StreamEvent::ToolCallDelta { id, arguments_delta } => Self::ToolCallDelta {
                id: id.clone(),
                arguments_delta: arguments_delta.clone(),
            },
            StreamEvent::ToolCallEnd { id } => Self::ToolCallEnd { id: id.clone() },
            StreamEvent::ToolResult { id, content, is_error } => Self::ToolResult {
                id: id.clone(),
                content: content.clone(),
                is_error: *is_error,
            },
            StreamEvent::Usage {
                iteration,
                input_tokens,
                output_tokens,
                estimated_cost,
            } => Self::Usage {
                iteration: *iteration,
                input_tokens: *input_tokens,
                output_tokens: *output_tokens,
                estimated_cost: *estimated_cost,
            },
            StreamEvent::Error(e) => Self::Error(e.clone()),
            StreamEvent::Done => Self::Done,
        }
    }
}

/// Trait for publishing and subscribing to task stream events.
///
/// Implement this for your transport layer (Redis pub/sub, NATS, etc.)
/// to stream agent events across process boundaries.
pub trait TaskEventBus: Send + Sync {
    /// Publishes an event for a given task.
    fn publish<'a>(
        &'a self,
        event: TaskStreamEvent,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
}

/// Object-safe erased version of [`TaskEventBus`].
pub trait ErasedTaskEventBus: Send + Sync {
    fn publish_erased<'a>(
        &'a self,
        event: TaskStreamEvent,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
}

impl<T: TaskEventBus> ErasedTaskEventBus for T {
    fn publish_erased<'a>(
        &'a self,
        event: TaskStreamEvent,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        self.publish(event)
    }
}

/// In-process event bus backed by a `tokio::sync::broadcast` channel.
///
/// All subscribers receive every event. Suitable for single-process use
/// and testing. For cross-process streaming, implement [`TaskEventBus`]
/// over your message broker.
pub struct InProcessEventBus {
    tx: broadcast::Sender<TaskStreamEvent>,
}

impl InProcessEventBus {
    /// Creates a new in-process event bus with the given channel capacity.
    pub fn new(capacity: usize) -> Self {
        let (tx, _) = broadcast::channel(capacity);
        Self { tx }
    }

    /// Returns a receiver that will get all future events.
    pub fn subscribe(&self) -> broadcast::Receiver<TaskStreamEvent> {
        self.tx.subscribe()
    }
}

impl Clone for InProcessEventBus {
    fn clone(&self) -> Self {
        Self {
            tx: self.tx.clone(),
        }
    }
}

impl TaskEventBus for InProcessEventBus {
    fn publish<'a>(
        &'a self,
        event: TaskStreamEvent,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(async move {
            let _ = self.tx.send(event);
            Ok(())
        })
    }
}

/// A worker that executes tasks with streaming and publishes events
/// through a [`TaskEventBus`].
///
/// Unlike [`TaskWorker`](super::TaskWorker), this worker uses
/// `Agent::prompt_stream()` to emit real-time events during execution.
pub struct StreamingTaskWorker {
    broker: Arc<dyn ErasedTaskBroker>,
    bus: Arc<dyn ErasedTaskEventBus>,
    factory: AgentFactory,
}

impl StreamingTaskWorker {
    /// Creates a new streaming worker.
    pub fn new<B, E, F>(broker: B, bus: E, factory: F) -> Self
    where
        B: super::broker::TaskBroker + 'static,
        E: TaskEventBus + 'static,
        F: Fn() -> Agent + Send + Sync + 'static,
    {
        Self {
            broker: Arc::new(broker),
            bus: Arc::new(bus),
            factory: Arc::new(factory),
        }
    }

    /// Creates a streaming worker from erased broker/bus and factory.
    pub fn from_erased(
        broker: Arc<dyn ErasedTaskBroker>,
        bus: Arc<dyn ErasedTaskEventBus>,
        factory: AgentFactory,
    ) -> Self {
        Self {
            broker,
            bus,
            factory,
        }
    }

    /// Processes a single task with streaming events.
    pub async fn run_once(&self) -> Result<Option<TaskResult>> {
        let task = match self.broker.receive_erased().await? {
            Some(t) => t,
            None => return Ok(None),
        };

        let result = self.execute_streaming(&task).await;

        match &result {
            Ok(tr) => {
                self.broker
                    .complete_erased(&task.task_id, tr.clone())
                    .await?;
            }
            Err(e) => {
                self.broker
                    .fail_erased(&task.task_id, e.to_string())
                    .await?;
            }
        }

        result.map(Some)
    }

    /// Runs the streaming worker loop indefinitely.
    pub async fn run(&self) -> Result<()> {
        loop {
            match self.run_once().await? {
                Some(_) => continue,
                None => {
                    tracing::info!("streaming worker: broker closed, exiting");
                    return Ok(());
                }
            }
        }
    }

    async fn execute_streaming(&self, task: &AgentTask) -> Result<TaskResult> {
        use futures::StreamExt;

        let agent = (self.factory)();

        let stream = match agent.prompt_stream(&task.input).await {
            Ok(s) => s,
            Err(e) => {
                self.bus
                    .publish_erased(TaskStreamEvent {
                        task_id: task.task_id.clone(),
                        event: SerializableStreamEvent::Error(e.to_string()),
                    })
                    .await?;
                return Ok(TaskResult {
                    task_id: task.task_id.clone(),
                    output: String::new(),
                    iterations: 0,
                    cost: 0.0,
                    error: Some(e.to_string()),
                });
            }
        };

        tokio::pin!(stream);

        let mut full_text = String::new();
        let mut iterations = 0;
        let mut cost = 0.0;

        while let Some(event_result) = stream.next().await {
            match event_result {
                Ok(ref event) => {
                    if let StreamEvent::TextDelta(t) = event {
                        full_text.push_str(t);
                    }
                    if let StreamEvent::Usage {
                        iteration,
                        estimated_cost,
                        ..
                    } = event
                    {
                        iterations = *iteration;
                        cost = *estimated_cost;
                    }

                    let serializable = SerializableStreamEvent::from(event);
                    let _ = self
                        .bus
                        .publish_erased(TaskStreamEvent {
                            task_id: task.task_id.clone(),
                            event: serializable,
                        })
                        .await;
                }
                Err(e) => {
                    let _ = self
                        .bus
                        .publish_erased(TaskStreamEvent {
                            task_id: task.task_id.clone(),
                            event: SerializableStreamEvent::Error(e.to_string()),
                        })
                        .await;
                    return Err(DaimonError::Other(format!("stream error: {e}")));
                }
            }
        }

        Ok(TaskResult {
            task_id: task.task_id.clone(),
            output: full_text,
            iterations,
            cost,
            error: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::distributed::{InProcessBroker, TaskBroker};
    use crate::error::Result as DResult;
    use crate::model::Model;
    use crate::model::types::*;
    use crate::stream::ResponseStream;

    struct EchoModel;

    impl Model for EchoModel {
        async fn generate(&self, request: &ChatRequest) -> DResult<ChatResponse> {
            let last = request
                .messages
                .last()
                .and_then(|m| m.content.as_deref())
                .unwrap_or("none");
            Ok(ChatResponse {
                message: Message::assistant(format!("Echo: {last}")),
                stop_reason: StopReason::EndTurn,
                usage: Some(Usage::default()),
            })
        }

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

    #[tokio::test]
    async fn test_streaming_worker_executes_task() {
        let broker = InProcessBroker::new(16);
        let bus = InProcessEventBus::new(64);
        let mut rx = bus.subscribe();

        let worker = StreamingTaskWorker::new(broker.clone(), bus, || {
            Agent::builder().model(EchoModel).build().unwrap()
        });

        let task = AgentTask::new("streaming test");
        let id = broker.submit(task).await.unwrap();

        let result = worker.run_once().await.unwrap().unwrap();
        assert_eq!(result.task_id, id);
        assert!(result.error.is_none());

        let mut got_done = false;
        while let Ok(evt) = rx.try_recv() {
            assert_eq!(evt.task_id, id);
            if matches!(evt.event, SerializableStreamEvent::Done) {
                got_done = true;
            }
        }
        assert!(got_done);
    }

    #[tokio::test]
    async fn test_event_bus_subscribe_after_publish() {
        let bus = InProcessEventBus::new(16);
        let mut rx = bus.subscribe();

        bus.publish(TaskStreamEvent {
            task_id: "t1".into(),
            event: SerializableStreamEvent::TextDelta("hello".into()),
        })
        .await
        .unwrap();

        let evt = rx.recv().await.unwrap();
        assert_eq!(evt.task_id, "t1");
        assert!(matches!(evt.event, SerializableStreamEvent::TextDelta(ref t) if t == "hello"));
    }

    #[test]
    fn test_serializable_stream_event_roundtrip() {
        let events = vec![
            SerializableStreamEvent::TextDelta("hi".into()),
            SerializableStreamEvent::ToolCallStart {
                id: "tc1".into(),
                name: "search".into(),
            },
            SerializableStreamEvent::ToolCallDelta {
                id: "tc1".into(),
                arguments_delta: "{\"q\":".into(),
            },
            SerializableStreamEvent::ToolCallEnd { id: "tc1".into() },
            SerializableStreamEvent::ToolResult {
                id: "tc1".into(),
                content: "found it".into(),
                is_error: false,
            },
            SerializableStreamEvent::Usage {
                iteration: 1,
                input_tokens: 100,
                output_tokens: 50,
                estimated_cost: 0.001,
            },
            SerializableStreamEvent::Error("oops".into()),
            SerializableStreamEvent::Done,
        ];

        for event in &events {
            let json = serde_json::to_string(event).unwrap();
            let deser: SerializableStreamEvent = serde_json::from_str(&json).unwrap();
            let json2 = serde_json::to_string(&deser).unwrap();
            assert_eq!(json, json2);
        }
    }

    #[test]
    fn test_task_stream_event_roundtrip() {
        let evt = TaskStreamEvent {
            task_id: "task-123".into(),
            event: SerializableStreamEvent::TextDelta("chunk".into()),
        };

        let json = serde_json::to_string(&evt).unwrap();
        let deser: TaskStreamEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(deser.task_id, "task-123");
    }

    #[test]
    fn test_from_stream_event() {
        let events = vec![
            StreamEvent::TextDelta("text".into()),
            StreamEvent::ToolCallStart {
                id: "1".into(),
                name: "fn".into(),
            },
            StreamEvent::Done,
        ];

        for event in &events {
            let serializable = SerializableStreamEvent::from(event);
            let json = serde_json::to_string(&serializable).unwrap();
            assert!(!json.is_empty());
        }
    }
}