loopctl 0.1.0

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! Agent core trait and foundational lifecycle types.
//!
//! Fundamental operations every agent must support, plus the data types
//! that flow through the agent lifecycle: configuration ([`LoopConfig`]),
//! lifecycle state ([`LoopState`]), turn and session results
//! ([`TurnResult`], [`SessionResult`]), and tool call representations
//! ([`ToolCall`]).
//!
//! # Lifecycle
//!
//! ```text
//! initialize(config)
//!   → process_turn(input)   [repeated]
//!   → process_turn(input)
//!   → ...
//!   → should_continue() → false
//! finalize()
//! ```
//!
//! # Implementing
//!
//! At a minimum you must provide [`initialize`](Loop::initialize),
//! [`process_turn`](Loop::process_turn),
//! [`should_continue`](Loop::should_continue),
//! [`finalize`](Loop::finalize),
//! [`state`](Loop::state), and
//! [`cancel`](Loop::cancel).
//!
//! # Quick Start
//!
//! ```
//! use loopctl::engine::loop_core::{LoopConfig, LoopState, TurnResult, SessionResult};
//!
//! let config = LoopConfig::default();
//! assert_eq!(config.max_turns, 200);
//!
//! let turn = TurnResult::completed("Task done.");
//! assert!(turn.is_complete);
//!
//! let session = SessionResult::success(config.session_id);
//! assert!(session.success);
//! ```

use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::error::LoopError;

// Re-export LoopConfig for convenience — it lives in crate::config.
pub use crate::config::LoopConfig;

// Re-export ToolDispatchResult so consumers of this module see the full
// tool-call type family in one place.
pub use crate::tool::ToolDispatchResult;

// ==================================================
// LoopState
// ==================================================

/// The lifecycle state of an agent.
///
/// Models the agent as an explicit state machine, making transitions clear
/// and invalid states unrepresentable. The framework reads and writes this
/// enum to drive the agent loop and report status to observers.
///
/// ```text
/// Idle → Processing → WaitingForTool → Processing → ... → Completed/Failed
///                  ↘ Compacting ↗
///                  ↘ Reflecting ↗
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LoopState {
    /// The agent is idle, waiting for a user message.
    ///
    /// Initial state after initialization and the state
    /// the agent returns to between user inputs.
    ///
    /// No background work is performed while idle.
    Idle,

    /// The agent is actively processing a turn.
    ///
    /// Entered when the agent core begins processing a user message
    /// or a tool result. The `turn` field tracks progress for observers.
    ///
    /// The agent transitions here from [`Idle`](LoopState::Idle) or
    /// [`WaitingForTool`](LoopState::WaitingForTool).
    Processing {
        /// Current turn number (0-indexed). Used to enforce [`LoopConfig::max_turns`].
        turn: usize,
    },

    /// The agent is waiting for a tool to complete.
    ///
    /// Entered after the LLM requests a tool call. The framework
    /// dispatches the tool and waits for its result before returning
    /// to [`Processing`](LoopState::Processing).
    WaitingForTool {
        /// Name of the tool being executed. Never empty — always matches a registered tool name.
        tool: String,

        /// When the tool call started. Used to compute execution duration.
        started_at: SystemTime,
    },

    /// The agent is compacting its conversation context.
    ///
    /// Entered when token usage exceeds the
    /// [`compact_threshold`](LoopConfig::compact_threshold) or when
    /// compaction is explicitly requested. The agent summarizes older
    /// messages to free context space, then returns to
    /// [`Processing`](LoopState::Processing).
    Compacting {
        /// Why compaction was triggered. See
        /// [`CompactReason`](crate::compact::types::CompactReason).
        reason: crate::compact::types::CompactReason,
    },

    /// The agent is reflecting on a failure and preparing a correction.
    ///
    /// Entered when a tool call fails and the reflection system is
    /// enabled (via configuration).
    /// The agent analyzes the error and produces a
    /// [`Correction`](crate::reflection::Correction) before retrying.
    Reflecting {
        /// Number of errors being analyzed; higher counts may need
        /// [`ApproachChange`](crate::reflection::CorrectionType::ApproachChange).
        error_count: usize,
    },

    /// The agent has completed its task.
    ///
    /// Terminal state. The framework calls
    /// `Loop::finalize` to produce
    /// a [`SessionResult`].
    Completed {
        /// May be empty if the agent produced only tool calls.
        summary: String,
    },

    /// The agent has failed with an unrecoverable error.
    ///
    /// Terminal state. The error is propagated through
    /// [`SessionResult::error`].
    ///
    /// No further turns will be executed after entering this state.
    Failed {
        /// A human-readable description of the error that caused the failure.
        error: String,
    },
}

