agent-orchestrator-sdk 0.1.1

Rust SDK for orchestrating LLM-powered agents, shared task execution, and teammate coordination
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
# agent-orchestrator-sdk

Orchestrate teams of LLM-powered agents in Rust. Coordinate multiple agent instances working together — one session acts as the team lead, coordinating work and assigning tasks. Teammates work independently, each with its own context, and communicate directly with each other.

The package is published as `agent-orchestrator-sdk` and imported in Rust code as `agent_sdk`.
Additional usage docs live under `docs/` in the repository.

## When to use agent teams

Agent teams are most effective when parallel exploration adds real value:

- **Research and review**: multiple teammates investigate different aspects simultaneously, then share and challenge findings
- **New modules or features**: teammates each own a separate piece without stepping on each other
- **Debugging with competing hypotheses**: teammates test different theories in parallel
- **Cross-layer coordination**: changes spanning frontend, backend, and tests — each owned by a different teammate

Agent teams use more tokens than a single session. For sequential tasks, same-file edits, or highly dependent work, a single `AgentLoop` is more effective.

### Compare: single agent vs agent team

| | Single Agent (`AgentLoop`) | Agent Team (`AgentTeam`) |
|:--|:--|:--|
| **Context** | One context window | Each teammate has its own context |
| **Communication** | N/A | Teammates message each other directly |
| **Coordination** | Sequential tool calls | Shared task list with self-coordination |
| **Best for** | Focused tasks, quick operations | Complex work requiring parallel exploration |
| **Token cost** | Lower | Higher: each teammate is a separate agent |

## Quick start

```toml
# Cargo.toml
[dependencies]
agent-orchestrator-sdk = "0.1"
tokio = { version = "1", features = ["full"] }
```

```bash
export ANTHROPIC_API_KEY="sk-ant-..."  # or OPENAI_API_KEY
```

### Start your first agent team

Create a team, describe the teammates you want, add tasks, and run. The lead spawns teammates, they claim work from the shared task list, and coordinate on their own:

```rust
use agent_sdk::agent::team::AgentTeam;
use agent_sdk::config::{LlmConfig, AgentConfig};
use agent_sdk::types::task::Task;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let task1 = Task::new("gen", "Create config module", "...", "src/config.rs");
    let task2 = Task::new("gen", "Create server module", "...", "src/server.rs")
        .with_dependencies(vec![task1.id]);

    let result = AgentTeam::new(LlmConfig::default(), AgentConfig::default())
        .source_root(".")
        .work_dir("./output")
        .add_teammate("backend-dev", "You build Rust backend modules")
        .add_teammate("reviewer", "You review code for correctness")
        .add_task(task1)
        .add_task(task2)
        .run("Build a server project")
        .await?;

    println!("Tokens used: {}", result.total_tokens());
    Ok(())
}
```

For simple tasks that don't need a team, use `run_single`:

```rust
let result = AgentTeam::new(LlmConfig::default(), AgentConfig::default())
    .run_single("Explain this codebase")
    .await?;
println!("{}", result.final_content);
```

### Interactive CLI

```bash
cargo run --bin agent                          # REPL mode
cargo run --bin agent -- "explain this code"   # One-shot
cargo run --bin agent -- -p openai -m gpt-4o   # OpenAI
cargo run --bin agent -- --allow-all-commands   # Unrestricted shell
```

## Architecture

```
          ┌─────────────────────────────────────────────┐
          │                 Team Lead                    │
          │  Spawns teammates, coordinates work,        │
          │  approves plans, routes messages             │
          └──────────┬──────────────┬───────────────────┘
                     │              │
               ┌─────▼────┐  ┌─────▼────┐
               │Teammate 1│  │Teammate 2│  ... (N parallel)
               │AgentLoop │  │AgentLoop │
               └─────┬────┘  └─────┬────┘
                     │              │
                     │    ┌─────────┘    Teammates can
                     │    │              message each other
               ┌─────▼────▼──────────────────────────┐
               │          Shared Services             │
               │  TaskStore · MemoryStore · Mailbox   │
               └─────────────────────────────────────┘
```

