klieo-core 0.41.1

Core traits + runtime for the klieo agent framework.
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
use super::*;
use crate::llm::{FinishReason, LlmClient};
use crate::memory::EpisodicMemory;
use crate::test_utils::{
    fake_context, FakeLlmClient, FakeStreamStep, FakeToolInvoker, InMemoryEpisodic,
};
use std::sync::Arc;
use tokio_stream::StreamExt;

fn ctx_with(llm: Arc<dyn LlmClient>) -> (AgentContext, Arc<InMemoryEpisodic>) {
    let episodic = Arc::new(InMemoryEpisodic::default());
    let mut ctx = fake_context("stream-test");
    ctx.llm = llm;
    ctx.episodic = episodic.clone();
    (ctx, episodic)
}

fn ctx_with_tools(
    llm: Arc<dyn LlmClient>,
    tools: Arc<FakeToolInvoker>,
) -> (AgentContext, Arc<InMemoryEpisodic>) {
    let episodic = Arc::new(InMemoryEpisodic::default());
    let mut ctx = fake_context("stream-test");
    ctx.llm = llm;
    ctx.episodic = episodic.clone();
    ctx.tools = tools;
    (ctx, episodic)
}

fn delta(s: &str) -> ChatChunk {
    ChatChunk {
        delta: s.into(),
        tool_calls: vec![],
        finish_reason: None,
        usage: None,
    }
}

fn final_stop_chunk() -> ChatChunk {
    ChatChunk {
        delta: String::new(),
        tool_calls: vec![],
        finish_reason: Some(FinishReason::Stop),
        usage: None,
    }
}

#[tokio::test(start_paused = true)]
async fn streaming_single_step_forwards_three_chunks() {
    let llm = Arc::new(
        FakeLlmClient::new("fake").with_stream_steps(vec![FakeStreamStep::Chunks(vec![
            Ok(delta("hel")),
            Ok(delta("lo ")),
            Ok(delta("world")),
            Ok(final_stop_chunk()),
        ])]),
    );
    let (ctx, ep) = ctx_with(llm);

    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
        .await
        .expect("stream opens");
    let mut chunks = Vec::new();
    while let Some(item) = s.next().await {
        chunks.push(item.expect("ok chunk"));
    }
    assert_eq!(chunks.len(), 4, "3 deltas + terminal");
    assert_eq!(chunks[0].delta, "hel");
    assert_eq!(chunks[1].delta, "lo ");
    assert_eq!(chunks[2].delta, "world");
    assert_eq!(chunks[3].finish_reason, Some(FinishReason::Stop));

    tokio::task::yield_now().await;
    tokio::task::yield_now().await;

    let events = ep.replay(ctx.run_id).await.unwrap();
    let llm_calls = events
        .iter()
        .filter(|e| matches!(e, Episode::LlmCall { .. }))
        .count();
    let completed = events
        .iter()
        .filter(|e| matches!(e, Episode::Completed))
        .count();
    assert_eq!(llm_calls, 1);
    assert_eq!(completed, 1);
}

