agentkit-compaction 0.7.0

Transcript compaction triggers, strategies, pipelines, and backend hooks for agentkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
//! Transcript compaction primitives for reducing context size while preserving
//! useful state.
//!
//! This crate provides the building blocks for compacting an agent transcript
//! when it grows too large. The main concepts are:
//!
//! - **Compactors** ([`Compactor`]) decide *when* and *how* to compact in a
//!   single trait. Register one with the agent builder via
//!   [`AgentBuilderCompactorExt::compactor`].
//! - **Strategies** ([`CompactionStrategy`]) decide *how* the transcript is
//!   transformed: dropping reasoning, removing failed tool results, keeping
//!   only recent items, or summarising older items via a backend.
//! - **Pipelines** ([`CompactionPipeline`]) chain multiple strategies into a
//!   single pass.
//! - **Backends** ([`CompactionBackend`]) provide provider-backed
//!   summarisation for strategies that need it (e.g.
//!   [`SummarizeOlderStrategy`]).
//!
//! Wire a [`StrategyCompactor`] (bundling a trigger closure + strategy +
//! optional backend) into the loop, or implement [`Compactor`] directly for
//! stateful triggers.

use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

use agentkit_core::{Item, ItemKind, MetadataMap, Part, SessionId, TurnCancellation};
use agentkit_loop::{
    Agent, AgentBuilder, AgentEvent, LoopCtx, LoopError, LoopMutator, LoopStep, ModelAdapter,
    MutationPoint, SessionConfig, TranscriptCursor,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// The reason a compaction was triggered.
///
/// Returned by [`CompactionTrigger::should_compact`] and forwarded to
/// strategies so they can adapt their behaviour.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompactionReason {
    /// The transcript exceeded a configured item count.
    TranscriptTooLong,
    /// A caller explicitly requested compaction.
    Manual,
    /// An application-specific reason described by the inner string.
    Custom(String),
}

/// Input to a [`CompactionStrategy`]. Carries the transcript plus request
/// metadata so strategies can decide which items to keep, drop, or summarise.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompactionRequest {
    /// The transcript to compact.
    pub transcript: Vec<Item>,
    /// Why compaction was triggered.
    pub reason: CompactionReason,
    /// Arbitrary key-value metadata forwarded through the pipeline.
    pub metadata: MetadataMap,
}

