awaken-contract 0.4.0

Core types, traits, and state model for the Awaken AI agent runtime
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
//! Run lifecycle, termination reasons, and stop condition specifications.

use serde::{Deserialize, Serialize};

/// Generic stopped payload emitted when a plugin decides to terminate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoppedReason {
    pub code: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

impl StoppedReason {
    #[must_use]
    pub fn new(code: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            detail: None,
        }
    }

    #[must_use]
    pub fn with_detail(code: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            detail: Some(detail.into()),
        }
    }
}

/// Why a run terminated.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum TerminationReason {
    /// LLM returned a response with no tool calls.
    NaturalEnd,
    /// A behavior requested inference skip.
    #[serde(alias = "plugin_requested")]
    BehaviorRequested,
    /// A configured stop condition fired.
    Stopped(StoppedReason),
    /// External run cancellation signal was received.
    Cancelled,
    /// A tool permission checker blocked the run.
    Blocked(String),
    /// Run paused waiting for external suspended tool-call resolution.
    Suspended,
    /// Run ended due to an error path.
    Error(String),
}

impl TerminationReason {
    #[must_use]
    pub fn stopped(code: impl Into<String>) -> Self {
        Self::Stopped(StoppedReason::new(code))
    }

    #[must_use]
    pub fn stopped_with_detail(code: impl Into<String>, detail: impl Into<String>) -> Self {
        Self::Stopped(StoppedReason::with_detail(code, detail))
    }

    /// Reconstruct a `TerminationReason` from the `done_reason` string stored in `RunLifecycleState`.
    pub fn from_done_reason(reason: &str) -> Self {
        match reason {
            "natural" => Self::NaturalEnd,
            "behavior_requested" => Self::BehaviorRequested,
            "cancelled" => Self::Cancelled,
            s if s.starts_with("blocked:") => {
                Self::Blocked(s.trim_start_matches("blocked:").to_string())
            }
            s if s.starts_with("stopped:") => {
                Self::Stopped(StoppedReason::new(s.trim_start_matches("stopped:")))
            }
            s if s.starts_with("error:") => Self::Error(s.trim_start_matches("error:").to_string()),
            other => Self::Error(other.to_string()),
        }
    }

    /// Map termination reason to durable run status and optional done_reason string.
    pub fn to_run_status(&self) -> (RunStatus, Option<String>) {
        match self {
            Self::Suspended => (RunStatus::Waiting, None),
            Self::NaturalEnd => (RunStatus::Done, Some("natural".to_string())),
            Self::BehaviorRequested => (RunStatus::Done, Some("behavior_requested".to_string())),
            Self::Cancelled => (RunStatus::Done, Some("cancelled".to_string())),
            Self::Blocked(reason) => (RunStatus::Done, Some(format!("blocked:{reason}"))),
            Self::Error(_) => (RunStatus::Done, Some("error".to_string())),
            Self::Stopped(stopped) => (RunStatus::Done, Some(format!("stopped:{}", stopped.code))),
        }
    }
}

/// Coarse run lifecycle status.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunStatus {
    /// Run has been accepted as a user intent but has not started executing.
    Created,
    /// Run is actively executing.
    #[default]
    Running,
    /// Run is waiting for external decisions.
    Waiting,
    /// Run has reached a terminal state.
    Done,
}

impl RunStatus {
    /// Whether this lifecycle status is terminal.
    pub fn is_terminal(self) -> bool {
        matches!(self, RunStatus::Done)
    }

    /// Validate lifecycle transition from `self` to `next`.
    pub fn can_transition_to(self, next: Self) -> bool {
        if self == next {
            return true;
        }
        match self {
            RunStatus::Created => matches!(next, RunStatus::Running | RunStatus::Done),
            RunStatus::Running => matches!(next, RunStatus::Waiting | RunStatus::Done),
            RunStatus::Waiting => matches!(next, RunStatus::Running | RunStatus::Done),
            RunStatus::Done => false,
        }
    }
}

