everruns-core 0.9.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
//! Session Schedule Capability
//!
//! Provides tools for scheduling future work within a session:
//! - `create_schedule`: Schedule a task (one-shot or recurring cron)
//! - `cancel_schedule`: Cancel/disable a schedule
//! - `list_schedules`: List all schedules for the current session

use super::{Capability, CapabilityStatus};
use crate::session_schedule::MAX_ACTIVE_SCHEDULES_PER_SESSION;
use crate::tool_types::ToolHints;
use crate::tools::{Tool, ToolExecutionResult};
use crate::traits::ToolContext;
use async_trait::async_trait;
use serde_json::{Value, json};

pub const SESSION_SCHEDULE_CAPABILITY_ID: &str = "session_schedule";

/// Session schedule capability — lets the agent schedule future work.
pub struct SessionScheduleCapability;

impl Capability for SessionScheduleCapability {
    fn id(&self) -> &str {
        SESSION_SCHEDULE_CAPABILITY_ID
    }

    fn name(&self) -> &str {
        "Schedules"
    }

    fn description(&self) -> &str {
        "Schedule future tasks within the current session. Supports one-shot and recurring (cron) schedules."
    }

    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    fn icon(&self) -> Option<&str> {
        Some("clock")
    }

    fn category(&self) -> Option<&str> {
        Some("Session")
    }

    fn system_prompt_addition(&self) -> Option<&str> {
        Some(
            "When a schedule fires, you will receive a message with the task description and should execute it. Maximum 5 active schedules per session.",
        )
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(CreateScheduleTool),
            Box::new(CancelScheduleTool),
            Box::new(ListSchedulesTool),
        ]
    }

    fn features(&self) -> Vec<&'static str> {
        vec!["schedules"]
    }
}

// ============================================================================
// create_schedule tool
// ============================================================================

pub struct CreateScheduleTool;

#[async_trait]
impl Tool for CreateScheduleTool {
    fn name(&self) -> &str {
        "create_schedule"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Create Schedule")
    }

    fn description(&self) -> &str {
        "Schedule a future task in this session. Provide description and either scheduled_at (one-shot) or cron_expression (recurring)."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "description": {
                    "type": "string",
                    "description": "What the agent should do when the schedule fires"
                },
                "cron_expression": {
                    "type": "string",
                    "description": "Standard 5-field cron expression for recurring schedules (e.g., '0 3 * * *' for daily at 3am)"
                },
                "scheduled_at": {
                    "type": "string",
                    "description": "ISO 8601 datetime for one-shot schedule (e.g., '2026-02-19T03:00:00Z')"
                },
                "timezone": {
                    "type": "string",
                    "description": "IANA timezone (e.g., 'America/New_York'). Default: UTC"
                }
            },
            "required": ["description"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "create_schedule requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let description = match arguments.get("description").and_then(|v| v.as_str()) {
            Some(d) if !d.trim().is_empty() => d.trim().to_string(),
            _ => return ToolExecutionResult::tool_error("Missing required parameter: description"),
        };

        let cron_expression = arguments
            .get("cron_expression")
            .and_then(|v| v.as_str())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        let scheduled_at = arguments
            .get("scheduled_at")
            .and_then(|v| v.as_str())
            .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.with_timezone(&chrono::Utc));

        if cron_expression.is_none() && scheduled_at.is_none() {
            return ToolExecutionResult::tool_error(
                "Must provide either cron_expression (recurring) or scheduled_at (one-shot)",
            );
        }

        let timezone = arguments
            .get("timezone")
            .and_then(|v| v.as_str())
            .unwrap_or("UTC")
            .to_string();

        let Some(store) = &context.schedule_store else {
            return ToolExecutionResult::tool_error("Schedule store not available in this context");
        };

        // Check max active limit
        match store.count_active_schedules(context.session_id).await {
            Ok(count) if count >= MAX_ACTIVE_SCHEDULES_PER_SESSION => {
                return ToolExecutionResult::tool_error(format!(
                    "Maximum {MAX_ACTIVE_SCHEDULES_PER_SESSION} active schedules per session. Cancel an existing schedule first."
                ));
            }
            Err(e) => return ToolExecutionResult::internal_error(e),
            _ => {}
        }

        match store
            .create_schedule(
                context.session_id,
                description,
                cron_expression,
                scheduled_at,
                timezone,
            )
            .await
        {
            Ok(schedule) => ToolExecutionResult::success(json!({
                "schedule_id": schedule.id.to_string(),
                "description": schedule.description,
                "schedule_type": schedule.schedule_type,
                "cron_expression": schedule.cron_expression,
                "scheduled_at": schedule.scheduled_at,
                "timezone": schedule.timezone,
                "next_trigger_at": schedule.next_trigger_at,
                "enabled": schedule.enabled,
                "created": true,
            })),
            Err(e) => ToolExecutionResult::internal_error(e),
        }
    }
}