#[tokio::test(start_paused = true)]
async fn streaming_tool_call_dispatch_starts_second_cycle() {
    let tool_call = crate::llm::ToolCall {
        id: "tc1".into(),
        name: "echo".into(),
        args: serde_json::json!({"x": 1}),
    };
    let stream1 = vec![Ok(ChatChunk {
        delta: String::new(),
        tool_calls: vec![tool_call.clone()],
        finish_reason: Some(FinishReason::ToolCalls),
        usage: None,
    })];
    let stream2 = vec![Ok(delta("done")), Ok(final_stop_chunk())];

    let llm = Arc::new(FakeLlmClient::new("fake").with_stream_steps(vec![
        FakeStreamStep::Chunks(stream1),
        FakeStreamStep::Chunks(stream2),
    ]));
    let tools = Arc::new(FakeToolInvoker::new().with_tool("echo", "echoes", Ok));
    let (ctx, ep) = ctx_with_tools(llm, tools);

    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
        .await
        .expect("stream opens");
    let mut deltas = Vec::new();
    while let Some(item) = s.next().await {
        deltas.push(item.expect("ok chunk"));
    }

    assert!(deltas.len() >= 3);
    let joined: String = deltas.iter().map(|c| c.delta.clone()).collect();
    assert_eq!(joined, "done");

    let events = ep.replay(ctx.run_id).await.unwrap();
    let llm_calls = events
        .iter()
        .filter(|e| matches!(e, Episode::LlmCall { .. }))
        .count();
    let tool_calls = events
        .iter()
        .filter(|e| matches!(e, Episode::ToolCall { .. }))
        .count();
    assert_eq!(llm_calls, 2, "two LLM cycles recorded");
    assert_eq!(tool_calls, 1, "one tool dispatched");
}

#[tokio::test(start_paused = true)]
async fn streaming_mid_stream_cancellation_emits_cancelled_error() {
    let mut chunks: Vec<Result<ChatChunk, LlmError>> = Vec::new();
    for i in 0..50 {
        chunks.push(Ok(delta(&format!("c{i} "))));
    }
    chunks.push(Ok(final_stop_chunk()));
    let llm = Arc::new(
        FakeLlmClient::new("fake").with_stream_steps(vec![FakeStreamStep::Chunks(chunks)]),
    );
    let (ctx, ep) = ctx_with(llm);

    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
        .await
        .expect("stream opens");

    let first = s.next().await.expect("first chunk").expect("ok");
    assert!(!first.delta.is_empty());
    ctx.cancel.cancel();

    let mut got_cancel_err = false;
    let mut tail_count = 0usize;
    while let Some(item) = s.next().await {
        tail_count += 1;
        match item {
            Err(LlmError::Cancelled) => {
                got_cancel_err = true;
                break;
            }
            Ok(_) => continue,
            Err(other) => panic!("unexpected error: {other:?}"),
        }
    }
    assert!(
        got_cancel_err,
        "expected terminal LlmError::Cancelled item, drained {tail_count} items"
    );

    tokio::task::yield_now().await;
    tokio::task::yield_now().await;

    let events = ep.replay(ctx.run_id).await.unwrap();
    let llm_calls = events
        .iter()
        .filter(|e| matches!(e, Episode::LlmCall { .. }))
        .count();
    assert_eq!(
        llm_calls, 0,
        "partial streaming cycle must not be recorded as a successful LlmCall"
    );
    let completed = events
        .iter()
        .filter(|e| matches!(e, Episode::Completed))
        .count();
    assert_eq!(completed, 0);
}

#[tokio::test(start_paused = true)]
async fn streaming_init_retries_server_then_succeeds() {
    let llm = Arc::new(FakeLlmClient::new("fake").with_stream_steps(vec![
        FakeStreamStep::init_err(LlmError::Server("503".into())),
        FakeStreamStep::Chunks(vec![Ok(delta("ok")), Ok(final_stop_chunk())]),
    ]));
    let (ctx, _ep) = ctx_with(llm.clone());

    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
        .await
        .expect("stream opens after retry");
    while let Some(item) = s.next().await {
        item.expect("ok");
    }
    assert_eq!(llm.stream_call_count(), 2, "one failure + one success");
}

#[tokio::test(start_paused = true)]
async fn streaming_init_unauthorized_propagates_after_one_attempt() {
    let llm = Arc::new(
        FakeLlmClient::new("fake")
            .with_stream_steps(vec![FakeStreamStep::init_err(LlmError::Unauthorized)]),
    );
    let (ctx, _ep) = ctx_with(llm.clone());

    let res = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    match res {
        Ok(_) => panic!("expected Unauthorized, got Ok"),
        Err(Error::Llm(LlmError::Unauthorized)) => {}
        Err(other) => panic!("expected Llm(Unauthorized), got {other:?}"),
    }
    assert_eq!(
        llm.stream_call_count(),
        1,
        "non-retryable: exactly one attempt"
    );
}

