oxios-kernel 0.1.1

Oxios kernel: supervisor, event bus, state store
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
//! Memory tools for cross-session agent memory.
//!
//! Provides three tools:
//! - `memory_write` — write a memory entry
//! - `memory_read` — read/list memory entries
//! - `memory_search` — search memory entries by content or tags

use std::sync::Arc;

use async_trait::async_trait;
use chrono::Utc;
use oxi_sdk::{AgentTool, AgentToolResult, ToolContext};
use serde_json::{json, Value};

use crate::memory::{MemoryEntry, MemoryManager, MemoryType};

/// Tool for writing memory entries that persist across sessions.
pub struct MemoryWriteTool {
    memory_manager: Arc<MemoryManager>,
}

impl MemoryWriteTool {
    /// Create a new MemoryWriteTool.
    pub fn new(memory_manager: Arc<MemoryManager>) -> Self {
        Self { memory_manager }
    }

    /// Create a `MemoryWriteTool` from a [`KernelHandle`].
    ///
    /// Extracts the memory manager from the kernel's agent facade.
    pub fn from_kernel(kernel: &crate::kernel_handle::KernelHandle) -> Self {
        Self::new(kernel.agents.memory_manager().clone())
    }
}

impl std::fmt::Debug for MemoryWriteTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MemoryWriteTool").finish()
    }
}

#[async_trait]
impl AgentTool for MemoryWriteTool {
    fn name(&self) -> &str {
        "memory_write"
    }

    fn label(&self) -> &str {
        "Memory Write"
    }

    fn description(&self) -> &str {
        "Write a memory entry that persists across sessions. Use this to save important facts, episodes, or knowledge for future reference."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "content": {
                    "type": "string",
                    "description": "The memory content to store"
                },
                "memory_type": {
                    "type": "string",
                    "enum": ["fact", "episode", "knowledge"],
                    "description": "The type of memory entry"
                },
                "tags": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Optional tags for categorization"
                },
                "importance": {
                    "type": "number",
                    "description": "Importance score 0.0-1.0 (default 0.5)"
                }
            },
            "required": ["content", "memory_type"]
        })
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        params: Value,
        _signal: Option<tokio::sync::oneshot::Receiver<()>>,
        _ctx: &ToolContext,
    ) -> Result<AgentToolResult, oxi_sdk::ToolError> {
        let content = params["content"].as_str().unwrap_or("").to_string();
        if content.is_empty() {
            return Ok(AgentToolResult::error("content is required"));
        }

        let memory_type_str = params["memory_type"].as_str().unwrap_or("fact");
        let memory_type = match memory_type_str {
            "fact" => MemoryType::Fact,
            "episode" => MemoryType::Episode,
            "knowledge" => MemoryType::Knowledge,
            _ => {
                return Ok(AgentToolResult::error(format!(
                    "Invalid memory_type '{}'. Must be one of: fact, episode, knowledge",
                    memory_type_str
                )))
            }
        };

        let tags: Vec<String> = params["tags"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();

        let importance = params["importance"].as_f64().unwrap_or(0.5) as f32;

        let now = Utc::now();
        let entry = MemoryEntry {
            id: uuid::Uuid::new_v4().to_string(),
            memory_type,
            content,
            source: "agent".to_string(),
            session_id: None,
            tags,
            importance: importance.clamp(0.0, 1.0),
            created_at: now,
            accessed_at: now,
            access_count: 0,
        };
        let entry_id = entry.id.clone();

        match self.memory_manager.remember(entry).await {
            Ok(_) => Ok(AgentToolResult::success(format!(
                "Memory entry saved (id: {}, type: {})",
                entry_id, memory_type_str,
            ))),
            Err(e) => Ok(AgentToolResult::error(format!(
                "Failed to write memory: {e}"
            ))),
        }
    }
}

/// Tool for reading memory entries.
pub struct MemoryReadTool {
    memory_manager: Arc<MemoryManager>,
}

impl MemoryReadTool {
    /// Create a new MemoryReadTool.
    pub fn new(memory_manager: Arc<MemoryManager>) -> Self {
        Self { memory_manager }
    }

    /// Create a `MemoryReadTool` from a [`KernelHandle`].
    ///
    /// Extracts the memory manager from the kernel's agent facade.
    pub fn from_kernel(kernel: &crate::kernel_handle::KernelHandle) -> Self {
        Self::new(kernel.agents.memory_manager().clone())
    }
}

impl std::fmt::Debug for MemoryReadTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MemoryReadTool").finish()
    }
}

#[async_trait]
impl AgentTool for MemoryReadTool {
    fn name(&self) -> &str {
        "memory_read"
    }