An agent team consists of:

| Component | Role |
|:--|:--|
| **Team lead** | The main session that creates the team, spawns teammates, and coordinates work |
| **Teammates** | Separate agent instances that each work on assigned tasks independently |
| **Task list** | Shared list of work items that teammates claim and complete |
| **Mailbox** | Messaging system for communication between all agents |
| **Memory** | Shared key-value store for inter-agent coordination |

The lead is the intelligence — there is no separate planning step. You tell it what you want and it coordinates the team, just like Claude Code's agent teams.

## Control your agent team

### Specify teammates and roles

Each teammate gets its own context window and works independently:

```rust
AgentTeam::new(LlmConfig::default(), AgentConfig::default())
    .add_teammate("security-reviewer", "Review for security vulnerabilities")
    .add_teammate("perf-reviewer", "Review for performance issues")
    .add_teammate("test-checker", "Validate test coverage")
```

### Add tasks with dependencies

Tasks are claimed by teammates from a shared task list. Dependencies are resolved automatically — blocked tasks unblock when their dependencies complete:

```rust
let schema = Task::new("analyze", "Parse API schema", "...", "schema.json")
    .with_priority(0);

let client = Task::new("codegen", "Generate client", "...", "client.rs")
    .with_dependencies(vec![schema.id])  // waits for schema
    .with_priority(1);

let tests = Task::new("test", "Write tests", "...", "tests.rs")
    .with_dependencies(vec![client.id])
    .with_priority(2);
```

Task claiming uses file locking to prevent race conditions when multiple teammates try to claim the same task.

### Require plan approval

For complex or risky work, require teammates to plan before implementing:

```rust
AgentTeam::new(LlmConfig::default(), AgentConfig::default())
    .add_teammate_with_plan_approval(
        "architect",
        "Refactor the authentication module"
    )
```

The teammate generates a plan, sends it to the lead for review. The lead evaluates using the LLM and either approves (teammate implements) or rejects with feedback (teammate revises).

### Teammate-to-teammate messaging

Teammates communicate directly through the message broker — not just through the lead:

```rust
use agent_sdk::types::message::*;

// Direct message to another teammate
let msg = Envelope::new(my_id, MessageTarget::Agent(other_id), MessageKind::TeammateMessage)
    .with_payload(serde_json::json!({ "content": "Found an issue in auth.rs" }));
broker.route(&msg)?;

// Broadcast to all teammates
let broadcast = Envelope::new(my_id, MessageTarget::Broadcast, MessageKind::ContextShare)
    .with_payload(serde_json::json!({ "topic": "conventions", "content": "Use snake_case" }));
broker.route(&broadcast)?;
```

### Shutdown negotiation

When the lead requests shutdown, teammates can accept or reject:

- **Accept**: teammate is idle, shuts down gracefully
- **Reject**: teammate is still working, provides a reason and keeps going

### Enforce quality gates with hooks

Hooks run at key points in the agent lifecycle. Return `Reject` to block an action and send feedback:

```rust
use agent_sdk::{Hook, HookEvent, HookResult};

struct RequireTestCoverage;

impl Hook for RequireTestCoverage {
    fn on_event(&self, event: &HookEvent) -> HookResult {
        match event {
            HookEvent::TaskCompleted { task, .. } => {
                if let Some(result) = &task.result {
                    if !result.notes.to_lowercase().contains("test") {
                        return HookResult::Reject {
                            feedback: "Must include test coverage".to_string(),
                        };
                    }
                }
                HookResult::Continue
            }
            HookEvent::TeammateIdle { tasks_completed, .. } if *tasks_completed == 0 => {
                HookResult::Reject { feedback: "Keep looking for work".to_string() }
            }
            _ => HookResult::Continue,
        }
    }
}
```