#[tokio::test(start_paused = true)]
async fn streaming_max_steps_exceeded_when_tools_loop() {
    let tool_call = crate::llm::ToolCall {
        id: "tc1".into(),
        name: "echo".into(),
        args: serde_json::json!({}),
    };
    let mk_tool_stream = || {
        FakeStreamStep::Chunks(vec![Ok(ChatChunk {
            delta: String::new(),
            tool_calls: vec![tool_call.clone()],
            finish_reason: Some(FinishReason::ToolCalls),
            usage: None,
        })])
    };
    let llm = Arc::new(FakeLlmClient::new("fake").with_stream_steps(vec![
        mk_tool_stream(),
        mk_tool_stream(),
        mk_tool_stream(),
        mk_tool_stream(),
        mk_tool_stream(),
    ]));
    let tools = Arc::new(
        FakeToolInvoker::new().with_tool("echo", "echoes", |_| Ok(serde_json::json!("ok"))),
    );
    let (ctx, ep) = ctx_with_tools(llm, tools);

    let opts = RunOptions {
        max_steps: 2,
        ..RunOptions::default()
    };
    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), opts)
        .await
        .expect("stream opens");

    let mut got_max_steps_err = false;
    while let Some(item) = s.next().await {
        if let Err(LlmError::Server(ref m)) = item {
            if m.contains("max steps exceeded") {
                got_max_steps_err = true;
            }
        }
    }
    assert!(
        got_max_steps_err,
        "expected terminal Err(Server(\"max steps exceeded: ...\")) before stream-close"
    );

    tokio::task::yield_now().await;
    tokio::task::yield_now().await;

    let events = ep.replay(ctx.run_id).await.unwrap();
    let failed = events
        .iter()
        .find(|e| matches!(e, Episode::Failed { .. }))
        .expect("must record Failed");
    match failed {
        Episode::Failed { error } => {
            assert!(
                error.contains("max steps"),
                "expected max-steps message, got {error}"
            );
        }
        _ => unreachable!(),
    }
}

#[tokio::test(start_paused = true)]
async fn streaming_response_byte_cap_aborts_oversized_stream() {
    let mut chunks: Vec<Result<ChatChunk, LlmError>> = Vec::new();
    for i in 0..20 {
        chunks.push(Ok(delta(&format!("payload-block-{i:02}"))));
    }
    chunks.push(Ok(final_stop_chunk()));
    let llm = Arc::new(
        FakeLlmClient::new("fake").with_stream_steps(vec![FakeStreamStep::Chunks(chunks)]),
    );
    let (ctx, ep) = ctx_with(llm);

    let opts = RunOptions {
        max_response_bytes: 64,
        ..RunOptions::default()
    };
    let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), opts)
        .await
        .expect("stream opens");

    let mut saw_cap_err = false;
    while let Some(item) = s.next().await {
        if let Err(LlmError::Server(ref m)) = item {
            if m.contains("max_response_bytes cap") {
                saw_cap_err = true;
                break;
            }
        }
    }
    assert!(
        saw_cap_err,
        "expected terminal Err carrying the byte-cap message"
    );

    tokio::task::yield_now().await;
    tokio::task::yield_now().await;

    let events = ep.replay(ctx.run_id).await.unwrap();
    let saw_failed = events.iter().any(
        |e| matches!(e, Episode::Failed { error } if error.contains("max_response_bytes cap")),
    );
    assert!(
        saw_failed,
        "expected Failed episode mentioning max_response_bytes cap, events: {events:?}"
    );
}

// ── AgentEvent emission tests ─────────────────────────────────────────────────

