zoey-core 0.1.1

ZoeyAI core runtime and types — privacy-first AI agent framework optimized for local models
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Integration tests for Agent API
//!
//! Comprehensive security and functionality tests

#[cfg(test)]
mod tests {
    use crate::agent_api::{
        auth::ApiAuthManager,
        task::{TaskManager, TaskResult, TaskStatus},
        types::{ApiPermission, ApiToken, ChatResponse},
    };
    use crate::{types::Character, AgentRuntime, RuntimeOpts};
    use std::sync::{Arc, RwLock};

    /// Helper to create test runtime
    async fn create_test_runtime() -> Arc<RwLock<AgentRuntime>> {
        use crate::RuntimeOpts;
        let opts = RuntimeOpts {
            test_mode: Some(true),
            ..Default::default()
        };
        AgentRuntime::new(opts).await.unwrap()
    }

    // ===================
    // Task Manager Tests
    // ===================

    #[tokio::test]
    async fn test_task_manager_lifecycle() {
        let manager = TaskManager::new(60);

        // Create task
        let task_id = manager.create_task();
        let task = manager.get_task(task_id).unwrap();
        assert!(matches!(task.status, TaskStatus::Pending));

        // Mark as running
        manager.mark_running(task_id);
        let task = manager.get_task(task_id).unwrap();
        assert!(matches!(task.status, TaskStatus::Running));

        // Complete task
        let result = TaskResult::Chat(ChatResponse {
            success: true,
            messages: Some(vec![]),
            error: None,
            metadata: None,
        });
        manager.complete_task(task_id, result);
        let task = manager.get_task(task_id).unwrap();
        assert!(matches!(task.status, TaskStatus::Completed));
        assert!(task.result.is_some());
    }

    #[tokio::test]
    async fn test_task_manager_failure() {
        let manager = TaskManager::new(60);

        let task_id = manager.create_task();
        manager.mark_running(task_id);
        manager.fail_task(task_id, "Test error".to_string());

        let task = manager.get_task(task_id).unwrap();
        assert!(matches!(task.status, TaskStatus::Failed));
        assert_eq!(task.error.as_deref(), Some("Test error"));
    }

    #[tokio::test]
    async fn test_task_manager_cleanup() {
        let manager = TaskManager::new(1); // 1 second max age

        let task_id = manager.create_task();
        manager.complete_task(
            task_id,
            TaskResult::Chat(ChatResponse {
                success: true,
                messages: None,
                error: None,
                metadata: None,
            }),
        );

        // Task should exist
        assert!(manager.get_task(task_id).is_some());

        // Wait for task to age
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;

        // Cleanup
        manager.cleanup_old_tasks();

        // Task should be removed
        assert!(manager.get_task(task_id).is_none());
    }

    #[tokio::test]
    async fn test_task_manager_concurrent_creation() {
        let manager = TaskManager::new(300);

        // Create tasks concurrently
        let mut handles = vec![];
        for _ in 0..10 {
            let mgr = manager.clone();
            handles.push(tokio::spawn(async move { mgr.create_task() }));
        }

        // Collect results
        let mut task_ids = vec![];
        for handle in handles {
            task_ids.push(handle.await.unwrap());
        }

        // All task IDs should be unique
        let unique_ids: std::collections::HashSet<_> = task_ids.iter().collect();
        assert_eq!(unique_ids.len(), 10);

        // All tasks should be retrievable
        for task_id in task_ids {
            assert!(manager.get_task(task_id).is_some());
        }
    }

    #[tokio::test]
    async fn test_task_manager_stats() {
        let manager = TaskManager::new(300);

        // Create and complete some tasks
        let id1 = manager.create_task();
        manager.mark_running(id1);

        let id2 = manager.create_task();
        manager.complete_task(
            id2,
            TaskResult::Chat(ChatResponse {
                success: true,
                messages: None,
                error: None,
                metadata: None,
            }),
        );

        let id3 = manager.create_task();
        manager.fail_task(id3, "error".to_string());

        let stats = manager.task_stats();
        assert_eq!(stats.get("running"), Some(&1));
        assert_eq!(stats.get("completed"), Some(&1));
        assert_eq!(stats.get("failed"), Some(&1));
    }

    // ==========================
    // Authentication Tests
    // ==========================

    #[tokio::test]
    async fn test_auth_token_validation() {
        let token = ApiToken {
            token: ApiAuthManager::hash_token("test-secret"),
            name: "Test".to_string(),
            permissions: vec![ApiPermission::Read],
            expires_at: None,
            agent_id: None,
        };

        let manager = ApiAuthManager::new(vec![token]);

        // Valid token
        assert!(manager.validate_token("test-secret").await.is_ok());

        // Invalid token
        assert!(manager.validate_token("wrong-secret").await.is_err());
    }