| Hook | When it fires | Reject effect |
|:--|:--|:--|
| `TeammateIdle` | Teammate has no more work | Keeps teammate active |
| `TaskCreated` | Task being added to store | Prevents task creation |
| `TaskCompleted` | Task being marked done | Prevents completion, task retries |

### Monitor agent events

Subscribe to events for logging, UI, or metrics:

```rust
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<AgentEvent>();

tokio::spawn(async move {
    while let Some(event) = rx.recv().await {
        match event {
            AgentEvent::TeammateSpawned { name, .. } => println!("+ {name}"),
            AgentEvent::TaskStarted { title, .. } => println!("> {title}"),
            AgentEvent::TaskCompleted { tokens_used, .. } => println!("  done ({tokens_used} tokens)"),
            AgentEvent::PlanSubmitted { plan_preview, .. } => println!("  plan: {plan_preview}"),
            AgentEvent::PlanApproved { .. } => println!("  approved"),
            AgentEvent::ShutdownRequested { .. } => println!("  shutting down"),
            _ => {}
        }
    }
});

let result = AgentTeam::new(LlmConfig::default(), AgentConfig::default())
    .event_channel(tx)
    // ...
    .run("...")
    .await?;
```

## Low-level API

### AgentLoop (single agent)

The building block underneath everything. Use it for full control:

```rust
use std::sync::Arc;
use agent_sdk::{AgentLoop, create_client, LlmConfig};
use agent_sdk::tools::registry::ToolRegistry;
use agent_sdk::tools::fs_tools::ReadFileTool;
use uuid::Uuid;

let client = create_client(&LlmConfig::default())?;
let mut tools = ToolRegistry::new();
tools.register(Arc::new(ReadFileTool { source_root: ".".into(), work_dir: ".".into() }));

let mut agent = AgentLoop::new(
    Uuid::new_v4(), client, tools,
    "You are a coding assistant.".to_string(), 50,
);
let result = agent.run("Summarize main.rs".to_string()).await?;
```

### Custom tools

Implement the `Tool` trait to give agents new capabilities:

```rust
use async_trait::async_trait;
use agent_sdk::{Tool, ToolDefinition, SdkResult};
use serde_json::json;

pub struct MyTool;

#[async_trait]
impl Tool for MyTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "my_tool".to_string(),
            description: "Does something useful".to_string(),
            parameters: json!({
                "type": "object",
                "properties": { "input": { "type": "string" } },
                "required": ["input"]
            }),
        }
    }

    async fn execute(&self, args: serde_json::Value) -> SdkResult<serde_json::Value> {
        let input = args["input"].as_str().unwrap_or("");
        Ok(json!({ "output": format!("processed: {input}") }))
    }
}
```

Add tools to teammates via `PromptBuilder::customize_tools`.

### TeamLead (direct control)

For full control over team orchestration:

```rust
use std::sync::Arc;
use agent_sdk::*;
use agent_sdk::config::AgentConfig;
use agent_sdk::agent::hooks::HookRegistry;
use agent_sdk::traits::prompt_builder::DefaultPromptBuilder;
use uuid::Uuid;

let lead = TeamLead {
    id: Uuid::new_v4(),
    task_store: Arc::new(TaskStore::new("./output".into())),
    broker: Arc::new(MessageBroker::new("./output/mailbox".into())?),
    llm_client: create_client(&LlmConfig::default())?,
    prompt_builder: Arc::new(DefaultPromptBuilder),
    config: AgentConfig::default(),
    source_root: ".".into(),
    work_dir: "./output".into(),
    memory_store: Arc::new(MemoryStore::new("./output/memory".into())?),
    event_tx: None,
    hooks: Arc::new(HookRegistry::new()),
    teammate_specs: vec![
        TeammateSpec { name: "worker-1".into(), prompt: "...".into(), require_plan_approval: false },
    ],
};
let summary = lead.run().await?;
```

## Built-in tools