// ============================================================================
// cancel_schedule tool
// ============================================================================

pub struct CancelScheduleTool;

#[async_trait]
impl Tool for CancelScheduleTool {
    fn name(&self) -> &str {
        "cancel_schedule"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Cancel Schedule")
    }

    fn description(&self) -> &str {
        "Cancel (disable) an active schedule by its ID."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "schedule_id": {
                    "type": "string",
                    "description": "The schedule ID to cancel (e.g., 'sched_...')"
                }
            },
            "required": ["schedule_id"],
            "additionalProperties": false
        })
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default().with_destructive(true)
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "cancel_schedule requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let schedule_id_str = match arguments.get("schedule_id").and_then(|v| v.as_str()) {
            Some(s) if !s.trim().is_empty() => s.trim(),
            _ => return ToolExecutionResult::tool_error("Missing required parameter: schedule_id"),
        };

        let schedule_id = match schedule_id_str.parse::<crate::typed_id::ScheduleId>() {
            Ok(id) => id,
            Err(_) => {
                return ToolExecutionResult::tool_error(format!(
                    "Invalid schedule_id format: {schedule_id_str}"
                ));
            }
        };

        let Some(store) = &context.schedule_store else {
            return ToolExecutionResult::tool_error("Schedule store not available in this context");
        };

        match store.cancel_schedule(context.session_id, schedule_id).await {
            Ok(schedule) => ToolExecutionResult::success(json!({
                "schedule_id": schedule.id.to_string(),
                "description": schedule.description,
                "enabled": schedule.enabled,
                "cancelled": true,
            })),
            Err(e) => ToolExecutionResult::internal_error(e),
        }
    }
}

// ============================================================================
// list_schedules tool
// ============================================================================

pub struct ListSchedulesTool;

#[async_trait]
impl Tool for ListSchedulesTool {
    fn name(&self) -> &str {
        "list_schedules"
    }

    fn display_name(&self) -> Option<&str> {
        Some("List Schedules")
    }

