aither-agent 0.31.0

AI agent framework with planning, memory, and tool execution for aither
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
//! The loop's contract: what a run emits, what hooks decide, and how a run
//! ends.

#![allow(clippy::unused_async, clippy::unused_async_trait_impl)]

use std::borrow::Cow;
use std::collections::VecDeque;
use std::ops::ControlFlow;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use aither_core::llm::tool::{Approval, ApprovalKind, ApprovalRequest, Approver, ApproverFailure};
use aither_core::llm::{
    Classify, Event, Failure, LLMRequest, LanguageModel, RetryPolicy, Tool, ToolCall, ToolContext,
    ToolResult, model::Profile,
};
use futures_core::Stream;
use schemars::JsonSchema;
use serde::Deserialize;

use crate::{
    Agent, AgentBuilder, AgentCheckpoint, AgentError, AgentEvent, AgentPath, Block, ContextBlock,
    ContextSource, Hooks, InjectionKind, Moment, RunOutcome, SourceId, StopCx, StopDecision,
    SubagentRuns, TimedEvent, ToolDecision, ToolInvocation, ToolVerdict,
};

#[derive(Debug)]
struct NeverFails;

impl std::fmt::Display for NeverFails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("never fails")
    }
}

impl std::error::Error for NeverFails {}

impl Classify for NeverFails {
    fn failure(&self) -> Failure {
        Failure::permanent()
    }
}

/// Answers each request with the next scripted response and records every
/// request it receives.
#[derive(Clone)]
struct Scripted {
    script: Arc<Mutex<VecDeque<Vec<Event>>>>,
    requests: Arc<Mutex<Vec<LLMRequest>>>,
}

impl Scripted {
    fn new(script: impl IntoIterator<Item = Vec<Event>>) -> Self {
        Self {
            script: Arc::new(Mutex::new(script.into_iter().collect())),
            requests: Arc::default(),
        }
    }

    fn requests(&self) -> Vec<LLMRequest> {
        self.requests.lock().unwrap().clone()
    }
}

impl LanguageModel for Scripted {
    type Error = NeverFails;

    fn respond(
        &self,
        request: LLMRequest,
    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
        self.requests.lock().unwrap().push(request);
        let response = self
            .script
            .lock()
            .unwrap()
            .pop_front()
            .expect("the script has a response for every request");
        futures_lite::stream::iter(response.into_iter().map(Ok))
    }

    fn retry_policy(&self) -> RetryPolicy {
        RetryPolicy::default()
    }

    fn profile(&self) -> impl std::future::Future<Output = Result<Profile, Self::Error>> + Send {
        std::future::ready(Ok(Profile::new(
            "scripted",
            "test",
            "scripted",
            "scripted model",
            128_000,
        )))
    }
}

fn say(text: &str) -> Vec<Event> {
    vec![Event::Text(text.to_string())]
}

fn call(id: &str, name: &str) -> Vec<Event> {
    vec![Event::ToolCall(ToolCall::new(
        id,
        name,
        serde_json::json!({}),
    ))]
}

#[derive(Debug, Deserialize, JsonSchema)]
struct NoArguments {}

/// Counts the calls that reach it.
#[derive(Clone, Default)]
struct Probe(Arc<Mutex<usize>>);

impl Tool for Probe {
    fn name(&self) -> Cow<'static, str> {
        "probe".into()
    }

    fn description(&self) -> Cow<'static, str> {
        "Counts the calls that reach it.".into()
    }

    type Arguments = NoArguments;
    type Res = ToolResult;

    fn call(
        &self,
        _arguments: Self::Arguments,
        _cx: ToolContext,
    ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
        *self.0.lock().unwrap() += 1;
        std::future::ready(Ok(ToolResult::text("probed")))
    }
}

/// Panics on every call.
struct Panicker;

impl Tool for Panicker {
    fn name(&self) -> Cow<'static, str> {
        "panicker".into()
    }

    fn description(&self) -> Cow<'static, str> {
        "Panics on every call.".into()
    }

    type Arguments = NoArguments;
    type Res = ToolResult;

    async fn call(
        &self,
        _arguments: Self::Arguments,
        _cx: ToolContext,
    ) -> aither_core::Result<Self::Res> {
        panic!("the disk is on fire");
    }
}

