roboticus-agent 0.11.4

Agent core with ReAct loop, policy engine, injection defense, memory system, and skill loader
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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use chrono::{DateTime, Utc};
use roboticus_core::{Result, RoboticusError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info, warn};

/// Orchestration pattern for multi-agent coordination.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OrchestrationPattern {
    Sequential,
    Parallel,
    FanOutFanIn,
    Handoff,
}

impl std::fmt::Display for OrchestrationPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OrchestrationPattern::Sequential => write!(f, "sequential"),
            OrchestrationPattern::Parallel => write!(f, "parallel"),
            OrchestrationPattern::FanOutFanIn => write!(f, "fan-out/fan-in"),
            OrchestrationPattern::Handoff => write!(f, "handoff"),
        }
    }
}

/// A subtask assigned to a specialist agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subtask {
    pub id: String,
    pub description: String,
    pub required_capabilities: Vec<String>,
    #[serde(default)]
    pub model_preference: Option<String>,
    pub assigned_agent: Option<String>,
    pub status: SubtaskStatus,
    pub result: Option<String>,
    pub created_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
}

/// Status of a subtask.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SubtaskStatus {
    Pending,
    Assigned,
    Running,
    Completed,
    Failed,
}

/// A workflow composed of subtasks with an orchestration pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workflow {
    pub id: String,
    pub name: String,
    pub pattern: OrchestrationPattern,
    pub subtasks: Vec<Subtask>,
    pub status: WorkflowStatus,
    pub created_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
}

/// Status of a workflow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkflowStatus {
    Created,
    Running,
    Completed,
    Failed,
    Cancelled,
}

/// Coordinates workflows and agent assignment.
pub struct Orchestrator {
    workflows: HashMap<String, Workflow>,
    workflow_counter: u64,
}

impl Orchestrator {
    pub fn new() -> Self {
        Self {
            workflows: HashMap::new(),
            workflow_counter: 0,
        }
    }

    /// Create a new workflow from subtask descriptions.
    pub fn create_workflow(
        &mut self,
        name: &str,
        pattern: OrchestrationPattern,
        subtasks: Vec<(String, Vec<String>)>,
    ) -> String {
        self.workflow_counter += 1;
        let workflow_id = format!("wf_{}", self.workflow_counter);

        let tasks: Vec<Subtask> = subtasks
            .into_iter()
            .enumerate()
            .map(|(i, (desc, caps))| Subtask {
                id: format!("{}_task_{}", workflow_id, i),
                description: desc,
                required_capabilities: caps,
                model_preference: None,
                assigned_agent: None,
                status: SubtaskStatus::Pending,
                result: None,
                created_at: Utc::now(),
                completed_at: None,
            })
            .collect();

        let workflow = Workflow {
            id: workflow_id.clone(),
            name: name.to_string(),
            pattern,
            subtasks: tasks,
            status: WorkflowStatus::Created,
            created_at: Utc::now(),
            completed_at: None,
        };

        info!(id = %workflow_id, name, pattern = %pattern, tasks = workflow.subtasks.len(), "created workflow");
        self.workflows.insert(workflow_id.clone(), workflow);
        workflow_id
    }

    /// Create a workflow where each task can optionally request a model.
    pub fn create_workflow_with_model_preferences(
        &mut self,
        name: &str,
        pattern: OrchestrationPattern,
        subtasks: Vec<(String, Vec<String>, Option<String>)>,
    ) -> String {
        self.workflow_counter += 1;
        let workflow_id = format!("wf_{}", self.workflow_counter);

        let tasks: Vec<Subtask> = subtasks
            .into_iter()
            .enumerate()
            .map(|(i, (desc, caps, model_pref))| Subtask {
                id: format!("{}_task_{}", workflow_id, i),
                description: desc,
                required_capabilities: caps,
                model_preference: model_pref,
                assigned_agent: None,
                status: SubtaskStatus::Pending,
                result: None,
                created_at: Utc::now(),
                completed_at: None,
            })
            .collect();

        let workflow = Workflow {
            id: workflow_id.clone(),
            name: name.to_string(),
            pattern,
            subtasks: tasks,
            status: WorkflowStatus::Created,
            created_at: Utc::now(),
            completed_at: None,
        };

        info!(
            id = %workflow_id,
            name,
            pattern = %pattern,
            tasks = workflow.subtasks.len(),
            "created workflow with model preferences"
        );
        self.workflows.insert(workflow_id.clone(), workflow);
        workflow_id
    }