// ==================================================
// TurnResult
// ==================================================

/// Result of a single agent turn (one API call → response cycle).
///
/// Produced by `Loop::process_turn`
/// after each LLM interaction. Contains the response text, any tool calls
/// requested, token usage, and timing information.
///
/// # Construction
///
/// Use [`TurnResult::completed`] for a terminal response or
/// [`TurnResult::continuing`] for a response that should keep the loop running.
/// Production code typically constructs this from the raw API response.
///
/// ```
/// use loopctl::engine::loop_core::TurnResult;
///
/// let done = TurnResult::completed("All tasks finished.");
/// assert!(done.is_complete);
///
/// let more = TurnResult::continuing("Still working...");
/// assert!(!more.is_complete);
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TurnResult {
    /// May be empty if the response consists entirely of tool calls.
    pub text: String,
    /// Tool calls requested by the LLM in this turn.
    pub tool_calls: Vec<ToolCall>,
    /// Results from dispatching the requested tool calls.
    pub tool_results: Vec<ToolDispatchResult>,
    /// Input tokens used (system prompt + history + user message). Reported by the provider.
    pub input_tokens: u64,
    /// Output tokens in the API response. Reported by the provider.
    pub output_tokens: u64,
    /// Wall-clock duration (API request → full response + tool execution).
    pub duration: Duration,
    /// When `true`, the framework skips `should_continue` and proceeds to finalization.
    pub is_complete: bool,
    /// Used by the framework to decide whether to dispatch tools ([`StopReason::ToolCall`]) or continue.
    pub stop_reason: StopReason,
}

impl TurnResult {
    /// Create a completed turn result with a simple text response.
    ///
    /// Sets [`is_complete`](TurnResult::is_complete) to `true` and all
    /// token counters to zero. Use this for the final turn of a session.
    ///
    /// # Example
    ///
    /// ```
    /// use loopctl::engine::loop_core::TurnResult;
    ///
    /// let result = TurnResult::completed("The file has been written successfully.");
    /// assert!(result.is_complete);
    /// assert_eq!(result.tool_calls.len(), 0);
    /// ```
    #[must_use]
    pub fn completed(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            tool_calls: Vec::new(),
            tool_results: Vec::new(),
            input_tokens: 0,
            output_tokens: 0,
            duration: Duration::ZERO,
            is_complete: true,
            stop_reason: StopReason::EndTurn,
        }
    }

    /// Create a turn result that should continue with more turns.
    ///
    /// Sets [`is_complete`](TurnResult::is_complete) to `false`, indicating
    /// that the agent loop should keep running.
    ///
    /// # Example
    ///
    /// ```
    /// use loopctl::engine::loop_core::TurnResult;
    ///
    /// let result = TurnResult::continuing("I need to read the file first...");
    /// assert!(!result.is_complete);
    /// ```
    #[must_use]
    pub fn continuing(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            tool_calls: Vec::new(),
            tool_results: Vec::new(),
            input_tokens: 0,
            output_tokens: 0,
            duration: Duration::ZERO,
            is_complete: false,
            stop_reason: StopReason::EndTurn,
        }
    }

    /// Check if this turn included any tool calls.
    ///
    /// Returns `true` when [`tool_calls`](TurnResult::tool_calls) is
    /// non-empty, indicating that the LLM requested tool execution.
    #[must_use]
    pub fn has_tool_calls(&self) -> bool {
        !self.tool_calls.is_empty()
    }

    /// Total tokens (input + output) for this turn.
    ///
    /// Sums [`input_tokens`](TurnResult::input_tokens)
    /// and [`output_tokens`](TurnResult::output_tokens).
    #[must_use]
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens.saturating_add(self.output_tokens)
    }
}

// ==================================================
// StopReason
// ==================================================