fn tool_results(llm: &Scripted) -> Vec<String> {
    llm.requests()
        .last()
        .expect("the model was asked at least once")
        .messages()
        .iter()
        .filter(|message| message.role() == aither_core::llm::Role::Tool)
        .map(|message| message.content().to_string())
        .collect()
}

async fn run_to_end<M, H, C, S>(
    agent: &mut Agent<M, H, C, S>,
    prompt: &str,
) -> (Result<(), AgentError>, Vec<TimedEvent>)
where
    S: crate::HandoffSchema,
    M: LanguageModel + 'static,
    C: LanguageModel + 'static,
    H: Hooks,
{
    let mut events = Vec::new();
    let result = agent
        .run(prompt, std::iter::empty())
        .drive(
            &mut events,
            std::future::pending::<()>(),
            |events, timed| async move {
                events.push(timed);
                ControlFlow::Continue(events)
            },
        )
        .await
        .map(|_| ());
    (result, events)
}

fn kinds(events: &[TimedEvent]) -> Vec<&'static str> {
    events
        .iter()
        .map(|timed| match &timed.event {
            AgentEvent::RunStarted { .. } => "run-started",
            AgentEvent::RunEnded { .. } => "run-ended",
            AgentEvent::TurnStarted { .. } => "turn-started",
            AgentEvent::TurnEnded { .. } => "turn-ended",
            AgentEvent::ToolCallStarted { .. } => "tool-started",
            AgentEvent::ToolCallDecided { .. } => "tool-decided",
            AgentEvent::ToolCallEnded { .. } => "tool-ended",
            AgentEvent::Paused { .. } => "paused",
            AgentEvent::Resumed { .. } => "resumed",
            _ => "other",
        })
        .filter(|kind| *kind != "other")
        .collect()
}

fn outcome(events: &[TimedEvent]) -> &RunOutcome {
    events
        .iter()
        .rev()
        .find_map(|timed| match &timed.event {
            AgentEvent::RunEnded { outcome, .. } => Some(outcome),
            _ => None,
        })
        .expect("a run ends with RunEnded")
}

#[tokio::test]
async fn a_run_is_bracketed_by_its_start_and_end() {
    let llm = Scripted::new([say("hello")]);
    let mut agent = AgentBuilder::new(llm).build();

    let (result, events) = run_to_end(&mut agent, "hi").await;

    result.expect("the run completes");
    assert_eq!(
        kinds(&events),
        ["run-started", "turn-started", "turn-ended", "run-ended"]
    );
    assert!(events.iter().all(|timed| timed.agent == AgentPath::main()));
    assert!(matches!(
        outcome(&events),
        RunOutcome::Completed { final_text } if final_text == "hello"
    ));
}

#[tokio::test]
async fn query_returns_the_reply() {
    let mut agent = AgentBuilder::new(Scripted::new([say("four")])).build();
    assert_eq!(agent.query("2+2").await.unwrap(), "four");
}

#[tokio::test]
async fn a_tool_call_is_decided_run_and_reported() {
    let llm = Scripted::new([call("c1", "probe"), say("done")]);
    let probe = Probe::default();
    let mut agent = AgentBuilder::new(llm).tool(probe.clone()).build();

    let (result, events) = run_to_end(&mut agent, "go").await;

    result.expect("the run completes");
    assert_eq!(*probe.0.lock().unwrap(), 1);
    let tool: Vec<_> = kinds(&events)
        .into_iter()
        .filter(|kind| kind.starts_with("tool"))
        .collect();
    assert_eq!(tool, ["tool-started", "tool-decided", "tool-ended"]);
}

struct DenyProbe;

impl Hooks for DenyProbe {
    async fn before_tool(&self, call: &ToolInvocation<'_>) -> ToolDecision {
        assert_eq!(call.name, "probe");
        ToolDecision::Deny("probing is off".into())
    }
}