/// Declarative stop-condition configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StopConditionSpec {
    MaxRounds { rounds: usize },
    Timeout { seconds: u64 },
    TokenBudget { max_total: usize },
    ConsecutiveErrors { max: usize },
    StopOnTool { tool_name: String },
    ContentMatch { pattern: String },
    LoopDetection { window: usize },
}

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

    #[test]
    fn run_status_transitions_match_state_machine() {
        assert!(RunStatus::Created.can_transition_to(RunStatus::Running));
        assert!(RunStatus::Created.can_transition_to(RunStatus::Done));
        assert!(RunStatus::Running.can_transition_to(RunStatus::Waiting));
        assert!(RunStatus::Running.can_transition_to(RunStatus::Done));
        assert!(RunStatus::Waiting.can_transition_to(RunStatus::Running));
        assert!(RunStatus::Waiting.can_transition_to(RunStatus::Done));
        assert!(RunStatus::Running.can_transition_to(RunStatus::Running));
    }

    #[test]
    fn run_status_rejects_done_reopen_transitions() {
        assert!(!RunStatus::Done.can_transition_to(RunStatus::Running));
        assert!(!RunStatus::Done.can_transition_to(RunStatus::Waiting));
    }

    #[test]
    fn run_status_terminal_matches_done_only() {
        assert!(!RunStatus::Created.is_terminal());
        assert!(!RunStatus::Running.is_terminal());
        assert!(!RunStatus::Waiting.is_terminal());
        assert!(RunStatus::Done.is_terminal());
    }

    #[test]
    fn termination_reason_to_run_status_mapping() {
        let cases = vec![
            (TerminationReason::Suspended, RunStatus::Waiting, None),
            (
                TerminationReason::NaturalEnd,
                RunStatus::Done,
                Some("natural"),
            ),
            (
                TerminationReason::BehaviorRequested,
                RunStatus::Done,
                Some("behavior_requested"),
            ),
            (
                TerminationReason::Cancelled,
                RunStatus::Done,
                Some("cancelled"),
            ),
            (
                TerminationReason::Blocked("unsafe tool".to_string()),
                RunStatus::Done,
                Some("blocked:unsafe tool"),
            ),
            (
                TerminationReason::Error("test error".to_string()),
                RunStatus::Done,
                Some("error"),
            ),
            (
                TerminationReason::stopped("max_turns"),
                RunStatus::Done,
                Some("stopped:max_turns"),
            ),
        ];
        for (reason, expected_status, expected_done) in cases {
            let (status, done) = reason.to_run_status();
            assert_eq!(status, expected_status, "status mismatch for {reason:?}");
            assert_eq!(
                done.as_deref(),
                expected_done,
                "done_reason mismatch for {reason:?}"
            );
        }
    }

    #[test]
    fn termination_reason_serde_roundtrip() {
        let reasons = vec![
            TerminationReason::NaturalEnd,
            TerminationReason::BehaviorRequested,
            TerminationReason::stopped_with_detail("max_turns", "reached 10 rounds"),
            TerminationReason::Cancelled,
            TerminationReason::Blocked("unsafe".into()),
            TerminationReason::Suspended,
            TerminationReason::Error("oops".into()),
        ];
        for reason in reasons {
            let json = serde_json::to_string(&reason).unwrap();
            let parsed: TerminationReason = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, reason);
        }
    }

    #[test]
    fn stopped_reason_helpers_build_expected_values() {
        let simple = StoppedReason::new("budget");
        assert_eq!(simple.code, "budget");
        assert!(simple.detail.is_none());

        let detailed = StoppedReason::with_detail("budget", "limit reached");
        assert_eq!(detailed.code, "budget");
        assert_eq!(detailed.detail.as_deref(), Some("limit reached"));

        assert_eq!(
            TerminationReason::stopped("budget"),
            TerminationReason::Stopped(simple)
        );
        assert_eq!(
            TerminationReason::stopped_with_detail("budget", "limit reached"),
            TerminationReason::Stopped(detailed)
        );
    }

    #[test]
    fn stop_condition_spec_serde_roundtrip() {
        let specs = vec![
            StopConditionSpec::MaxRounds { rounds: 10 },
            StopConditionSpec::Timeout { seconds: 300 },
            StopConditionSpec::TokenBudget { max_total: 100_000 },
            StopConditionSpec::ConsecutiveErrors { max: 3 },
            StopConditionSpec::StopOnTool {
                tool_name: "done".into(),
            },
            StopConditionSpec::ContentMatch {
                pattern: r"\bDONE\b".into(),
            },
            StopConditionSpec::LoopDetection { window: 5 },
        ];
        for spec in specs {
            let json = serde_json::to_string(&spec).unwrap();
            let parsed: StopConditionSpec = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, spec);
        }
    }

    #[test]
    fn run_status_serde_roundtrip() {
        for status in [
            RunStatus::Created,
            RunStatus::Running,
            RunStatus::Waiting,
            RunStatus::Done,
        ] {
            let json = serde_json::to_string(&status).unwrap();
            let parsed: RunStatus = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, status);
        }
    }

    #[test]
    fn termination_reason_from_done_reason_natural() {
        let reason = TerminationReason::from_done_reason("natural");
        assert_eq!(reason, TerminationReason::NaturalEnd);
    }

    #[test]
    fn termination_reason_from_done_reason_behavior_requested() {
        let reason = TerminationReason::from_done_reason("behavior_requested");
        assert_eq!(reason, TerminationReason::BehaviorRequested);
    }

    #[test]
    fn termination_reason_from_done_reason_cancelled() {
        let reason = TerminationReason::from_done_reason("cancelled");
        assert_eq!(reason, TerminationReason::Cancelled);
    }

    #[test]
    fn termination_reason_from_done_reason_blocked() {
        let reason = TerminationReason::from_done_reason("blocked:unsafe tool");
        assert_eq!(
            reason,
            TerminationReason::Blocked("unsafe tool".to_string())
        );
    }

    #[test]
    fn termination_reason_from_done_reason_stopped() {
        let reason = TerminationReason::from_done_reason("stopped:max_turns");
        assert_eq!(
            reason,
            TerminationReason::Stopped(StoppedReason::new("max_turns"))
        );
    }

    #[test]
    fn termination_reason_from_done_reason_error() {
        let reason = TerminationReason::from_done_reason("error:boom");
        assert_eq!(reason, TerminationReason::Error("boom".to_string()));
    }

    #[test]
    fn termination_reason_from_done_reason_unknown_becomes_error() {
        let reason = TerminationReason::from_done_reason("unknown_value");
        assert_eq!(
            reason,
            TerminationReason::Error("unknown_value".to_string())
        );
    }

    #[test]
    fn run_status_done_self_transition() {
        assert!(RunStatus::Done.can_transition_to(RunStatus::Done));
    }

    #[test]
    fn termination_reason_stopped_with_detail_serde_roundtrip() {
        let reason = TerminationReason::stopped_with_detail("budget", "limit reached");
        let json = serde_json::to_string(&reason).unwrap();
        let parsed: TerminationReason = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, reason);
        if let TerminationReason::Stopped(s) = &parsed {
            assert_eq!(s.code, "budget");
            assert_eq!(s.detail.as_deref(), Some("limit reached"));
        } else {
            panic!("expected Stopped variant");
        }
    }

    #[test]
    fn stopped_reason_omits_none_detail_in_serde() {
        let reason = StoppedReason::new("budget");
        let json = serde_json::to_string(&reason).unwrap();
        assert!(!json.contains("detail"));
    }

    #[test]
    fn termination_reason_from_done_reason_malformed_input() {
        // Empty string: falls through to the catch-all, becomes Error("").
        let empty = TerminationReason::from_done_reason("");
        assert_eq!(empty, TerminationReason::Error(String::new()));

        // Unknown prefix without colon: becomes Error with the whole string.
        let unknown = TerminationReason::from_done_reason("gibberish_no_prefix");
        assert_eq!(
            unknown,
            TerminationReason::Error("gibberish_no_prefix".to_string())
        );

        // Extra colons in blocked value: everything after "blocked:" is kept as-is.
        let extra_colons = TerminationReason::from_done_reason("blocked:reason:with:colons");
        assert_eq!(
            extra_colons,
            TerminationReason::Blocked("reason:with:colons".to_string())
        );

        // Extra colons in stopped value: everything after "stopped:" is kept as code.
        let stopped_colons = TerminationReason::from_done_reason("stopped:code:extra");
        assert_eq!(
            stopped_colons,
            TerminationReason::Stopped(StoppedReason::new("code:extra"))
        );

        // Extra colons in error value: everything after "error:" is kept.
        let error_colons = TerminationReason::from_done_reason("error:msg:detail");
        assert_eq!(
            error_colons,
            TerminationReason::Error("msg:detail".to_string())
        );

        // Prefix with empty value after colon.
        let blocked_empty = TerminationReason::from_done_reason("blocked:");
        assert_eq!(blocked_empty, TerminationReason::Blocked(String::new()));

        let stopped_empty = TerminationReason::from_done_reason("stopped:");
        assert_eq!(
            stopped_empty,
            TerminationReason::Stopped(StoppedReason::new(""))
        );

        let error_empty = TerminationReason::from_done_reason("error:");
        assert_eq!(error_empty, TerminationReason::Error(String::new()));
    }

    #[test]
    fn stop_condition_all_variants_serde() {
        use serde_json::json;

        let cases: Vec<(StopConditionSpec, serde_json::Value)> = vec![
            (
                StopConditionSpec::MaxRounds { rounds: 10 },
                json!({"type": "max_rounds", "rounds": 10}),
            ),
            (
                StopConditionSpec::Timeout { seconds: 300 },
                json!({"type": "timeout", "seconds": 300}),
            ),
            (
                StopConditionSpec::TokenBudget { max_total: 50_000 },
                json!({"type": "token_budget", "max_total": 50000}),
            ),
            (
                StopConditionSpec::ConsecutiveErrors { max: 3 },
                json!({"type": "consecutive_errors", "max": 3}),
            ),
            (
                StopConditionSpec::StopOnTool {
                    tool_name: "finish".into(),
                },
                json!({"type": "stop_on_tool", "tool_name": "finish"}),
            ),
            (
                StopConditionSpec::ContentMatch {
                    pattern: r"(?i)complete".into(),
                },
                json!({"type": "content_match", "pattern": "(?i)complete"}),
            ),
            (
                StopConditionSpec::LoopDetection { window: 4 },
                json!({"type": "loop_detection", "window": 4}),
            ),
        ];

        for (spec, expected_json) in &cases {
            // Verify serialization matches expected JSON structure.
            let serialized = serde_json::to_value(spec).unwrap();
            assert_eq!(
                &serialized, expected_json,
                "Serialization mismatch for {spec:?}"
            );

            // Verify deserialization from expected JSON produces the correct variant.
            let parsed: StopConditionSpec = serde_json::from_value(expected_json.clone()).unwrap();
            assert_eq!(
                &parsed, spec,
                "Deserialization mismatch for {expected_json}"
            );
        }
    }

    #[test]
    fn run_status_all_valid_transitions() {
        // Valid transitions (including self-transitions).
        let valid = [
            (RunStatus::Created, RunStatus::Created),
            (RunStatus::Created, RunStatus::Running),
            (RunStatus::Created, RunStatus::Done),
            (RunStatus::Running, RunStatus::Running),
            (RunStatus::Running, RunStatus::Waiting),
            (RunStatus::Running, RunStatus::Done),
            (RunStatus::Waiting, RunStatus::Running),
            (RunStatus::Waiting, RunStatus::Waiting),
            (RunStatus::Waiting, RunStatus::Done),
            (RunStatus::Done, RunStatus::Done),
        ];
        for (from, to) in &valid {
            assert!(
                from.can_transition_to(*to),
                "Expected valid transition: {from:?} -> {to:?}"
            );
        }

        // Invalid transitions: Done cannot go back to Running or Waiting.
        let invalid = [
            (RunStatus::Created, RunStatus::Waiting),
            (RunStatus::Done, RunStatus::Running),
            (RunStatus::Done, RunStatus::Waiting),
            (RunStatus::Done, RunStatus::Created),
        ];
        for (from, to) in &invalid {
            assert!(
                !from.can_transition_to(*to),
                "Expected invalid transition: {from:?} -> {to:?}"
            );
        }
    }
}