oxi-sdk 0.25.8

oxi AI agent SDK — build isolated, multi-agent AI systems
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
//! Work queue — distributed task queue for inter-agent coordination.

use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::broadcast;

/// Unique work item ID type.
type WorkId = String;

/// A unit of work in the queue.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkItem {
    /// Unique identifier.
    pub id: WorkId,
    /// Work type (for filtering).
    pub work_type: String,
    /// Payload for the worker.
    pub payload: serde_json::Value,
    /// Priority (higher = more urgent).
    pub priority: i32,
    /// Current status.
    pub status: WorkStatus,
    /// Agent that claimed this item.
    pub claimed_by: Option<String>,
    /// Execution result.
    pub result: Option<WorkResult>,
    /// Creation timestamp.
    pub created_at_ms: u64,
    /// Claim timestamp.
    pub claimed_at_ms: Option<u64>,
    /// Completion timestamp.
    pub completed_at_ms: Option<u64>,
    /// Maximum retries.
    pub max_retries: usize,
    /// Current retry count.
    pub retry_count: usize,
}

/// Status of a work item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkStatus {
    Pending,
    Claimed,
    InProgress,
    Completed,
    Failed,
    Cancelled,
}

/// Result of work item execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkResult {
    pub success: bool,
    pub content: String,
    pub error: Option<String>,
    pub duration_ms: u64,
    pub tokens_used: Option<u64>,
}

/// Events emitted by the work queue.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkEvent {
    Enqueued { id: WorkId, work_type: String },
    Claimed { id: WorkId, agent_id: String },
    Started { id: WorkId },
    Completed { id: WorkId, success: bool },
    Cancelled { id: WorkId },
}

/// Queue statistics.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkQueueStats {
    pub pending: usize,
    pub claimed: usize,
    pub in_progress: usize,
    pub completed: usize,
    pub failed: usize,
    pub cancelled: usize,
}

/// Configuration for the work queue.
#[derive(Debug, Clone)]
pub struct WorkQueueConfig {
    /// Maximum items in the queue before eviction.
    pub max_items: usize,
}

impl Default for WorkQueueConfig {
    fn default() -> Self {
        Self { max_items: 10_000 }
    }
}

/// In-memory work queue with priority-based atomic claim.
pub struct WorkQueue {
    items: Arc<RwLock<HashMap<WorkId, WorkItem>>>,
    next_id: AtomicU64,
    #[allow(dead_code)]
    config: WorkQueueConfig,
    tx: broadcast::Sender<WorkEvent>,
}

impl WorkQueue {
    /// Create a new work queue.
    pub fn new(config: WorkQueueConfig) -> Self {
        let (tx, _) = broadcast::channel(256);
        Self {
            items: Arc::new(RwLock::new(HashMap::new())),
            next_id: AtomicU64::new(1),
            config,
            tx,
        }
    }

    /// Enqueue a new work item. Returns its ID.
    pub fn enqueue(
        &self,
        work_type: impl Into<String>,
        payload: serde_json::Value,
        priority: i32,
    ) -> WorkId {
        let id = format!("wq-{}", self.next_id.fetch_add(1, Ordering::SeqCst));
        let item = WorkItem {
            id: id.clone(),
            work_type: work_type.into(),
            payload,
            priority,
            status: WorkStatus::Pending,
            claimed_by: None,
            result: None,
            created_at_ms: now_ms(),
            claimed_at_ms: None,
            completed_at_ms: None,
            max_retries: 3,
            retry_count: 0,
        };
        self.items.write().insert(id.clone(), item);
        let _ = self.tx.send(WorkEvent::Enqueued {
            id: id.clone(),
            work_type: String::new(),
        });
        id
    }