#[tokio::test]
async fn a_denied_call_does_not_run_and_the_model_reads_the_reason() {
    let llm = Scripted::new([call("c1", "probe"), say("ok")]);
    let probe = Probe::default();
    let mut agent = AgentBuilder::new(llm.clone())
        .tool(probe.clone())
        .hooks(DenyProbe)
        .build();

    let (result, events) = run_to_end(&mut agent, "go").await;

    result.expect("the run completes");
    assert_eq!(*probe.0.lock().unwrap(), 0);
    assert!(events.iter().any(|timed| matches!(
        &timed.event,
        AgentEvent::ToolCallDecided {
            decision: ToolVerdict::Denied { reason },
            ..
        } if reason == "probing is off"
    )));
    let second = format!("{:?}", llm.requests()[1].messages());
    assert!(second.contains("probing is off"), "{second}");
}

struct AskProbe;

impl Hooks for AskProbe {
    async fn before_tool(&self, _call: &ToolInvocation<'_>) -> ToolDecision {
        ToolDecision::Ask(ApprovalRequest::new(ApprovalKind::new("test"), "probe"))
    }
}

/// Approves once the test sends the go-ahead.
struct Gate(async_channel::Receiver<()>);

impl Approver for Gate {
    fn approve(
        &self,
        _request: ApprovalRequest,
    ) -> impl std::future::Future<Output = Result<Approval, ApproverFailure>> + Send {
        let gate = self.0.clone();
        async move {
            gate.recv().await.expect("the test answers");
            Ok(Approval::Approved)
        }
    }
}

#[tokio::test]
async fn a_pending_approval_pauses_the_run_and_resumes_it_on_the_answer() {
    let llm = Scripted::new([call("c1", "probe"), say("done")]);
    let probe = Probe::default();
    let (answer, gate) = async_channel::bounded(1);
    let mut agent = AgentBuilder::new(llm)
        .tool(probe.clone())
        .hooks(AskProbe)
        .approver(Gate(gate))
        .build();

    let mut events = Vec::new();
    let _ = agent
        .run("go", std::iter::empty())
        .drive(
            (&mut events, answer),
            std::future::pending::<()>(),
            |(events, answer), timed| async move {
                if let AgentEvent::Paused { call, kind, .. } = &timed.event {
                    assert!(call.is_some(), "the pause names the call");
                    assert_eq!(kind.as_str(), "test");
                    answer.send(()).await.unwrap();
                }
                events.push(timed);
                ControlFlow::Continue((events, answer))
            },
        )
        .await
        .expect("the run completes");

    assert_eq!(*probe.0.lock().unwrap(), 1);
    let order = kinds(&events);
    let paused = order.iter().position(|kind| *kind == "paused").unwrap();
    let resumed = order.iter().position(|kind| *kind == "resumed").unwrap();
    let ended = order.iter().position(|kind| *kind == "tool-ended").unwrap();
    assert!(paused < resumed && resumed < ended, "{order:?}");
}

#[tokio::test]
async fn an_approval_with_no_approver_fails_the_run() {
    let llm = Scripted::new([call("c1", "probe")]);
    let mut agent = AgentBuilder::new(llm)
        .tool(Probe::default())
        .hooks(AskProbe)
        .build();

    let (result, _) = run_to_end(&mut agent, "go").await;

    assert!(matches!(
        result.expect_err("no approver"),
        AgentError::Approval(_)
    ));
}

#[tokio::test]
async fn cancelling_a_run_ends_it_as_cancelled() {
    let llm = Scripted::new([say("never read")]);
    let mut agent = AgentBuilder::new(llm).build();
    let run = agent.run("hi", std::iter::empty());
    run.cancel();

    let mut events = Vec::new();
    let _ = run
        .drive(
            &mut events,
            std::future::pending::<()>(),
            |events, timed| async move {
                events.push(timed);
                ControlFlow::Continue(events)
            },
        )
        .await
        .expect("a cancelled run is not an error");

    assert!(matches!(outcome(&events), RunOutcome::Cancelled));
}

#[tokio::test]
async fn stopping_a_drive_still_delivers_the_cancelled_end() {
    let llm = Scripted::new([say("never read")]);
    let mut agent = AgentBuilder::new(llm).build();
    let mut events = Vec::new();

    let flow = agent
        .run("hi", std::iter::empty())
        .drive(
            &mut events,
            std::future::ready("stop"),
            |events, timed| async move {
                events.push(timed);
                ControlFlow::Continue(events)
            },
        )
        .await
        .expect("a stopped run is not an error");

    assert!(matches!(flow, ControlFlow::Break("stop")));
    assert!(matches!(outcome(&events), RunOutcome::Cancelled));
}

