enact-core 0.0.2

Core agent runtime for Enact - Graph-Native AI agents
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
//! Trigger System for Background Callables
//!
//! Triggers enable event-based callable invocation. A trigger watches for
//! specific events and spawns background executions when conditions are met.
//!
//! ## Trigger Types
//!
//! - **Event**: Fired by execution/step events
//! - **Schedule**: Fired by cron/interval schedules
//! - **Webhook**: Fired by external webhooks
//! - **Threshold**: Fired when metrics cross thresholds
//! - **Lifecycle**: Fired by thread/user lifecycle events
//!
//! @see packages/enact-schemas/src/execution.schemas.ts

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use svix_ksuid::KsuidLike;

use crate::kernel::ids::{ExecutionId, TenantId};

/// TriggerId - Unique identifier for a trigger
/// Format: trigger_[27-char KSUID]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TriggerId(String);

impl TriggerId {
    /// Create a new TriggerId
    pub fn new() -> Self {
        Self(format!("trigger_{}", svix_ksuid::Ksuid::new(None, None)))
    }

    /// Create from string (for deserialization)
    pub fn from_string(s: String) -> Self {
        Self(s)
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for TriggerId {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for TriggerId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// TriggerType - What kind of trigger this is
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerTypeSchema
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggerType {
    /// Fired by an event (e.g., execution.completed, step.failed)
    Event,
    /// Fired by a schedule (cron, interval)
    Schedule,
    /// Fired by an external webhook
    Webhook,
    /// Fired when a metric crosses a threshold
    Threshold,
    /// Fired manually by user
    Manual,
    /// Fired by lifecycle events (thread.created, user.signup)
    Lifecycle,
}

/// TriggerStatus - Current status of a trigger
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerStatusSchema
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TriggerStatus {
    /// Trigger is active and will fire
    #[default]
    Active,
    /// Trigger is paused (won't fire)
    Paused,
    /// Trigger is disabled (won't fire, hidden)
    Disabled,
    /// Trigger has fired (for one-shot triggers)
    Fired,
    /// Trigger has expired (past end_at)
    Expired,
}

/// ThresholdOperator - Comparison operator for threshold triggers
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThresholdOperator {
    Gt,
    Gte,
    Lt,
    Lte,
    Eq,
    Neq,
}

/// TriggerCondition - When the trigger should fire
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerConditionSchema
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerCondition {
    /// Event type to match (for event triggers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,

    /// Pattern to match against event data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_pattern: Option<HashMap<String, serde_json::Value>>,

    /// Cron expression (for schedule triggers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cron_expression: Option<String>,

    /// Interval in seconds (for schedule triggers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_seconds: Option<u64>,

    /// Metric name (for threshold triggers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metric_name: Option<String>,

    /// Threshold value (for threshold triggers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold_value: Option<f64>,

    /// Threshold operator
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold_operator: Option<ThresholdOperator>,
}

/// RetryConfig - Configuration for retry behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RetryConfig {
    /// Maximum number of retry attempts
    #[serde(default = "default_max_attempts")]
    pub max_attempts: u32,

    /// Initial backoff in milliseconds
    #[serde(default = "default_backoff_ms")]
    pub backoff_ms: u64,

    /// Backoff multiplier for exponential backoff
    #[serde(default = "default_backoff_multiplier")]
    pub backoff_multiplier: f64,
}

fn default_max_attempts() -> u32 {
    3
}

fn default_backoff_ms() -> u64 {
    1000
}

fn default_backoff_multiplier() -> f64 {
    2.0
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: default_max_attempts(),
            backoff_ms: default_backoff_ms(),
            backoff_multiplier: default_backoff_multiplier(),
        }
    }
}

/// TargetBindingConfig - Where to write the result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetBindingConfig {
    /// Target type (where to write the result)
    pub target_type: TargetBindingType,

    /// Custom target path (for custom target type)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_path: Option<String>,
}

/// TargetBindingType - What kind of target to bind to
/// @see packages/enact-schemas/src/execution.schemas.ts - targetBindingTypeSchema
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetBindingType {
    /// Set thread title
    #[serde(rename = "thread.title")]
    ThreadTitle,
    /// Set thread summary
    #[serde(rename = "thread.summary")]
    ThreadSummary,
    /// Set execution summary
    #[serde(rename = "execution.summary")]
    ExecutionSummary,
    /// Add to message metadata
    #[serde(rename = "message.metadata")]
    MessageMetadata,
    /// Create an artifact
    #[serde(rename = "artifact.create")]
    ArtifactCreate,
    /// Write to memory
    #[serde(rename = "memory.write")]
    MemoryWrite,
    /// Custom target (requires targetPath)
    Custom,
}

/// TriggerAction - What to do when the trigger fires
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerActionSchema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerAction {
    /// Callable to invoke
    pub callable_name: String,

    /// Input to pass to the callable
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,

    /// Context to pass
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<HashMap<String, String>>,

    /// System prompt override
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,

    /// Target binding for the result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_binding: Option<TargetBindingConfig>,

    /// Execute in background (fire-and-forget)
    #[serde(default = "default_background")]
    pub background: bool,

    /// Retry configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry: Option<RetryConfig>,
}

fn default_background() -> bool {
    true
}