    /// Atomically claim the highest-priority pending item.
    ///
    /// If `work_type_filter` is provided, only items of those types are considered.
    /// Returns `None` if no items are available.
    pub fn claim(&self, agent_id: &str, work_type_filter: Option<&[String]>) -> Option<WorkItem> {
        let mut items = self.items.write();
        let mut best: Option<(WorkId, i32)> = None;

        for (id, item) in items.iter() {
            if item.status != WorkStatus::Pending {
                continue;
            }
            if let Some(filter) = work_type_filter {
                if !filter.contains(&item.work_type) {
                    continue;
                }
            }
            match &best {
                Some((_, best_pri)) if item.priority <= *best_pri => {}
                _ => best = Some((id.clone(), item.priority)),
            }
        }

        if let Some((id, _)) = best {
            let item = items.get_mut(&id).unwrap();
            item.status = WorkStatus::Claimed;
            item.claimed_by = Some(agent_id.to_string());
            item.claimed_at_ms = Some(now_ms());
            let claimed = item.clone();
            let _ = self.tx.send(WorkEvent::Claimed {
                id: id.clone(),
                agent_id: agent_id.to_string(),
            });
            Some(claimed)
        } else {
            None
        }
    }

    /// Transition claimed item to in-progress.
    pub fn start(&self, item_id: &str) -> anyhow::Result<()> {
        let mut items = self.items.write();
        let item =
            items
                .get_mut(item_id)
                .ok_or_else(|| crate::error::SdkError::WorkItemNotFound {
                    item_id: item_id.to_string(),
                })?;
        if item.status != WorkStatus::Claimed {
            return Err(anyhow::anyhow!("Item {} not in Claimed state", item_id));
        }
        item.status = WorkStatus::InProgress;
        let _ = self.tx.send(WorkEvent::Started {
            id: item_id.to_string(),
        });
        Ok(())
    }

    /// Mark item as completed with result.
    pub fn complete(&self, item_id: &str, result: WorkResult) -> anyhow::Result<()> {
        let mut items = self.items.write();
        let item =
            items
                .get_mut(item_id)
                .ok_or_else(|| crate::error::SdkError::WorkItemNotFound {
                    item_id: item_id.to_string(),
                })?;
        item.status = WorkStatus::Completed;
        item.result = Some(result);
        item.completed_at_ms = Some(now_ms());
        let success = item.result.as_ref().map(|r| r.success).unwrap_or(false);
        let _ = self.tx.send(WorkEvent::Completed {
            id: item_id.to_string(),
            success,
        });
        Ok(())
    }

    /// Retry a failed item.
    pub fn retry(&self, item_id: &str) -> anyhow::Result<bool> {
        let mut items = self.items.write();
        let item =
            items
                .get_mut(item_id)
                .ok_or_else(|| crate::error::SdkError::WorkItemNotFound {
                    item_id: item_id.to_string(),
                })?;
        if item.retry_count >= item.max_retries {
            return Ok(false);
        }
        item.retry_count += 1;
        item.status = WorkStatus::Pending;
        item.claimed_by = None;
        item.claimed_at_ms = None;
        Ok(true)
    }

    /// Cancel an item.
    pub fn cancel(&self, item_id: &str) -> anyhow::Result<()> {
        let mut items = self.items.write();
        let item =
            items
                .get_mut(item_id)
                .ok_or_else(|| crate::error::SdkError::WorkItemNotFound {
                    item_id: item_id.to_string(),
                })?;
        item.status = WorkStatus::Cancelled;
        let _ = self.tx.send(WorkEvent::Cancelled {
            id: item_id.to_string(),
        });
        Ok(())
    }

    /// Get a work item by ID.
    pub fn get(&self, item_id: &str) -> Option<WorkItem> {
        self.items.read().get(item_id).cloned()
    }

    /// List items, optionally filtered by status.
    pub fn list(&self, filter: Option<WorkStatus>) -> Vec<WorkItem> {
        self.items
            .read()
            .values()
            .filter(|item| match filter {
                Some(s) => item.status == s,
                None => true,
            })
            .cloned()
            .collect()
    }

