daimon 0.19.0

A Rust-native AI agent framework
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# Distributed Execution

Daimon supports distributed agent execution across multiple processes via a broker-worker pattern. Tasks are submitted to a queue, workers pull and execute them, and results are reported back. Checkpointing persists agent state across process boundaries for resumable runs and time-travel debugging.

---

## Architecture Overview

Distributed execution in Daimon uses four core abstractions:

| Component | Role |
|-----------|------|
| **TaskBroker** | Queue for agent tasks — submit, receive, complete, fail |
| **TaskWorker** | Pulls tasks, runs agent, reports results |
| **Checkpoint** | Persists agent state across process boundaries |
| **TaskEventBus** | Streams events from distributed workers (optional) |

```
┌─────────────┐  submit    ┌─────────────┐  receive   ┌─────────────┐
│  Producer   │ ────────►  │ TaskBroker  │  ───────►  │ TaskWorker  │
└─────────────┘            └─────────────┘            └─────────────┘
                                  ▲                          │
                                  │     complete / fail      │
                                  └──────────────────────────┘
```

Producers submit `AgentTask` instances; workers block on `receive()`, run the agent, and call `complete()` or `fail()`. Status can be polled via `status(task_id)`.

---

## Task Broker Implementations

### InProcessBroker

Tokio MPSC channels. Single process. Ideal for testing and single-process parallelism.

```rust
use daimon::distributed::{InProcessBroker, TaskBroker, AgentTask};

let broker = InProcessBroker::new(64);
let task_id = broker.submit(AgentTask::new("Summarize this")).await?;
```

`InProcessBroker::new(capacity)` — capacity is the channel buffer size. Clone-friendly; all clones share the same underlying state.

---

### RedisBroker (feature = "redis")

Redis Lists for the queue, Redis Hashes for status and results. Multi-process.

```rust
use daimon::distributed::{RedisBroker, TaskBroker, AgentTask};

let broker = RedisBroker::new("redis://127.0.0.1/", "daimon:tasks").await?;
let task_id = broker.submit(AgentTask::new("Summarize this")).await?;
```

- `RedisBroker::new(url, prefix)``url` is the Redis connection URL; `prefix` is the key prefix (e.g. `daimon:tasks`).
- Keys: `{prefix}:queue`, `{prefix}:status`, `{prefix}:results`.

---

### NatsBroker (feature = "nats")

NATS JetStream with durable pull consumers. At-least-once delivery.

```rust
use daimon::distributed::{NatsBroker, TaskBroker, AgentTask};

let broker = NatsBroker::connect("nats://127.0.0.1:4222", "daimon-tasks").await?;
let task_id = broker.submit(AgentTask::new("Summarize this")).await?;
```

- `NatsBroker::connect(url, stream_name)` — creates or reuses a JetStream stream with WorkQueue retention.
- Durable consumer `daimon-worker` with explicit ack.

---

### AmqpBroker (feature = "amqp")

RabbitMQ via AMQP 0-9-1. Durable queue, manual ack.

```rust
use daimon::distributed::{AmqpBroker, TaskBroker, AgentTask};

let broker = AmqpBroker::connect("amqp://guest:guest@127.0.0.1:5672", "daimon-tasks").await?;
let task_id = broker.submit(AgentTask::new("Summarize this")).await?;
```

- `AmqpBroker::connect(url, queue_name)` — declares a durable queue if it doesn't exist.

---

### GrpcBrokerServer / GrpcBrokerClient (feature = "grpc")

gRPC transport. Server wraps any broker; client connects remotely.

**Server:**

```rust
use daimon::distributed::{InProcessBroker, GrpcBrokerServer};

let broker = InProcessBroker::new(64);
GrpcBrokerServer::new(broker)
    .serve("[::1]:50051")
    .await?;
```

**Client:**

```rust
use daimon::distributed::{GrpcBrokerClient, TaskBroker, AgentTask};

let client = GrpcBrokerClient::connect("http://[::1]:50051").await?;
let task_id = client.submit(AgentTask::new("Hello")).await?;
let status = client.status(&task_id).await?;
```

Note: `receive()` is not supported on `GrpcBrokerClient`. Workers must run on the server side, connected to the underlying broker.

---

### Cloud-Native Brokers