/// Scenario labels for the shared `build_ctx_for_events` helper.
enum LlmScenario {
    /// LLM returns one final text response immediately.
    FinalText,
    /// LLM returns one tool-call step then a final text response.
    OneToolCall,
    /// LLM always returns a tool-call step (infinite loop until max_steps).
    InfiniteToolLoop,
}

/// Which tool outcome to simulate.
enum ToolBehaviour {
    Succeeds,
    Fails,
}

/// Build an `AgentContext` wired to `progress` tx and program the
/// `FakeLlmClient` + `FakeToolInvoker` according to the supplied
/// scenario. Returns `(ctx, broadcast_receiver)`.
fn build_ctx_for_events(
    scenario: LlmScenario,
    tool_behaviour: ToolBehaviour,
    tx: tokio::sync::broadcast::Sender<crate::agent::AgentEvent>,
) -> AgentContext {
    use crate::error::ToolError;
    use crate::llm::ToolCall;
    use crate::test_utils::FakeLlmStep;

    let echo_call = ToolCall {
        id: "tc-evt".into(),
        name: "echo".into(),
        args: serde_json::json!({}),
    };

    let llm = match scenario {
        LlmScenario::FinalText => {
            Arc::new(FakeLlmClient::new("fake").with_steps(vec![FakeLlmStep::Text("done".into())]))
        }
        LlmScenario::OneToolCall => Arc::new(FakeLlmClient::new("fake").with_steps(vec![
            FakeLlmStep::ToolCalls(vec![echo_call]),
            FakeLlmStep::Text("done".into()),
        ])),
        LlmScenario::InfiniteToolLoop => {
            let calls = vec![
                FakeLlmStep::ToolCalls(vec![ToolCall {
                    id: "tc1".into(),
                    name: "echo".into(),
                    args: serde_json::json!({}),
                }]),
                FakeLlmStep::ToolCalls(vec![ToolCall {
                    id: "tc2".into(),
                    name: "echo".into(),
                    args: serde_json::json!({}),
                }]),
                FakeLlmStep::ToolCalls(vec![ToolCall {
                    id: "tc3".into(),
                    name: "echo".into(),
                    args: serde_json::json!({}),
                }]),
            ];
            Arc::new(FakeLlmClient::new("fake").with_steps(calls))
        }
    };

    let tools = Arc::new(match tool_behaviour {
        ToolBehaviour::Succeeds => {
            FakeToolInvoker::new().with_tool("echo", "echoes", |_| Ok(serde_json::json!("ok")))
        }
        ToolBehaviour::Fails => FakeToolInvoker::new().with_tool("echo", "echoes", |_| {
            Err(ToolError::Retryable {
                message: "transient".into(),
                retry_after_secs: 0,
            })
        }),
    });

    let mut ctx = fake_context("evt-test");
    ctx.llm = llm;
    ctx.tools = tools;
    ctx.progress = Some(tx);
    ctx
}

/// Drive `fut` to completion and drain every [`crate::agent::AgentEvent`]
/// that was sent to `rx` before the sender was dropped.
///
/// A brief yield after the future returns lets the runtime's final
/// `emit` calls land before we drain the channel.
async fn collect_agent_events<F>(
    tx: tokio::sync::broadcast::Sender<crate::agent::AgentEvent>,
    mut rx: tokio::sync::broadcast::Receiver<crate::agent::AgentEvent>,
    fut: F,
) -> Vec<crate::agent::AgentEvent>
where
    F: std::future::Future,
{
    let _ = fut.await;
    // One yield so any spawned-task emit calls land before we drain.
    tokio::task::yield_now().await;
    drop(tx);
    let mut events = Vec::new();
    while let Ok(ev) = rx.try_recv() {
        events.push(ev);
    }
    events
}