| Tool | Description |
|:--|:--|
| `read_file` | Read file contents with optional offset/limit |
| `write_file` | Write/create files in the work directory |
| `list_directory` | List files and directories |
| `search_files` | Search by glob pattern and/or content regex |
| `run_command` | Execute shell commands (configurable whitelist) |
| `read_memory` / `write_memory` / `list_memory` | Shared key-value memory |
| `get_task_context` / `list_completed_tasks` | Inspect other agents' work |

## Configuration

### LlmConfig

```rust
LlmConfig {
    provider: LlmProvider::Claude,        // Claude or OpenAi
    model: "claude-sonnet-4-20250514".into(),
    max_tokens: 4096,
    requests_per_minute: 50,
    tokens_per_minute: 80_000,
    api_key: None,       // falls back to ANTHROPIC_API_KEY / OPENAI_API_KEY
    api_base_url: None,  // falls back to env or default
}
```

### AgentConfig

```rust
AgentConfig {
    max_parallel_agents: 4,      // concurrent teammates
    poll_interval_ms: 200,       // task polling interval
    max_task_retries: 3,         // retries before permanent failure
    max_loop_iterations: 50,     // max ReAct iterations per task
    max_context_tokens: 200_000, // context window budget
}
```

### Environment variables

| Variable | Description |
|:--|:--|
| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | API key (required) |
| `LLM_PROVIDER` | `claude` or `openai` (auto-detected from keys) |
| `LLM_MODEL` / `ANTHROPIC_MODEL` / `OPENAI_MODEL` | Model override |
| `ANTHROPIC_API_BASE_URL` / `OPENAI_API_BASE_URL` | Custom endpoint |

## Best practices

### Give teammates enough context

Teammates don't inherit the lead's conversation. Include details in task descriptions and context:

```rust
Task::new("review", "Security review", "Review src/auth/ for vulnerabilities...", "review.md")
    .with_context(json!({ "app_uses": "JWT in httpOnly cookies", "focus": ["token handling"] }))
```

### Choose appropriate team size

Start with 3-5 teammates. 5-6 tasks per teammate keeps everyone productive. Three focused teammates often outperform five scattered ones.

### Size tasks appropriately

- **Too small**: coordination overhead exceeds benefit
- **Too large**: teammates work too long without check-ins
- **Just right**: self-contained units that produce a clear deliverable

### Avoid file conflicts

Two teammates editing the same file leads to overwrites. Break work so each teammate owns different files.

## Examples

```bash
cargo run --example single_agent    # Direct AgentLoop with custom tools
cargo run --example multi_agent     # Team with tasks and dependencies
cargo run --example named_team      # Named teammates with roles + hooks + plan approval
```

## Project structure

```
src/
  lib.rs                # Public API re-exports
  config.rs             # LlmConfig, AgentConfig
  error.rs              # SdkError, TaskId, AgentId
  types/                # ChatMessage, Task, Envelope, MemoryEntry, FileChange
  traits/               # LlmClient, Tool, PromptBuilder traits
  llm/                  # Claude + OpenAI clients, rate limiter
  agent/
    team.rs             # AgentTeam — high-level entry point
    team_lead.rs        # TeamLead orchestrator
    teammate.rs         # Teammate worker (plan mode, shutdown negotiation)
    agent_loop.rs       # ReAct loop (Reason + Act)
    hooks.rs            # Hook system (TeammateIdle, TaskCreated, TaskCompleted)
    events.rs           # AgentEvent enum
    context.rs          # Per-agent context
    memory.rs           # MemoryStore
  task/                 # TaskStore, dependency graph, file locking
  mailbox/              # MessageBroker, file-based mailboxes
  tools/                # Built-in tools (fs, search, command, memory, context)
  bin/agent.rs          # Interactive CLI
examples/
  single_agent.rs       # Direct AgentLoop usage
  multi_agent.rs        # Team with tasks
  named_team.rs         # Named teammates + hooks + plan approval
```

## License

MIT