| Broker | Crate | Feature | Constructor |
|--------|-------|---------|-------------|
| **SqsBroker** | daimon-provider-bedrock | sqs | `SqsBroker::new(queue_url).await?` |
| **PubSubBroker** | daimon-provider-gemini | pubsub | `PubSubBroker::with_api_key(project, topic, sub, api_key)` or `with_bearer_token(...)` |
| **ServiceBusBroker** | daimon-provider-azure | servicebus | `ServiceBusBroker::new(namespace_url, queue_name, sas_token)` |

**SqsBroker** — AWS SQS. Uses visibility timeout for in-flight tracking. For FIFO queues, uses `message_group_id`.

```rust
use daimon_provider_bedrock::SqsBroker;
use daimon_core::distributed::{TaskBroker, AgentTask};

let broker = SqsBroker::new("https://sqs.us-east-1.amazonaws.com/123456789/daimon-tasks").await?;
broker.submit(AgentTask::new("Summarize")).await?;
```

**PubSubBroker** — Google Cloud Pub/Sub. Base64-encoded JSON in message bodies.

```rust
use daimon_provider_gemini::PubSubBroker;

let broker = PubSubBroker::with_api_key(
    "my-project",
    "daimon-tasks",
    "daimon-worker-sub",
    "api-key",
);
```

**ServiceBusBroker** — Azure Service Bus REST API. Peek-lock for receive; delete on complete.

```rust
use daimon_provider_azure::ServiceBusBroker;

let broker = ServiceBusBroker::new(
    "https://my-ns.servicebus.windows.net",
    "daimon-tasks",
    "SharedAccessKey...",
);
```

---

## TaskWorker

`TaskWorker` pulls tasks from a broker and executes them using agent instances from a factory.

```rust
use daimon::distributed::{TaskWorker, InProcessBroker, AgentTask};
use daimon::Agent;

let broker = InProcessBroker::new(64);
let worker = TaskWorker::new(broker.clone(), || {
    Agent::builder()
        .model(my_model)
        .build()
        .unwrap()
});

// Single task
let result = worker.run_once().await?;

// Indefinite loop
worker.run().await?;

// Parallel workers (up to N concurrent tasks)
worker.run_parallel(4).await?;
```

### run_once()

Waits for one task, executes it, reports the result. Returns `Ok(None)` if the broker is closed.

### Agent factory pattern

The factory closure `|| Agent { ... }` is called **once per task**. Each task gets a fresh agent so:

- Conversations do not bleed across tasks
- Memory is isolated per task
- No shared mutable state between tasks

### Worker loop example

```rust
loop {
    match worker.run_once().await? {
        Some(result) => {
            tracing::info!(task_id = %result.task_id, "completed: {} iterations", result.iterations);
        }
        None => {
            tracing::info!("broker closed, exiting");
            break;
        }
    }
}
```

---

## StreamingTaskWorker

`StreamingTaskWorker` uses `Agent::prompt_stream()` and publishes events through a `TaskEventBus`. Use when you need real-time visibility into agent execution across processes.

```rust
use daimon::distributed::streaming::*;
use daimon::distributed::{StreamingTaskWorker, InProcessBroker, AgentTask};

let broker = InProcessBroker::new(64);
let bus = InProcessEventBus::new(64);

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

// Subscribe before submitting
let mut rx = bus.subscribe();

// Run worker in background
tokio::spawn(async move { worker.run().await });

// Submit and receive live events
let task_id = broker.submit(AgentTask::new("Summarize")).await?;

while let Ok(evt) = rx.recv().await {
    if evt.task_id == task_id {
        match &evt.event {
            SerializableStreamEvent::TextDelta(t) => print!("{t}"),
            SerializableStreamEvent::ToolCallStart { name, .. } => println!("Calling {name}"),
            SerializableStreamEvent::Done => break,
            _ => {}
        }
    }
}
```

### InProcessEventBus

`InProcessEventBus::new(capacity)` — tokio broadcast channel. All subscribers receive every event. For cross-process streaming, implement `TaskEventBus` over Redis Pub/Sub, NATS, etc.

### SerializableStreamEvent

Wire format for stream events:

- `TextDelta(String)`
- `ToolCallStart { id, name }`
- `ToolCallDelta { id, arguments_delta }`
- `ToolCallEnd { id }`
- `ToolResult { id, content, is_error }`
- `Usage { iteration, input_tokens, output_tokens, estimated_cost }`
- `Error(String)`
- `Done`

---

## Checkpoint & State Persistence

### Checkpoint Trait

```rust
pub trait Checkpoint: Send + Sync {
    async fn save(&self, state: &CheckpointState) -> Result<()>;
    async fn load(&self, run_id: &str) -> Result<Option<CheckpointState>>;
    async fn list_runs(&self) -> Result<Vec<String>>;
    async fn delete(&self, run_id: &str) -> Result<()>;
}
```

### Implementations

| Implementation | Feature | Use Case |
|----------------|---------|----------|
| `InMemoryCheckpoint` | (built-in) | Ephemeral, testing |
| `FileCheckpoint::new(dir)` | (built-in) | JSON files on disk |
| `RedisCheckpoint::new(url, prefix)` | redis | Shared, multi-process |
| `NatsKvCheckpoint::connect(url, bucket)` | nats | JetStream KV |

```rust
use daimon::checkpoint::{InMemoryCheckpoint, FileCheckpoint, RedisCheckpoint, NatsKvCheckpoint};

let mem = InMemoryCheckpoint::new();
let file = FileCheckpoint::new("/var/daimon/checkpoints");
let redis = RedisCheckpoint::new("redis://127.0.0.1/", "daimon:checkpoints").await?;
let nats = NatsKvCheckpoint::connect("nats://127.0.0.1:4222", "daimon-checkpoints").await?;
```

### CheckpointState

```rust
pub struct CheckpointState {
    pub run_id: String,
    pub messages: Vec<Message>,
    pub iteration: usize,
    pub completed: bool,
    pub metadata: HashMap<String, serde_json::Value>,
    pub created_at: u64,
}
```

### CheckpointSync

Write-through to local + remote. Load prefers local, falls back to remote and backfills local.

```rust
use daimon::checkpoint::{InMemoryCheckpoint, FileCheckpoint, CheckpointSync};

let local = InMemoryCheckpoint::new();
let remote = FileCheckpoint::new("/shared/nfs/checkpoints");
let synced = CheckpointSync::new(local, remote);

// Use synced as the checkpoint backend
let agent = Agent::builder()
    .model(model)
    .checkpoint(synced)
    .build()?;
```

### CheckpointReplicator

Background task that periodically pulls from remote into local.

```rust
use daimon::checkpoint::{InMemoryCheckpoint, FileCheckpoint, CheckpointReplicator};
use std::sync::Arc;

let local = Arc::new(InMemoryCheckpoint::new());
let remote = Arc::new(FileCheckpoint::new("/shared/checkpoints"));

let replicator = CheckpointReplicator::new(
    local.clone() as Arc<dyn ErasedCheckpoint>,
    remote.clone() as Arc<dyn ErasedCheckpoint>,
    std::time::Duration::from_secs(30),
);

tokio::spawn(replicator.run());
```

### Bulk sync

- `CheckpointSync::pull_all()` — pull all remote checkpoints into local
- `CheckpointSync::push_all()` — push all local checkpoints to remote

---

## Time-Travel Debugging

### inspect_run

Reconstructs an execution trace from checkpoint data.

```rust
use daimon::checkpoint::{inspect_run, ExecutionTrace, RunSummary};

let trace: ExecutionTrace = inspect_run(checkpoint, run_id).await?;

println!("Run {}: {} iterations, completed={}", trace.run_id, trace.total_iterations, trace.completed);
for step in &trace.steps {
    println!("  Iteration {}: {} tool calls", step.iteration, step.tool_calls.len());
}
```

### list_runs

Lists all checkpointed runs with metadata.

```rust
let summaries: Vec<RunSummary> = list_runs(checkpoint).await?;
for s in &summaries {
    println!("{}: iter={}, completed={}, messages={}", s.run_id, s.iteration, s.completed, s.message_count);
}
```

### ExecutionTrace

- `run_id`, `steps`, `completed`, `total_iterations`
- `TraceStep`: `iteration`, `messages`, `tool_calls`, `response_text`, `usage`
- `final_text()`, `total_tool_calls()` helpers

---

## Agent Replay

