awaken-runtime 0.4.0

Phase-based execution engine, plugin system, and agent loop for Awaken
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
//! Integration tests for the runtime event lifecycle.
//!
//! Verifies the actual event sequences produced by `AgentRuntime::run()`
//! under different scenarios: simple text, max-rounds termination, and
//! tool-call flows.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use async_trait::async_trait;
use serde_json::{Value, json};

use awaken_contract::StateError;
use awaken_contract::contract::content::ContentBlock;
use awaken_contract::contract::event::AgentEvent;
use awaken_contract::contract::event_sink::{EventSink, VecEventSink};
use awaken_contract::contract::executor::{InferenceExecutionError, InferenceRequest, LlmExecutor};
use awaken_contract::contract::inference::{StopReason, StreamResult, TokenUsage};
use awaken_contract::contract::lifecycle::TerminationReason;
use awaken_contract::contract::message::{Message, ToolCall};
use awaken_contract::contract::tool::{
    Tool, ToolCallContext, ToolDescriptor, ToolError, ToolOutput, ToolResult,
};
use awaken_contract::state::{StateKey, StateKeyOptions};

use awaken_runtime::engine::MockLlmExecutor;
use awaken_runtime::execution::ParallelToolExecutor;
use awaken_runtime::loop_runner::build_agent_env;
use awaken_runtime::phase::ToolGateHook;
use awaken_runtime::plugins::{Plugin, PluginDescriptor, PluginRegistrar};
use awaken_runtime::registry::{AgentResolver, ResolvedAgent};
use awaken_runtime::runtime::{AgentRuntime, RunRequest};
use awaken_runtime::{PhaseContext, StateCommand};

struct ScriptedLlm {
    responses: std::sync::Mutex<Vec<StreamResult>>,
}

impl ScriptedLlm {
    fn new(responses: Vec<StreamResult>) -> Self {
        Self {
            responses: std::sync::Mutex::new(responses),
        }
    }
}

#[async_trait]
impl LlmExecutor for ScriptedLlm {
    async fn execute(
        &self,
        _request: InferenceRequest,
    ) -> Result<StreamResult, InferenceExecutionError> {
        let mut responses = self.responses.lock().expect("lock poisoned");
        Ok(responses.remove(0))
    }

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

struct SuspendOnceTool {
    calls: AtomicUsize,
}

#[async_trait]
impl Tool for SuspendOnceTool {
    fn descriptor(&self) -> ToolDescriptor {
        ToolDescriptor::new("dangerous", "dangerous", "suspend once")
    }

    async fn execute(&self, _args: Value, _ctx: &ToolCallContext) -> Result<ToolOutput, ToolError> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        if n == 0 {
            Ok(ToolResult::suspended("dangerous", "needs approval").into())
        } else {
            Ok(ToolResult::success("dangerous", json!({"ok": true})).into())
        }
    }
}

struct UnlockState;

impl StateKey for UnlockState {
    const KEY: &'static str = "test.event_lifecycle.unlock_state";
    type Value = bool;
    type Update = bool;

    fn apply(value: &mut Self::Value, update: Self::Update) {
        *value = update;
    }
}

struct UnlockTool {
    calls: Arc<AtomicUsize>,
}

#[async_trait]
impl Tool for UnlockTool {
    fn descriptor(&self) -> ToolDescriptor {
        ToolDescriptor::new("unlock", "unlock", "marks the guard as unlocked")
    }

    async fn execute(&self, _args: Value, _ctx: &ToolCallContext) -> Result<ToolOutput, ToolError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        let mut cmd = StateCommand::new();
        cmd.update::<UnlockState>(true);
        Ok(ToolOutput::with_command(
            ToolResult::success("unlock", json!({"unlocked": true})),
            cmd,
        ))
    }
}

struct GuardedTool {
    calls: Arc<AtomicUsize>,
}

#[async_trait]
impl Tool for GuardedTool {
    fn descriptor(&self) -> ToolDescriptor {
        ToolDescriptor::new("guarded", "guarded", "requires unlock state")
    }