    /// Get queue statistics.
    pub fn stats(&self) -> WorkQueueStats {
        let items = self.items.read();
        let mut stats = WorkQueueStats::default();
        for item in items.values() {
            match item.status {
                WorkStatus::Pending => stats.pending += 1,
                WorkStatus::Claimed => stats.claimed += 1,
                WorkStatus::InProgress => stats.in_progress += 1,
                WorkStatus::Completed => stats.completed += 1,
                WorkStatus::Failed => stats.failed += 1,
                WorkStatus::Cancelled => stats.cancelled += 1,
            }
        }
        stats
    }

    /// Subscribe to work events.
    pub fn subscribe(&self) -> broadcast::Receiver<WorkEvent> {
        self.tx.subscribe()
    }
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

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

    #[test]
    fn enqueue_and_claim() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        let id = q.enqueue("review", serde_json::json!({"file": "main.rs"}), 1);
        let item = q.claim("agent-1", None).unwrap();
        assert_eq!(item.id, id);
        assert_eq!(item.claimed_by.unwrap(), "agent-1");
        assert_eq!(item.status, WorkStatus::Claimed);
    }

    #[test]
    fn claim_is_atomic() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        q.enqueue("task", serde_json::json!({}), 0);
        let first = q.claim("a1", None);
        let second = q.claim("a2", None);
        assert!(first.is_some());
        assert!(second.is_none());
    }

    #[test]
    fn claim_respects_priority() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        q.enqueue("low", serde_json::json!({}), 1);
        q.enqueue("high", serde_json::json!({}), 10);
        let item = q.claim("a1", None).unwrap();
        assert_eq!(item.priority, 10);
    }

    #[test]
    fn claim_with_type_filter() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        q.enqueue("review", serde_json::json!({}), 0);
        q.enqueue("build", serde_json::json!({}), 0);
        let item = q.claim("a1", Some(&["build".into()]));
        assert!(item.is_some());
        assert_eq!(item.unwrap().work_type, "build");
    }

    #[test]
    fn complete_item() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        let id = q.enqueue("task", serde_json::json!({}), 0);
        let item = q.claim("a1", None).unwrap();
        q.start(&id).unwrap();
        q.complete(
            &id,
            WorkResult {
                success: true,
                content: "done".into(),
                error: None,
                duration_ms: 100,
                tokens_used: None,
            },
        )
        .unwrap();
        let item = q.get(&id).unwrap();
        assert_eq!(item.status, WorkStatus::Completed);
        assert!(item.result.unwrap().success);
    }

    #[test]
    fn retry_item() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        let id = q.enqueue("task", serde_json::json!({}), 0);
        {
            let mut items = q.items.write();
            let item = items.get_mut(&id).unwrap();
            item.status = WorkStatus::Failed;
            item.max_retries = 2;
        }
        assert!(q.retry(&id).unwrap());
        let item = q.get(&id).unwrap();
        assert_eq!(item.status, WorkStatus::Pending);
        assert_eq!(item.retry_count, 1);
    }

    #[test]
    fn cancel_item() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        let id = q.enqueue("task", serde_json::json!({}), 0);
        q.cancel(&id).unwrap();
        assert_eq!(q.get(&id).unwrap().status, WorkStatus::Cancelled);
    }

    #[test]
    fn queue_stats() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        q.enqueue("t1", serde_json::json!({}), 0);
        q.enqueue("t2", serde_json::json!({}), 0);
        q.claim("a1", None);
        let stats = q.stats();
        assert_eq!(stats.pending, 1);
        assert_eq!(stats.claimed, 1);
    }

    #[test]
    fn subscribe_events() {
        let q = WorkQueue::new(WorkQueueConfig::default());
        let mut rx = q.subscribe();
        q.enqueue("task", serde_json::json!({}), 0);
        let event = rx.try_recv().unwrap();
        assert!(matches!(event, WorkEvent::Enqueued { .. }));
    }
}