struct NotYet(Mutex<bool>);

impl Hooks for NotYet {
    async fn on_stop(&self, cx: &StopCx<'_>) -> StopDecision {
        let mut held = self.0.lock().unwrap();
        if std::mem::replace(&mut *held, true) {
            StopDecision::End
        } else {
            assert_eq!(cx.final_text, "first");
            StopDecision::Continue {
                reason: "check your work".into(),
            }
        }
    }
}

#[tokio::test]
async fn on_stop_can_hold_the_run_for_another_turn() {
    let llm = Scripted::new([say("first"), say("second")]);
    let mut agent = AgentBuilder::new(llm.clone())
        .hooks(NotYet(Mutex::new(false)))
        .build();

    let (result, events) = run_to_end(&mut agent, "go").await;

    result.expect("the run completes");
    assert!(matches!(
        outcome(&events),
        RunOutcome::Completed { final_text } if final_text == "second"
    ));
    let second = format!("{:?}", llm.requests()[1].messages());
    assert!(second.contains("check your work"), "{second}");
}

/// Puts a tail block in every request and a stable one at the first.
struct Notes {
    committed: Arc<Mutex<Vec<String>>>,
}

impl ContextSource for Notes {
    fn id(&self) -> SourceId {
        SourceId::new("notes")
    }

    async fn blocks(&mut self, moment: Moment) -> Vec<ContextBlock> {
        self.peek(moment).await
    }

    async fn peek(&self, moment: Moment) -> Vec<ContextBlock> {
        match moment {
            Moment::Request { reassembled: true } => vec![
                ContextBlock::stable("note", "stable-note"),
                ContextBlock::tail("clock", "tail-note"),
            ],
            Moment::Request { .. } => vec![ContextBlock::tail("clock", "tail-note")],
            _ => Vec::new(),
        }
    }

    async fn committed(&mut self, tail: &[Block]) {
        let mut committed = self.committed.lock().unwrap();
        committed.extend(tail.iter().map(|block| block.content().to_string()));
    }
}

#[tokio::test]
async fn a_source_contributes_stable_and_tail_blocks_and_hears_what_was_sent() {
    let llm = Scripted::new([say("hi")]);
    let committed = Arc::new(Mutex::new(Vec::new()));
    let mut agent = AgentBuilder::new(llm.clone())
        .context_source(Notes {
            committed: Arc::clone(&committed),
        })
        .build();

    let (result, events) = run_to_end(&mut agent, "go").await;

    result.expect("the run completes");
    let sent = format!("{:?}", llm.requests()[0].messages());
    assert!(sent.contains("tail-note"), "{sent}");
    assert_eq!(*committed.lock().unwrap(), ["tail-note"]);
    let kinds: Vec<_> = events
        .iter()
        .filter_map(|timed| match &timed.event {
            AgentEvent::ContextInjected { source, kind } if source.as_str() == "notes" => {
                Some(*kind)
            }
            _ => None,
        })
        .collect();
    assert_eq!(kinds, [InjectionKind::Tail]);
}

/// Returns a tail block where only a request has a tail.
struct BadTail;

impl ContextSource for BadTail {
    fn id(&self) -> SourceId {
        SourceId::new("bad")
    }

    async fn blocks(&mut self, moment: Moment) -> Vec<ContextBlock> {
        self.peek(moment).await
    }

    async fn peek(&self, moment: Moment) -> Vec<ContextBlock> {
        match moment {
            Moment::FinalTurn => vec![ContextBlock::tail("oops", "tail at the end")],
            _ => Vec::new(),
        }
    }
}

#[tokio::test]
#[should_panic(expected = "only a request has a tail")]
async fn a_tail_block_outside_a_request_is_a_contract_breach() {
    let mut agent = AgentBuilder::new(Scripted::new([say("hi")]))
        .context_source(BadTail)
        .build();
    let _ = run_to_end(&mut agent, "go").await;
}