/// Why the API stopped generating.
///
/// Mirrors the stop reasons returned by LLM APIs. The framework uses this
/// to determine the next step: dispatch tools, continue the conversation,
/// or end the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum StopReason {
    /// The model decided to stop (natural end of turn).
    ///
    /// The LLM finished its response without requesting tools or hitting
    /// any limit. The framework should check
    /// [`TurnResult::is_complete`] to decide whether to continue.
    EndTurn,

    /// The model requested tool execution.
    ///
    /// The LLM response contains one or more tool calls in
    /// [`TurnResult::tool_calls`]. The framework should dispatch them
    /// and feed the results back.
    ToolCall,

    /// The maximum token limit was reached.
    ///
    /// The LLM hit the [`LoopConfig::max_tokens`] limit before
    /// finishing. The response may be truncated. The framework may
    /// choose to continue the turn to let the model complete its output.
    MaxTokens,

    /// The stop sequence was encountered.
    ///
    /// The model generated a configured stop sequence. Rare in
    /// standard usage; typically indicates custom API configuration.
    StopSequence,
}

// ==================================================
// ToolCall
// ==================================================

/// A tool call requested by the agent.
///
/// Represents a single tool invocation that the LLM has requested during a
/// turn. The framework matches each `ToolCall` to a registered tool, executes
/// it, and produces a [`ToolDispatchResult`] with the output.
///
/// # Serialization
///
/// Implements `Serialize` and `Deserialize` for persistence and inter-process
/// communication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Assigned by the LLM API. Correlates with [`ToolDispatchResult::tool_call_id`].
    pub id: String,

    /// Must match a tool registered in the `ToolRegistry`.
    pub tool: String,

    /// JSON object whose schema depends on the tool.
    pub input: serde_json::Value,
}

impl ToolCall {
    /// Apply a [`Correction`](crate::reflection::Correction) from the reflection system in place.
    ///
    /// Modifies `self` according to the correction strategy:
    ///
    /// - [`InputFix`](crate::reflection::CorrectionType::InputFix) — replaces
    ///   `self.input` with the corrected input.
    /// - [`ToolChange`](crate::reflection::CorrectionType::ToolChange) — replaces
    ///   `self.tool` with an alternative tool name.
    /// - Other types — no mutation; the retry proceeds with unchanged parameters.
    ///
    /// Returns a [`CorrectionResult`](crate::reflection::CorrectionResult) indicating whether the correction
    /// was applied, failed, or skipped.
    pub fn apply_correction(
        &mut self,
        correction: &crate::reflection::Correction,
        _prior_result: &crate::tool::ToolDispatchResult,
    ) -> crate::reflection::CorrectionResult {
        use crate::reflection::CorrectionType;
        match correction.correction_type {
            CorrectionType::InputFix => {
                if let Some(ref modified) = correction.modified_input {
                    if modified.is_object() {
                        tracing::debug!(
                            tool = %self.tool,
                            "applying InputFix correction from reflector"
                        );
                        self.input = modified.clone();
                        crate::reflection::CorrectionResult::Applied
                    } else {
                        crate::reflection::CorrectionResult::Failed(
                            "InputFix correction modified_input must be a JSON object".to_string(),
                        )
                    }
                } else {
                    crate::reflection::CorrectionResult::Failed(
                        "InputFix correction missing modified_input".to_string(),
                    )
                }
            }
            CorrectionType::ToolChange => {
                if let Some(ref alt) = correction.alternative_tool {
                    tracing::debug!(
                        old_tool = %self.tool,
                        new_tool = %alt,
                        "applying ToolChange correction from reflector"
                    );
                    self.tool.clone_from(alt);
                    crate::reflection::CorrectionResult::Applied
                } else {
                    crate::reflection::CorrectionResult::Failed(
                        "ToolChange correction missing alternative_tool".to_string(),
                    )
                }
            }
            CorrectionType::PrerequisiteFix | CorrectionType::ApproachChange => {
                crate::reflection::CorrectionResult::Skipped
            }
            CorrectionType::Escalate => crate::reflection::CorrectionResult::Skipped,
        }
    }
}

// ==================================================
// SessionResult
// ==================================================