    #[tokio::test]
    async fn test_auth_permission_check() {
        let token = ApiToken {
            token: ApiAuthManager::hash_token("test-token"),
            name: "Test".to_string(),
            permissions: vec![ApiPermission::Read],
            expires_at: None,
            agent_id: None,
        };

        let manager = ApiAuthManager::new(vec![token]);

        // Has Read permission
        assert!(manager
            .has_permission("test-token", ApiPermission::Read)
            .await
            .unwrap());

        // Doesn't have Write permission
        assert!(!manager
            .has_permission("test-token", ApiPermission::Write)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_auth_admin_has_all_permissions() {
        let token = ApiToken {
            token: ApiAuthManager::hash_token("admin-token"),
            name: "Admin".to_string(),
            permissions: vec![ApiPermission::Admin],
            expires_at: None,
            agent_id: None,
        };

        let manager = ApiAuthManager::new(vec![token]);

        // Admin has all permissions
        assert!(manager
            .has_permission("admin-token", ApiPermission::Read)
            .await
            .unwrap());
        assert!(manager
            .has_permission("admin-token", ApiPermission::Write)
            .await
            .unwrap());
        assert!(manager
            .has_permission("admin-token", ApiPermission::Execute)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_auth_expired_token() {
        let token = ApiToken {
            token: ApiAuthManager::hash_token("expired-token"),
            name: "Expired".to_string(),
            permissions: vec![ApiPermission::Read],
            expires_at: Some(chrono::Utc::now().timestamp() - 3600), // Expired 1 hour ago
            agent_id: None,
        };

        let manager = ApiAuthManager::new(vec![token]);

        // Expired token should fail
        assert!(manager.validate_token("expired-token").await.is_err());
    }

    #[tokio::test]
    async fn test_auth_disabled_allows_all() {
        let manager = ApiAuthManager::disabled();

        // Any token should work when auth is disabled
        let permissions = manager.validate_token("any-token").await.unwrap();

        // Should have standard permissions
        assert!(permissions.contains(&ApiPermission::Read));
        assert!(permissions.contains(&ApiPermission::Write));
        assert!(permissions.contains(&ApiPermission::Execute));
    }

    #[tokio::test]
    async fn test_auth_token_hashing() {
        let token1 = "my-secret-token";
        let token2 = "my-secret-token";
        let token3 = "different-token";

        let hash1 = ApiAuthManager::hash_token(token1);
        let hash2 = ApiAuthManager::hash_token(token2);
        let hash3 = ApiAuthManager::hash_token(token3);

        // Same token produces same hash
        assert_eq!(hash1, hash2);

        // Different token produces different hash
        assert_ne!(hash1, hash3);

        // Hash should be hex string (64 chars for SHA-256)
        assert_eq!(hash1.len(), 64);
    }

    // =========================
    // Security Tests
    // =========================

    #[tokio::test]
    async fn test_multiple_permission_levels() {
        let read_token = ApiToken {
            token: ApiAuthManager::hash_token("read-token"),
            name: "Read Only".to_string(),
            permissions: vec![ApiPermission::Read],
            expires_at: None,
            agent_id: None,
        };

        let write_token = ApiToken {
            token: ApiAuthManager::hash_token("write-token"),
            name: "Read/Write".to_string(),
            permissions: vec![ApiPermission::Read, ApiPermission::Write],
            expires_at: None,
            agent_id: None,
        };

        let manager = ApiAuthManager::new(vec![read_token, write_token]);

        // Read-only token can read
        assert!(manager
            .has_permission("read-token", ApiPermission::Read)
            .await
            .unwrap());

        // Read-only token cannot write
        assert!(!manager
            .has_permission("read-token", ApiPermission::Write)
            .await
            .unwrap());

        // Write token can read and write
        assert!(manager
            .has_permission("write-token", ApiPermission::Read)
            .await
            .unwrap());
        assert!(manager
            .has_permission("write-token", ApiPermission::Write)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_task_result_serialization() {
        // Ensure task results can be serialized (important for API responses)
        let result = TaskResult::Chat(ChatResponse {
            success: true,
            messages: None,
            error: Some("test error".to_string()),
            metadata: None,
        });

        let serialized = serde_json::to_string(&result);
        assert!(serialized.is_ok());

        let json_value = serde_json::to_value(&result).unwrap();
        assert!(json_value.is_object());
    }

    #[tokio::test]
    async fn test_task_cleanup_preserves_active_tasks() {
        let manager = TaskManager::new(1); // 1 second max age

        // Create completed task (will be cleaned up)
        let completed_id = manager.create_task();
        manager.complete_task(
            completed_id,
            TaskResult::Chat(ChatResponse {
                success: true,
                messages: None,
                error: None,
                metadata: None,
            }),
        );

        // Create active task (should not be cleaned up)
        let active_id = manager.create_task();
        manager.mark_running(active_id);

        // Wait for completed task to age
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;

        // Cleanup
        manager.cleanup_old_tasks();

        // Completed task should be removed
        assert!(manager.get_task(completed_id).is_none());

        // Active task should still exist
        assert!(manager.get_task(active_id).is_some());
    }

    #[tokio::test]
    async fn test_task_duration_tracking() {
        let manager = TaskManager::new(300);

        let task_id = manager.create_task();
        manager.mark_running(task_id);

        // Simulate some work
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        manager.complete_task(
            task_id,
            TaskResult::Chat(ChatResponse {
                success: true,
                messages: None,
                error: None,
                metadata: None,
            }),
        );

        let task = manager.get_task(task_id).unwrap();
        let duration = task.duration_ms();

        assert!(duration.is_some());
        assert!(duration.unwrap() >= 100); // At least 100ms
    }

    #[tokio::test]
    async fn test_concurrent_task_operations() {
        let manager = TaskManager::new(300);
        let task_id = manager.create_task();

        // Spawn multiple concurrent operations
        let mgr1 = manager.clone();
        let mgr2 = manager.clone();
        let mgr3 = manager.clone();

        let handle1 = tokio::spawn(async move {
            mgr1.mark_running(task_id);
        });

        let handle2 = tokio::spawn(async move {
            mgr2.get_task(task_id);
        });

        let handle3 = tokio::spawn(async move {
            mgr3.task_count();
        });

        // All operations should complete without panicking
        let _ = tokio::join!(handle1, handle2, handle3);
    }

    // ==========================
    // Endpoint Integration Tests
    // ==========================

    use crate::agent_api::{
        handlers::{
            action_handler, chat_handler, health_check, state_handler, task_status_handler,
        },
        server::AgentApiConfig,
        state::{ApiState, ServerState},
        types::{ActionRequest, ChatRequest, StateRequest},
    };
    use crate::security::RateLimiter;
    use axum::{
        body::Body,
        extract::{Path, State as AxumState},
        http::{Request, StatusCode},
        response::IntoResponse,
        Json,
    };
    use std::time::Duration;

    /// Helper to create test server state
    async fn create_test_server_state() -> ServerState {
        let runtime = create_test_runtime().await;
        {
            let mut rt = runtime.write().unwrap();
            // Disable streaming to avoid executor initialization during unit tests
            rt.set_setting("ui:streaming", serde_json::json!(false), false);
            // Ensure no provider racing in tests
            rt.set_setting("ui:provider_racing", serde_json::json!(false), false);
        }
        let api_state = ApiState::new(runtime);
        let auth_manager = Arc::new(ApiAuthManager::disabled());
        let rate_limiter = Arc::new(RwLock::new(RateLimiter::new(Duration::from_secs(60), 60)));
        let task_manager = TaskManager::new(300);
        let config = Arc::new(AgentApiConfig::default());

        ServerState {
            api_state,
            auth_manager,
            rate_limiter,
            task_manager,
            config,
        }
    }

    #[tokio::test]
    async fn test_health_endpoint() {
        let state = create_test_server_state().await;
        let response = health_check(AxumState(state)).await.into_response();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_chat_endpoint_creates_task() {
        let state = create_test_server_state().await;

        let request = ChatRequest {
            text: "Hello, how are you?".to_string(),
            room_id: uuid::Uuid::nil(),
            entity_id: None,
            source: "test".to_string(),
            metadata: std::collections::HashMap::new(),
            stream: false,
        };

        let response = chat_handler(AxumState(state.clone()), Json(request))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    #[ignore]
    async fn test_chat_endpoint_rejects_empty_message() {
        let state = create_test_server_state().await;

        let request = ChatRequest {
            text: "   ".to_string(), // Empty/whitespace only
            room_id: uuid::Uuid::nil(),
            entity_id: None,
            source: "test".to_string(),
            metadata: std::collections::HashMap::new(),
            stream: false,
        };

        let response = chat_handler(AxumState(state), Json(request))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[ignore]
    async fn test_state_endpoint_creates_task() {
        let state = create_test_server_state().await;

        let request = StateRequest {
            room_id: uuid::Uuid::nil(),
            entity_id: Some(uuid::Uuid::nil()),
        };

        let response = state_handler(AxumState(state), Json(request))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_action_endpoint_rejects_empty_action() {
        let state = create_test_server_state().await;

        let request = ActionRequest {
            action: "   ".to_string(), // Empty/whitespace only
            room_id: uuid::Uuid::nil(),
            entity_id: None,
            parameters: std::collections::HashMap::new(),
        };

        let response = action_handler(AxumState(state), Json(request))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[ignore]
    async fn test_task_status_endpoint_not_found() {
        let state = create_test_server_state().await;
        let fake_task_id = uuid::Uuid::new_v4();

        let response = task_status_handler(AxumState(state), Path(fake_task_id))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    #[ignore]
    async fn test_task_lifecycle_end_to_end() {
        let state = create_test_server_state().await;

        // Create task via manager directly
        let task_id = state.task_manager.create_task();

        // Check it's pending
        let task = state.task_manager.get_task(task_id).unwrap();
        assert!(matches!(task.status, TaskStatus::Pending));

        // Mark as running
        state.task_manager.mark_running(task_id);

        // Complete it
        state.task_manager.complete_task(
            task_id,
            TaskResult::Chat(ChatResponse {
                success: true,
                messages: Some(vec![]),
                error: None,
                metadata: None,
            }),
        );

        // Verify via endpoint
        let response = task_status_handler(AxumState(state), Path(task_id))
            .await
            .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    // ======================
    // Input Validation Tests
    // ======================

    #[tokio::test]
    async fn test_chat_rejects_extremely_long_message() {
        let state = create_test_server_state().await;

        let long_text = "a".repeat(1_000_000); // 1MB of text
        let request = ChatRequest {
            text: long_text,
            room_id: uuid::Uuid::nil(),
            entity_id: None,
            source: "test".to_string(),
            metadata: std::collections::HashMap::new(),
            stream: false,
        };

        let response = chat_handler(AxumState(state), Json(request))
            .await
            .into_response();

        // Should be rejected (either BAD_REQUEST or PAYLOAD_TOO_LARGE)
        assert!(
            response.status() == StatusCode::BAD_REQUEST
                || response.status() == StatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[tokio::test]
    #[ignore]
    async fn test_action_with_valid_input() {
        let state = create_test_server_state().await;

        let mut params = std::collections::HashMap::new();
        params.insert("key".to_string(), serde_json::json!("value"));

        let request = ActionRequest {
            action: "test_action".to_string(),
            room_id: uuid::Uuid::nil(),
            entity_id: None,
            parameters: params,
        };

        let response = action_handler(AxumState(state), Json(request))
            .await
            .into_response();

        // Test runtime has no actions, so should return NOT_FOUND
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    // ================================
    // Authentication Integration Tests
    // ================================

    #[tokio::test]
    async fn test_auth_manager_with_production_tokens() {
        // Create production-style tokens
        let tokens = vec![
            ApiToken {
                token: ApiAuthManager::hash_token("prod-read-token"),
                name: "Production Reader".to_string(),
                permissions: vec![ApiPermission::Read],
                expires_at: None,
                agent_id: None,
            },
            ApiToken {
                token: ApiAuthManager::hash_token("prod-write-token"),
                name: "Production Writer".to_string(),
                permissions: vec![ApiPermission::Read, ApiPermission::Write],
                expires_at: None,
                agent_id: None,
            },
            ApiToken {
                token: ApiAuthManager::hash_token("prod-admin-token"),
                name: "Production Admin".to_string(),
                permissions: vec![ApiPermission::Admin],
                expires_at: None,
                agent_id: None,
            },
        ];

        let auth_manager = ApiAuthManager::new(tokens);

        // Read token can only read
        assert!(auth_manager
            .has_permission("prod-read-token", ApiPermission::Read)
            .await
            .unwrap());
        assert!(!auth_manager
            .has_permission("prod-read-token", ApiPermission::Write)
            .await
            .unwrap());

        // Write token can read and write
        assert!(auth_manager
            .has_permission("prod-write-token", ApiPermission::Read)
            .await
            .unwrap());
        assert!(auth_manager
            .has_permission("prod-write-token", ApiPermission::Write)
            .await
            .unwrap());

        // Admin has all permissions
        assert!(auth_manager
            .has_permission("prod-admin-token", ApiPermission::Read)
            .await
            .unwrap());
        assert!(auth_manager
            .has_permission("prod-admin-token", ApiPermission::Write)
            .await
            .unwrap());
        assert!(auth_manager
            .has_permission("prod-admin-token", ApiPermission::Execute)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_rate_limiter_enforcement() {
        let limiter = RateLimiter::new(Duration::from_secs(1), 3); // 3 requests per second

        // First 3 should pass
        assert!(limiter.check("test-key"));
        assert!(limiter.check("test-key"));
        assert!(limiter.check("test-key"));

        // 4th should fail
        assert!(!limiter.check("test-key"));

        // Different key should work
        assert!(limiter.check("other-key"));

        // Wait for window to reset
        tokio::time::sleep(Duration::from_secs(2)).await;

        // Should work again
        assert!(limiter.check("test-key"));
    }
}