fn event_kinds(events: &[crate::agent::AgentEvent]) -> Vec<&'static str> {
    use crate::agent::AgentEvent;
    events
        .iter()
        .map(|e| match e {
            AgentEvent::LlmCallStarted => "LlmCallStarted",
            AgentEvent::LlmCallCompleted { .. } => "LlmCallCompleted",
            AgentEvent::ToolCallStarted { .. } => "ToolCallStarted",
            AgentEvent::ToolCallCompleted { .. } => "ToolCallCompleted",
            AgentEvent::Completed => "Completed",
            AgentEvent::Failed { .. } => "Failed",
        })
        .collect()
}

#[tokio::test(start_paused = true)]
async fn run_steps_emits_event_sequence_on_clean_run() {
    use crate::runtime::run_steps;

    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let ctx = build_ctx_for_events(LlmScenario::FinalText, ToolBehaviour::Succeeds, tx.clone());

    let events = collect_agent_events(tx, rx, async {
        let _ = run_steps(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    })
    .await;

    let kinds = event_kinds(&events);
    assert!(
        kinds.first() == Some(&"LlmCallStarted"),
        "first event must be LlmCallStarted; got: {kinds:?}"
    );
    assert!(
        kinds.contains(&"LlmCallCompleted"),
        "expected LlmCallCompleted; got: {kinds:?}"
    );
    assert!(
        kinds.last() == Some(&"Completed"),
        "last event must be Completed; got: {kinds:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn run_steps_emits_tool_call_events() {
    use crate::agent::AgentEvent;
    use crate::runtime::run_steps;

    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let ctx = build_ctx_for_events(
        LlmScenario::OneToolCall,
        ToolBehaviour::Succeeds,
        tx.clone(),
    );

    let events = collect_agent_events(tx, rx, async {
        let _ = run_steps(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    })
    .await;

    assert!(
        events
            .iter()
            .any(|e| matches!(e, AgentEvent::ToolCallStarted { name } if name == "echo")),
        "expected ToolCallStarted{{name:echo}}; got: {:?}",
        event_kinds(&events)
    );
    assert!(
        events
            .iter()
            .any(|e| matches!(e, AgentEvent::ToolCallCompleted { ok: true, .. })),
        "expected ToolCallCompleted{{ok:true}}; got: {:?}",
        event_kinds(&events)
    );
}

#[tokio::test(start_paused = true)]
async fn run_steps_emits_tool_failure() {
    use crate::agent::AgentEvent;
    use crate::runtime::run_steps;

    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let ctx = build_ctx_for_events(LlmScenario::OneToolCall, ToolBehaviour::Fails, tx.clone());

    let events = collect_agent_events(tx, rx, async {
        let _ = run_steps(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    })
    .await;

    assert!(
        events
            .iter()
            .any(|e| matches!(e, AgentEvent::ToolCallCompleted { ok: false, .. })),
        "expected ToolCallCompleted{{ok:false}}; got: {:?}",
        event_kinds(&events)
    );
}

#[tokio::test(start_paused = true)]
async fn run_steps_emits_failed_on_max_steps() {
    use crate::agent::AgentEvent;
    use crate::runtime::run_steps;

    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let ctx = build_ctx_for_events(
        LlmScenario::InfiniteToolLoop,
        ToolBehaviour::Succeeds,
        tx.clone(),
    );
    let opts = RunOptions {
        max_steps: 1,
        ..RunOptions::default()
    };

    let events = collect_agent_events(tx, rx, async {
        let _ = run_steps(&ctx, "sys", ThreadId::new("t"), opts).await;
    })
    .await;

    match events.last() {
        Some(AgentEvent::Failed { reason }) => {
            assert!(
                reason.to_lowercase().contains("max steps"),
                "expected 'max steps' in reason; got: {reason}"
            );
        }
        other => panic!("expected last event Failed; got: {other:?}"),
    }
}

#[tokio::test(start_paused = true)]
async fn run_steps_emits_failed_on_cancel() {
    use crate::agent::AgentEvent;
    use crate::runtime::run_steps;

    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let ctx = build_ctx_for_events(LlmScenario::FinalText, ToolBehaviour::Succeeds, tx.clone());
    ctx.cancel.cancel();

    let events = collect_agent_events(tx, rx, async {
        let _ = run_steps(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    })
    .await;

    match events.last() {
        Some(AgentEvent::Failed { reason }) => {
            assert!(
                reason.to_lowercase().contains("cancel"),
                "expected 'cancel' in reason; got: {reason}"
            );
        }
        other => panic!("expected Failed last; got: {other:?}"),
    }
}

#[tokio::test(start_paused = true)]
async fn run_steps_streaming_emits_same_event_kind_sequence_as_run_steps() {
    use crate::runtime::run_steps;

    // Blocking path — one tool call then final text.
    let tool_call_chunk = crate::llm::ToolCall {
        id: "tc-par".into(),
        name: "echo".into(),
        args: serde_json::json!({}),
    };
    let stream1 = vec![Ok(ChatChunk {
        delta: String::new(),
        tool_calls: vec![tool_call_chunk],
        finish_reason: Some(FinishReason::ToolCalls),
        usage: None,
    })];
    let stream2 = vec![
        Ok(ChatChunk {
            delta: "done".into(),
            tool_calls: vec![],
            finish_reason: None,
            usage: None,
        }),
        Ok(ChatChunk {
            delta: String::new(),
            tool_calls: vec![],
            finish_reason: Some(FinishReason::Stop),
            usage: None,
        }),
    ];

    let (tx1, rx1) = tokio::sync::broadcast::channel(64);
    let mut ctx1 = fake_context("parity-blk");
    ctx1.llm = Arc::new(FakeLlmClient::new("fake").with_steps(vec![
        crate::test_utils::FakeLlmStep::ToolCalls(vec![crate::llm::ToolCall {
            id: "tc-blk".into(),
            name: "echo".into(),
            args: serde_json::json!({}),
        }]),
        crate::test_utils::FakeLlmStep::Text("done".into()),
    ]));
    ctx1.tools = Arc::new(
        FakeToolInvoker::new().with_tool("echo", "echoes", |_| Ok(serde_json::json!("ok"))),
    );
    ctx1.progress = Some(tx1.clone());
    let events_blocking = collect_agent_events(tx1, rx1, async {
        let _ = run_steps(&ctx1, "sys", ThreadId::new("t"), RunOptions::default()).await;
    })
    .await;

    // Streaming path — same trajectory.
    let (tx2, rx2) = tokio::sync::broadcast::channel(64);
    let mut ctx2 = fake_context("parity-str");
    ctx2.llm = Arc::new(FakeLlmClient::new("fake").with_stream_steps(vec![
        FakeStreamStep::Chunks(stream1),
        FakeStreamStep::Chunks(stream2),
    ]));
    ctx2.tools = Arc::new(
        FakeToolInvoker::new().with_tool("echo", "echoes", |_| Ok(serde_json::json!("ok"))),
    );
    ctx2.progress = Some(tx2.clone());
    let events_streaming = collect_agent_events(tx2, rx2, async {
        let mut s = run_steps_streaming(&ctx2, "sys", ThreadId::new("t"), RunOptions::default())
            .await
            .expect("stream opens");
        while s.next().await.is_some() {}
    })
    .await;

    let kinds_blocking = event_kinds(&events_blocking);
    let kinds_streaming = event_kinds(&events_streaming);
    assert_eq!(
        kinds_blocking, kinds_streaming,
        "blocking vs streaming event-kind sequence mismatch:\n  blocking:  {kinds_blocking:?}\n  streaming: {kinds_streaming:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn emit_is_noop_when_progress_unset() {
    use crate::runtime::run_steps;

    // ctx.progress stays None — run must complete without panic.
    let mut ctx = fake_context("noop-progress");
    ctx.llm = Arc::new(
        FakeLlmClient::new("fake")
            .with_steps(vec![crate::test_utils::FakeLlmStep::Text("ok".into())]),
    );
    let result = run_steps(&ctx, "sys", ThreadId::new("t"), RunOptions::default()).await;
    assert!(
        result.is_ok(),
        "progress=None must not panic; got: {result:?}"
    );
}

mod terminal_chunk_for_tests {
    //! Per-arm coverage of [`terminal_chunk_for`].
    //!
    //! The streaming spawn wrapper relies on `terminal_chunk_for` to
    //! translate every loop-driver `Error` into the pair forwarded to
    //! the consumer + persisted to `Episode::Failed`. Streaming
    //! integration tests indirectly cover the `Cancelled` arms only.
    //! These unit tests pin the remaining arms against their
    //! documented prefix shape so accidental rewording is caught.
    use super::super::terminal_chunk_for;
    use crate::error::{Error, LlmError, MemoryError, ToolError};

    #[test]
    fn cancelled_with_cancel_observed_yields_cancelled_episode() {
        let (chunk, episode) = terminal_chunk_for(Error::Cancelled, true);
        assert!(matches!(chunk, LlmError::Cancelled));
        assert_eq!(episode, "cancelled");
    }

    #[test]
    fn cancelled_without_cancel_observed_yields_consumer_dropped_episode() {
        let (chunk, episode) = terminal_chunk_for(Error::Cancelled, false);
        assert!(matches!(chunk, LlmError::Cancelled));
        assert_eq!(episode, "consumer-dropped");
    }

    #[test]
    fn max_steps_exceeded_renders_step_count() {
        let (chunk, episode) = terminal_chunk_for(Error::MaxStepsExceeded { steps: 7 }, false);
        let message = match chunk {
            LlmError::Server(m) => m,
            other => panic!("expected Server, got {other:?}"),
        };
        assert_eq!(message, "max steps exceeded: 7");
        assert_eq!(episode, "max steps exceeded: 7");
    }

    #[test]
    fn tool_error_prefixed_with_tool() {
        let (chunk, episode) =
            terminal_chunk_for(Error::Tool(ToolError::Permanent("boom".into())), false);
        let message = match chunk {
            LlmError::Server(m) => m,
            other => panic!("expected Server, got {other:?}"),
        };
        assert!(message.starts_with("tool: "), "got {message}");
        assert!(message.contains("boom"));
        assert_eq!(message, episode);
    }

    #[test]
    fn llm_variant_preserved_end_to_end_not_rewrapped_as_server() {
        let (chunk, episode) = terminal_chunk_for(Error::Llm(LlmError::Unauthorized), false);
        assert!(
            matches!(chunk, LlmError::Unauthorized),
            "Llm-wrapped variants must round-trip unchanged"
        );
        assert!(episode.to_lowercase().contains("unauthorized"));
    }

    #[test]
    fn llm_rate_limit_preserves_retry_after_seconds() {
        let (chunk, _) = terminal_chunk_for(
            Error::Llm(LlmError::RateLimit {
                retry_after_secs: 11,
            }),
            false,
        );
        match chunk {
            LlmError::RateLimit { retry_after_secs } => assert_eq!(retry_after_secs, 11),
            other => panic!("expected RateLimit, got {other:?}"),
        }
    }

    #[test]
    fn refused_prefixed_with_refused() {
        let (chunk, episode) = terminal_chunk_for(
            Error::Refused {
                reason: "policy".into(),
            },
            false,
        );
        let message = match chunk {
            LlmError::Server(m) => m,
            other => panic!("expected Server, got {other:?}"),
        };
        assert_eq!(message, "refused: policy");
        assert_eq!(message, episode);
    }

    #[test]
    fn handoff_includes_target_agent_and_reason() {
        let (chunk, episode) = terminal_chunk_for(
            Error::Handoff {
                agent: "safety".into(),
                reason: "needs human review".into(),
            },
            false,
        );
        let message = match chunk {
            LlmError::Server(m) => m,
            other => panic!("expected Server, got {other:?}"),
        };
        assert_eq!(message, "handoff to safety: needs human review");
        assert_eq!(message, episode);
    }

    #[test]
    fn unmatched_variant_falls_through_to_server_with_display() {
        // Memory is one of the Error variants not enumerated by the
        // explicit arms. The catch-all should wrap its Display.
        let (chunk, episode) =
            terminal_chunk_for(Error::Memory(MemoryError::Store("disk full".into())), false);
        let message = match chunk {
            LlmError::Server(m) => m,
            other => panic!("expected Server, got {other:?}"),
        };
        assert!(message.contains("disk full"), "got {message}");
        assert_eq!(message, episode);
    }
}

#[tokio::test(start_paused = true)]
async fn streaming_llm_call_completed_emits_zero_tokens_when_provider_omits_usage() {
    use crate::agent::AgentEvent;

    // All chunks carry usage: None — no streaming_usage configured on the
    // fake provider. The contract (ADR-015): LlmCallCompleted must carry
    // tokens=0 AND the next event must be Completed (not Failed), proving
    // the dropped-sentinel contract.
    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let mut ctx = fake_context("usage-none-test");
    ctx.llm = Arc::new(
        FakeLlmClient::new("fake").with_stream_steps(vec![FakeStreamStep::Chunks(vec![
            Ok(delta("hi")),
            Ok(final_stop_chunk()),
        ])]),
    );
    ctx.progress = Some(tx.clone());

    let events = collect_agent_events(tx, rx, async {
        let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
            .await
            .expect("stream opens");
        while s.next().await.is_some() {}
    })
    .await;

    let completed_idx = events
        .iter()
        .position(|e| matches!(e, AgentEvent::LlmCallCompleted { .. }))
        .expect("LlmCallCompleted must be emitted");
    match &events[completed_idx] {
        AgentEvent::LlmCallCompleted { tokens, .. } => {
            assert_eq!(
                *tokens, 0,
                "expected tokens=0 (provider omitted usage); got {tokens}"
            );
        }
        _ => unreachable!(),
    }
    // Next event must be Completed, not Failed — proves tokens=0 doesn't
    // trigger a retry or error path.
    let next = events.get(completed_idx + 1);
    assert!(
        matches!(next, Some(AgentEvent::Completed)),
        "expected next event Completed (not Failed); got: {next:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn streaming_llm_call_completed_emits_real_token_count() {
    use crate::agent::AgentEvent;
    use crate::llm::Usage;

    // Final chunk carries usage so forward_chunks can surface it.
    let final_chunk_with_usage = ChatChunk {
        delta: String::new(),
        tool_calls: vec![],
        finish_reason: Some(FinishReason::Stop),
        usage: Some(Usage {
            prompt_tokens: 12,
            completion_tokens: 7,
        }),
    };
    let (tx, rx) = tokio::sync::broadcast::channel(64);
    let mut ctx = fake_context("usage-test");
    ctx.llm = Arc::new(
        FakeLlmClient::new("fake").with_stream_steps(vec![FakeStreamStep::Chunks(vec![
            Ok(delta("hi")),
            Ok(final_chunk_with_usage),
        ])]),
    );
    ctx.progress = Some(tx.clone());

    let events = collect_agent_events(tx, rx, async {
        let mut s = run_steps_streaming(&ctx, "sys", ThreadId::new("t"), RunOptions::default())
            .await
            .expect("stream opens");
        while s.next().await.is_some() {}
    })
    .await;

    let completed_event = events
        .iter()
        .find(|e| matches!(e, AgentEvent::LlmCallCompleted { .. }))
        .expect("LlmCallCompleted must be emitted");
    match completed_event {
        AgentEvent::LlmCallCompleted { tokens, .. } => {
            assert_eq!(*tokens, 19, "tokens must be prompt(12)+completion(7)=19");
        }
        _ => unreachable!(),
    }
}