impl CompactionRequest {
    /// Build a compaction request with empty metadata.
    pub fn new(transcript: Vec<Item>, reason: CompactionReason) -> Self {
        Self {
            transcript,
            reason,
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the request metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Output of a [`CompactionStrategy`].
///
/// Contains the compacted transcript along with metadata about what changed.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompactionResult {
    /// The compacted transcript.
    pub transcript: Vec<Item>,
    /// How many items were removed or replaced during compaction.
    pub replaced_items: usize,
    /// Metadata produced by the strategy (e.g. summarisation statistics).
    pub metadata: MetadataMap,
}

impl CompactionResult {
    /// Builds a compaction result with empty metadata.
    pub fn new(transcript: Vec<Item>, replaced_items: usize) -> Self {
        Self {
            transcript,
            replaced_items,
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the result metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Request sent to a [`CompactionBackend`] asking it to summarise a set of
/// transcript items.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SummaryRequest {
    /// The transcript items to summarise.
    pub items: Vec<Item>,
    /// Why compaction was triggered.
    pub reason: CompactionReason,
    /// Arbitrary key-value metadata forwarded from the pipeline.
    pub metadata: MetadataMap,
}

impl SummaryRequest {
    /// Build a summary request with empty metadata.
    pub fn new(items: Vec<Item>, reason: CompactionReason) -> Self {
        Self {
            items,
            reason,
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the request metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Response from a [`CompactionBackend`] containing the summarised items.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SummaryResult {
    /// The summary items that replace the originals in the transcript.
    pub items: Vec<Item>,
    /// Metadata produced during summarisation (e.g. token counts).
    pub metadata: MetadataMap,
}

impl SummaryResult {
    /// Builds a summary result with empty metadata.
    pub fn new(items: Vec<Item>) -> Self {
        Self {
            items,
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the result metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Provider-backed summarisation service.
///
/// Implement this trait to connect a language model (or any other
/// summarisation service) so that strategies like [`SummarizeOlderStrategy`]
/// can condense older transcript items into a shorter summary.
///
/// # Errors
///
/// Implementations should return [`CompactionError::Failed`] when
/// summarisation cannot be completed, or [`CompactionError::Cancelled`] when
/// the cancellation token is signalled.
#[async_trait]
pub trait CompactionBackend: Send + Sync {
    /// Summarise the given items into a shorter set of replacement items.
    ///
    /// # Arguments
    ///
    /// * `request` - The items to summarise together with session context.
    /// * `cancellation` - An optional cancellation token; implementations
    ///   should check this periodically and bail early when cancelled.
    ///
    /// # Errors
    ///
    /// Returns [`CompactionError`] on failure or cancellation.
    async fn summarize(
        &self,
        request: SummaryRequest,
        cancellation: Option<TurnCancellation>,
    ) -> Result<SummaryResult, CompactionError>;
}

/// High-level compaction primitive. Implementations decide whether and how
/// to compact, owning their own derived state (e.g. running token totals
/// behind interior mutability) so the framework doesn't need to plumb a
/// separate observer or shared atomic.
///
/// Wire a `Compactor` into the loop via [`AgentBuilderCompactorExt::compactor`],
/// which adapts it to a [`LoopMutator`] under the hood.
#[async_trait]
pub trait Compactor: Send + Sync {
    /// Decide whether to compact based on the current transcript and
    /// mutation point. Returning `None` is a no-op.
    fn should_compact(&self, transcript: &[Item], point: MutationPoint)
    -> Option<CompactionReason>;

    /// Produce the replacement transcript. Called only after
    /// [`should_compact`](Self::should_compact) returns `Some`.
    /// Implementations should respect `cancellation`.
    async fn compact(
        &self,
        transcript: &[Item],
        reason: CompactionReason,
        cancellation: Option<TurnCancellation>,
    ) -> Result<Vec<Item>, CompactionError>;
}

/// Runtime context passed to each [`CompactionStrategy`] during execution.
///
/// Provides access to an optional [`CompactionBackend`] (needed by
/// [`SummarizeOlderStrategy`]), shared metadata, and a cancellation token
/// that strategies should respect.
pub struct CompactionContext<'a> {
    /// An optional backend for strategies that need to call an external
    /// summarisation service.
    pub backend: Option<&'a dyn CompactionBackend>,
    /// Cancellation token; strategies should check this and return
    /// [`CompactionError::Cancelled`] when signalled.
    pub cancellation: Option<TurnCancellation>,
}

impl<'a> CompactionContext<'a> {
    /// Build an empty context with no backend and no cancellation token.
    pub fn new() -> Self {
        Self {
            backend: None,
            cancellation: None,
        }
    }

    /// Attach a backend reference.
    pub fn with_backend(mut self, backend: &'a dyn CompactionBackend) -> Self {
        self.backend = Some(backend);
        self
    }

    /// Attach a cancellation token.
    pub fn with_cancellation(mut self, cancellation: TurnCancellation) -> Self {
        self.cancellation = Some(cancellation);
        self
    }
}

impl Default for CompactionContext<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// A single compaction step that transforms a transcript.
///
/// Strategies are the core abstraction in this crate. Each strategy receives
/// the transcript inside a [`CompactionRequest`] and returns a
/// [`CompactionResult`] with the (possibly shorter) transcript.
///
/// Built-in strategies:
///
/// | Strategy | What it does |
/// |---|---|
/// | [`DropReasoningStrategy`] | Strips reasoning parts from items |
/// | [`DropFailedToolResultsStrategy`] | Removes errored tool results |
/// | [`KeepRecentStrategy`] | Keeps only the N most recent removable items |
/// | [`SummarizeOlderStrategy`] | Replaces older items with a backend-generated summary |
///
/// Use [`CompactionPipeline`] to chain multiple strategies together.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::DropReasoningStrategy;
///
/// // Strategies are composable via CompactionPipeline
/// let strategy = DropReasoningStrategy::new();
/// ```
#[async_trait]
pub trait CompactionStrategy: Send + Sync {
    /// Apply this strategy to the transcript in `request`.
    ///
    /// # Arguments
    ///
    /// * `request` - The transcript and session context to compact.
    /// * `ctx` - Runtime context providing the backend, metadata, and
    ///   cancellation token.
    ///
    /// # Errors
    ///
    /// Returns [`CompactionError`] on failure or cancellation.
    async fn apply(
        &self,
        request: CompactionRequest,
        ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError>;
}

/// An ordered sequence of [`CompactionStrategy`] steps executed one after
/// another.
///
/// Each strategy receives the transcript produced by the previous one,
/// creating a pipeline effect. The pipeline itself implements
/// [`CompactionStrategy`], so it can be nested or used anywhere a single
/// strategy is expected.
///
/// The pipeline checks the [`CompactionContext::cancellation`] token between
/// steps and returns [`CompactionError::Cancelled`] early if cancellation is
/// signalled.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::{
///     CompactionPipeline, DropFailedToolResultsStrategy,
///     DropReasoningStrategy, KeepRecentStrategy,
/// };
/// use agentkit_core::ItemKind;
///
/// let pipeline = CompactionPipeline::new()
///     .with_strategy(DropReasoningStrategy::new())
///     .with_strategy(DropFailedToolResultsStrategy::new())
///     .with_strategy(
///         KeepRecentStrategy::new(24)
///             .preserve_kind(ItemKind::System)
///             .preserve_kind(ItemKind::Context),
///     );
/// ```
#[derive(Clone, Default)]
pub struct CompactionPipeline {
    strategies: Vec<Arc<dyn CompactionStrategy>>,
}

impl CompactionPipeline {
    /// Create an empty pipeline with no strategies.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a strategy to the end of the pipeline.
    ///
    /// Strategies run in the order they are added.
    pub fn with_strategy(mut self, strategy: impl CompactionStrategy + 'static) -> Self {
        self.strategies.push(Arc::new(strategy));
        self
    }
}

#[async_trait]
impl CompactionStrategy for CompactionPipeline {
    async fn apply(
        &self,
        mut request: CompactionRequest,
        ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError> {
        let mut replaced_items = 0;
        let mut metadata = MetadataMap::new();

        for strategy in &self.strategies {
            if ctx
                .cancellation
                .as_ref()
                .is_some_and(TurnCancellation::is_cancelled)
            {
                return Err(CompactionError::Cancelled);
            }
            let result = strategy.apply(request.clone(), ctx).await?;
            request.transcript = result.transcript;
            replaced_items += result.replaced_items;
            metadata.extend(result.metadata);
        }

        Ok(CompactionResult {
            transcript: request.transcript,
            replaced_items,
            metadata,
        })
    }
}

/// Strategy that removes [`Part::Reasoning`] parts from every item.
///
/// Reasoning parts contain chain-of-thought content that is useful during
/// generation but rarely needed once the answer has been produced. Stripping
/// them reduces transcript size without losing user-visible content.
///
/// When `drop_empty_items` is `true` (the default), items that become empty
/// after reasoning removal are dropped entirely.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::DropReasoningStrategy;
///
/// let strategy = DropReasoningStrategy::new();
///
/// // Keep items that become empty after stripping reasoning:
/// let keep_empties = DropReasoningStrategy::new().drop_empty_items(false);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DropReasoningStrategy {
    drop_empty_items: bool,
}

impl DropReasoningStrategy {
    /// Create a new strategy that drops reasoning parts and removes items
    /// that become empty as a result.
    pub fn new() -> Self {
        Self {
            drop_empty_items: true,
        }
    }

    /// Control whether items that become empty after reasoning removal are
    /// dropped from the transcript.
    ///
    /// Defaults to `true`.
    pub fn drop_empty_items(mut self, value: bool) -> Self {
        self.drop_empty_items = value;
        self
    }
}

#[async_trait]
impl CompactionStrategy for DropReasoningStrategy {
    async fn apply(
        &self,
        request: CompactionRequest,
        _ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError> {
        let mut transcript = Vec::with_capacity(request.transcript.len());
        let mut replaced_items = 0;

        for mut item in request.transcript {
            let original_len = item.parts.len();
            item.parts
                .retain(|part| !matches!(part, Part::Reasoning(_)));
            let changed = item.parts.len() != original_len;
            if item.parts.is_empty() && self.drop_empty_items {
                if changed {
                    replaced_items += 1;
                }
                continue;
            }
            if changed {
                replaced_items += 1;
            }
            transcript.push(item);
        }

        Ok(CompactionResult {
            transcript,
            replaced_items,
            metadata: MetadataMap::new(),
        })
    }
}

/// Strategy that removes [`Part::ToolResult`] parts where `is_error` is
/// `true`.
///
/// Failed tool invocations clutter the transcript and can confuse the model
/// on subsequent turns. This strategy strips those results while leaving
/// successful tool output intact.
///
/// When `drop_empty_items` is `true` (the default), items that become empty
/// after removal are dropped entirely.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::DropFailedToolResultsStrategy;
///
/// let strategy = DropFailedToolResultsStrategy::new();
///
/// // Keep items that become empty after stripping failed results:
/// let keep_empties = DropFailedToolResultsStrategy::new().drop_empty_items(false);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DropFailedToolResultsStrategy {
    drop_empty_items: bool,
}

impl DropFailedToolResultsStrategy {
    /// Create a new strategy that drops failed tool results and removes
    /// items that become empty as a result.
    pub fn new() -> Self {
        Self {
            drop_empty_items: true,
        }
    }

    /// Control whether items that become empty after failed-result removal
    /// are dropped from the transcript.
    ///
    /// Defaults to `true`.
    pub fn drop_empty_items(mut self, value: bool) -> Self {
        self.drop_empty_items = value;
        self
    }
}

#[async_trait]
impl CompactionStrategy for DropFailedToolResultsStrategy {
    async fn apply(
        &self,
        request: CompactionRequest,
        _ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError> {
        let failed_call_ids = request
            .transcript
            .iter()
            .flat_map(|item| item.parts.iter())
            .filter_map(|part| match part {
                Part::ToolResult(result) if result.is_error => Some(result.call_id.clone()),
                _ => None,
            })
            .collect::<BTreeSet<_>>();
        let mut transcript = Vec::with_capacity(request.transcript.len());
        let mut replaced_items = 0;

        for mut item in request.transcript {
            let original_len = item.parts.len();
            item.parts.retain(|part| {
                !matches!(part, Part::ToolResult(result) if result.is_error)
                    && !matches!(part, Part::ToolCall(call) if failed_call_ids.contains(&call.id))
            });
            let changed = item.parts.len() != original_len;
            if item.parts.is_empty() && self.drop_empty_items {
                if changed {
                    replaced_items += 1;
                }
                continue;
            }
            if changed {
                replaced_items += 1;
            }
            transcript.push(item);
        }

        Ok(CompactionResult {
            transcript,
            replaced_items,
            metadata: MetadataMap::new(),
        })
    }
}

/// Strategy that keeps only the `N` most recent removable items and drops
/// the rest.
///
/// Items whose [`ItemKind`] is in the `preserve_kinds` set are always
/// retained regardless of their position. This lets you protect system
/// prompts and context items while trimming older conversation turns.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::KeepRecentStrategy;
/// use agentkit_core::ItemKind;
///
/// let strategy = KeepRecentStrategy::new(16)
///     .preserve_kind(ItemKind::System)
///     .preserve_kind(ItemKind::Context);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeepRecentStrategy {
    keep_last: usize,
    preserve_kinds: BTreeSet<ItemKind>,
}

impl KeepRecentStrategy {
    /// Create a strategy that keeps the last `keep_last` removable items.
    pub fn new(keep_last: usize) -> Self {
        Self {
            keep_last,
            preserve_kinds: BTreeSet::new(),
        }
    }

    /// Mark an [`ItemKind`] as preserved so that items of this kind are never
    /// dropped, regardless of their position in the transcript.
    pub fn preserve_kind(mut self, kind: ItemKind) -> Self {
        self.preserve_kinds.insert(kind);
        self
    }
}

#[async_trait]
impl CompactionStrategy for KeepRecentStrategy {
    async fn apply(
        &self,
        request: CompactionRequest,
        _ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError> {
        let removable = removable_indices(&request.transcript, &self.preserve_kinds);
        if removable.len() <= self.keep_last {
            return Ok(CompactionResult {
                transcript: request.transcript,
                replaced_items: 0,
                metadata: MetadataMap::new(),
            });
        }

        let keep_indices = removable
            .iter()
            .skip(removable.len() - self.keep_last)
            .copied()
            .collect::<BTreeSet<_>>();
        let keep_indices =
            expand_indices_to_tool_pairs(&request.transcript, keep_indices, &self.preserve_kinds);
        let replaced_items = removable
            .iter()
            .filter(|index| !keep_indices.contains(index))
            .count();
        let transcript = request
            .transcript
            .into_iter()
            .enumerate()
            .filter_map(|(index, item)| {
                (self.preserve_kinds.contains(&item.kind) || keep_indices.contains(&index))
                    .then_some(item)
            })
            .collect::<Vec<_>>();

        Ok(CompactionResult {
            transcript,
            replaced_items,
            metadata: MetadataMap::new(),
        })
    }
}

/// Strategy that replaces older transcript items with a backend-generated
/// summary.
///
/// The most recent `keep_last` removable items are kept verbatim. Everything
/// older (excluding items with a preserved [`ItemKind`]) is sent to the
/// configured [`CompactionBackend`] for summarisation. The summary items
/// replace the originals at their position in the transcript.
///
/// This strategy requires a backend. If [`CompactionContext::backend`] is
/// `None`, [`CompactionError::MissingBackend`] is returned.
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::SummarizeOlderStrategy;
/// use agentkit_core::ItemKind;
///
/// let strategy = SummarizeOlderStrategy::new(8)
///     .preserve_kind(ItemKind::System);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SummarizeOlderStrategy {
    keep_last: usize,
    preserve_kinds: BTreeSet<ItemKind>,
}

impl SummarizeOlderStrategy {
    /// Create a strategy that keeps the last `keep_last` removable items and
    /// summarises everything older.
    pub fn new(keep_last: usize) -> Self {
        Self {
            keep_last,
            preserve_kinds: BTreeSet::new(),
        }
    }

    /// Mark an [`ItemKind`] as preserved so that items of this kind are never
    /// summarised, regardless of their position in the transcript.
    pub fn preserve_kind(mut self, kind: ItemKind) -> Self {
        self.preserve_kinds.insert(kind);
        self
    }
}

#[async_trait]
impl CompactionStrategy for SummarizeOlderStrategy {
    async fn apply(
        &self,
        request: CompactionRequest,
        ctx: &mut CompactionContext<'_>,
    ) -> Result<CompactionResult, CompactionError> {
        let Some(backend) = ctx.backend else {
            return Err(CompactionError::MissingBackend(
                "summarize strategy requires a compaction backend".into(),
            ));
        };

        let removable = removable_indices(&request.transcript, &self.preserve_kinds);
        if removable.len() <= self.keep_last {
            return Ok(CompactionResult {
                transcript: request.transcript,
                replaced_items: 0,
                metadata: MetadataMap::new(),
            });
        }

        let keep_indices = removable
            .iter()
            .skip(removable.len() - self.keep_last)
            .copied()
            .collect::<BTreeSet<_>>();
        let keep_indices =
            expand_indices_to_tool_pairs(&request.transcript, keep_indices, &self.preserve_kinds);
        let summary_indices = removable
            .iter()
            .copied()
            .filter(|index| !keep_indices.contains(index))
            .collect::<Vec<_>>();
        if summary_indices.is_empty() {
            return Ok(CompactionResult {
                transcript: request.transcript,
                replaced_items: 0,
                metadata: MetadataMap::new(),
            });
        }
        let first_summary_index = summary_indices[0];
        let summary_index_set = summary_indices.iter().copied().collect::<BTreeSet<_>>();
        let summary_items = summary_indices
            .iter()
            .map(|index| request.transcript[*index].clone())
            .collect::<Vec<_>>();
        let summary = backend
            .summarize(
                SummaryRequest {
                    items: summary_items,
                    reason: request.reason.clone(),
                    metadata: request.metadata.clone(),
                },
                ctx.cancellation.clone(),
            )
            .await?;

        let mut transcript = Vec::new();
        let mut inserted_summary = false;
        let mut summary_output = Some(summary.items);
        for (index, item) in request.transcript.into_iter().enumerate() {
            if summary_index_set.contains(&index) {
                if !inserted_summary && index == first_summary_index {
                    transcript.extend(summary_output.take().unwrap_or_default());
                    inserted_summary = true;
                }
                continue;
            }
            transcript.push(item);
        }

        Ok(CompactionResult {
            transcript,
            replaced_items: summary_indices.len(),
            metadata: summary.metadata,
        })
    }
}

fn removable_indices(transcript: &[Item], preserve_kinds: &BTreeSet<ItemKind>) -> Vec<usize> {
    transcript
        .iter()
        .enumerate()
        .filter_map(|(index, item)| (!preserve_kinds.contains(&item.kind)).then_some(index))
        .collect()
}

fn expand_indices_to_tool_pairs(
    transcript: &[Item],
    mut keep_indices: BTreeSet<usize>,
    preserve_kinds: &BTreeSet<ItemKind>,
) -> BTreeSet<usize> {
    keep_indices.extend(
        transcript
            .iter()
            .enumerate()
            .filter_map(|(index, item)| preserve_kinds.contains(&item.kind).then_some(index)),
    );

    let mut calls = HashMap::new();
    let mut results: HashMap<_, Vec<usize>> = HashMap::new();
    for (index, item) in transcript.iter().enumerate() {
        for part in &item.parts {
            match part {
                Part::ToolCall(call) => {
                    calls.entry(call.id.clone()).or_insert(index);
                }
                Part::ToolResult(result) => {
                    results
                        .entry(result.call_id.clone())
                        .or_default()
                        .push(index);
                }
                _ => {}
            }
        }
    }

    loop {
        let before_len = keep_indices.len();
        for (call_id, call_index) in &calls {
            if keep_indices.contains(call_index)
                && let Some(result_indices) = results.get(call_id)
            {
                keep_indices.extend(result_indices.iter().copied());
            }
        }
        for (call_id, result_indices) in &results {
            if result_indices
                .iter()
                .any(|result_index| keep_indices.contains(result_index))
                && let Some(call_index) = calls.get(call_id)
            {
                keep_indices.insert(*call_index);
            }
        }
        if keep_indices.len() == before_len {
            break;
        }
    }

    keep_indices
}

/// Errors that can occur during compaction.
#[derive(Debug, Error)]
pub enum CompactionError {
    /// The operation was cancelled via the [`TurnCancellation`] token.
    #[error("compaction cancelled")]
    Cancelled,
    /// A strategy that requires a [`CompactionBackend`] was invoked without
    /// one.
    #[error("missing compaction backend: {0}")]
    MissingBackend(String),
    /// A catch-all for other failures (e.g. backend errors).
    #[error("compaction failed: {0}")]
    Failed(String),
}

/// Adapts any [`Compactor`] to a [`LoopMutator`] so it can be registered
/// directly via [`AgentBuilder::mutator`]. Most callers reach this through
/// [`AgentBuilderCompactorExt::compactor`] rather than constructing it
/// directly.
///
/// `CompactorMutator` owns the telemetry contract: it emits
/// [`AgentEvent::MutationStarted`] before calling [`Compactor::compact`] and
/// [`AgentEvent::MutationFinished`] after, populating `metadata` with the
/// compaction reason and replaced item count.
pub struct CompactorMutator<C> {
    compactor: C,
    name: String,
}

impl<C: Compactor> CompactorMutator<C> {
    /// Wrap `compactor` with the default mutator label `"compactor"`.
    pub fn new(compactor: C) -> Self {
        Self {
            compactor,
            name: "compactor".into(),
        }
    }

    /// Override the mutator label that appears in
    /// [`AgentEvent::MutationStarted`]/[`AgentEvent::MutationFinished`].
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }
}

#[async_trait]
impl<C: Compactor + 'static> LoopMutator for CompactorMutator<C> {
    async fn mutate(
        &self,
        cursor: &mut TranscriptCursor<'_>,
        ctx: LoopCtx<'_>,
    ) -> Result<(), LoopError> {
        let Some(reason) = self.compactor.should_compact(cursor.as_slice(), ctx.point) else {
            return Ok(());
        };

        ctx.emitter.emit(AgentEvent::MutationStarted {
            session_id: ctx.session_id.clone(),
            turn_id: ctx.turn_id.cloned(),
            mutator: self.name.clone(),
            point: ctx.point,
        });

        let before_len = cursor.len();
        let result = self
            .compactor
            .compact(cursor.as_slice(), reason.clone(), ctx.cancellation.clone())
            .await;

        let mut metadata = MetadataMap::new();
        metadata.insert("reason".into(), format!("{reason:?}").into());

        match result {
            Ok(new_items) => {
                let replaced = before_len.saturating_sub(new_items.len());
                metadata.insert("replaced_items".into(), (replaced as u64).into());
                **cursor = new_items;
                ctx.emitter.emit(AgentEvent::MutationFinished {
                    session_id: ctx.session_id.clone(),
                    turn_id: ctx.turn_id.cloned(),
                    mutator: self.name.clone(),
                    dirty: true,
                    metadata,
                });
                Ok(())
            }
            Err(err) => {
                metadata.insert("error".into(), err.to_string().into());
                ctx.emitter.emit(AgentEvent::MutationFinished {
                    session_id: ctx.session_id.clone(),
                    turn_id: ctx.turn_id.cloned(),
                    mutator: self.name.clone(),
                    dirty: false,
                    metadata,
                });
                match err {
                    CompactionError::Cancelled => Err(LoopError::Cancelled),
                    other => Err(LoopError::Mutator(other.to_string())),
                }
            }
        }
    }
}

/// Extension trait that adds [`compactor`](Self::compactor) to
/// [`AgentBuilder`], wrapping any [`Compactor`] in a [`CompactorMutator`]
/// and registering it via [`AgentBuilder::mutator`].
pub trait AgentBuilderCompactorExt<M: ModelAdapter>: Sized {
    /// Register `compactor` as a [`LoopMutator`].
    fn compactor<C: Compactor + 'static>(self, compactor: C) -> Self;
}

impl<M: ModelAdapter> AgentBuilderCompactorExt<M> for AgentBuilder<M> {
    fn compactor<C: Compactor + 'static>(self, compactor: C) -> Self {
        self.mutator(CompactorMutator::new(compactor))
    }
}

/// Boxed predicate driving [`StrategyCompactor`]: it inspects the transcript
/// and current [`MutationPoint`] and returns the reason to fire compaction,
/// or `None` to skip.
pub type TriggerFn = Box<dyn Fn(&[Item], MutationPoint) -> Option<CompactionReason> + Send + Sync>;

/// A reusable [`Compactor`] that bundles a trigger closure with a
/// [`CompactionStrategy`] (often a [`CompactionPipeline`]) and an optional
/// [`CompactionBackend`]. Use this when your trigger logic is a simple
/// predicate over the transcript; implement [`Compactor`] directly when you
/// need richer state (token meters, atomics, etc.).
///
/// # Example
///
/// ```rust
/// use agentkit_compaction::{
///     CompactionPipeline, CompactionReason, DropReasoningStrategy,
///     KeepRecentStrategy, StrategyCompactor,
/// };
/// use agentkit_core::ItemKind;
///
/// let compactor = StrategyCompactor::new(
///     |transcript: &[_], _point| {
///         (transcript.len() > 32).then_some(CompactionReason::TranscriptTooLong)
///     },
///     CompactionPipeline::new()
///         .with_strategy(DropReasoningStrategy::new())
///         .with_strategy(
///             KeepRecentStrategy::new(24)
///                 .preserve_kind(ItemKind::System)
///                 .preserve_kind(ItemKind::Context),
///         ),
/// );
/// ```
pub struct StrategyCompactor {
    trigger: TriggerFn,
    strategy: Arc<dyn CompactionStrategy>,
    backend: Option<Arc<dyn CompactionBackend>>,
    metadata: MetadataMap,
}

impl StrategyCompactor {
    /// Create a new compactor from a trigger closure and a strategy.
    ///
    /// The trigger receives the current transcript and [`MutationPoint`] and
    /// returns `Some(reason)` to fire compaction.
    pub fn new<T, S>(trigger: T, strategy: S) -> Self
    where
        T: Fn(&[Item], MutationPoint) -> Option<CompactionReason> + Send + Sync + 'static,
        S: CompactionStrategy + 'static,
    {
        Self {
            trigger: Box::new(trigger),
            strategy: Arc::new(strategy),
            backend: None,
            metadata: MetadataMap::new(),
        }
    }

    /// Start a builder for [`StrategyCompactor`].
    pub fn builder() -> StrategyCompactorBuilder {
        StrategyCompactorBuilder::default()
    }

    /// Attach a [`CompactionBackend`] for strategies that require
    /// summarisation (e.g. [`SummarizeOlderStrategy`]).
    pub fn with_backend(mut self, backend: impl CompactionBackend + 'static) -> Self {
        self.backend = Some(Arc::new(backend));
        self
    }

    /// Reuse an existing `Arc<dyn CompactionBackend>` (e.g. one already shared
    /// elsewhere) without re-wrapping.
    pub fn with_shared_backend(mut self, backend: Arc<dyn CompactionBackend>) -> Self {
        self.backend = Some(backend);
        self
    }

    /// Set metadata forwarded to every strategy invocation.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

#[async_trait]
impl Compactor for StrategyCompactor {
    fn should_compact(
        &self,
        transcript: &[Item],
        point: MutationPoint,
    ) -> Option<CompactionReason> {
        (self.trigger)(transcript, point)
    }

    async fn compact(
        &self,
        transcript: &[Item],
        reason: CompactionReason,
        cancellation: Option<TurnCancellation>,
    ) -> Result<Vec<Item>, CompactionError> {
        let request = CompactionRequest {
            transcript: transcript.to_vec(),
            reason,
            metadata: self.metadata.clone(),
        };
        let mut ctx = CompactionContext {
            backend: self.backend.as_deref(),
            cancellation,
        };
        let result = self.strategy.apply(request, &mut ctx).await?;
        Ok(result.transcript)
    }
}

/// Builder error for [`StrategyCompactor`].
#[derive(Debug, Error)]
pub enum StrategyCompactorBuildError {
    /// `trigger` was not provided.
    #[error("trigger is required")]
    MissingTrigger,
    /// `strategy` was not provided.
    #[error("strategy is required")]
    MissingStrategy,
}

/// Builder for [`StrategyCompactor`].
#[derive(Default)]
pub struct StrategyCompactorBuilder {
    trigger: Option<TriggerFn>,
    strategy: Option<Arc<dyn CompactionStrategy>>,
    backend: Option<Arc<dyn CompactionBackend>>,
    metadata: MetadataMap,
}

impl StrategyCompactorBuilder {
    /// Set the trigger closure.
    pub fn trigger<T>(mut self, trigger: T) -> Self
    where
        T: Fn(&[Item], MutationPoint) -> Option<CompactionReason> + Send + Sync + 'static,
    {
        self.trigger = Some(Box::new(trigger));
        self
    }

    /// Fire when the transcript exceeds `max_items`.
    pub fn item_count_trigger(self, max_items: usize) -> Self {
        self.trigger(move |transcript: &[Item], _point| {
            (transcript.len() > max_items).then_some(CompactionReason::TranscriptTooLong)
        })
    }

    /// Set the strategy.
    pub fn strategy(mut self, strategy: impl CompactionStrategy + 'static) -> Self {
        self.strategy = Some(Arc::new(strategy));
        self
    }

    /// Attach a backend for strategies that need summarisation.
    pub fn backend(mut self, backend: impl CompactionBackend + 'static) -> Self {
        self.backend = Some(Arc::new(backend));
        self
    }

    /// Reuse an existing `Arc<dyn CompactionBackend>`.
    pub fn shared_backend(mut self, backend: Arc<dyn CompactionBackend>) -> Self {
        self.backend = Some(backend);
        self
    }

    /// Set metadata forwarded to every strategy invocation.
    pub fn metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }

    /// Build the configured [`StrategyCompactor`].
    pub fn build(self) -> Result<StrategyCompactor, StrategyCompactorBuildError> {
        Ok(StrategyCompactor {
            trigger: self
                .trigger
                .ok_or(StrategyCompactorBuildError::MissingTrigger)?,
            strategy: self
                .strategy
                .ok_or(StrategyCompactorBuildError::MissingStrategy)?,
            backend: self.backend,
            metadata: self.metadata,
        })
    }
}

const DEFAULT_COMPACTION_PROMPT: &str = "You are a compaction agent. Compress the \
transcript that follows into a durable context note for an assistant that has lost the \
original messages. Preserve every named person, every year and date, every place, every \
decision the assistant committed to, every tool the assistant invoked, and every \
actionable fact in the tool results. Drop chatter, narration, and chain-of-thought. \
Return only the compacted note as plain text.";

/// Build a trigger closure that fires when the most recent transcript item's
/// reported `usage.tokens.input_tokens` reaches `window * percent / 100`.
///
/// Only fires at [`MutationPoint::AfterTurnEnded`]; other points return
/// `None`. `percent` is clamped to `1..=100`.
///
/// Plug into [`StrategyCompactorBuilder::trigger`] (or use it directly as a
/// [`TriggerFn`]).
pub fn context_window_trigger(window: u64, percent: u32) -> TriggerFn {
    let percent = percent.clamp(1, 100);
    let threshold = window.saturating_mul(percent as u64) / 100;
    Box::new(move |transcript: &[Item], point: MutationPoint| {
        if point != MutationPoint::AfterTurnEnded {
            return None;
        }
        let last_input = transcript
            .iter()
            .rev()
            .find_map(|i| i.usage.as_ref()?.tokens.as_ref().map(|t| t.input_tokens))?;
        (last_input >= threshold).then(|| {
            CompactionReason::Custom(format!(
                "input_tokens={last_input} >= threshold={threshold} (window={window}, {percent}%)",
            ))
        })
    })
}

/// Build a trigger closure that fires when the transcript grows beyond
/// `max_items` items. Convenience matching
/// [`StrategyCompactorBuilder::item_count_trigger`].
pub fn item_count_trigger(max_items: usize) -> TriggerFn {
    Box::new(move |transcript: &[Item], _point: MutationPoint| {
        (transcript.len() > max_items).then_some(CompactionReason::TranscriptTooLong)
    })
}

/// Builder error for [`AgentCompactor`].
#[derive(Debug, Error)]
pub enum AgentCompactorBuildError {
    /// `agent` was not provided.
    #[error("agent is required")]
    MissingAgent,
    /// `session_id` was not provided.
    #[error("session_id is required")]
    MissingSessionId,
}

/// [`CompactionBackend`] that summarises items by running a nested loop over
/// a sub-agent.
///
/// Plug into any [`CompactionStrategy`] that needs a backend (e.g.
/// [`SummarizeOlderStrategy`]) via [`StrategyCompactorBuilder::backend`].
/// Pair with whatever trigger fits — see [`context_window_trigger`] for a
/// token-aware default.
pub struct AgentCompactor<M: ModelAdapter + Clone + 'static> {
    inner: Arc<Agent<M>>,
    session_id: SessionId,
    system_prompt: String,
}

impl<M: ModelAdapter + Clone + 'static> AgentCompactor<M> {
    /// Start a new builder. `agent` and `session_id` are required.
    pub fn builder() -> AgentCompactorBuilder<M> {
        AgentCompactorBuilder::new()
    }
}

/// Builder for [`AgentCompactor`].
pub struct AgentCompactorBuilder<M: ModelAdapter + Clone + 'static> {
    agent: Option<Arc<Agent<M>>>,
    session_id: Option<SessionId>,
    system_prompt: Option<String>,
}

impl<M: ModelAdapter + Clone + 'static> AgentCompactorBuilder<M> {
    fn new() -> Self {
        Self {
            agent: None,
            session_id: None,
            system_prompt: None,
        }
    }

    /// The sub-agent that runs nested summary turns.
    pub fn agent(mut self, agent: Arc<Agent<M>>) -> Self {
        self.agent = Some(agent);
        self
    }

    /// Session id passed to [`Agent::start`] for every nested compaction.
    pub fn session_id(mut self, id: SessionId) -> Self {
        self.session_id = Some(id);
        self
    }

    /// Override the system prompt used by the nested compaction agent.
    pub fn system_prompt(mut self, s: impl Into<String>) -> Self {
        self.system_prompt = Some(s.into());
        self
    }

    /// Build the configured [`AgentCompactor`].
    pub fn build(self) -> Result<AgentCompactor<M>, AgentCompactorBuildError> {
        Ok(AgentCompactor {
            inner: self.agent.ok_or(AgentCompactorBuildError::MissingAgent)?,
            session_id: self
                .session_id
                .ok_or(AgentCompactorBuildError::MissingSessionId)?,
            system_prompt: self
                .system_prompt
                .unwrap_or_else(|| DEFAULT_COMPACTION_PROMPT.into()),
        })
    }
}

#[async_trait]
impl<M: ModelAdapter + Clone + 'static> CompactionBackend for AgentCompactor<M> {
    async fn summarize(
        &self,
        request: SummaryRequest,
        cancellation: Option<TurnCancellation>,
    ) -> Result<SummaryResult, CompactionError> {
        if cancellation
            .as_ref()
            .is_some_and(TurnCancellation::is_cancelled)
        {
            return Err(CompactionError::Cancelled);
        }

        let rendered = render_items_for_summary(&request.items);

        let driver_input = vec![
            Item::text(ItemKind::System, self.system_prompt.clone()),
            Item::text(
                ItemKind::User,
                format!(
                    "Compress the transcript below into a durable context note. \
                     Preserve names, places, dates, decisions, and tool outcomes.\n\n{rendered}"
                ),
            ),
        ];

        let mut driver = self
            .inner
            .start(SessionConfig::new(self.session_id.clone()))
            .await
            .map_err(|e| CompactionError::Failed(e.to_string()))?;
        driver
            .submit_input(driver_input)
            .map_err(|e| CompactionError::Failed(e.to_string()))?;

        let summary = run_compactor_to_completion(&mut driver)
            .await
            .map_err(CompactionError::Failed)?;

        Ok(SummaryResult {
            items: vec![Item::text(ItemKind::Context, summary)],
            metadata: MetadataMap::new(),
        })
    }
}

async fn run_compactor_to_completion<S>(
    driver: &mut agentkit_loop::LoopDriver<S>,
) -> Result<String, String>
where
    S: agentkit_loop::ModelSession,
{
    use agentkit_loop::LoopInterrupt;
    loop {
        let step = driver.next().await.map_err(|e| e.to_string())?;
        match step {
            LoopStep::Finished(result) => {
                let mut sections = Vec::new();
                for item in result.items {
                    if item.kind != ItemKind::Assistant {
                        continue;
                    }
                    for part in item.parts {
                        if let Part::Text(t) = part {
                            sections.push(t.text);
                        }
                    }
                }
                return Ok(sections.join("\n"));
            }
            LoopStep::Interrupt(LoopInterrupt::AfterToolResult(_)) => continue,
            LoopStep::Interrupt(LoopInterrupt::AwaitingInput(_)) => {
                return Err("compactor sub-agent unexpectedly awaiting input".into());
            }
            LoopStep::Interrupt(LoopInterrupt::ApprovalRequest(_)) => {
                return Err("compactor sub-agent unexpectedly required approval".into());
            }
        }
    }
}

fn render_items_for_summary(items: &[Item]) -> String {
    items
        .iter()
        .map(|item| {
            let kind = match item.kind {
                ItemKind::User => "USER",
                ItemKind::Assistant => "ASSISTANT",
                ItemKind::System => "SYSTEM",
                ItemKind::Developer => "DEVELOPER",
                ItemKind::Tool => "TOOL",
                ItemKind::Context => "CONTEXT",
                ItemKind::Notification => "NOTIFICATION",
            };
            let body = item
                .parts
                .iter()
                .filter_map(|p| match p {
                    Part::Text(t) => Some(t.text.clone()),
                    Part::Structured(v) => Some(v.value.to_string()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("\n");
            format!("[{kind}]\n{body}")
        })
        .collect::<Vec<_>>()
        .join("\n\n")
}

#[cfg(test)]
mod tests {
    use agentkit_core::{
        CancellationController, Part, TextPart, ToolCallPart, ToolOutput, ToolResultPart,
    };

    use super::*;

    fn user_item(text: &str) -> Item {
        Item {
            id: None,
            kind: ItemKind::User,
            parts: vec![Part::Text(TextPart {
                text: text.into(),
                metadata: MetadataMap::new(),
            })],
            metadata: MetadataMap::new(),
            usage: None,
            finish_reason: None,
            created_at: None,
        }
    }

    fn assistant_with_reasoning() -> Item {
        Item {
            id: None,
            kind: ItemKind::Assistant,
            parts: vec![
                Part::Reasoning(agentkit_core::ReasoningPart {
                    summary: Some("think".into()),
                    data: None,
                    redacted: false,
                    metadata: MetadataMap::new(),
                }),
                Part::Text(TextPart {
                    text: "answer".into(),
                    metadata: MetadataMap::new(),
                }),
            ],
            metadata: MetadataMap::new(),
            usage: None,
            finish_reason: None,
            created_at: None,
        }
    }

    fn failed_tool_item() -> Item {
        Item {
            id: None,
            kind: ItemKind::Tool,
            parts: vec![Part::ToolResult(ToolResultPart {
                call_id: "call-1".into(),
                output: ToolOutput::Text("failed".into()),
                is_error: true,
                metadata: MetadataMap::new(),
            })],
            metadata: MetadataMap::new(),
            usage: None,
            finish_reason: None,
            created_at: None,
        }
    }

    fn tool_call_item(id: &str) -> Item {
        Item {
            id: None,
            kind: ItemKind::Assistant,
            parts: vec![Part::ToolCall(ToolCallPart {
                id: id.into(),
                name: "lookup".into(),
                input: serde_json::json!({}),
                metadata: MetadataMap::new(),
            })],
            metadata: MetadataMap::new(),
            usage: None,
            finish_reason: None,
            created_at: None,
        }
    }

    fn tool_result_item(id: &str, is_error: bool) -> Item {
        Item {
            id: None,
            kind: ItemKind::Tool,
            parts: vec![Part::ToolResult(ToolResultPart {
                call_id: id.into(),
                output: ToolOutput::Text("result".into()),
                is_error,
                metadata: MetadataMap::new(),
            })],
            metadata: MetadataMap::new(),
            usage: None,
            finish_reason: None,
            created_at: None,
        }
    }

    #[tokio::test]
    async fn pipeline_applies_local_strategies_in_order() {
        let request = CompactionRequest {
            transcript: vec![
                user_item("a"),
                assistant_with_reasoning(),
                failed_tool_item(),
                user_item("b"),
                user_item("c"),
            ],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let pipeline = CompactionPipeline::new()
            .with_strategy(DropReasoningStrategy::new())
            .with_strategy(DropFailedToolResultsStrategy::new())
            .with_strategy(
                KeepRecentStrategy::new(2)
                    .preserve_kind(ItemKind::System)
                    .preserve_kind(ItemKind::Context),
            );
        let mut ctx = CompactionContext {
            backend: None,
            cancellation: None,
        };

        let result = pipeline.apply(request, &mut ctx).await.unwrap();
        assert_eq!(result.transcript.len(), 2);
        assert!(result.replaced_items >= 2);
        assert!(result.transcript.iter().all(|item| {
            item.parts
                .iter()
                .all(|part| !matches!(part, Part::Reasoning(_)))
        }));
    }

    #[tokio::test]
    async fn keep_recent_preserves_tool_call_result_pairs() {
        let request = CompactionRequest {
            transcript: vec![
                user_item("old"),
                tool_call_item("call-1"),
                tool_result_item("call-1", false),
                user_item("recent"),
            ],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let strategy = KeepRecentStrategy::new(2);
        let mut ctx = CompactionContext {
            backend: None,
            cancellation: None,
        };

        let result = strategy.apply(request, &mut ctx).await.unwrap();
        assert_eq!(result.replaced_items, 1);
        assert_eq!(result.transcript.len(), 3);
        assert!(matches!(result.transcript[0].parts[0], Part::ToolCall(_)));
        assert!(matches!(result.transcript[1].parts[0], Part::ToolResult(_)));
    }

    #[tokio::test]
    async fn failed_tool_result_removal_drops_matching_tool_call() {
        let request = CompactionRequest {
            transcript: vec![
                tool_call_item("call-1"),
                tool_result_item("call-1", true),
                user_item("recent"),
            ],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let strategy = DropFailedToolResultsStrategy::new();
        let mut ctx = CompactionContext {
            backend: None,
            cancellation: None,
        };

        let result = strategy.apply(request, &mut ctx).await.unwrap();
        assert_eq!(result.replaced_items, 2);
        assert_eq!(result.transcript.len(), 1);
        assert!(matches!(result.transcript[0].kind, ItemKind::User));
    }

    struct FakeBackend;

    #[async_trait]
    impl CompactionBackend for FakeBackend {
        async fn summarize(
            &self,
            request: SummaryRequest,
            _cancellation: Option<TurnCancellation>,
        ) -> Result<SummaryResult, CompactionError> {
            Ok(SummaryResult {
                items: vec![Item {
                    id: None,
                    kind: ItemKind::Context,
                    parts: vec![Part::Text(TextPart {
                        text: format!("summary of {} items", request.items.len()),
                        metadata: MetadataMap::new(),
                    })],
                    metadata: MetadataMap::new(),
                    usage: None,
                    finish_reason: None,
                    created_at: None,
                }],
                metadata: MetadataMap::new(),
            })
        }
    }

    #[tokio::test]
    async fn summarize_strategy_uses_backend() {
        let request = CompactionRequest {
            transcript: vec![user_item("a"), user_item("b"), user_item("c")],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let strategy = SummarizeOlderStrategy::new(1);
        let mut ctx = CompactionContext {
            backend: Some(&FakeBackend),
            cancellation: None,
        };

        let result = strategy.apply(request, &mut ctx).await.unwrap();
        assert_eq!(result.replaced_items, 2);
        assert_eq!(result.transcript.len(), 2);
        match &result.transcript[0].parts[0] {
            Part::Text(text) => assert_eq!(text.text, "summary of 2 items"),
            other => panic!("unexpected part: {other:?}"),
        }
    }

    #[tokio::test]
    async fn summarize_strategy_preserves_tool_call_result_pairs() {
        let request = CompactionRequest {
            transcript: vec![
                user_item("old"),
                tool_call_item("call-1"),
                tool_result_item("call-1", false),
                user_item("recent"),
            ],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let strategy = SummarizeOlderStrategy::new(2);
        let mut ctx = CompactionContext {
            backend: Some(&FakeBackend),
            cancellation: None,
        };

        let result = strategy.apply(request, &mut ctx).await.unwrap();
        assert_eq!(result.replaced_items, 1);
        assert_eq!(result.transcript.len(), 4);
        match &result.transcript[0].parts[0] {
            Part::Text(text) => assert_eq!(text.text, "summary of 1 items"),
            other => panic!("unexpected part: {other:?}"),
        }
        assert!(matches!(result.transcript[1].parts[0], Part::ToolCall(_)));
        assert!(matches!(result.transcript[2].parts[0], Part::ToolResult(_)));
    }

    #[tokio::test]
    async fn pipeline_stops_when_cancelled() {
        let controller = CancellationController::new();
        let checkpoint = controller.handle().checkpoint();
        controller.interrupt();
        let request = CompactionRequest {
            transcript: vec![user_item("a"), user_item("b"), user_item("c")],
            reason: CompactionReason::TranscriptTooLong,
            metadata: MetadataMap::new(),
        };
        let pipeline = CompactionPipeline::new().with_strategy(DropReasoningStrategy::new());
        let mut ctx = CompactionContext {
            backend: None,
            cancellation: Some(checkpoint),
        };

        let error = pipeline.apply(request, &mut ctx).await.unwrap_err();
        assert!(matches!(error, CompactionError::Cancelled));
    }
}