    fn label(&self) -> &str {
        "Memory Read"
    }

    fn description(&self) -> &str {
        "Read memory entries. Provide 'id' and 'memory_type' to read a specific entry, or just 'memory_type' to list entries of that type."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "id": {
                    "type": "string",
                    "description": "Optional specific memory entry ID to read."
                },
                "memory_type": {
                    "type": "string",
                    "enum": ["fact", "episode", "knowledge"],
                    "description": "Type of memory to list (required if no id provided)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max entries to return when listing (default 10)"
                }
            }
        })
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        params: Value,
        _signal: Option<tokio::sync::oneshot::Receiver<()>>,
        _ctx: &ToolContext,
    ) -> Result<AgentToolResult, oxi_sdk::ToolError> {
        let limit = params["limit"].as_u64().unwrap_or(10) as usize;

        if let Some(id) = params["id"].as_str() {
            // Need memory_type to look up by ID
            let memory_type_str = params["memory_type"].as_str().unwrap_or("fact");
            let memory_type = parse_memory_type(memory_type_str);

            match self.memory_manager.get(id, memory_type).await {
                Ok(Some(entry)) => {
                    let output = format!(
                        "ID: {}\nType: {}\nSource: {}\nTags: {}\nImportance: {:.2}\nCreated: {}\n\n{}",
                        entry.id,
                        entry.memory_type.label(),
                        entry.source,
                        entry.tags.join(", "),
                        entry.importance,
                        entry.created_at,
                        entry.content,
                    );
                    Ok(AgentToolResult::success(&output))
                }
                Ok(None) => Ok(AgentToolResult::error(format!(
                    "Memory entry '{}' not found",
                    id
                ))),
                Err(e) => Ok(AgentToolResult::error(format!(
                    "Failed to read memory: {e}"
                ))),
            }
        } else {
            // List entries by type
            let memory_type_str = params["memory_type"].as_str().unwrap_or("fact");
            let memory_type = parse_memory_type(memory_type_str);

            match self.memory_manager.list(memory_type, limit).await {
                Ok(entries) => {
                    if entries.is_empty() {
                        return Ok(AgentToolResult::success(format!(
                            "No {} memory entries found.",
                            memory_type_str,
                        )));
                    }
                    let mut output =
                        format!("Found {} {} entries:\n\n", entries.len(), memory_type_str,);
                    for entry in &entries {
                        let preview = truncate_str(&entry.content, 100);
                        output.push_str(&format!(
                            "- [{}] {} (id: {}…, tags: {})\n",
                            entry.memory_type.label(),
                            preview,
                            &entry.id[..8.min(entry.id.len())],
                            entry.tags.join(", "),
                        ));
                    }
                    Ok(AgentToolResult::success(&output))
                }
                Err(e) => Ok(AgentToolResult::error(format!(
                    "Failed to list memory: {e}"
                ))),
            }
        }
    }
}

/// Tool for searching memory entries by content or tags.
pub struct MemorySearchTool {
    memory_manager: Arc<MemoryManager>,
}

impl MemorySearchTool {
    /// Create a new MemorySearchTool.
    pub fn new(memory_manager: Arc<MemoryManager>) -> Self {
        Self { memory_manager }
    }

    /// Create a `MemorySearchTool` from a [`KernelHandle`].
    ///
    /// Extracts the memory manager from the kernel's agent facade.
    pub fn from_kernel(kernel: &crate::kernel_handle::KernelHandle) -> Self {
        Self::new(kernel.agents.memory_manager().clone())
    }
}

impl std::fmt::Debug for MemorySearchTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MemorySearchTool").finish()
    }
}

#[async_trait]
impl AgentTool for MemorySearchTool {
    fn name(&self) -> &str {
        "memory_search"
    }

    fn label(&self) -> &str {
        "Memory Search"
    }

