radkit 0.0.5

Rust AI Agent Development Kit
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
//! In-memory implementation of the `MemoryService` trait.
//!
//! This module provides both native (thread-safe) and WASM (single-threaded)
//! implementations of the memory service using keyword matching.
//!
//! # Usage
//!
//! This backend is intended for **development and testing only**. It does not
//! persist data and uses simple keyword matching instead of semantic search.
//!
//! For production use cases requiring semantic search, use a vector backend
//! like `QdrantMemoryService`.
//!
//! # Platform Differences
//!
//! - **Native**: Uses `DashMap` for thread-safe concurrent access
//! - **WASM**: Uses `RefCell<HashMap>` for single-threaded interior mutability

use std::collections::{HashMap, HashSet};

use crate::errors::AgentResult;
use crate::runtime::context::AuthContext;
use crate::runtime::memory::{
    ContentSource, MemoryContent, MemoryEntry, MemoryService, SearchOptions,
};

/// Stored entry in the in-memory backend.
#[derive(Debug, Clone)]
struct StoredEntry {
    id: String,
    text: String,
    source: ContentSource,
    metadata: HashMap<String, serde_json::Value>,
}

// ============================================================================
// Native Implementation (Thread-Safe)
// ============================================================================

#[cfg(not(all(target_os = "wasi", target_env = "p1")))]
mod native {
    use super::{
        AgentResult, AuthContext, HashSet, MemoryContent, MemoryEntry, MemoryService,
        SearchOptions, StoredEntry,
    };
    use dashmap::DashMap;
    use std::sync::Arc;

    /// In-memory implementation using keyword matching.
    ///
    /// For development and testing only. No embeddings, no persistence.
    ///
    /// # Platform Notes
    ///
    /// Uses `DashMap` for thread-safe concurrent access.
    #[derive(Debug)]
    pub struct InMemoryMemoryService {
        store: Arc<DashMap<String, DashMap<String, StoredEntry>>>,
    }

    impl Default for InMemoryMemoryService {
        fn default() -> Self {
            Self {
                store: Arc::new(DashMap::new()),
            }
        }
    }

    impl InMemoryMemoryService {
        /// Creates a new `InMemoryMemoryService`.
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        fn namespace(auth_ctx: &AuthContext) -> String {
            format!("{}/{}", auth_ctx.app_name, auth_ctx.user_name)
        }

        fn extract_words(text: &str) -> HashSet<String> {
            // Simple word extraction without regex for WASM compatibility
            text.split(|c: char| !c.is_alphanumeric())
                .filter(|s| !s.is_empty())
                .map(str::to_lowercase)
                .collect()
        }

        #[allow(clippy::cast_precision_loss)] // acceptable for keyword scoring heuristic
        fn keyword_score(query_words: &HashSet<String>, text: &str) -> f32 {
            let text_words = Self::extract_words(text);
            if text_words.is_empty() || query_words.is_empty() {
                return 0.0;
            }
            let matches = query_words.intersection(&text_words).count();
            matches as f32 / query_words.len() as f32
        }
    }

    #[async_trait::async_trait]
    impl MemoryService for InMemoryMemoryService {
        async fn add(&self, auth_ctx: &AuthContext, content: MemoryContent) -> AgentResult<String> {
            let ns = Self::namespace(auth_ctx);
            let id = content.source.generate_id();
            let entry = StoredEntry {
                id: id.clone(),
                text: content.text,
                source: content.source,
                metadata: content.metadata,
            };
            self.store.entry(ns).or_default().insert(id.clone(), entry);
            Ok(id)
        }

        async fn add_batch(
            &self,
            auth_ctx: &AuthContext,
            contents: Vec<MemoryContent>,
        ) -> AgentResult<Vec<String>> {
            let ns = Self::namespace(auth_ctx);
            let mut ids = Vec::with_capacity(contents.len());
            for content in contents {
                let id = content.source.generate_id();
                let entry = StoredEntry {
                    id: id.clone(),
                    text: content.text,
                    source: content.source,
                    metadata: content.metadata,
                };
                self.store
                    .entry(ns.clone())
                    .or_default()
                    .insert(id.clone(), entry);
                ids.push(id);
            }
            Ok(ids)
        }