/// Summary of a complete agent session.
///
/// Produced by `Loop::finalize`
/// after the last turn. Aggregates all session-level metrics: total turns,
/// tokens, duration, tool calls, and final output.
///
/// # Construction
///
/// Use [`SessionResult::success`] for a completed session or
/// [`SessionResult::failed`] for a session that ended with an error.
///
/// ```
/// use loopctl::engine::loop_core::SessionResult;
/// use uuid::Uuid;
///
/// let session_id = Uuid::new_v4();
///
/// let ok = SessionResult::success(session_id);
/// assert!(ok.success);
///
/// let err = SessionResult::failed(session_id, "API rate limit exceeded");
/// assert!(!err.success);
/// assert_eq!(err.error.unwrap(), "API rate limit exceeded");
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SessionResult {
    /// Matches [`LoopConfig::session_id`].
    pub session_id: Uuid,
    /// Total turns executed. Compared against [`LoopConfig::max_turns`].
    pub total_turns: usize,
    /// Sum of [`TurnResult::input_tokens`] across all turns.
    pub input_tokens: u64,
    /// Sum of [`TurnResult::output_tokens`] across all turns.
    pub output_tokens: u64,
    /// Wall-clock time from session start to finalization.
    pub total_duration: Duration,
    /// Total number of tool calls executed across all turns.
    pub tool_calls: usize,
    /// `true` on [`LoopState::Completed`], `false` on [`LoopState::Failed`].
    pub success: bool,
    /// Last meaningful text response from the agent. `None` if no final message.
    pub final_output: Option<String>,
    /// `Some` on failure with a human-readable error description.
    pub error: Option<String>,
}

impl Default for SessionResult {
    fn default() -> Self {
        Self {
            session_id: Uuid::nil(),
            total_turns: 0,
            input_tokens: 0,
            output_tokens: 0,
            total_duration: Duration::ZERO,
            tool_calls: 0,
            success: false,
            final_output: None,
            error: None,
        }
    }
}

impl SessionResult {
    /// Create a successful session result.
    ///
    /// Initializes all counters to zero and sets [`success`](SessionResult::success)
    /// to `true`. The framework or production code should fill in the actual
    /// counters before returning.
    ///
    /// # Example
    ///
    /// ```
    /// use loopctl::engine::loop_core::SessionResult;
    /// use uuid::Uuid;
    ///
    /// let session_id = Uuid::new_v4();
    /// let result = SessionResult::success(session_id);
    /// assert!(result.success);
    /// assert!(result.error.is_none());
    /// ```
    #[must_use]
    pub fn success(session_id: Uuid) -> Self {
        Self {
            session_id,
            total_turns: 0,
            input_tokens: 0,
            output_tokens: 0,
            total_duration: Duration::ZERO,
            tool_calls: 0,
            success: true,
            final_output: None,
            error: None,
        }
    }

    /// Create a failed session result.
    ///
    /// Sets [`success`](SessionResult::success) to `false` and records the
    /// error message. All counters are initialized to zero.
    ///
    /// # Example
    ///
    /// ```
    /// use loopctl::engine::loop_core::SessionResult;
    /// use uuid::Uuid;
    ///
    /// let session_id = Uuid::new_v4();
    /// let result = SessionResult::failed(session_id, "API rate limit exceeded");
    /// assert!(!result.success);
    /// assert_eq!(result.error.unwrap(), "API rate limit exceeded");
    /// ```
    #[must_use]
    pub fn failed(session_id: Uuid, error: impl Into<String>) -> Self {
        Self {
            session_id,
            total_turns: 0,
            input_tokens: 0,
            output_tokens: 0,
            total_duration: Duration::ZERO,
            tool_calls: 0,
            success: false,
            final_output: None,
            error: Some(error.into()),
        }
    }

    /// Total tokens (input + output) for this session.
    ///
    /// Sums [`input_tokens`](SessionResult::input_tokens)
    /// and [`output_tokens`](SessionResult::output_tokens).
    #[must_use]
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens.saturating_add(self.output_tokens)
    }

    /// Construct a `SessionResult` with full control over every field.
    ///
    /// Intended for tests that need to assert on specific field
    /// combinations that the `success()` / `failed()` constructors
    /// don't cover (e.g. non-zero `tool_calls` or `total_turns`).
    ///
    /// Only available with the `testing` feature.
    ///
    /// # Example
    ///
    /// ```
    /// # use loopctl::engine::loop_core::SessionResult;
    /// # use std::time::Duration;
    /// # use uuid::Uuid;
    /// let result = SessionResult::builder()
    ///     .session_id(Uuid::nil())
    ///     .total_turns(5)
    ///     .tool_calls(3)
    ///     .success(true)
    /// .build();
    /// assert_eq!(result.total_turns, 5);
    /// assert_eq!(result.tool_calls, 3);
    /// assert!(result.success);
    /// ```
    #[cfg(feature = "testing")]
    #[must_use]
    pub fn builder() -> SessionResultBuilder {
        SessionResultBuilder {
            session_id: Uuid::nil(),
            total_turns: 0,
            input_tokens: 0,
            output_tokens: 0,
            total_duration: Duration::ZERO,
            tool_calls: 0,
            success: false,
            final_output: None,
            error: None,
        }
    }
}