    fn description(&self) -> &str {
        "List all schedules for the current session."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        })
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default()
            .with_readonly(true)
            .with_idempotent(true)
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "list_schedules requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        _arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let Some(store) = &context.schedule_store else {
            return ToolExecutionResult::tool_error("Schedule store not available in this context");
        };

        match store.list_schedules(context.session_id).await {
            Ok(schedules) => {
                let items: Vec<Value> = schedules
                    .iter()
                    .map(|s| {
                        json!({
                            "schedule_id": s.id.to_string(),
                            "description": s.description,
                            "schedule_type": s.schedule_type,
                            "cron_expression": s.cron_expression,
                            "scheduled_at": s.scheduled_at,
                            "timezone": s.timezone,
                            "enabled": s.enabled,
                            "next_trigger_at": s.next_trigger_at,
                            "last_triggered_at": s.last_triggered_at,
                            "trigger_count": s.trigger_count,
                        })
                    })
                    .collect();

                ToolExecutionResult::success(json!({
                    "schedules": items,
                    "total": schedules.len(),
                }))
            }
            Err(e) => ToolExecutionResult::internal_error(e),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session_schedule::SessionSchedule;
    use crate::traits::SessionScheduleStore;
    use crate::typed_id::{ScheduleId, SessionId};
    use async_trait::async_trait;
    use chrono::Utc;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    struct MockScheduleStore {
        schedules: Arc<Mutex<Vec<SessionSchedule>>>,
    }

    impl MockScheduleStore {
        fn new() -> Self {
            Self {
                schedules: Arc::new(Mutex::new(Vec::new())),
            }
        }
    }

    #[async_trait]
    impl SessionScheduleStore for MockScheduleStore {
        async fn create_schedule(
            &self,
            session_id: SessionId,
            description: String,
            cron_expression: Option<String>,
            scheduled_at: Option<chrono::DateTime<Utc>>,
            timezone: String,
        ) -> crate::error::Result<SessionSchedule> {
            let schedule = SessionSchedule {
                id: ScheduleId::new(),
                session_id,
                owner_principal_id: crate::PrincipalId::from_seed(1),
                resolved_owner_user_id: None,
                owner: None,
                effective_owner: None,
                description,
                schedule_type: SessionSchedule::derive_type(&cron_expression),
                cron_expression,
                scheduled_at,
                timezone,
                enabled: true,
                next_trigger_at: Some(Utc::now() + chrono::Duration::hours(1)),
                last_triggered_at: None,
                trigger_count: 0,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            };
            self.schedules.lock().unwrap().push(schedule.clone());
            Ok(schedule)
        }

        async fn cancel_schedule(
            &self,
            _session_id: SessionId,
            schedule_id: ScheduleId,
        ) -> crate::error::Result<SessionSchedule> {
            let mut schedules = self.schedules.lock().unwrap();
            let schedule = schedules
                .iter_mut()
                .find(|s| s.id == schedule_id)
                .ok_or_else(|| crate::error::AgentLoopError::tool("Schedule not found"))?;
            schedule.enabled = false;
            Ok(schedule.clone())
        }

        async fn list_schedules(
            &self,
            session_id: SessionId,
        ) -> crate::error::Result<Vec<SessionSchedule>> {
            let schedules = self.schedules.lock().unwrap();
            Ok(schedules
                .iter()
                .filter(|s| s.session_id == session_id)
                .cloned()
                .collect())
        }

        async fn count_active_schedules(&self, session_id: SessionId) -> crate::error::Result<u32> {
            let schedules = self.schedules.lock().unwrap();
            Ok(schedules
                .iter()
                .filter(|s| s.session_id == session_id && s.enabled)
                .count() as u32)
        }
    }

    #[tokio::test]
    async fn create_schedule_one_shot() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store));

        let tool = CreateScheduleTool;
        let result = tool
            .execute_with_context(
                json!({
                    "description": "Run backup",
                    "scheduled_at": "2026-02-19T03:00:00Z"
                }),
                &context,
            )
            .await;

        match result {
            ToolExecutionResult::Success(value) => {
                assert_eq!(value["created"], true);
                assert_eq!(value["description"], "Run backup");
                assert_eq!(value["schedule_type"], "oneshot");
            }
            other => panic!("expected success, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_schedule_recurring() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store));

        let tool = CreateScheduleTool;
        let result = tool
            .execute_with_context(
                json!({
                    "description": "Check logs",
                    "cron_expression": "0 3 * * *"
                }),
                &context,
            )
            .await;

        match result {
            ToolExecutionResult::Success(value) => {
                assert_eq!(value["created"], true);
                assert_eq!(value["schedule_type"], "recurring");
                assert_eq!(value["cron_expression"], "0 3 * * *");
            }
            other => panic!("expected success, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_schedule_rejects_missing_time() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store));

        let tool = CreateScheduleTool;
        let result = tool
            .execute_with_context(json!({"description": "No time"}), &context)
            .await;

        assert!(matches!(result, ToolExecutionResult::ToolError(_)));
    }

    #[tokio::test]
    async fn create_schedule_enforces_max_limit() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store.clone()));

        let tool = CreateScheduleTool;

        // Create 5 schedules
        for i in 0..5 {
            let result = tool
                .execute_with_context(
                    json!({
                        "description": format!("Task {i}"),
                        "scheduled_at": "2026-12-01T00:00:00Z"
                    }),
                    &context,
                )
                .await;
            assert!(matches!(result, ToolExecutionResult::Success(_)));
        }

        // 6th should fail
        let result = tool
            .execute_with_context(
                json!({
                    "description": "Task 6",
                    "scheduled_at": "2026-12-01T00:00:00Z"
                }),
                &context,
            )
            .await;
        assert!(matches!(result, ToolExecutionResult::ToolError(_)));
    }

    #[tokio::test]
    async fn cancel_schedule_works() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store.clone()));

        // Create a schedule first
        let schedule = store
            .create_schedule(
                session_id,
                "test".to_string(),
                None,
                Some(Utc::now() + chrono::Duration::hours(1)),
                "UTC".to_string(),
            )
            .await
            .unwrap();

        let tool = CancelScheduleTool;
        let result = tool
            .execute_with_context(json!({"schedule_id": schedule.id.to_string()}), &context)
            .await;

        match result {
            ToolExecutionResult::Success(value) => {
                assert_eq!(value["cancelled"], true);
                assert_eq!(value["enabled"], false);
            }
            other => panic!("expected success, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_schedules_works() {
        let store = MockScheduleStore::new();
        let session_id = SessionId::new();
        let mut context = ToolContext::new(session_id);
        context.schedule_store = Some(Arc::new(store.clone()));

        // Create 2 schedules
        store
            .create_schedule(
                session_id,
                "first".to_string(),
                None,
                Some(Utc::now() + chrono::Duration::hours(1)),
                "UTC".to_string(),
            )
            .await
            .unwrap();
        store
            .create_schedule(
                session_id,
                "second".to_string(),
                Some("0 * * * *".to_string()),
                None,
                "UTC".to_string(),
            )
            .await
            .unwrap();

        let tool = ListSchedulesTool;
        let result = tool.execute_with_context(json!({}), &context).await;

        match result {
            ToolExecutionResult::Success(value) => {
                assert_eq!(value["total"], 2);
                assert_eq!(value["schedules"].as_array().unwrap().len(), 2);
            }
            other => panic!("expected success, got: {other:?}"),
        }
    }

    #[test]
    fn capability_metadata() {
        let cap = SessionScheduleCapability;
        assert_eq!(cap.id(), "session_schedule");
        assert_eq!(cap.status(), CapabilityStatus::Available);
        assert!(cap.system_prompt_addition().is_some());
        assert_eq!(cap.tools().len(), 3);
    }
}