        async fn search(
            &self,
            auth_ctx: &AuthContext,
            query: &str,
            options: SearchOptions,
        ) -> AgentResult<Vec<MemoryEntry>> {
            let ns = Self::namespace(auth_ctx);
            let limit = options.limit.unwrap_or(10);
            let min_score = options.min_score.unwrap_or(0.0);
            let query_words = Self::extract_words(query);

            let mut results = Vec::new();

            if let Some(ns_store) = self.store.get(&ns) {
                for entry in ns_store.iter() {
                    if let Some(ref types) = options.source_types {
                        if !types.contains(&entry.source.source_type()) {
                            continue;
                        }
                    }
                    if let Some(ref filter) = options.metadata_filter {
                        let mut matches = true;
                        for (key, value) in filter {
                            if entry.metadata.get(key) != Some(value) {
                                matches = false;
                                break;
                            }
                        }
                        if !matches {
                            continue;
                        }
                    }
                    let score = if query.is_empty() {
                        1.0
                    } else {
                        Self::keyword_score(&query_words, &entry.text)
                    };
                    if score >= min_score {
                        results.push((entry.clone(), score));
                    }
                }
            }

            results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
            results.truncate(limit);

            Ok(results
                .into_iter()
                .map(|(entry, score)| MemoryEntry {
                    id: entry.id,
                    text: entry.text,
                    source: entry.source,
                    score,
                    metadata: entry.metadata,
                })
                .collect())
        }

        async fn delete(&self, auth_ctx: &AuthContext, id: &str) -> AgentResult<bool> {
            let ns = Self::namespace(auth_ctx);
            Ok(self
                .store
                .get_mut(&ns)
                .is_some_and(|ns_store| ns_store.remove(id).is_some()))
        }

        async fn delete_batch(&self, auth_ctx: &AuthContext, ids: &[String]) -> AgentResult<usize> {
            let ns = Self::namespace(auth_ctx);
            let mut count = 0;
            if let Some(ns_store) = self.store.get_mut(&ns) {
                for id in ids {
                    if ns_store.remove(id).is_some() {
                        count += 1;
                    }
                }
            }
            Ok(count)
        }
    }
}

#[cfg(not(all(target_os = "wasi", target_env = "p1")))]
pub use native::InMemoryMemoryService;