#[tokio::test]
async fn instructions_render_in_the_order_they_were_added() {
    let llm = Scripted::new([say("hi")]);
    let mut agent = AgentBuilder::new(llm.clone())
        .instruction("first rule")
        .instruction("second rule")
        .build();

    let (result, _) = run_to_end(&mut agent, "go").await;

    result.expect("the run completes");
    let sent = format!("{:?}", llm.requests()[0].messages());
    let first = sent.find("first rule").expect("first instruction");
    let second = sent.find("second rule").expect("second instruction");
    assert!(first < second);
}

#[tokio::test]
async fn a_child_is_registered_bracketed_and_cancelled_through_the_registry() {
    let runs = SubagentRuns::default();
    let started_by = aither_core::llm::CallIdentity::new(
        aither_core::llm::ToolCallId::new("c1"),
        aither_core::llm::AgentIdentity::Main,
    );
    let run = runs.start(&started_by, "researcher", "look into it");
    assert_eq!(runs.list().len(), 1);
    assert_eq!(runs.list()[0].name, "researcher");

    let llm = Scripted::new([say("found it")]);
    let mut child = AgentBuilder::new(llm).identity(run.identity()).build();
    let signal = run.cancel_signal();
    assert!(!signal.is_cancelled());
    assert!(runs.cancel(run.id()));
    assert!(signal.is_cancelled());
    assert!(!runs.cancel(999));

    let outcome = run.run(&mut child, "look into it").await;

    assert!(matches!(outcome, RunOutcome::Cancelled));
    assert!(runs.list().is_empty());
}

#[tokio::test]
async fn a_childs_events_reach_the_parents_stream_with_its_path() {
    let runs = SubagentRuns::default();
    let started_by = aither_core::llm::CallIdentity::new(
        aither_core::llm::ToolCallId::new("c1"),
        aither_core::llm::AgentIdentity::Main,
    );
    let run = runs.start(&started_by, "researcher", "look");
    let path = run.path().clone();
    let mut child = AgentBuilder::new(Scripted::new([say("found")]))
        .identity(run.identity())
        .build();
    let outcome = run.run(&mut child, "look").await;
    assert!(matches!(outcome, RunOutcome::Completed { .. }));

    let mut parent = AgentBuilder::new(Scripted::new([say("hi")]))
        .subagents(runs)
        .build();
    let (result, events) = run_to_end(&mut parent, "go").await;
    result.expect("the parent completes");

    let child_events: Vec<_> = events.iter().filter(|timed| timed.agent == path).collect();
    assert!(
        child_events
            .iter()
            .any(|timed| matches!(timed.event, AgentEvent::RunStarted { .. }))
    );
    assert!(events.iter().any(|timed| matches!(
        &timed.event,
        AgentEvent::SubagentStarted { child, name, .. } if *child == path && name == "researcher"
    )));
    assert!(events.iter().any(|timed| matches!(
        &timed.event,
        AgentEvent::SubagentEnded { child, outcome: RunOutcome::Completed { .. } } if *child == path
    )));
    let _ = Duration::ZERO;
}

/// A tail block that reads the source's state and a one-shot stable block
/// that `blocks` consumes and `peek` leaves in place.
struct OneShot {
    pending: bool,
}

impl ContextSource for OneShot {
    fn id(&self) -> SourceId {
        SourceId::new("one-shot")
    }

    async fn blocks(&mut self, moment: Moment) -> Vec<ContextBlock> {
        let blocks = self.peek(moment).await;
        if matches!(moment, Moment::Request { .. }) {
            self.pending = false;
        }
        blocks
    }

    async fn peek(&self, moment: Moment) -> Vec<ContextBlock> {
        let Moment::Request { .. } = moment else {
            return Vec::new();
        };
        let mut blocks = vec![ContextBlock::tail("state", "tail-state")];
        if self.pending {
            blocks.push(ContextBlock::stable("correction", "one-shot-correction"));
        }
        blocks
    }
}

fn texts(messages: &[aither_core::llm::Message]) -> Vec<String> {
    messages
        .iter()
        .map(|message| format!("{message:?}"))
        .collect()
}