/// Trigger - Event-based callable invocation definition
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerSchema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Trigger {
    /// Unique trigger identifier
    pub trigger_id: TriggerId,

    /// Tenant that owns this trigger
    pub tenant_id: TenantId,

    /// Human-readable name
    pub name: String,

    /// Optional description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Trigger type
    #[serde(rename = "type")]
    pub trigger_type: TriggerType,

    /// Current status
    #[serde(default)]
    pub status: TriggerStatus,

    /// Condition (when to fire)
    pub condition: TriggerCondition,

    /// Action (what to do when fired)
    pub action: TriggerAction,

    /// When to start listening
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_at: Option<DateTime<Utc>>,

    /// When to stop (expire)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_at: Option<DateTime<Utc>>,

    /// Max times to fire (None = unlimited)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fires: Option<u32>,

    /// Times fired so far
    #[serde(default)]
    pub fire_count: u32,

    /// Cooldown in milliseconds (prevent rapid re-firing)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cooldown_ms: Option<u64>,

    /// Last time this trigger fired
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_fired_at: Option<DateTime<Utc>>,

    /// When the trigger was created
    pub created_at: DateTime<Utc>,

    /// When the trigger was last updated
    pub updated_at: DateTime<Utc>,
}

impl Trigger {
    /// Create a new trigger
    pub fn new(
        tenant_id: TenantId,
        name: impl Into<String>,
        trigger_type: TriggerType,
        condition: TriggerCondition,
        action: TriggerAction,
    ) -> Self {
        let now = Utc::now();
        Self {
            trigger_id: TriggerId::new(),
            tenant_id,
            name: name.into(),
            description: None,
            trigger_type,
            status: TriggerStatus::Active,
            condition,
            action,
            start_at: None,
            end_at: None,
            max_fires: None,
            fire_count: 0,
            cooldown_ms: None,
            last_fired_at: None,
            created_at: now,
            updated_at: now,
        }
    }

    /// Check if the trigger can fire right now
    pub fn can_fire(&self) -> bool {
        // Must be active
        if self.status != TriggerStatus::Active {
            return false;
        }

        let now = Utc::now();

        // Check start_at
        if let Some(start_at) = self.start_at {
            if now < start_at {
                return false;
            }
        }

        // Check end_at
        if let Some(end_at) = self.end_at {
            if now > end_at {
                return false;
            }
        }

        // Check max_fires
        if let Some(max_fires) = self.max_fires {
            if self.fire_count >= max_fires {
                return false;
            }
        }

        // Check cooldown
        if let (Some(cooldown_ms), Some(last_fired_at)) = (self.cooldown_ms, self.last_fired_at) {
            let cooldown = chrono::Duration::milliseconds(cooldown_ms as i64);
            if now < last_fired_at + cooldown {
                return false;
            }
        }

        true
    }

    /// Record that the trigger fired
    pub fn record_fire(&mut self) {
        self.fire_count += 1;
        self.last_fired_at = Some(Utc::now());
        self.updated_at = Utc::now();

        // Check if we've hit max_fires
        if let Some(max_fires) = self.max_fires {
            if self.fire_count >= max_fires {
                self.status = TriggerStatus::Fired;
            }
        }
    }

    /// Pause the trigger
    pub fn pause(&mut self) {
        self.status = TriggerStatus::Paused;
        self.updated_at = Utc::now();
    }

    /// Resume the trigger
    pub fn resume(&mut self) {
        if self.status == TriggerStatus::Paused {
            self.status = TriggerStatus::Active;
            self.updated_at = Utc::now();
        }
    }

    /// Disable the trigger
    pub fn disable(&mut self) {
        self.status = TriggerStatus::Disabled;
        self.updated_at = Utc::now();
    }
}

/// TriggerFiredEvent - Emitted when a trigger fires
/// @see packages/enact-schemas/src/execution.schemas.ts - triggerFiredEventSchema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerFiredEvent {
    pub trigger_id: TriggerId,
    pub trigger_name: String,
    pub trigger_type: TriggerType,
    pub execution_id: ExecutionId,
    pub fired_at: DateTime<Utc>,
    pub trigger_source: serde_json::Value,
}

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

    #[test]
    fn test_trigger_id_generation() {
        let id = TriggerId::new();
        assert!(id.as_str().starts_with("trigger_"));
        assert_eq!(id.as_str().len(), 35); // "trigger_" + 27 chars
    }

    #[test]
    fn test_trigger_can_fire() {
        let tenant_id = TenantId::new();
        let condition = TriggerCondition {
            event_type: Some("execution.completed".to_string()),
            ..Default::default()
        };
        let action = TriggerAction {
            callable_name: "summarizer".to_string(),
            input: None,
            context: None,
            system_prompt: None,
            target_binding: Some(TargetBindingConfig {
                target_type: TargetBindingType::ThreadTitle,
                target_path: None,
            }),
            background: true,
            retry: None,
        };

        let mut trigger = Trigger::new(
            tenant_id,
            "Auto-title",
            TriggerType::Event,
            condition,
            action,
        );

        assert!(trigger.can_fire());

        // Record fire and check again
        trigger.record_fire();
        assert_eq!(trigger.fire_count, 1);
        assert!(trigger.last_fired_at.is_some());
    }

    #[test]
    fn test_trigger_max_fires() {
        let tenant_id = TenantId::new();
        let mut trigger = Trigger::new(
            tenant_id,
            "One-shot",
            TriggerType::Event,
            TriggerCondition::default(),
            TriggerAction {
                callable_name: "task".to_string(),
                input: None,
                context: None,
                system_prompt: None,
                target_binding: None,
                background: true,
                retry: None,
            },
        );

        trigger.max_fires = Some(1);

        assert!(trigger.can_fire());
        trigger.record_fire();
        assert!(!trigger.can_fire());
        assert_eq!(trigger.status, TriggerStatus::Fired);
    }
}