#[cfg(all(target_os = "wasi", target_env = "p1"))]
pub use wasm::InMemoryMemoryService;

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

    fn test_auth() -> AuthContext {
        AuthContext {
            app_name: "test-app".into(),
            user_name: "alice".into(),
        }
    }

    fn other_auth() -> AuthContext {
        AuthContext {
            app_name: "test-app".into(),
            user_name: "bob".into(),
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_and_search_returns_results() {
        let service = InMemoryMemoryService::new();
        let auth = test_auth();

        let content = MemoryContent {
            text: "User prefers dark mode theme".to_string(),
            source: ContentSource::UserFact {
                category: Some("preferences".to_string()),
            },
            metadata: HashMap::new(),
        };

        let id = service.add(&auth, content).await.expect("add failed");
        assert!(id.starts_with("fact:preferences:"));

        let results = service
            .search(&auth, "dark mode", SearchOptions::default())
            .await
            .expect("search failed");

        assert_eq!(results.len(), 1);
        assert!(results[0].text.contains("dark mode"));
        assert!(results[0].score > 0.0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn search_filters_by_source_type() {
        let service = InMemoryMemoryService::new();
        let auth = test_auth();

        // Add a user fact
        service
            .add(
                &auth,
                MemoryContent {
                    text: "User likes cats".to_string(),
                    source: ContentSource::UserFact { category: None },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("add fact");

        // Add a document
        service
            .add(
                &auth,
                MemoryContent {
                    text: "Cats are mammals".to_string(),
                    source: ContentSource::Document {
                        document_id: "doc1".to_string(),
                        name: "Animals".to_string(),
                        chunk_index: 0,
                        total_chunks: 1,
                    },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("add doc");

        // Search only user facts
        let results = service
            .search(&auth, "cats", SearchOptions::history_only())
            .await
            .expect("search");
        assert_eq!(results.len(), 1);
        assert!(results[0].text.contains("likes cats"));

        // Search only documents
        let results = service
            .search(&auth, "cats", SearchOptions::knowledge_only())
            .await
            .expect("search");
        assert_eq!(results.len(), 1);
        assert!(results[0].text.contains("mammals"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn empty_query_returns_all_entries() {
        let service = InMemoryMemoryService::new();
        let auth = test_auth();

        service
            .add(
                &auth,
                MemoryContent {
                    text: "First entry".to_string(),
                    source: ContentSource::UserFact { category: None },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("add 1");

        service
            .add(
                &auth,
                MemoryContent {
                    text: "Second entry".to_string(),
                    source: ContentSource::UserFact { category: None },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("add 2");

        let results = service
            .search(&auth, "", SearchOptions::default())
            .await
            .expect("search");

        assert_eq!(results.len(), 2);
        assert!(results
            .iter()
            .all(|r| (r.score - 1.0_f32).abs() < f32::EPSILON));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn multi_tenant_isolation() {
        let service = InMemoryMemoryService::new();
        let alice = test_auth();
        let bob = other_auth();

        // Alice adds data
        service
            .add(
                &alice,
                MemoryContent {
                    text: "Alice secret".to_string(),
                    source: ContentSource::UserFact { category: None },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("alice add");

        // Bob adds data
        service
            .add(
                &bob,
                MemoryContent {
                    text: "Bob secret".to_string(),
                    source: ContentSource::UserFact { category: None },
                    metadata: HashMap::new(),
                },
            )
            .await
            .expect("bob add");

        // Alice can only see her data
        let alice_results = service
            .search(&alice, "secret", SearchOptions::default())
            .await
            .expect("alice search");
        assert_eq!(alice_results.len(), 1);
        assert!(alice_results[0].text.contains("Alice"));

        // Bob can only see his data
        let bob_results = service
            .search(&bob, "secret", SearchOptions::default())
            .await
            .expect("bob search");
        assert_eq!(bob_results.len(), 1);
        assert!(bob_results[0].text.contains("Bob"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn delete_removes_entry() {
        let service = InMemoryMemoryService::new();
        let auth = test_auth();

        let content = MemoryContent {
            text: "To be deleted".to_string(),
            source: ContentSource::UserFact { category: None },
            metadata: HashMap::new(),
        };

        let id = service.add(&auth, content).await.expect("add");

        // Verify it exists
        let results = service
            .search(&auth, "deleted", SearchOptions::default())
            .await
            .expect("search");
        assert_eq!(results.len(), 1);

        // Delete it
        let deleted = service.delete(&auth, &id).await.expect("delete");
        assert!(deleted);

        // Verify it's gone
        let results = service
            .search(&auth, "deleted", SearchOptions::default())
            .await
            .expect("search after delete");
        assert_eq!(results.len(), 0);

        // Deleting again returns false
        let deleted_again = service.delete(&auth, &id).await.expect("delete again");
        assert!(!deleted_again);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_batch_adds_multiple() {
        let service = InMemoryMemoryService::new();
        let auth = test_auth();

        let contents = vec![
            MemoryContent {
                text: "First batch item".to_string(),
                source: ContentSource::UserFact { category: None },
                metadata: HashMap::new(),
            },
            MemoryContent {
                text: "Second batch item".to_string(),
                source: ContentSource::UserFact { category: None },
                metadata: HashMap::new(),
            },
            MemoryContent {
                text: "Third batch item".to_string(),
                source: ContentSource::UserFact { category: None },
                metadata: HashMap::new(),
            },
        ];

        let ids = service.add_batch(&auth, contents).await.expect("add batch");
        assert_eq!(ids.len(), 3);

        let results = service
            .search(&auth, "batch item", SearchOptions::default())
            .await
            .expect("search");
        assert_eq!(results.len(), 3);
    }
}