/// Builder for constructing [`SessionResult`] instances in tests.
///
/// Created by [`SessionResult::builder`]. All fields default to zeroed
/// or empty values; override only the ones your test cares about, then
/// call `.build()`.
#[cfg(feature = "testing")]
#[derive(Debug, Clone)]
pub struct SessionResultBuilder {
    /// Unique session identifier.
    session_id: Uuid,
    /// Number of turns executed.
    total_turns: usize,
    /// Total input tokens consumed.
    input_tokens: u64,
    /// Total output tokens produced.
    output_tokens: u64,
    /// Wall-clock duration of the session.
    total_duration: Duration,
    /// Number of tool calls dispatched.
    tool_calls: usize,
    /// Whether the session completed successfully.
    success: bool,
    /// Final text output, if any.
    final_output: Option<String>,
    /// Error message if the session failed.
    error: Option<String>,
}

#[cfg(feature = "testing")]
impl SessionResultBuilder {
    /// Set the session ID.
    #[must_use]
    pub fn session_id(mut self, id: Uuid) -> Self {
        self.session_id = id;
        self
    }

    /// Set the total turns executed.
    #[must_use]
    pub fn total_turns(mut self, turns: usize) -> Self {
        self.total_turns = turns;
        self
    }

    /// Set the total input tokens.
    #[must_use]
    pub fn input_tokens(mut self, tokens: u64) -> Self {
        self.input_tokens = tokens;
        self
    }

    /// Set the total output tokens.
    #[must_use]
    pub fn output_tokens(mut self, tokens: u64) -> Self {
        self.output_tokens = tokens;
        self
    }

    /// Set the total session duration.
    #[must_use]
    pub fn total_duration(mut self, duration: Duration) -> Self {
        self.total_duration = duration;
        self
    }

    /// Set the total tool calls made.
    #[must_use]
    pub fn tool_calls(mut self, calls: usize) -> Self {
        self.tool_calls = calls;
        self
    }

    /// Set whether the session succeeded.
    #[must_use]
    pub fn success(mut self, success: bool) -> Self {
        self.success = success;
        self
    }

    /// Set the final output text.
    #[must_use]
    pub fn final_output(mut self, output: impl Into<String>) -> Self {
        self.final_output = Some(output.into());
        self
    }

    /// Set the error message.
    #[must_use]
    pub fn error(mut self, error: impl Into<String>) -> Self {
        self.error = Some(error.into());
        self
    }

    /// Build the [`SessionResult`].
    #[must_use]
    pub fn build(self) -> SessionResult {
        SessionResult {
            session_id: self.session_id,
            total_turns: self.total_turns,
            input_tokens: self.input_tokens,
            output_tokens: self.output_tokens,
            total_duration: self.total_duration,
            tool_calls: self.tool_calls,
            success: self.success,
            final_output: self.final_output,
            error: self.error,
        }
    }
}

// ==================================================
// Loop trait
// ==================================================