    async fn execute(&self, _args: Value, _ctx: &ToolCallContext) -> Result<ToolOutput, ToolError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        Ok(ToolResult::success("guarded", json!({"ok": true})).into())
    }
}

#[derive(Clone)]
struct UnlockGuardHook;

#[async_trait]
impl ToolGateHook for UnlockGuardHook {
    async fn run(
        &self,
        ctx: &PhaseContext,
    ) -> Result<Option<awaken_contract::contract::tool_intercept::ToolInterceptPayload>, StateError>
    {
        let Some(tool_name) = ctx.tool_name.as_deref() else {
            return Ok(None);
        };
        if tool_name != "guarded" || ctx.state::<UnlockState>().copied().unwrap_or(false) {
            return Ok(None);
        }
        Ok(Some(
            awaken_contract::contract::tool_intercept::ToolInterceptPayload::Block {
                reason: "guarded tool requires unlock".into(),
            },
        ))
    }
}

struct UnlockGuardPlugin;

impl Plugin for UnlockGuardPlugin {
    fn descriptor(&self) -> PluginDescriptor {
        PluginDescriptor {
            name: "unlock-guard-plugin",
        }
    }

    fn register(&self, registrar: &mut PluginRegistrar) -> Result<(), StateError> {
        registrar.register_key::<UnlockState>(StateKeyOptions::default())?;
        registrar.register_tool_gate_hook("unlock-guard-plugin", UnlockGuardHook)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

struct FixedResolver {
    agent: ResolvedAgent,
    plugins: Vec<Arc<dyn Plugin>>,
}

impl AgentResolver for FixedResolver {
    fn resolve(&self, _agent_id: &str) -> Result<ResolvedAgent, awaken_runtime::RuntimeError> {
        let mut agent = self.agent.clone();
        agent.env = build_agent_env(&self.plugins, &agent)?;
        Ok(agent)
    }
}

fn event_type(e: &AgentEvent) -> &'static str {
    match e {
        AgentEvent::RunStart { .. } => "run_start",
        AgentEvent::RunFinish { .. } => "run_finish",
        AgentEvent::StepStart { .. } => "step_start",
        AgentEvent::StepEnd => "step_end",
        AgentEvent::TextDelta { .. } => "text_delta",
        AgentEvent::ToolCallStart { .. } => "tool_call_start",
        AgentEvent::ToolCallDelta { .. } => "tool_call_delta",
        AgentEvent::ToolCallReady { .. } => "tool_call_ready",
        AgentEvent::ToolCallDone { .. } => "tool_call_done",
        AgentEvent::InferenceComplete { .. } => "inference_complete",
        AgentEvent::StateSnapshot { .. } => "state_snapshot",
        AgentEvent::StateDelta { .. } => "state_delta",
        AgentEvent::ReasoningDelta { .. } => "reasoning_delta",
        AgentEvent::ReasoningEncryptedValue { .. } => "reasoning_encrypted_value",
        AgentEvent::MessagesSnapshot { .. } => "messages_snapshot",
        AgentEvent::ActivitySnapshot { .. } => "activity_snapshot",
        AgentEvent::ActivityDelta { .. } => "activity_delta",
        AgentEvent::ToolCallResumed { .. } => "tool_call_resumed",
        AgentEvent::ToolCallStreamDelta { .. } => "tool_call_stream_delta",
        AgentEvent::ToolCallCancel { .. } => "tool_call_cancel",
        AgentEvent::StreamReset { .. } => "stream_reset",
        AgentEvent::Error { .. } => "error",
    }
}

fn verify_event_ordering(events: &[AgentEvent]) {
    let types: Vec<&str> = events.iter().map(event_type).collect();

    assert!(!types.is_empty(), "no events emitted");
    assert_eq!(
        types[0], "run_start",
        "first event must be run_start, got: {types:?}"
    );
    assert_eq!(
        *types.last().unwrap(),
        "run_finish",
        "last event must be run_finish, got: {types:?}"
    );

    let mut step_depth = 0i32;
    for (i, t) in types.iter().enumerate() {
        match *t {
            "step_start" => {
                step_depth += 1;
                assert_eq!(
                    step_depth, 1,
                    "nested step_start without step_end at index {i}: {types:?}"
                );
            }
            "step_end" => {
                step_depth -= 1;
                assert!(
                    step_depth >= 0,
                    "step_end without step_start at index {i}: {types:?}"
                );
            }
            _ => {}
        }
    }
    assert_eq!(
        step_depth, 0,
        "unclosed step: step_start without step_end: {types:?}"
    );
}

fn count_event(events: &[AgentEvent], target: &str) -> usize {
    events.iter().filter(|e| event_type(e) == target).count()
}

// ---------------------------------------------------------------------------
// Test 1: Simple text response — event sequence
// ---------------------------------------------------------------------------

#[tokio::test]
async fn simple_text_response_event_sequence() {
    let llm = Arc::new(MockLlmExecutor::new().with_responses(vec!["Hello!".into()]));
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "You are a test assistant.", llm),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    runtime
        .run(
            RunRequest::new("thread-1", vec![Message::user("hello")]).with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // Verify ordering invariants
    verify_event_ordering(&events);

    // Verify expected event types are present
    assert!(
        types.contains(&"text_delta"),
        "should contain text_delta: {types:?}"
    );
    assert!(
        types.contains(&"inference_complete"),
        "should contain inference_complete: {types:?}"
    );

    // Verify counts
    assert_eq!(count_event(&events, "run_start"), 1);
    assert_eq!(count_event(&events, "run_finish"), 1);
    assert_eq!(count_event(&events, "step_start"), 1);
    assert_eq!(count_event(&events, "step_end"), 1);

    // Verify termination reason is NaturalEnd
    if let AgentEvent::RunFinish { termination, .. } = events.last().unwrap() {
        assert_eq!(*termination, TerminationReason::NaturalEnd);
    } else {
        panic!("last event should be RunFinish");
    }
}

#[tokio::test]
async fn suspended_tool_cancel_emits_resumed_event_and_finishes() {
    let llm = Arc::new(ScriptedLlm::new(vec![
        StreamResult {
            content: vec![ContentBlock::text("tools")],
            tool_calls: vec![ToolCall::new("c1", "dangerous", json!({"note": "x"}))],
            usage: None,
            stop_reason: Some(StopReason::ToolUse),
            has_incomplete_tool_calls: false,
        },
        StreamResult {
            content: vec![ContentBlock::text("understood, not proceeding")],
            tool_calls: vec![],
            usage: None,
            stop_reason: Some(StopReason::EndTurn),
            has_incomplete_tool_calls: false,
        },
    ]));
    let tool = Arc::new(SuspendOnceTool {
        calls: AtomicUsize::new(0),
    });
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("agent", "m", "sys", llm).with_tool(tool),
        plugins: vec![],
    });
    let runtime = Arc::new(AgentRuntime::new(resolver));
    let sink = Arc::new(VecEventSink::new());

    let run_task = {
        let runtime = Arc::clone(&runtime);
        let sink = sink.clone();
        tokio::spawn(async move {
            runtime
                .run(
                    RunRequest::new("thread-deny", vec![Message::user("go")])
                        .with_agent_id("agent"),
                    sink as Arc<dyn EventSink>,
                )
                .await
        })
    };

    let mut sent = false;
    for _ in 0..40 {
        if runtime.send_decisions(
            "thread-deny",
            vec![(
                "c1".into(),
                awaken_contract::contract::suspension::ToolCallResume {
                    decision_id: "d1".into(),
                    action: awaken_contract::contract::suspension::ResumeDecisionAction::Cancel,
                    result: json!({"approved": false}),
                    reason: Some("user denied".into()),
                    updated_at: 1,
                },
            )],
        ) {
            sent = true;
            break;
        }
        tokio::task::yield_now().await;
    }
    assert!(sent, "should send deny decision while run is active");

    let result = run_task
        .await
        .expect("join should succeed")
        .expect("run should succeed");
    assert_eq!(result.termination, TerminationReason::NaturalEnd);

    let events = sink.take();
    verify_event_ordering(&events);
    assert!(
        events.iter().any(|event| matches!(
            event,
            AgentEvent::ToolCallResumed { target_id, result }
                if target_id == "c1" && result.get("approved") == Some(&json!(false))
        )),
        "deny flow should emit ToolCallResumed false: {events:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 2: Max rounds termination — StepEnd emitted before RunFinish
// ---------------------------------------------------------------------------

#[tokio::test]
async fn max_rounds_termination_emits_step_end() {
    let llm = Arc::new(MockLlmExecutor::new().with_responses(vec!["Response".into()]));
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm).with_max_rounds(1),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    runtime
        .run(
            RunRequest::new("thread-max", vec![Message::user("hi")]).with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // Verify ordering invariants
    verify_event_ordering(&events);

    // Verify StepEnd is emitted before RunFinish
    let step_end_idx = types.iter().rposition(|t| *t == "step_end");
    let run_finish_idx = types.iter().rposition(|t| *t == "run_finish");
    assert!(
        step_end_idx.is_some() && run_finish_idx.is_some(),
        "both step_end and run_finish should exist: {types:?}"
    );
    assert!(
        step_end_idx.unwrap() < run_finish_idx.unwrap(),
        "step_end should come before run_finish: {types:?}"
    );

    // With max_rounds=1 and a simple text response (no tool calls),
    // the run should finish naturally since the LLM returned EndTurn
    if let AgentEvent::RunFinish { termination, .. } = events.last().unwrap() {
        // NaturalEnd is expected because the mock returns EndTurn stop reason
        assert_eq!(*termination, TerminationReason::NaturalEnd);
    } else {
        panic!("last event should be RunFinish");
    }
}

// ---------------------------------------------------------------------------
// Test 3: Tool call flow — complete lifecycle
// ---------------------------------------------------------------------------

struct ToolCallMockExecutor {
    call_count: AtomicUsize,
}

#[async_trait]
impl LlmExecutor for ToolCallMockExecutor {
    async fn execute(
        &self,
        _req: InferenceRequest,
    ) -> Result<StreamResult, InferenceExecutionError> {
        let count = self.call_count.fetch_add(1, Ordering::Relaxed);
        if count == 0 {
            // First call: return a tool call
            Ok(StreamResult {
                content: vec![],
                tool_calls: vec![ToolCall::new(
                    "call_1",
                    "get_weather",
                    json!({"location": "Tokyo"}),
                )],
                usage: Some(TokenUsage::default()),
                stop_reason: Some(StopReason::ToolUse),
                has_incomplete_tool_calls: false,
            })
        } else {
            // Second call: return text (after tool result)
            Ok(StreamResult {
                content: vec![ContentBlock::text("It's sunny in Tokyo")],
                tool_calls: vec![],
                usage: Some(TokenUsage::default()),
                stop_reason: Some(StopReason::EndTurn),
                has_incomplete_tool_calls: false,
            })
        }
    }

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

struct GetWeatherTool;

#[async_trait]
impl Tool for GetWeatherTool {
    fn descriptor(&self) -> ToolDescriptor {
        ToolDescriptor::new(
            "get_weather",
            "get_weather",
            "Gets the weather for a location",
        )
    }

    async fn execute(&self, _args: Value, _ctx: &ToolCallContext) -> Result<ToolOutput, ToolError> {
        Ok(ToolResult::success("get_weather", json!({"temp": 25, "condition": "sunny"})).into())
    }
}

#[tokio::test]
async fn tool_call_flow_complete_lifecycle() {
    let llm = Arc::new(ToolCallMockExecutor {
        call_count: AtomicUsize::new(0),
    });
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm).with_tool(Arc::new(GetWeatherTool)),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    runtime
        .run(
            RunRequest::new(
                "thread-tool",
                vec![Message::user("What's the weather in Tokyo?")],
            )
            .with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // Verify ordering invariants
    verify_event_ordering(&events);

    // Verify tool call events are present
    assert!(
        types.contains(&"tool_call_start"),
        "should contain tool_call_start: {types:?}"
    );
    assert!(
        types.contains(&"tool_call_done"),
        "should contain tool_call_done: {types:?}"
    );

    // Verify text delta from the second inference call
    assert!(
        types.contains(&"text_delta"),
        "should contain text_delta: {types:?}"
    );

    // Verify: 2 StepStart and 2 StepEnd (one for tool call round, one for text round)
    assert_eq!(
        count_event(&events, "step_start"),
        2,
        "expected 2 step_start events: {types:?}"
    );
    assert_eq!(
        count_event(&events, "step_end"),
        2,
        "expected 2 step_end events: {types:?}"
    );

    // Verify tool_call_done comes before the second step_start
    let tool_done_idx = types.iter().position(|t| *t == "tool_call_done").unwrap();
    let second_step_start_idx = types
        .iter()
        .enumerate()
        .filter(|(_, t)| **t == "step_start")
        .nth(1)
        .map(|(i, _)| i)
        .unwrap();
    assert!(
        tool_done_idx < second_step_start_idx,
        "tool_call_done ({tool_done_idx}) should come before second step_start ({second_step_start_idx}): {types:?}"
    );

    // Verify termination is NaturalEnd
    if let AgentEvent::RunFinish { termination, .. } = events.last().unwrap() {
        assert_eq!(*termination, TerminationReason::NaturalEnd);
    } else {
        panic!("last event should be RunFinish");
    }
}

#[tokio::test]
async fn prior_tool_state_allows_later_guarded_tool_in_same_step() {
    let llm = Arc::new(ScriptedLlm::new(vec![
        StreamResult {
            content: vec![ContentBlock::text("tools")],
            tool_calls: vec![
                ToolCall::new("u1", "unlock", json!({})),
                ToolCall::new("g1", "guarded", json!({})),
            ],
            usage: None,
            stop_reason: Some(StopReason::ToolUse),
            has_incomplete_tool_calls: false,
        },
        StreamResult {
            content: vec![ContentBlock::text("done")],
            tool_calls: vec![],
            usage: None,
            stop_reason: Some(StopReason::EndTurn),
            has_incomplete_tool_calls: false,
        },
    ]));
    let unlock_calls = Arc::new(AtomicUsize::new(0));
    let guarded_calls = Arc::new(AtomicUsize::new(0));
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm)
            .with_tool(Arc::new(UnlockTool {
                calls: unlock_calls.clone(),
            }))
            .with_tool(Arc::new(GuardedTool {
                calls: guarded_calls.clone(),
            }))
            .with_tool_executor(Arc::new(ParallelToolExecutor::streaming())),
        plugins: vec![Arc::new(UnlockGuardPlugin)],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    let result = runtime
        .run(
            RunRequest::new("thread-unlock", vec![Message::user("go")]).with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    assert_eq!(result.termination, TerminationReason::NaturalEnd);
    assert_eq!(unlock_calls.load(Ordering::SeqCst), 1);
    assert_eq!(guarded_calls.load(Ordering::SeqCst), 1);

    let events = sink.take();
    verify_event_ordering(&events);
    let done_ids: Vec<_> = events
        .iter()
        .filter_map(|event| match event {
            AgentEvent::ToolCallDone { id, outcome, .. } => Some((id.as_str(), *outcome)),
            _ => None,
        })
        .collect();
    assert_eq!(
        done_ids,
        vec![
            (
                "u1",
                awaken_contract::contract::suspension::ToolCallOutcome::Succeeded
            ),
            (
                "g1",
                awaken_contract::contract::suspension::ToolCallOutcome::Succeeded
            ),
        ]
    );
}

#[tokio::test]
async fn guarded_tool_before_unlock_still_blocks_same_step() {
    let llm = Arc::new(ScriptedLlm::new(vec![StreamResult {
        content: vec![ContentBlock::text("tools")],
        tool_calls: vec![
            ToolCall::new("g1", "guarded", json!({})),
            ToolCall::new("u1", "unlock", json!({})),
        ],
        usage: None,
        stop_reason: Some(StopReason::ToolUse),
        has_incomplete_tool_calls: false,
    }]));
    let unlock_calls = Arc::new(AtomicUsize::new(0));
    let guarded_calls = Arc::new(AtomicUsize::new(0));
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm)
            .with_tool(Arc::new(UnlockTool {
                calls: unlock_calls.clone(),
            }))
            .with_tool(Arc::new(GuardedTool {
                calls: guarded_calls.clone(),
            }))
            .with_tool_executor(Arc::new(ParallelToolExecutor::streaming())),
        plugins: vec![Arc::new(UnlockGuardPlugin)],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    let result = runtime
        .run(
            RunRequest::new("thread-blocked-order", vec![Message::user("go")])
                .with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    assert!(
        matches!(result.termination, TerminationReason::Blocked(ref reason) if reason == "guarded tool requires unlock")
    );
    assert_eq!(unlock_calls.load(Ordering::SeqCst), 0);
    assert_eq!(guarded_calls.load(Ordering::SeqCst), 0);

    let events = sink.take();
    verify_event_ordering(&events);
    let done_ids: Vec<_> = events
        .iter()
        .filter_map(|event| match event {
            AgentEvent::ToolCallDone { id, outcome, .. } => Some((id.as_str(), *outcome)),
            _ => None,
        })
        .collect();
    assert_eq!(
        done_ids,
        vec![
            (
                "g1",
                awaken_contract::contract::suspension::ToolCallOutcome::Failed,
            ),
            (
                "u1",
                awaken_contract::contract::suspension::ToolCallOutcome::Failed,
            ),
        ]
    );
}

// ---------------------------------------------------------------------------
// Test 4: Error event on inference failure
// ---------------------------------------------------------------------------

struct FailingLlmExecutor;

#[async_trait]
impl LlmExecutor for FailingLlmExecutor {
    async fn execute(
        &self,
        _req: InferenceRequest,
    ) -> Result<StreamResult, InferenceExecutionError> {
        Err(InferenceExecutionError::Provider("model overloaded".into()))
    }

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

#[tokio::test]
async fn error_event_emitted_on_inference_failure() {
    let llm = Arc::new(FailingLlmExecutor);
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    let result = runtime
        .run(
            RunRequest::new("thread-err", vec![Message::user("hello")]).with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await;

    // The run should return an error because inference failed
    assert!(result.is_err(), "run should fail on inference error");
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("inference failed"),
        "error should be InferenceFailed, got: {err}"
    );

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // RunStart should always be the first event, even on failure
    assert!(
        !types.is_empty(),
        "at least RunStart should have been emitted"
    );
    assert_eq!(
        types[0], "run_start",
        "first event must be run_start even on failure, got: {types:?}"
    );

    // When inference fails, the error propagates before RunFinish is emitted,
    // so RunFinish should NOT be present in the stream.
    assert!(
        !types.contains(&"run_finish"),
        "run_finish should not appear when inference errors out, got: {types:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 5: ActivitySnapshot emitted during tool execution
// ---------------------------------------------------------------------------

struct ActivityReportingToolMockExecutor {
    call_count: AtomicUsize,
}

#[async_trait]
impl LlmExecutor for ActivityReportingToolMockExecutor {
    async fn execute(
        &self,
        _req: InferenceRequest,
    ) -> Result<StreamResult, InferenceExecutionError> {
        let count = self.call_count.fetch_add(1, Ordering::Relaxed);
        if count == 0 {
            Ok(StreamResult {
                content: vec![],
                tool_calls: vec![ToolCall::new(
                    "call_act",
                    "reporting_tool",
                    json!({"task": "report"}),
                )],
                usage: Some(TokenUsage::default()),
                stop_reason: Some(StopReason::ToolUse),
                has_incomplete_tool_calls: false,
            })
        } else {
            Ok(StreamResult {
                content: vec![ContentBlock::text("Done reporting")],
                tool_calls: vec![],
                usage: Some(TokenUsage::default()),
                stop_reason: Some(StopReason::EndTurn),
                has_incomplete_tool_calls: false,
            })
        }
    }

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

/// A tool that emits an ActivitySnapshot via the context's activity_sink.
struct ReportingTool;

#[async_trait]
impl Tool for ReportingTool {
    fn descriptor(&self) -> ToolDescriptor {
        ToolDescriptor::new(
            "reporting_tool",
            "reporting_tool",
            "Reports activity progress",
        )
    }

    async fn execute(&self, _args: Value, ctx: &ToolCallContext) -> Result<ToolOutput, ToolError> {
        // Emit an activity snapshot through the context
        ctx.report_activity("progress", "50% complete").await;
        Ok(ToolResult::success("reporting_tool", json!({"status": "done"})).into())
    }
}

#[tokio::test]
async fn activity_snapshot_emitted_during_tool_execution() {
    let llm = Arc::new(ActivityReportingToolMockExecutor {
        call_count: AtomicUsize::new(0),
    });
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm).with_tool(Arc::new(ReportingTool)),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    runtime
        .run(
            RunRequest::new("thread-activity", vec![Message::user("do task")])
                .with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // Verify ordering invariants
    verify_event_ordering(&events);

    // ActivitySnapshot should be present
    assert!(
        types.contains(&"activity_snapshot"),
        "should contain activity_snapshot: {types:?}"
    );

    // ActivitySnapshot should appear between tool_call_start and tool_call_done
    let tool_start_idx = types.iter().position(|t| *t == "tool_call_start").unwrap();
    let tool_done_idx = types.iter().position(|t| *t == "tool_call_done").unwrap();
    let activity_idx = types
        .iter()
        .position(|t| *t == "activity_snapshot")
        .unwrap();

    assert!(
        activity_idx > tool_start_idx,
        "activity_snapshot ({activity_idx}) should come after tool_call_start ({tool_start_idx}): {types:?}"
    );
    assert!(
        activity_idx < tool_done_idx,
        "activity_snapshot ({activity_idx}) should come before tool_call_done ({tool_done_idx}): {types:?}"
    );

    // Verify the activity snapshot content
    let activity_event = events
        .iter()
        .find(|e| matches!(e, AgentEvent::ActivitySnapshot { .. }))
        .unwrap();
    if let AgentEvent::ActivitySnapshot {
        activity_type,
        content,
        ..
    } = activity_event
    {
        assert_eq!(activity_type, "progress");
        assert_eq!(content, &json!("50% complete"));
    } else {
        panic!("expected ActivitySnapshot");
    }
}

// ---------------------------------------------------------------------------
// Test 6: StateSnapshot emitted after StepEnd
// ---------------------------------------------------------------------------

#[tokio::test]
async fn state_snapshot_emitted_after_step() {
    let llm = Arc::new(MockLlmExecutor::new().with_responses(vec!["Simple reply".into()]));
    let resolver = Arc::new(FixedResolver {
        agent: ResolvedAgent::new("test", "m", "sys", llm),
        plugins: vec![],
    });
    let runtime = AgentRuntime::new(resolver);
    let sink = Arc::new(VecEventSink::new());

    runtime
        .run(
            RunRequest::new("thread-state", vec![Message::user("hi")]).with_agent_id("test"),
            sink.clone() as Arc<dyn EventSink>,
        )
        .await
        .expect("run should succeed");

    let events = sink.take();
    let types: Vec<&str> = events.iter().map(event_type).collect();

    // Verify ordering invariants
    verify_event_ordering(&events);

    // StateSnapshot should be present
    assert!(
        types.contains(&"state_snapshot"),
        "should contain state_snapshot: {types:?}"
    );

    // The orchestrator emits state_snapshot as part of complete_step (before step_end)
    // and also before run_finish. Verify that at least one state_snapshot exists
    // and that a state_snapshot appears before run_finish.
    let last_state_snapshot_idx = types.iter().rposition(|t| *t == "state_snapshot").unwrap();
    let run_finish_idx = types.iter().rposition(|t| *t == "run_finish").unwrap();
    assert!(
        last_state_snapshot_idx < run_finish_idx,
        "state_snapshot ({last_state_snapshot_idx}) should appear before run_finish ({run_finish_idx}): {types:?}"
    );

    // Verify that within complete_step, state_snapshot is emitted before step_end.
    // Find the first step_end and look for a state_snapshot before it.
    let first_step_end_idx = types.iter().position(|t| *t == "step_end").unwrap();
    let has_snapshot_before_step_end = types[..first_step_end_idx].contains(&"state_snapshot");
    assert!(
        has_snapshot_before_step_end,
        "state_snapshot should appear before step_end: {types:?}"
    );

    // Verify the state snapshot is a valid JSON object
    let snapshot_event = events
        .iter()
        .find(|e| matches!(e, AgentEvent::StateSnapshot { .. }))
        .unwrap();
    if let AgentEvent::StateSnapshot { snapshot } = snapshot_event {
        assert!(
            snapshot.is_object(),
            "state snapshot should be a JSON object"
        );
    } else {
        panic!("expected StateSnapshot");
    }
}

// ---------------------------------------------------------------------------
// Test 7: Event ordering invariants on all scenarios combined
// ---------------------------------------------------------------------------

#[tokio::test]
async fn event_ordering_invariants_hold_across_scenarios() {
    // Scenario A: simple text
    {
        let llm = Arc::new(MockLlmExecutor::new());
        let resolver = Arc::new(FixedResolver {
            agent: ResolvedAgent::new("test", "m", "sys", llm),
            plugins: vec![],
        });
        let runtime = AgentRuntime::new(resolver);
        let sink = Arc::new(VecEventSink::new());

        runtime
            .run(
                RunRequest::new("thread-inv-a", vec![Message::user("hi")]).with_agent_id("test"),
                sink.clone() as Arc<dyn EventSink>,
            )
            .await
            .expect("run should succeed");

        verify_event_ordering(&sink.take());
    }

    // Scenario B: tool call flow
    {
        let llm = Arc::new(ToolCallMockExecutor {
            call_count: AtomicUsize::new(0),
        });
        let resolver = Arc::new(FixedResolver {
            agent: ResolvedAgent::new("test", "m", "sys", llm).with_tool(Arc::new(GetWeatherTool)),
            plugins: vec![],
        });
        let runtime = AgentRuntime::new(resolver);
        let sink = Arc::new(VecEventSink::new());

        runtime
            .run(
                RunRequest::new("thread-inv-b", vec![Message::user("weather?")])
                    .with_agent_id("test"),
                sink.clone() as Arc<dyn EventSink>,
            )
            .await
            .expect("run should succeed");

        verify_event_ordering(&sink.take());
    }

    // Scenario C: max_rounds=1 with tool call (forced early stop)
    {
        let llm = Arc::new(ToolCallMockExecutor {
            call_count: AtomicUsize::new(0),
        });
        let resolver = Arc::new(FixedResolver {
            agent: ResolvedAgent::new("test", "m", "sys", llm)
                .with_max_rounds(1)
                .with_tool(Arc::new(GetWeatherTool)),
            plugins: vec![],
        });
        let runtime = AgentRuntime::new(resolver);
        let sink = Arc::new(VecEventSink::new());

        runtime
            .run(
                RunRequest::new("thread-inv-c", vec![Message::user("weather?")])
                    .with_agent_id("test"),
                sink.clone() as Arc<dyn EventSink>,
            )
            .await
            .expect("run should succeed");

        let events = sink.take();
        verify_event_ordering(&events);

        // With max_rounds=1 and a tool call, the run should be stopped
        if let AgentEvent::RunFinish { termination, .. } = events.last().unwrap() {
            // After 1 round with tool use, the loop hits max_rounds
            assert!(
                matches!(termination, TerminationReason::Stopped(_)),
                "expected Stopped termination with max_rounds=1 + tool call, got: {termination:?}"
            );
        }
    }
}