Re-run an agent from a previous checkpoint with the current agent config (model, tools, system prompt). Useful for "what-if" debugging.

```rust
// Replay from the beginning of the checkpoint
let response = agent.replay(run_id, &checkpoint, None).await?;

// Replay from a specific iteration (truncate messages to that point)
let response = agent.replay(run_id, &checkpoint, Some(3)).await?;
```

- `from_iteration: None` — replay from the start of the checkpoint's message history
- `from_iteration: Some(n)` — truncate to iteration `n` and re-run

Modify the agent (tools, system prompt, model) before calling `replay` to see how the outcome changes.

---

## Choosing a Broker

| Scenario | Broker |
|---------|--------|
| Single process / testing | `InProcessBroker` |
| Redis already in stack | `RedisBroker` |
| Event streaming, durable delivery | `NatsBroker` |
| Enterprise messaging | `AmqpBroker` |
| Microservices, RPC-style | `GrpcBrokerClient` / `GrpcBrokerServer` |
| AWS native | `SqsBroker` |
| GCP native | `PubSubBroker` |
| Azure native | `ServiceBusBroker` |

---

## Full Example: Redis

```rust
use daimon::distributed::{RedisBroker, TaskWorker, TaskBroker, AgentTask, TaskStatus};
use daimon::Agent;

#[tokio::main]
async fn main() -> daimon::error::Result<()> {
    tracing_subscriber::fmt::init();

    let broker = RedisBroker::new("redis://127.0.0.1/", "daimon:tasks").await?;
    let broker_clone = broker.clone();

    let worker = TaskWorker::new(broker_clone, || {
        Agent::builder()
            .model(/* your model */)
            .build()
            .unwrap()
    });

    // Producer: submit tasks
    let task_id = broker
        .submit(AgentTask::new("Summarize the key points of distributed systems"))
        .await?;
    println!("Submitted task: {}", task_id);

    // Worker: process (run in same process for demo; in production, run in separate process)
    if let Some(result) = worker.run_once().await? {
        println!("Completed: {} iterations, output: {}", result.iterations, result.output);
    }

    // Poll status
    let status = broker.status(&task_id).await?;
    match &status {
        TaskStatus::Completed(r) => println!("Result: {}", r.output),
        TaskStatus::Failed(e) => eprintln!("Failed: {}", e),
        _ => println!("Still pending or running"),
    }

    Ok(())
}
```

---

## Full Example: NATS

```rust
use daimon::distributed::{NatsBroker, TaskWorker, TaskBroker, AgentTask};
use daimon::Agent;

#[tokio::main]
async fn main() -> daimon::error::Result<()> {
    tracing_subscriber::fmt::init();

    let broker = NatsBroker::connect("nats://127.0.0.1:4222", "daimon-tasks").await?;
    let broker_clone = broker.clone();

    let worker = TaskWorker::new(broker_clone, || {
        Agent::builder()
            .model(/* your model */)
            .build()
            .unwrap()
    });

    // Submit
    let task_id = broker.submit(AgentTask::new("What is NATS?")).await?;
    println!("Submitted: {}", task_id);

    // Worker loop
    loop {
        match worker.run_once().await? {
            Some(result) => {
                println!("Task {}: {} iterations", result.task_id, result.iterations);
                if let Some(e) = &result.error {
                    eprintln!("Error: {}", e);
                }
            }
            None => {
                tracing::info!("No more tasks (broker closed)");
                break;
            }
        }
    }

    Ok(())
}
```

---

## Cargo Features

Enable the broker you need:

```toml
[dependencies]
daimon = { version = "0.16", features = ["redis"] }   # RedisBroker
daimon = { version = "0.16", features = ["nats"] }     # NatsBroker
daimon = { version = "0.16", features = ["amqp"] }     # AmqpBroker
daimon = { version = "0.16", features = ["grpc"] }     # GrpcBrokerServer/Client
daimon = { version = "0.16", features = ["sqs"] }      # SqsBroker (via daimon-provider-bedrock)
daimon = { version = "0.16", features = ["pubsub"] }   # PubSubBroker (via daimon-provider-gemini)
daimon = { version = "0.16", features = ["servicebus"] }  # ServiceBusBroker (via daimon-provider-azure)
```

InProcessBroker is always available (no feature).