/// The core agent lifecycle trait.
///
/// Implement this trait to create a new type of agent. The framework
/// provides shared infrastructure for context management, tool execution,
/// reflection, and observability, so implementations only need to define
/// the core processing logic.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::engine::loop_core::Loop;
/// use loopctl::error::LoopError;
/// use loopctl::engine::loop_core::{LoopConfig, LoopState, SessionResult, TurnResult};
///
/// struct MyAgent {
///     state: MyState,
/// }
///
/// impl Loop for MyAgent {
///     fn initialize<'a>(&'a mut self, config: &'a LoopConfig) -> Pin<Box<dyn Future<Output = Result<(), LoopError>> + Send + 'a>> {
///         Box::pin(async { Ok(()) })
///     }
///     fn process_turn<'a>(&'a mut self, input: &'a str) -> Pin<Box<dyn Future<Output = Result<TurnResult, LoopError>> + Send + 'a>> {
///         Box::pin(async { Ok(TurnResult::completed("Done!")) })
///     }
///     fn should_continue(&self) -> bool {
///         !self.state.is_complete
///     }
///     fn finalize<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<SessionResult, LoopError>> + Send + 'a>> {
///         Box::pin(async { Ok(SessionResult::success(self.state.session_id)) })
///     }
///     fn state(&self) -> LoopState {
///         LoopState::Idle
///     }
///     fn cancel(&self) {}
/// }
/// ```
pub trait Loop: Send + Sync {
    /// Initialize the agent with the given configuration.
    ///
    /// Called once before any turns are processed. Use this to set up
    /// internal state, validate configuration, and prepare resources.
    fn initialize<'a>(
        &'a mut self,
        config: &'a LoopConfig,
    ) -> Pin<Box<dyn Future<Output = Result<(), LoopError>> + Send + 'a>>;

    /// Process a single turn of the loop.
    ///
    /// Main entry point for loop logic. On the **first** call within a
    /// [`run`](Loop::run) session, `input` contains the user's message;
    /// subsequent calls receive an empty string (`""`) to signal a
    /// continuation turn (tool results are already in the conversation
    /// history). Implementations that need the original user message should
    /// capture it during [`initialize`](Loop::initialize) or the first
    /// `process_turn` call.
    fn process_turn<'a>(
        &'a mut self,
        input: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<TurnResult, LoopError>> + Send + 'a>>;

    /// Check whether the agent should continue processing turns.
    ///
    /// Called after each turn. Return `false` to end the session.
    fn should_continue(&self) -> bool;

    /// Finalize the agent session and produce a summary.
    ///
    /// Called once after the last turn. Use this to clean up resources
    /// and produce a final [`SessionResult`].
    fn finalize<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<SessionResult, LoopError>> + Send + 'a>>;

    /// Get the current state of the agent.
    ///
    /// Used by the framework to drive the state machine and by observers
    /// to report status.
    fn state(&self) -> LoopState;

    /// Cancel the agent's current operation.
    ///
    /// Implementations must use thread-safe interior mutability (e.g.
    /// [`AtomicBool`](std::sync::atomic::AtomicBool), `Mutex<bool>`) to
    /// store the cancellation flag, since this method takes `&self`. The
    /// flag should be set in a non-blocking fashion so that
    /// [`process_turn`](Loop::process_turn) and
    /// [`should_continue`](Loop::should_continue) can observe it
    /// and return promptly across threads.
    fn cancel(&self);

    /// Explain *why* [`should_continue`](Loop::should_continue) returned `false`.
    ///
    /// Called by [`run`](Loop::run) after the drive loop exits. Return:
    ///
    /// - `None` — the session ended normally (model finished).
    /// - `Some(err)` — the session was forced to stop (`Cancelled`,
    ///   `MaxTurnsExceeded`, etc.).
    ///
    /// The default implementation returns `None` (normal completion).
    fn stop_reason(&self) -> Option<LoopError> {
        None
    }

    /// Drive the full agent session: initialize → turn loop → finalize.
    ///
    /// This is the main entry point for running an agent. It calls
    /// [`initialize`](Loop::initialize) with the agent's stored config,
    /// then repeatedly calls [`process_turn`](Loop::process_turn) until either:
    ///
    /// - The turn result is marked `is_complete` (the model finished), or
    /// - [`should_continue`](Loop::should_continue) returns `false`.
    ///
    /// When `should_continue` returns `false`,
    /// [`stop_reason`](Loop::stop_reason) is consulted to distinguish
    /// normal completion from an error (cancellation, max-turns, etc.).
    ///
    /// # Errors
    ///
    /// - [`LoopError::Cancelled`] — if the session was cancelled.
    /// - [`LoopError::MaxTurnsExceeded`] — if the turn limit was reached.
    /// - Any error returned by [`process_turn`](Loop::process_turn) or
    ///   [`finalize`](Loop::finalize).
    fn run<'a>(
        &'a mut self,
        user_input: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<SessionResult, LoopError>> + Send + 'a>> {
        Box::pin(async move {
            // Clone is required: `initialize` takes `&mut self` which
            // conflicts with the shared borrow from `config()`.
            let config = self.config().clone();
            self.initialize(&config).await?;

            let mut is_first_turn = true;
            loop {
                if !self.should_continue() {
                    break;
                }

                // Pass user_input only on the first turn; subsequent turns
                // receive "" to signal continuation (tool results are
                // already in the conversation history).
                let input = if is_first_turn {
                    is_first_turn = false;
                    user_input
                } else {
                    ""
                };
                match self.process_turn(input).await {
                    Ok(turn_result) if turn_result.is_complete => {
                        return self.finalize().await;
                    }
                    Ok(_) => { /* turn produced tool calls — continue */ }
                    Err(e) => {
                        self.finalize().await?;
                        return Err(e);
                    }
                }
            }

            // should_continue() returned false — ask the impl why.
            if let Some(err) = self.stop_reason() {
                self.finalize().await?;
                return Err(err);
            }

            self.finalize().await
        })
    }

    /// Return the configuration that [`run`](Loop::run) passes to
    /// [`initialize`](Loop::initialize).
    ///
    /// Implementors should return a reference to the [`LoopConfig`] they
    /// want to use for the session.  Returning a reference (rather than an
    /// owned clone) avoids a mandatory `Clone` on every call — the default
    /// [`run`](Loop::run) implementation only needs the config during
    /// initialization, so the borrow is short-lived.
    fn config(&self) -> &LoopConfig;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::reflection::{Correction, CorrectionResult, CorrectionType};
    use crate::tool::ToolDispatchResult;
    use serde_json::json;
    use std::time::Duration;

    fn make_call() -> ToolCall {
        ToolCall {
            id: "test".to_string(),
            tool: "Read".to_string(),
            input: json!({"path": "/tmp"}),
        }
    }

    fn empty_prior_result() -> ToolDispatchResult {
        ToolDispatchResult::ok("Read", String::new(), Duration::ZERO)
    }

    #[test]
    fn input_fix_accepts_json_object() {
        let mut call = make_call();
        let correction = Correction {
            correction_type: CorrectionType::InputFix,
            description: "fix path".into(),
            modified_input: Some(json!({"path": "/tmp/fixed"})),
            alternative_tool: None,
            guidance: None,
        };
        let result = call.apply_correction(&correction, &empty_prior_result());
        assert!(matches!(result, CorrectionResult::Applied));
        assert_eq!(call.input, json!({"path": "/tmp/fixed"}));
    }

    #[test]
    fn input_fix_rejects_scalar() {
        let mut call = make_call();
        let correction = Correction {
            correction_type: CorrectionType::InputFix,
            description: "bad fix".into(),
            modified_input: Some(json!("/tmp/scalar")),
            alternative_tool: None,
            guidance: None,
        };
        let result = call.apply_correction(&correction, &empty_prior_result());
        match result {
            CorrectionResult::Failed(msg) => {
                assert!(msg.contains("JSON object"), "{msg}");
            }
            other => panic!("expected Failed, got {other:?}"),
        }
        // Input should remain unchanged.
        assert_eq!(call.input, json!({"path": "/tmp"}));
    }

    #[test]
    fn input_fix_rejects_array() {
        let mut call = make_call();
        let correction = Correction {
            correction_type: CorrectionType::InputFix,
            description: "bad fix".into(),
            modified_input: Some(json!(["a", "b"])),
            alternative_tool: None,
            guidance: None,
        };
        let result = call.apply_correction(&correction, &empty_prior_result());
        assert!(matches!(result, CorrectionResult::Failed(_)));
        assert_eq!(call.input, json!({"path": "/tmp"}));
    }

    #[test]
    fn input_fix_rejects_null() {
        let mut call = make_call();
        let correction = Correction {
            correction_type: CorrectionType::InputFix,
            description: "bad fix".into(),
            modified_input: Some(serde_json::Value::Null),
            alternative_tool: None,
            guidance: None,
        };
        let result = call.apply_correction(&correction, &empty_prior_result());
        assert!(matches!(result, CorrectionResult::Failed(_)));
        assert_eq!(call.input, json!({"path": "/tmp"}));
    }

    #[test]
    fn input_fix_rejects_missing() {
        let mut call = make_call();
        let correction = Correction {
            correction_type: CorrectionType::InputFix,
            description: "no input".into(),
            modified_input: None,
            alternative_tool: None,
            guidance: None,
        };
        let result = call.apply_correction(&correction, &empty_prior_result());
        assert!(matches!(result, CorrectionResult::Failed(_)));
        assert_eq!(call.input, json!({"path": "/tmp"}));
    }
}