    fn description(&self) -> &str {
        "Search memory entries by keyword query. Optionally filter by memory type."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Text to search for in memory content"
                },
                "memory_type": {
                    "type": "string",
                    "enum": ["fact", "episode", "knowledge", "conversation", "session"],
                    "description": "Optional memory type to filter by"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 10)"
                }
            },
            "required": ["query"]
        })
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        params: Value,
        _signal: Option<tokio::sync::oneshot::Receiver<()>>,
        _ctx: &ToolContext,
    ) -> Result<AgentToolResult, oxi_sdk::ToolError> {
        let query = params["query"].as_str().unwrap_or("");
        if query.is_empty() {
            return Ok(AgentToolResult::error("query is required"));
        }

        let limit = params["limit"].as_u64().unwrap_or(10) as usize;

        let memory_type = params["memory_type"].as_str().map(parse_memory_type);

        match self.memory_manager.search(query, memory_type, limit).await {
            Ok(entries) => {
                if entries.is_empty() {
                    return Ok(AgentToolResult::success(
                        "No matching memory entries found.",
                    ));
                }
                let mut output = format!("Found {} matching entries:\n\n", entries.len());
                for entry in &entries {
                    let preview = truncate_str(&entry.content, 100);
                    output.push_str(&format!(
                        "- [{}] {} (id: {}…, importance: {:.2}, tags: {})\n",
                        entry.memory_type.label(),
                        preview,
                        &entry.id[..8.min(entry.id.len())],
                        entry.importance,
                        entry.tags.join(", "),
                    ));
                }
                Ok(AgentToolResult::success(&output))
            }
            Err(e) => Ok(AgentToolResult::error(format!(
                "Failed to search memory: {e}"
            ))),
        }
    }
}

/// Parse a memory type string, defaulting to Fact.
fn parse_memory_type(s: &str) -> MemoryType {
    match s {
        "conversation" => MemoryType::Conversation,
        "session" => MemoryType::Session,
        "fact" => MemoryType::Fact,
        "episode" => MemoryType::Episode,
        "knowledge" => MemoryType::Knowledge,
        _ => MemoryType::Fact,
    }
}

/// Truncate a string to at most `max_chars` characters, respecting UTF-8 boundaries.
fn truncate_str(s: &str, max_chars: usize) -> &str {
    if s.len() <= max_chars {
        return s;
    }
    // Find the largest valid char boundary <= max_chars.
    let mut boundary = max_chars;
    while boundary > 0 && !s.is_char_boundary(boundary) {
        boundary -= 1;
    }
    &s[..boundary]
}

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

    #[test]
    fn test_truncate_str_ascii() {
        assert_eq!(truncate_str("hello world", 5), "hello");
        assert_eq!(truncate_str("hello", 10), "hello");
        assert_eq!(truncate_str("", 5), "");
    }

    #[test]
    fn test_truncate_str_utf8_korean() {
        // Each Korean character is 3 bytes in UTF-8.
        let korean = "안녕하세요"; // 15 bytes
        assert_eq!(truncate_str(korean, 6), "안녕"); // 6 bytes = 2 chars
        assert_eq!(truncate_str(korean, 7), "안녕"); // 7 bytes splits char → back to 6
        assert_eq!(truncate_str(korean, 15), "안녕하세요");
    }

    #[test]
    fn test_truncate_str_mixed() {
        let mixed = "Hi 안녕"; // 2 + 1 + 6 = 9 bytes
        assert_eq!(truncate_str(mixed, 3), "Hi ");
        assert_eq!(truncate_str(mixed, 4), "Hi "); // 4 splits 안 → back to 3
    }

    #[test]
    fn test_parse_memory_type() {
        assert!(matches!(parse_memory_type("fact"), MemoryType::Fact));
        assert!(matches!(parse_memory_type("episode"), MemoryType::Episode));
        assert!(matches!(
            parse_memory_type("knowledge"),
            MemoryType::Knowledge
        ));
        assert!(matches!(
            parse_memory_type("conversation"),
            MemoryType::Conversation
        ));
        assert!(matches!(parse_memory_type("session"), MemoryType::Session));
        assert!(matches!(parse_memory_type("unknown"), MemoryType::Fact));
    }

    fn make_test_mm() -> std::sync::Arc<crate::memory::MemoryManager> {
        let dir = std::env::temp_dir().join(format!("test-memory-{}", uuid::Uuid::new_v4()));
        let state_store = std::sync::Arc::new(
            crate::state_store::StateStore::new(dir).expect("test state store"),
        );
        std::sync::Arc::new(crate::memory::MemoryManager::new(state_store))
    }

    #[test]
    fn test_memory_write_tool_schema() {
        let mm = make_test_mm();
        let tool = MemoryWriteTool::new(mm);
        assert_eq!(tool.name(), "memory_write");
        let schema = tool.parameters_schema();
        assert!(schema["required"].is_array());
    }

    #[test]
    fn test_memory_read_tool_schema() {
        let mm = make_test_mm();
        let tool = MemoryReadTool::new(mm);
        assert_eq!(tool.name(), "memory_read");
    }

    #[test]
    fn test_memory_search_tool_schema() {
        let mm = make_test_mm();
        let tool = MemorySearchTool::new(mm);
        assert_eq!(tool.name(), "memory_search");
        let schema = tool.parameters_schema();
        assert!(schema["required"].is_array());
    }
}