#[tokio::test]
async fn a_preview_carries_what_the_run_then_sends_and_consumes_nothing() {
    let llm = Scripted::new([say("hi")]);
    let mut agent = AgentBuilder::new(llm.clone())
        .context_source(OneShot { pending: true })
        .build();

    let previewed = agent
        .preview_request_messages("go", std::iter::empty())
        .await
        .expect("the preview renders");
    let again = agent
        .preview_request_messages("go", std::iter::empty())
        .await
        .expect("a second preview renders");
    assert_eq!(
        texts(&previewed),
        texts(&again),
        "a preview consumes nothing"
    );

    let (result, _) = run_to_end(&mut agent, "go").await;
    result.expect("the run completes");

    let sent = llm.requests()[0].messages().to_vec();
    assert_eq!(
        texts(&previewed),
        texts(&sent),
        "the preview is the request the run sends"
    );
    let sent_text = texts(&sent).join("\n");
    assert!(sent_text.contains("tail-state"), "{sent_text}");
    assert!(
        sent_text.contains("one-shot-correction"),
        "the one-shot block reaches the run after a preview: {sent_text}"
    );
}

#[tokio::test]
async fn a_panicking_tool_fails_its_call_and_the_next_call_runs() {
    let llm = Scripted::new([call("c1", "panicker"), call("c2", "probe"), say("done")]);
    let probe = Probe::default();
    let mut agent = AgentBuilder::new(llm.clone())
        .tool(Panicker)
        .tool(probe.clone())
        .build();

    let (result, _) = run_to_end(&mut agent, "go").await;

    result.expect("the run survives the panic");
    assert_eq!(*probe.0.lock().unwrap(), 1, "the next call ran normally");
    let results = tool_results(&llm);
    assert_eq!(
        results,
        [
            "Error: tool 'panicker' panicked: the disk is on fire",
            "probed"
        ]
    );
}

#[tokio::test]
async fn a_panic_in_one_parallel_call_leaves_the_other_result_intact() {
    let llm = Scripted::new([
        vec![
            Event::ToolCall(ToolCall::new("c1", "panicker", serde_json::json!({}))),
            Event::ToolCall(ToolCall::new("c2", "probe", serde_json::json!({}))),
        ],
        say("done"),
    ]);
    let probe = Probe::default();
    let mut agent = AgentBuilder::new(llm.clone())
        .tool(Panicker)
        .tool(probe.clone())
        .build();

    let (result, _) = run_to_end(&mut agent, "go").await;

    result.expect("the run survives the panic");
    assert_eq!(*probe.0.lock().unwrap(), 1);
    let results = tool_results(&llm);
    assert_eq!(results.len(), 2);
    assert!(results.contains(&"probed".to_owned()), "{results:?}");
    assert!(
        results.contains(&"Error: tool 'panicker' panicked: the disk is on fire".to_owned()),
        "{results:?}"
    );
}

#[tokio::test]
async fn a_checkpoint_taken_mid_run_restores_the_completed_steps() {
    let llm = Scripted::new([call("c1", "probe"), say("done")]);
    let mut agent = AgentBuilder::new(llm).tool(Probe::default()).build();
    let run = agent.run("go", std::iter::empty());
    let checkpoints = run.checkpoints();

    let flow = run
        .drive(
            (),
            std::future::pending::<Option<AgentCheckpoint>>(),
            |(), timed| {
                let taken = match timed.event {
                    AgentEvent::Checkpoint { .. } => Some(checkpoints.latest()),
                    _ => None,
                };
                async move { taken.map_or(ControlFlow::Continue(()), ControlFlow::Break) }
            },
        )
        .await
        .expect("the run is stopped, not failed");
    let ControlFlow::Break(checkpoint) = flow else {
        panic!("the run emitted a checkpoint");
    };
    let checkpoint = checkpoint.expect("a checkpoint event follows a recorded checkpoint");

    let mut restored = AgentBuilder::new(Scripted::new([]))
        .tool(Probe::default())
        .build();
    restored
        .restore_checkpoint(checkpoint)
        .expect("the checkpoint restores");
    let history = format!("{:?}", restored.history());
    assert!(history.contains("go"), "the user message: {history}");
    assert!(history.contains("c1"), "the completed tool call: {history}");
}