tkach 0.3.0

A provider-independent agent runtime for Rust with built-in tools
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
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use futures::StreamExt;
use serde_json::json;
use tkach::message::{Content, Message, StopReason, Usage};
use tkach::provider::Response;
use tkach::providers::Mock;
use tkach::{Agent, AgentError, CancellationToken, StreamEvent};

fn test_dir() -> std::path::PathBuf {
    std::env::current_dir().unwrap()
}

fn prompt(text: &str) -> Vec<Message> {
    vec![Message::user_text(text)]
}

// --- Simple text response (no tools, 1 turn) ---

#[tokio::test]
async fn single_turn_text_response() {
    let agent = Agent::builder()
        .provider(Mock::with_text("Hello, world!"))
        .model("test")
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("Hi"), CancellationToken::new())
        .await
        .unwrap();

    assert_eq!(result.text, "Hello, world!");
    // Delta is assistant-only: input user message is not echoed back.
    assert_eq!(result.new_messages.len(), 1);
    assert_eq!(result.stop_reason, StopReason::EndTurn);
}

// --- Tool call → result → final text (2 LLM calls) ---

#[tokio::test]
async fn tool_call_then_text_response() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hello"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("The command output: hello")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("run echo hello"), CancellationToken::new())
        .await
        .unwrap();

    assert_eq!(result.text, "The command output: hello");
    // Delta: assistant(tool_use), user(tool_result), assistant(text) = 3
    assert_eq!(result.new_messages.len(), 3);
}

// --- Multiple tool calls in a single response ---

#[tokio::test]
async fn multiple_tool_calls_single_response() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![
                    Content::ToolUse {
                        id: "t1".into(),
                        name: "bash".into(),
                        input: json!({"command": "echo first"}),
                    },
                    Content::ToolUse {
                        id: "t2".into(),
                        name: "bash".into(),
                        input: json!({"command": "echo second"}),
                    },
                ],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("Both commands ran successfully")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("run two commands"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "Both commands ran successfully");

    // new_messages[1] is the user(tool_results) message
    let tool_results_msg = &result.new_messages[1];
    assert_eq!(tool_results_msg.content.len(), 2);
}

// --- Max turns exceeded ---