    /// Assign an agent to a subtask.
    pub fn assign_agent(&mut self, workflow_id: &str, task_id: &str, agent_id: &str) -> Result<()> {
        let workflow = self.workflows.get_mut(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        let task = workflow
            .subtasks
            .iter_mut()
            .find(|t| t.id == task_id)
            .ok_or_else(|| RoboticusError::Config(format!("task '{}' not found", task_id)))?;

        task.assigned_agent = Some(agent_id.to_string());
        task.status = SubtaskStatus::Assigned;
        debug!(
            workflow = workflow_id,
            task = task_id,
            agent = agent_id,
            "agent assigned"
        );
        Ok(())
    }

    /// Set or clear a model preference for a specific task.
    pub fn set_task_model_preference(
        &mut self,
        workflow_id: &str,
        task_id: &str,
        model_preference: Option<String>,
    ) -> Result<()> {
        let workflow = self.workflows.get_mut(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;
        let task = workflow
            .subtasks
            .iter_mut()
            .find(|t| t.id == task_id)
            .ok_or_else(|| RoboticusError::Config(format!("task '{}' not found", task_id)))?;
        task.model_preference = model_preference;
        Ok(())
    }

    /// Match subtasks to available agents by capability overlap.
    pub fn match_capabilities(
        &self,
        workflow_id: &str,
        available_agents: &[(String, Vec<String>)],
    ) -> Result<Vec<(String, String)>> {
        let workflow = self.workflows.get(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        let mut assignments = Vec::new();

        for task in &workflow.subtasks {
            if task.status != SubtaskStatus::Pending {
                continue;
            }

            let best_agent = available_agents.iter().max_by_key(|(_, caps)| {
                task.required_capabilities
                    .iter()
                    .filter(|rc| caps.contains(rc))
                    .count()
            });

            if let Some((agent_id, caps)) = best_agent {
                let overlap = task
                    .required_capabilities
                    .iter()
                    .filter(|rc| caps.contains(rc))
                    .count();
                if overlap > 0 {
                    assignments.push((task.id.clone(), agent_id.clone()));
                }
            }
        }

        Ok(assignments)
    }

    /// Start a subtask.
    pub fn start_task(&mut self, workflow_id: &str, task_id: &str) -> Result<()> {
        let workflow = self.workflows.get_mut(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        let task = workflow
            .subtasks
            .iter_mut()
            .find(|t| t.id == task_id)
            .ok_or_else(|| RoboticusError::Config(format!("task '{}' not found", task_id)))?;

        task.status = SubtaskStatus::Running;
        workflow.status = WorkflowStatus::Running;
        Ok(())
    }

    /// Complete a subtask with a result.
    pub fn complete_task(
        &mut self,
        workflow_id: &str,
        task_id: &str,
        result: String,
    ) -> Result<()> {
        let workflow = self.workflows.get_mut(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        let task = workflow
            .subtasks
            .iter_mut()
            .find(|t| t.id == task_id)
            .ok_or_else(|| RoboticusError::Config(format!("task '{}' not found", task_id)))?;

        task.status = SubtaskStatus::Completed;
        task.result = Some(result);
        task.completed_at = Some(Utc::now());

        if workflow
            .subtasks
            .iter()
            .all(|t| t.status == SubtaskStatus::Completed)
        {
            workflow.status = WorkflowStatus::Completed;
            workflow.completed_at = Some(Utc::now());
            info!(id = %workflow_id, "workflow completed");
        }

        Ok(())
    }

    /// Fail a subtask.
    pub fn fail_task(&mut self, workflow_id: &str, task_id: &str, error: &str) -> Result<()> {
        let workflow = self.workflows.get_mut(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        let task = workflow
            .subtasks
            .iter_mut()
            .find(|t| t.id == task_id)
            .ok_or_else(|| RoboticusError::Config(format!("task '{}' not found", task_id)))?;

        task.status = SubtaskStatus::Failed;
        task.result = Some(format!("ERROR: {}", error));
        task.completed_at = Some(Utc::now());

        workflow.status = WorkflowStatus::Failed;
        warn!(workflow = workflow_id, task = task_id, error, "task failed");
        Ok(())
    }

    /// Get a workflow by ID.
    pub fn get_workflow(&self, id: &str) -> Option<&Workflow> {
        self.workflows.get(id)
    }

    /// Get the next actionable tasks for a workflow based on its pattern.
    pub fn next_tasks(&self, workflow_id: &str) -> Result<Vec<&Subtask>> {
        let workflow = self.workflows.get(workflow_id).ok_or_else(|| {
            RoboticusError::Config(format!("workflow '{}' not found", workflow_id))
        })?;

        match workflow.pattern {
            OrchestrationPattern::Sequential => Ok(workflow
                .subtasks
                .iter()
                .find(|t| t.status == SubtaskStatus::Pending || t.status == SubtaskStatus::Assigned)
                .into_iter()
                .collect()),
            OrchestrationPattern::Parallel | OrchestrationPattern::FanOutFanIn => Ok(workflow
                .subtasks
                .iter()
                .filter(|t| {
                    t.status == SubtaskStatus::Pending || t.status == SubtaskStatus::Assigned
                })
                .collect()),
            OrchestrationPattern::Handoff => {
                let last_completed = workflow
                    .subtasks
                    .iter()
                    .rposition(|t| t.status == SubtaskStatus::Completed);
                let start_idx = last_completed.map(|i| i + 1).unwrap_or(0);
                // Skip past any Failed tasks to find the next actionable one
                Ok(workflow.subtasks[start_idx..]
                    .iter()
                    .find(|t| {
                        t.status == SubtaskStatus::Pending || t.status == SubtaskStatus::Assigned
                    })
                    .into_iter()
                    .collect())
            }
        }
    }

    pub fn workflow_count(&self) -> usize {
        self.workflows.len()
    }
}

impl Default for Orchestrator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_tasks() -> Vec<(String, Vec<String>)> {
        vec![
            ("Research the topic".into(), vec!["research".into()]),
            ("Write the summary".into(), vec!["summarization".into()]),
            ("Review the output".into(), vec!["review".into()]),
        ]
    }

    #[test]
    fn create_workflow() {
        let mut orch = Orchestrator::new();
        let id = orch.create_workflow(
            "Test Flow",
            OrchestrationPattern::Sequential,
            simple_tasks(),
        );
        assert!(id.starts_with("wf_"));
        let wf = orch.get_workflow(&id).unwrap();
        assert_eq!(wf.subtasks.len(), 3);
        assert_eq!(wf.status, WorkflowStatus::Created);
        assert!(wf.subtasks.iter().all(|t| t.model_preference.is_none()));
    }

    #[test]
    fn create_workflow_with_model_preferences() {
        let mut orch = Orchestrator::new();
        let id = orch.create_workflow_with_model_preferences(
            "Model Aware Flow",
            OrchestrationPattern::Parallel,
            vec![
                (
                    "Draft summary".into(),
                    vec!["summarization".into()],
                    Some("ollama/qwen3:8b".into()),
                ),
                ("Review output".into(), vec!["review".into()], None),
            ],
        );
        let wf = orch.get_workflow(&id).unwrap();
        assert_eq!(
            wf.subtasks[0].model_preference.as_deref(),
            Some("ollama/qwen3:8b")
        );
        assert!(wf.subtasks[1].model_preference.is_none());
    }

    #[test]
    fn assign_and_start() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Test", OrchestrationPattern::Sequential, simple_tasks());
        let task_id = orch.get_workflow(&wf_id).unwrap().subtasks[0].id.clone();

        orch.assign_agent(&wf_id, &task_id, "agent-research")
            .unwrap();
        let task = &orch.get_workflow(&wf_id).unwrap().subtasks[0];
        assert_eq!(task.status, SubtaskStatus::Assigned);
        assert_eq!(task.assigned_agent.as_deref(), Some("agent-research"));

        orch.start_task(&wf_id, &task_id).unwrap();
        assert_eq!(
            orch.get_workflow(&wf_id).unwrap().subtasks[0].status,
            SubtaskStatus::Running
        );
    }

    #[test]
    fn set_task_model_preference_updates_task() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow(
            "Model Edit",
            OrchestrationPattern::Sequential,
            simple_tasks(),
        );
        let task_id = orch.get_workflow(&wf_id).unwrap().subtasks[0].id.clone();
        orch.set_task_model_preference(&wf_id, &task_id, Some("openai/gpt-4o".into()))
            .unwrap();
        let task = &orch.get_workflow(&wf_id).unwrap().subtasks[0];
        assert_eq!(task.model_preference.as_deref(), Some("openai/gpt-4o"));
    }

    #[test]
    fn complete_workflow() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Test", OrchestrationPattern::Parallel, simple_tasks());
        let task_ids: Vec<String> = orch
            .get_workflow(&wf_id)
            .unwrap()
            .subtasks
            .iter()
            .map(|t| t.id.clone())
            .collect();

        for tid in &task_ids {
            orch.complete_task(&wf_id, tid, "done".into()).unwrap();
        }

        let wf = orch.get_workflow(&wf_id).unwrap();
        assert_eq!(wf.status, WorkflowStatus::Completed);
        assert!(wf.completed_at.is_some());
    }

    #[test]
    fn fail_task_fails_workflow() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Test", OrchestrationPattern::Sequential, simple_tasks());
        let task_id = orch.get_workflow(&wf_id).unwrap().subtasks[0].id.clone();

        orch.fail_task(&wf_id, &task_id, "something broke").unwrap();
        assert_eq!(
            orch.get_workflow(&wf_id).unwrap().status,
            WorkflowStatus::Failed
        );
    }

    #[test]
    fn sequential_next_tasks() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Seq", OrchestrationPattern::Sequential, simple_tasks());

        let next = orch.next_tasks(&wf_id).unwrap();
        assert_eq!(next.len(), 1);
        assert_eq!(next[0].description, "Research the topic");
    }