#[tokio::test]
async fn max_turns_exceeded() {
    let mock = Mock::new(|_req| {
        Ok(Response {
            content: vec![Content::ToolUse {
                id: "t1".into(),
                name: "bash".into(),
                input: json!({"command": "echo loop"}),
            }],
            stop_reason: StopReason::ToolUse,
            usage: Usage::default(),
        })
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .max_turns(3)
        .working_dir(test_dir())
        .build();

    let err = agent
        .run(prompt("loop forever"), CancellationToken::new())
        .await
        .unwrap_err();
    let AgentError::MaxTurnsReached { turns, partial } = &err else {
        panic!("expected MaxTurnsReached, got {err:?}");
    };
    assert_eq!(*turns, 3);
    // Partial holds the delta: (assistant + user tool_result) × 3 = 6
    assert_eq!(partial.new_messages.len(), 6);
    assert_eq!(partial.stop_reason, StopReason::ToolUse);
}

// --- Cancellation ---

#[tokio::test]
async fn cancel_before_run_returns_cancelled_immediately() {
    let mock = Mock::with_text("should never get here");
    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .working_dir(test_dir())
        .build();

    let cancel = CancellationToken::new();
    cancel.cancel();

    let err = agent.run(prompt("hi"), cancel).await.unwrap_err();
    let AgentError::Cancelled { partial } = &err else {
        panic!("expected Cancelled, got {err:?}");
    };
    assert_eq!(partial.new_messages.len(), 0);
    assert_eq!(partial.stop_reason, StopReason::Cancelled);
}

// --- Tool not found ---

#[tokio::test]
async fn tool_not_found_returns_error_result() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "nonexistent_tool".into(),
                    input: json!({}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => {
                let last_msg = req.messages.last().unwrap();
                let has_error = last_msg.content.iter().any(|c| match c {
                    Content::ToolResult { is_error, .. } => *is_error,
                    _ => false,
                });
                assert!(has_error, "LLM should receive tool error");

                Ok(Response {
                    content: vec![Content::text("Tool not found, sorry.")],
                    stop_reason: StopReason::EndTurn,
                    usage: Usage::default(),
                })
            }
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("use a fake tool"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "Tool not found, sorry.");
}

// --- Usage accumulation across turns ---

#[tokio::test]
async fn usage_accumulates_across_turns() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hi"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage {
                    input_tokens: 100,
                    output_tokens: 50,
                    cache_creation_input_tokens: 0,
                    cache_read_input_tokens: 0,
                },
            }),
            _ => Ok(Response {
                content: vec![Content::text("done")],
                stop_reason: StopReason::EndTurn,
                usage: Usage {
                    input_tokens: 200,
                    output_tokens: 30,
                    cache_creation_input_tokens: 0,
                    cache_read_input_tokens: 0,
                },
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("test"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.usage.input_tokens, 300);
    assert_eq!(result.usage.output_tokens, 80);
}

// --- Read tool integration ---

#[tokio::test]
async fn read_tool_reads_actual_file() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "read".into(),
                    input: json!({"file_path": "Cargo.toml"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => {
                let last_msg = req.messages.last().unwrap();
                let content = match &last_msg.content[0] {
                    Content::ToolResult { content, .. } => content.clone(),
                    _ => panic!("expected tool result"),
                };
                assert!(content.contains("tkach"), "should contain package name");

                Ok(Response {
                    content: vec![Content::text("I read the Cargo.toml")],
                    stop_reason: StopReason::EndTurn,
                    usage: Usage::default(),
                })
            }
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("read cargo toml"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "I read the Cargo.toml");
}

// --- Glob tool integration ---

#[tokio::test]
async fn glob_tool_finds_files() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "glob".into(),
                    input: json!({"pattern": "src/**/*.rs"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => {
                let last_msg = req.messages.last().unwrap();
                let content = match &last_msg.content[0] {
                    Content::ToolResult { content, .. } => content.clone(),
                    _ => panic!("expected tool result"),
                };
                assert!(content.contains("lib.rs"), "should find lib.rs");

                Ok(Response {
                    content: vec![Content::text("Found Rust files")],
                    stop_reason: StopReason::EndTurn,
                    usage: Usage::default(),
                })
            }
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("find rust files"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "Found Rust files");
}

// --- Multi-turn tool chain (read → edit → verify) ---

#[tokio::test]
async fn multi_turn_tool_chain() {
    let tmp_dir = std::env::temp_dir().join("tkach_test");
    let _ = std::fs::create_dir_all(&tmp_dir);
    let test_file = tmp_dir.join("test.txt");
    std::fs::write(&test_file, "hello world").unwrap();

    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();
    let file_path = test_file.display().to_string();
    let file_path_clone = file_path.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "read".into(),
                    input: json!({"file_path": file_path_clone}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            1 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t2".into(),
                    name: "edit".into(),
                    input: json!({
                        "file_path": file_path_clone,
                        "old_string": "hello world",
                        "new_string": "hello agent"
                    }),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("File updated successfully")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(&tmp_dir)
        .build();

    let result = agent
        .run(prompt("update the file"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "File updated successfully");

    let content = std::fs::read_to_string(&test_file).unwrap();
    assert_eq!(content, "hello agent");

    let _ = std::fs::remove_dir_all(&tmp_dir);
}

// --- No tools configured ---

#[tokio::test]
async fn no_tools_text_only() {
    let agent = Agent::builder()
        .provider(Mock::with_text("I have no tools but I can chat!"))
        .model("test")
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("hello"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "I have no tools but I can chat!");
}

// --- EndTurn with tool_use content stops the loop ---

#[tokio::test]
async fn end_turn_stops_even_with_tool_use_content() {
    // stop_reason is EndTurn but content has tool_use — loop honours stop_reason.
    let mock = Mock::new(|_req| {
        Ok(Response {
            content: vec![
                Content::text("Let me think..."),
                Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo orphan"}),
                },
            ],
            stop_reason: StopReason::EndTurn,
            usage: Usage::default(),
        })
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let result = agent
        .run(prompt("test"), CancellationToken::new())
        .await
        .unwrap();
    assert_eq!(result.text, "Let me think...");
    // Delta: 1 assistant message, no tool execution.
    assert_eq!(result.new_messages.len(), 1);
}

// --- Cancel during tool batch: Bash honours it, loop returns Cancelled ---

#[tokio::test]
async fn cancel_during_bash_tool_returns_cancelled() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    // sleep longer than our cancel delay — bash honours
                    // ctx.cancel via select! + kill_on_drop.
                    input: json!({"command": "sleep 10", "timeout_ms": 30000}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => panic!("loop should not reach a second turn — cancel fired mid-batch"),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let cancel = CancellationToken::new();
    let cancel_clone = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        cancel_clone.cancel();
    });

    let start = std::time::Instant::now();
    let err = agent.run(prompt("sleep"), cancel).await.unwrap_err();
    let elapsed = start.elapsed();

    let AgentError::Cancelled { partial } = &err else {
        panic!("expected Cancelled, got {err:?}");
    };
    assert_eq!(partial.stop_reason, StopReason::Cancelled);
    // The actual signal here is "cancelled long before sleep 10 elapsed";
    // 5s is loose enough to absorb shared-CI runner jitter (process spawn +
    // SIGKILL + reap can stretch on macOS/Windows agents) while still
    // proving prompt termination — the worst-case "didn't honour cancel"
    // would push elapsed close to 10s.
    assert!(
        elapsed < std::time::Duration::from_secs(5),
        "expected prompt cancel, took {elapsed:?}"
    );
}

// --- Provider error surfaces with partial ---

#[tokio::test]
async fn provider_error_returns_partial() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hi"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage {
                    input_tokens: 10,
                    output_tokens: 5,
                    cache_creation_input_tokens: 0,
                    cache_read_input_tokens: 0,
                },
            }),
            _ => Err(tkach::ProviderError::Overloaded {
                retry_after_ms: Some(2_000),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let err = agent
        .run(prompt("test"), CancellationToken::new())
        .await
        .unwrap_err();

    let AgentError::Provider { source, partial } = &err else {
        panic!("expected Provider error, got {err:?}");
    };
    assert!(source.is_retryable());
    // One full tool round-trip happened before the provider failed.
    assert_eq!(partial.new_messages.len(), 2);
    assert_eq!(partial.usage.input_tokens, 10);
}

// ---------------------------------------------------------------------------
// Streaming
// ---------------------------------------------------------------------------

#[tokio::test]
async fn stream_text_response_emits_delta_then_collects_result() {
    let agent = Agent::builder()
        .provider(Mock::with_text("Hello, world!"))
        .model("test")
        .working_dir(test_dir())
        .build();

    let mut stream = agent.stream(prompt("hi"), CancellationToken::new());
    let mut events: Vec<StreamEvent> = Vec::new();
    while let Some(ev) = stream.next().await {
        events.push(ev.unwrap());
    }
    let result = stream.into_result().await.unwrap();

    // Mock emits one ContentDelta per Text block; ToolUse/MessageDelta/
    // Usage/Done are absorbed by the agent loop and not forwarded.
    assert_eq!(events.len(), 1);
    assert!(matches!(&events[0], StreamEvent::ContentDelta(t) if t == "Hello, world!"));

    // Final history matches the run() shape: one assistant message with
    // text body assembled from deltas.
    assert_eq!(result.new_messages.len(), 1);
    assert_eq!(result.text, "Hello, world!");
    assert_eq!(result.stop_reason, StopReason::EndTurn);
}

#[tokio::test]
async fn stream_tool_call_then_text_response_executes_tool_inline() {
    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hi"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("done")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let mut stream = agent.stream(prompt("run echo"), CancellationToken::new());
    let mut tool_use_seen = false;
    let mut final_text = String::new();
    while let Some(ev) = stream.next().await {
        match ev.unwrap() {
            StreamEvent::ToolUse { name, .. } => {
                assert_eq!(name, "bash");
                tool_use_seen = true;
            }
            StreamEvent::ContentDelta(t) => final_text.push_str(&t),
            _ => {}
        }
    }
    let result = stream.into_result().await.unwrap();

    assert!(tool_use_seen, "consumer should see ToolUse event");
    assert_eq!(final_text, "done");
    // Delta history: assistant(tool_use), user(tool_result), assistant(text) = 3
    assert_eq!(result.new_messages.len(), 3);
    assert_eq!(result.text, "done");
}

#[tokio::test]
async fn stream_collect_result_skips_event_drain() {
    let agent = Agent::builder()
        .provider(Mock::with_text("ignored content"))
        .model("test")
        .working_dir(test_dir())
        .build();

    // Don't iterate events; collect_result should still complete.
    let stream = agent.stream(prompt("hi"), CancellationToken::new());
    let result = stream.collect_result().await.unwrap();

    assert_eq!(result.text, "ignored content");
    assert_eq!(result.new_messages.len(), 1);
}

#[tokio::test]
async fn stream_cancel_before_start_returns_cancelled_via_into_result() {
    let mock = Mock::with_text("never");
    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .working_dir(test_dir())
        .build();

    let cancel = CancellationToken::new();
    cancel.cancel();
    let stream = agent.stream(prompt("hi"), cancel);

    let err = stream.collect_result().await.unwrap_err();
    let AgentError::Cancelled { partial } = &err else {
        panic!("expected Cancelled, got {err:?}");
    };
    assert_eq!(partial.stop_reason, StopReason::Cancelled);
    assert!(partial.new_messages.is_empty());
}

// --- Approval flow streaming events -----------------------------------------

#[tokio::test]
async fn stream_emits_tool_call_pending_before_executing_tool() {
    use tkach::ToolClass;

    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hi"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("done")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .working_dir(test_dir())
        .build();

    let mut stream = agent.stream(prompt("run echo"), CancellationToken::new());
    let mut sequence: Vec<&'static str> = Vec::new();
    let mut pending_class: Option<ToolClass> = None;
    while let Some(ev) = stream.next().await {
        match ev.unwrap() {
            StreamEvent::ToolUse { .. } => sequence.push("ToolUse"),
            StreamEvent::ToolCallPending { name, class, .. } => {
                assert_eq!(name, "bash");
                pending_class = Some(class);
                sequence.push("ToolCallPending");
            }
            StreamEvent::ContentDelta(_) => sequence.push("ContentDelta"),
            _ => {}
        }
    }
    let result = stream.into_result().await.unwrap();

    // Critical ordering invariant: ToolUse arrives first (provider
    // event), then the agent emits ToolCallPending right before
    // dispatching to the executor (where approval gate runs).
    let tu_pos = sequence
        .iter()
        .position(|x| *x == "ToolUse")
        .expect("ToolUse");
    let pending_pos = sequence
        .iter()
        .position(|x| *x == "ToolCallPending")
        .expect("ToolCallPending");
    assert!(
        tu_pos < pending_pos,
        "ToolUse must come before ToolCallPending; got: {sequence:?}"
    );

    // Class is resolved through the registry.
    assert_eq!(
        pending_class,
        Some(ToolClass::Mutating),
        "bash is Mutating; class should be threaded through"
    );

    // Tool still ran end-to-end (AutoApprove default).
    assert_eq!(result.text, "done");
}

#[tokio::test]
async fn stream_with_deny_handler_emits_pending_but_skips_execution() {
    use async_trait::async_trait;
    use serde_json::Value;
    use tkach::{ApprovalDecision, ApprovalHandler, ToolClass};

    struct DenyAll;
    #[async_trait]
    impl ApprovalHandler for DenyAll {
        async fn approve(&self, _: &str, _: &Value, _: ToolClass) -> ApprovalDecision {
            ApprovalDecision::Deny("nope".into())
        }
    }

    let call = Arc::new(AtomicUsize::new(0));
    let call_clone = call.clone();

    let mock = Mock::new(move |_req| {
        let n = call_clone.fetch_add(1, Ordering::SeqCst);
        match n {
            0 => Ok(Response {
                content: vec![Content::ToolUse {
                    id: "t1".into(),
                    name: "bash".into(),
                    input: json!({"command": "echo hi"}),
                }],
                stop_reason: StopReason::ToolUse,
                usage: Usage::default(),
            }),
            _ => Ok(Response {
                content: vec![Content::text("acknowledged the denial")],
                stop_reason: StopReason::EndTurn,
                usage: Usage::default(),
            }),
        }
    });

    let agent = Agent::builder()
        .provider(mock)
        .model("test")
        .tools(tkach::tools::defaults())
        .approval(DenyAll)
        .working_dir(test_dir())
        .build();

    let mut stream = agent.stream(prompt("run echo hi"), CancellationToken::new());
    let mut got_pending = false;
    while let Some(ev) = stream.next().await {
        if let StreamEvent::ToolCallPending { .. } = ev.unwrap() {
            got_pending = true;
        }
    }
    let result = stream.into_result().await.unwrap();

    assert!(
        got_pending,
        "ToolCallPending must still fire even when handler will deny"
    );

    // Tool result in history must carry the denial reason — proves
    // the executor's gate ran and the model saw the rejection.
    let saw_denial = result.new_messages.iter().any(|m| {
        m.content.iter().any(|c| match c {
            Content::ToolResult {
                content, is_error, ..
            } => *is_error && content.contains("nope"),
            _ => false,
        })
    });
    assert!(
        saw_denial,
        "expected denial tool_result containing 'nope' in history"
    );
}