    #[test]
    fn parallel_next_tasks() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Par", OrchestrationPattern::Parallel, simple_tasks());

        let next = orch.next_tasks(&wf_id).unwrap();
        assert_eq!(next.len(), 3);
    }

    #[test]
    fn capability_matching() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Match", OrchestrationPattern::Parallel, simple_tasks());

        let agents = vec![
            (
                "researcher".into(),
                vec!["research".into(), "analysis".into()],
            ),
            (
                "writer".into(),
                vec!["summarization".into(), "writing".into()],
            ),
        ];

        let matches = orch.match_capabilities(&wf_id, &agents).unwrap();
        assert!(!matches.is_empty());
    }

    #[test]
    fn pattern_display() {
        assert_eq!(
            format!("{}", OrchestrationPattern::Sequential),
            "sequential"
        );
        assert_eq!(format!("{}", OrchestrationPattern::Parallel), "parallel");
        assert_eq!(
            format!("{}", OrchestrationPattern::FanOutFanIn),
            "fan-out/fan-in"
        );
        assert_eq!(format!("{}", OrchestrationPattern::Handoff), "handoff");
    }

    #[test]
    fn pattern_serde() {
        for pattern in [
            OrchestrationPattern::Sequential,
            OrchestrationPattern::Parallel,
            OrchestrationPattern::FanOutFanIn,
            OrchestrationPattern::Handoff,
        ] {
            let json = serde_json::to_string(&pattern).unwrap();
            let back: OrchestrationPattern = serde_json::from_str(&json).unwrap();
            assert_eq!(pattern, back);
        }
    }

    #[test]
    fn handoff_skips_failed_tasks() {
        let mut orch = Orchestrator::new();
        let wf_id = orch.create_workflow("Handoff", OrchestrationPattern::Handoff, simple_tasks());
        let task_ids: Vec<String> = orch
            .get_workflow(&wf_id)
            .unwrap()
            .subtasks
            .iter()
            .map(|t| t.id.clone())
            .collect();

        // Complete first task, fail second
        orch.complete_task(&wf_id, &task_ids[0], "done".into())
            .unwrap();
        orch.fail_task(&wf_id, &task_ids[1], "broken").unwrap();

        // Handoff should skip the Failed task and return the third (Pending) task
        let next = orch.next_tasks(&wf_id).unwrap();
        assert_eq!(next.len(), 1);
        assert_eq!(next[0].description, "Review the output");
    }

    #[test]
    fn workflow_not_found() {
        let orch = Orchestrator::new();
        assert!(orch.get_workflow("nope").is_none());
        assert!(orch.next_tasks("nope").is_err());
    }
}