halter-protocol 0.1.0

Protocol crate for halter
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
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
// pattern: Functional Core

use std::fmt;
use std::path::PathBuf;

use bytes::Bytes;
use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use uuid::Uuid;

/// Shared string payloads stay as `String` for now; this is the swap point for any future `Arc<str>` migration.
pub type SharedStr = String;

/// Historical sampling temperature used by older config resolution. Provider
/// requests now omit temperature unless `[providers.<name>].temperature` is
/// configured explicitly.
pub const DEFAULT_TEMPERATURE: f32 = 0.7;
pub type MediaType = String;
pub type ReplaySignature = String;
pub type ContentHash = String;
pub type Timestamp = DateTime<Utc>;

macro_rules! id_type {
    ($name:ident) => {
        #[derive(
            Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
        )]
        pub struct $name(pub String);

        impl $name {
            #[must_use]
            pub fn new() -> Self {
                Self(Uuid::new_v4().to_string())
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                Self(value.to_owned())
            }
        }

        impl From<String> for $name {
            fn from(value: String) -> Self {
                Self(value)
            }
        }
    };
}

macro_rules! string_wrapper {
    ($name:ident) => {
        #[derive(
            Debug,
            Clone,
            PartialEq,
            Eq,
            PartialOrd,
            Ord,
            Hash,
            Default,
            Serialize,
            Deserialize,
            JsonSchema,
        )]
        pub struct $name(pub String);

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                Self(value.to_owned())
            }
        }

        impl From<String> for $name {
            fn from(value: String) -> Self {
                Self(value)
            }
        }
    };
}

id_type!(MessageId);
id_type!(BlockId);
id_type!(ToolCallId);
id_type!(PromptId);
id_type!(PromptSegmentId);
id_type!(SessionId);
id_type!(TurnId);
id_type!(SkillId);
id_type!(PluginId);
id_type!(AgentId);

string_wrapper!(Revision);
string_wrapper!(ModelId);
string_wrapper!(ToolName);
string_wrapper!(ToolAlias);
string_wrapper!(SkillName);
string_wrapper!(AgentName);
string_wrapper!(ProviderName);

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ModelRole {
    Default,
    Plan,
    Subagent,
    Small,
}

impl ModelRole {
    #[must_use]
    pub const fn default_role() -> Self {
        Self::Default
    }

    #[must_use]
    pub const fn plan() -> Self {
        Self::Plan
    }

    #[must_use]
    pub const fn subagent() -> Self {
        Self::Subagent
    }

    #[must_use]
    pub const fn small() -> Self {
        Self::Small
    }

    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Plan => "plan",
            Self::Subagent => "subagent",
            Self::Small => "small",
        }
    }
}

impl Default for ModelRole {
    fn default() -> Self {
        Self::default_role()
    }
}

impl std::str::FromStr for ModelRole {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "default" => Ok(Self::Default),
            "plan" => Ok(Self::Plan),
            "subagent" => Ok(Self::Subagent),
            "small" => Ok(Self::Small),
            other => Err(format!(
                "unknown ModelRole '{other}'; expected one of: default, plan, subagent, small"
            )),
        }
    }
}

impl fmt::Display for ModelRole {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SubagentEventForwarding {
    #[default]
    Off,
    All,
}

impl SubagentEventForwarding {
    #[must_use]
    pub const fn is_enabled(self) -> bool {
        matches!(self, Self::All)
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
    Anthropic,
    OpenAi,
    OpenRouter,
    Fake,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ApiKind {
    AnthropicMessages,
    OpenAiResponses,
    OpenAiChat,
    Fake,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningEffort {
    Low,
    Medium,
    High,
    Xhigh,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct Usage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_creation_input_tokens: u64,
    pub cache_read_input_tokens: u64,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    EndTurn,
    ToolUse,
    Interrupted,
    MaxTokens,
    Error,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct ReplayMeta {
    pub provider_name: Option<ProviderName>,
    pub model: Option<ModelId>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum HookWarningSeverity {
    #[default]
    Warning,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct HookWarning {
    pub severity: HookWarningSeverity,
    pub category: SharedStr,
    pub plugin_id: Option<PluginId>,
    pub plugin_name: Option<SharedStr>,
    pub source_path: Option<PathBuf>,
    pub message: SharedStr,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SystemMessage {
    pub id: MessageId,
    pub created_at: Timestamp,
    pub text: SharedStr,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct UserMessage {
    pub id: MessageId,
    pub created_at: Timestamp,
    pub parts: Vec<UserPart>,
}

impl UserMessage {
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            id: MessageId::new(),
            created_at: Utc::now(),
            parts: vec![UserPart::Text { text: text.into() }],
        }
    }

    #[must_use]
    pub fn plain_text(&self) -> String {
        self.parts
            .iter()
            .filter_map(|part| match part {
                UserPart::Text { text } => Some(text.as_str()),
                UserPart::Image { .. } | UserPart::Document { .. } => None,
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UserPart {
    Text {
        text: SharedStr,
    },
    Image {
        media_type: MediaType,
        #[schemars(with = "Vec<u8>")]
        data: Bytes,
    },
    Document {
        media_type: MediaType,
        #[schemars(with = "Vec<u8>")]
        data: Bytes,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct AssistantMessage {
    pub id: MessageId,
    pub created_at: Timestamp,
    pub parts: Vec<AssistantPart>,
    pub stop_reason: Option<StopReason>,
    pub usage: Option<Usage>,
    pub replay_meta: ReplayMeta,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AssistantPart {
    Text { text: SharedStr },
    Thinking(ThinkingBlock),
    ToolCall(ToolCall),
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ThinkingBlock {
    pub text: SharedStr,
    pub signature: Option<ReplaySignature>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolCall {
    pub id: ToolCallId,
    pub name: ToolName,
    pub arguments: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolResultMessage {
    pub id: MessageId,
    pub call_id: ToolCallId,
    pub content: ToolResult,
    pub error: Option<ToolError>,
    pub created_at: Timestamp,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum Message {
    System(SystemMessage),
    User(UserMessage),
    Assistant(AssistantMessage),
    Tool(ToolResultMessage),
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StreamEvent {
    MessageStart {
        id: MessageId,
    },
    TextStart {
        id: BlockId,
    },
    TextDelta {
        id: BlockId,
        delta: SharedStr,
    },
    TextEnd {
        id: BlockId,
    },
    ThinkingStart {
        id: BlockId,
    },
    ThinkingDelta {
        id: BlockId,
        delta: SharedStr,
    },
    ThinkingEnd {
        id: BlockId,
        signature: Option<ReplaySignature>,
    },
    ToolCallStart {
        id: BlockId,
        tool_call_id: ToolCallId,
        name: ToolName,
    },
    ToolArgsDelta {
        id: BlockId,
        delta: SharedStr,
    },
    ToolCallEnd {
        id: BlockId,
    },
    UsageUpdate {
        usage: Usage,
    },
    MessageEnd {
        id: MessageId,
        stop_reason: StopReason,
        /// The provider's response ID, used for `previous_response_id` chaining.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        response_id: Option<String>,
    },
    ProviderWarning {
        message: SharedStr,
    },
    Error {
        error: ProviderError,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct Turn {
    pub id: TurnId,
    pub user_message: UserMessage,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_model: Option<ModelId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subagent_model: Option<ModelId>,
}

impl Turn {
    #[must_use]
    pub fn user(text: impl Into<String>) -> Self {
        Self {
            id: TurnId::new(),
            user_message: UserMessage::text(text),
            default_model: None,
            subagent_model: None,
        }
    }

    #[must_use]
    pub fn with_default_model(mut self, model: impl Into<ModelId>) -> Self {
        self.default_model = Some(model.into());
        self
    }

    #[must_use]
    pub fn with_subagent_model(mut self, model: impl Into<ModelId>) -> Self {
        self.subagent_model = Some(model.into());
        self
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SubagentState {
    Running,
    Completed,
    Failed,
    Cancelled,
    Closed,
}

impl SubagentState {
    #[must_use]
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Cancelled | Self::Closed
        )
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SpawnSubagentRequest {
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_type: Option<AgentName>,
    #[serde(default)]
    pub fork_context: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelId>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SendSubagentInputRequest {
    pub target: AgentId,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct WaitSubagentRequest {
    pub targets: Vec<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct CloseSubagentRequest {
    pub target: AgentId,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SubagentStatus {
    pub agent_id: AgentId,
    pub session_id: SessionId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_type: Option<AgentName>,
    pub task: String,
    pub state: SubagentState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_message: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl SubagentStatus {
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        self.state.is_terminal()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct WaitSubagentResponse {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<SubagentStatus>,
    pub timed_out: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct CloseSubagentResponse {
    pub previous_status: SubagentStatus,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SubagentSpecWire {
    pub role: Option<ModelRole>,
    pub task: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SessionCommand {
    SubmitTurn { turn: Turn },
    InterruptTurn,
    AppendSystemPrompt { id: PromptId, text: SharedStr },
    SetModelRole { role: ModelRole },
    SetModel { model: ModelId },
    SpawnSubagent { spec: SubagentSpecWire },
    ReloadResources,
    Shutdown,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum Delivery {
    Lossless,
    BestEffort,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct DeltaItem {
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolExecutionOutcome {
    pub call: ToolCall,
    pub result: Result<ToolResult, ToolError>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HookHandlerType {
    Command,
    Http,
    Prompt,
    Agent,
    Callback,
    Function,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HookRunStatus {
    Running,
    Completed,
    Failed,
    Blocked,
    Stopped,
    Cancelled,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HookOutputKind {
    Warning,
    Stop,
    Feedback,
    Context,
    Error,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct HookOutputEntry {
    pub kind: HookOutputKind,
    pub text: String,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HookSessionStartSource {
    Startup,
    Resume,
    Clear,
    Compact,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct HookRunSummary {
    pub run_id: String,
    pub event_name: String,
    pub handler_type: HookHandlerType,
    pub plugin_id: PluginId,
    pub plugin_root: PathBuf,
    pub status: HookRunStatus,
    pub status_message: Option<String>,
    pub started_at: Timestamp,
    pub completed_at: Option<Timestamp>,
    pub duration_ms: Option<u64>,
    pub entries: Vec<HookOutputEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SessionEventPayload {
    SessionStarted,
    Warning {
        message: String,
    },
    TurnStarted {
        turn_id: TurnId,
    },
    MessageItem {
        message: Message,
    },
    DeltaItem {
        delta: DeltaItem,
    },
    ToolExecutionStarted {
        call: ToolCall,
    },
    ToolOutput {
        call_id: ToolCallId,
        tool_name: ToolName,
        chunk: SharedStr,
    },
    HookStarted {
        run: HookRunSummary,
    },
    HookCompleted {
        run: HookRunSummary,
    },
    ToolExecutionCompleted {
        outcome: ToolExecutionOutcome,
    },
    ApprovalRequested {
        tool_name: ToolName,
        reason: String,
    },
    ContextCompacted {
        summary: String,
    },
    TurnCompleted {
        turn_id: TurnId,
        usage: Usage,
    },
    TurnFailed {
        turn_id: TurnId,
        error: String,
        /// Whether the failure came from explicit user/runtime cancellation.
        #[serde(default)]
        cancelled: bool,
        /// Whether the underlying provider error advertised itself as
        /// retryable. Defaults to `false` so historical replays without this
        /// field deserialize cleanly.
        #[serde(default)]
        retryable: bool,
    },
    Lagged {
        dropped_events: u64,
    },
    SessionShutdownComplete,
}

/// An event that has been committed to the session store and therefore has
/// been assigned a monotonic `sequence` by the commit boundary. Construct a
/// `SessionEvent` only via `PendingEvent::into_committed`, `SessionEvent::new_committed`,
/// or deserialization — the `sequence` field is intentionally not publicly
/// settable.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SessionEvent {
    pub session_id: SessionId,
    pub(crate) sequence: u64,
    pub delivery: Delivery,
    pub payload: SessionEventPayload,
}

impl SessionEvent {
    /// Construct a committed event with an explicit sequence. This is the
    /// only public constructor that sets the `sequence` field; call sites
    /// outside commit boundaries must use `PendingEvent`.
    #[must_use]
    pub fn new_committed(
        session_id: SessionId,
        sequence: u64,
        delivery: Delivery,
        payload: SessionEventPayload,
    ) -> Self {
        Self {
            session_id,
            sequence,
            delivery,
            payload,
        }
    }

    #[must_use]
    pub fn sequence(&self) -> u64 {
        self.sequence
    }
}

/// An event produced during turn execution, before the session store has
/// assigned a sequence. Convert to `SessionEvent` via `into_committed` once
/// the store has allocated a sequence number. Holding `sequence`-less events
/// until commit makes the commit-then-publish invariant type-enforced.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PendingEvent {
    pub session_id: SessionId,
    pub delivery: Delivery,
    pub payload: SessionEventPayload,
}

impl PendingEvent {
    #[must_use]
    pub fn new(session_id: SessionId, delivery: Delivery, payload: SessionEventPayload) -> Self {
        Self {
            session_id,
            delivery,
            payload,
        }
    }

    #[must_use]
    pub fn into_committed(self, sequence: u64) -> SessionEvent {
        SessionEvent {
            session_id: self.session_id,
            sequence,
            delivery: self.delivery,
            payload: self.payload,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum ToolConcurrency {
    Exclusive,
    ReadOnly,
    ParallelSafe,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolCapabilities {
    pub mutating: bool,
    pub requires_approval: bool,
    pub cancellable: bool,
    pub long_running: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolSpec {
    pub name: ToolName,
    pub description: SharedStr,
    pub input_schema: Value,
    pub concurrency: ToolConcurrency,
    pub capabilities: ToolCapabilities,
    pub provider_aliases: IndexMap<ProviderKind, ToolAlias>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ToolResult {
    Empty,
    Text { text: String },
    Json { value: Value },
}

#[derive(Debug, Clone, Error, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[error("{message}")]
pub struct ToolError {
    pub message: String,
}

impl ToolError {
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

#[derive(Debug, Clone, Error, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[error("{message}")]
pub struct ProviderError {
    pub message: String,
    pub retryable: bool,
}

impl ProviderError {
    /// Sentinel message produced by `ProviderError::cancelled` and recognized
    /// by `is_cancelled`. New consumers should prefer the constructor /
    /// predicate over inline message comparison.
    pub const CANCELLED_MESSAGE: &str = "failed to execute provider request: request cancelled";

    #[must_use]
    pub fn new(message: impl Into<String>, retryable: bool) -> Self {
        Self {
            message: message.into(),
            retryable,
        }
    }

    /// Construct a non-retryable cancellation error with the canonical
    /// message. Existing consumers that match on message text continue to
    /// work; new consumers should use `is_cancelled()` to distinguish.
    #[must_use]
    pub fn cancelled() -> Self {
        Self {
            message: Self::CANCELLED_MESSAGE.to_owned(),
            retryable: false,
        }
    }

    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.message == Self::CANCELLED_MESSAGE
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PromptSegment {
    pub id: PromptSegmentId,
    pub text: SharedStr,
    pub volatility: Volatility,
    pub cache_scope: CacheScope,
    pub content_hash: ContentHash,
    /// Logical section the segment belongs to. The prompt assembler groups
    /// segments by kind so the wire layout (system, then skills, then the
    /// turn) is independent of insertion order, and so codecs can emit
    /// cache breakpoints on stable boundaries.
    #[serde(default)]
    pub kind: PromptSegmentKind,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum PromptSegmentKind {
    #[default]
    System,
    Skill,
    Append,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum Volatility {
    Static,
    SessionStable,
    TurnDynamic,
    AlwaysDynamic,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum CacheScope {
    PrefixCacheable,
    Dynamic,
}

/// Marks the four section boundaries the runtime asks codecs to expose as
/// cache breakpoints when the underlying provider supports them.
///
/// The order is fixed: system prompt, tool descriptions, skills, then the
/// most recent user prompt. The "rest of the session" follows the last
/// breakpoint and is therefore the only window eligible for in-band
/// compaction by non-dedicated providers.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct CacheBreakpoints {
    pub after_system: bool,
    pub after_tools: bool,
    pub after_skills: bool,
    pub after_user_prompt: bool,
}

impl CacheBreakpoints {
    /// All four breakpoints active. The prompt assembler emits this layout
    /// for any session that has a non-empty system prompt and at least one
    /// user message; codecs may downgrade as needed.
    #[must_use]
    pub fn all() -> Self {
        Self {
            after_system: true,
            after_tools: true,
            after_skills: true,
            after_user_prompt: true,
        }
    }

    #[must_use]
    pub fn count_active(&self) -> usize {
        usize::from(self.after_system)
            + usize::from(self.after_tools)
            + usize::from(self.after_skills)
            + usize::from(self.after_user_prompt)
    }
}

pub type FileViewCache = IndexMap<PathBuf, FileViewEntry>;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct FileViewEntry {
    pub path: PathBuf,
    pub full_hash: ContentHash,
    pub mtime: Timestamp,
    pub size: u64,
    pub viewed_ranges: Vec<ViewedRange>,
    pub last_shown_turn: TurnId,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ViewedRange {
    pub start_line: u32,
    pub end_line: u32,
    pub line_anchors: Vec<LineAnchor>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LineAnchor {
    pub line: u32,
    pub anchor: [u8; 3],
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PendingToolCall {
    pub call: ToolCall,
    pub submitted_at: Timestamp,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SummarySlice {
    pub id: String,
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct TranscriptWindow {
    pub messages: Vec<Message>,
    pub elided_message_count: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(transparent)]
pub struct CompactedContext(pub Vec<Value>);

impl CompactedContext {
    #[must_use]
    pub fn new(items: Vec<Value>) -> Self {
        Self(items)
    }

    #[must_use]
    pub fn items(&self) -> &[Value] {
        &self.0
    }

    #[must_use]
    pub fn into_items(self) -> Vec<Value> {
        self.0
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl From<Vec<Value>> for CompactedContext {
    fn from(value: Vec<Value>) -> Self {
        Self(value)
    }
}

impl AsRef<[Value]> for CompactedContext {
    fn as_ref(&self) -> &[Value] {
        self.items()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct CompactionWindow {
    pub eligible_messages: Vec<Message>,
    pub preserved_messages: Vec<Message>,
    pub reserved_response_block: bool,
}

impl CompactionWindow {
    /// Preserve the latest assistant response block and compact the older
    /// prefix. Providers with a first-class compaction endpoint use this
    /// broader window because the provider restores the compacted context as
    /// provider-native content.
    #[must_use]
    pub fn preserve_latest_assistant_response_block(messages: &[Message]) -> Self {
        let Some(last_assistant_index) = messages
            .iter()
            .rposition(|message| matches!(message, Message::Assistant(_)))
        else {
            return Self {
                eligible_messages: messages.to_vec(),
                preserved_messages: Vec::new(),
                reserved_response_block: false,
            };
        };

        Self {
            eligible_messages: messages[..last_assistant_index].to_vec(),
            preserved_messages: messages[last_assistant_index..].to_vec(),
            reserved_response_block: true,
        }
    }

    /// Preserve every message through the latest user message and compact
    /// only the post-user tail. Inline compaction providers use this narrower
    /// window so system, tool, skill, and latest-user cache anchors remain
    /// verbatim.
    #[must_use]
    pub fn preserve_through_latest_user(messages: &[Message]) -> Self {
        let Some(last_user_index) = messages
            .iter()
            .rposition(|message| matches!(message, Message::User(_)))
        else {
            return Self {
                eligible_messages: Vec::new(),
                preserved_messages: messages.to_vec(),
                reserved_response_block: false,
            };
        };
        let pivot = last_user_index + 1;
        Self {
            eligible_messages: messages[pivot..].to_vec(),
            preserved_messages: messages[..pivot].to_vec(),
            reserved_response_block: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct FileViewSlice {
    pub path: PathBuf,
    pub full_hash: ContentHash,
    pub viewed_ranges: Vec<ViewedRange>,
    pub last_shown_turn: TurnId,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct ElisionMarker {
    pub kind: String,
    pub count: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct MemoryItem {
    pub key: String,
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SubagentRef {
    pub session_id: SessionId,
    pub task: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SessionBlueprint {
    pub session_id: SessionId,
    pub parent_session_id: Option<SessionId>,
    pub default_model: ModelId,
    pub subagent_model: ModelId,
    #[serde(default)]
    pub subagent_event_forwarding: SubagentEventForwarding,
    pub snapshot_revision: Revision,
    pub working_dir: PathBuf,
    pub system_prompt_seed: Vec<PromptSegment>,
    pub max_turns: Option<u32>,
    pub subagent_depth: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct SessionState {
    pub messages: Vec<Message>,
    #[serde(default)]
    pub compacted_prefix: Vec<Value>,
    pub file_view_cache: FileViewCache,
    pub appended_prompt_segments: Vec<PromptSegment>,
    pub pending_tool_calls: IndexMap<ToolCallId, PendingToolCall>,
    pub usage_so_far: Usage,
    pub summaries: Vec<SummarySlice>,
    pub lineage: Vec<SubagentRef>,
    pub fired_hook_ids: Vec<String>,
    pub pending_session_start_source: Option<HookSessionStartSource>,
    pub pending_warning_messages: Vec<HookWarning>,
    /// The OpenAI Responses API response ID from the last successful turn.
    /// Used for `previous_response_id` chaining to avoid re-sending full history.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_response_id: Option<String>,
    /// Number of messages the model has already seen via `previous_response_id`.
    /// Messages at indices `[0..messages_seen_by_provider)` don't need re-sending.
    #[serde(default)]
    pub messages_seen_by_provider: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ObservedState {
    pub cwd: PathBuf,
    pub git_branch: Option<String>,
    pub git_dirty: Option<bool>,
    pub now_utc: Timestamp,
    pub env_facts: IndexMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct InstructionFile {
    pub path: PathBuf,
    pub body: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct SkillDef {
    pub id: SkillId,
    pub name: String,
    pub description: String,
    pub body: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct AgentDef {
    pub id: AgentId,
    pub name: String,
    pub prompt: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct PluginManifest {
    pub name: String,
    pub version: String,
    pub skills: Vec<String>,
    pub agents: Vec<String>,
    pub hooks: Option<String>,
    pub mcp_servers: Option<String>,
    pub lsp_servers: Option<String>,
    pub allowed_http_hosts: Vec<String>,
    pub allowed_env_vars: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub struct PromptRegistry {
    pub prompts: IndexMap<String, Vec<PromptSegment>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ResourceSnapshot {
    pub revision: Revision,
    pub tools: IndexMap<ToolName, ToolSpec>,
    pub skills: IndexMap<SkillName, SkillDef>,
    pub agents: IndexMap<AgentName, AgentDef>,
    pub prompts: PromptRegistry,
    pub plugins: IndexMap<PluginId, PluginManifest>,
    pub instruction_files: Vec<InstructionFile>,
}

impl ResourceSnapshot {
    #[must_use]
    pub fn empty() -> Self {
        Self {
            revision: Revision("empty".to_owned()),
            tools: IndexMap::new(),
            skills: IndexMap::new(),
            agents: IndexMap::new(),
            prompts: PromptRegistry::default(),
            plugins: IndexMap::new(),
            instruction_files: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ProviderCapabilities {
    pub supports_tools: bool,
    pub supports_streaming: bool,
    pub supports_reasoning: bool,
    pub supports_interleaved_reasoning: bool,
    pub supports_images: bool,
    pub supports_documents: bool,
    pub supports_prompt_cache: bool,
    pub supports_compaction: bool,
    /// How the provider implements compaction. This remains exposed for
    /// diagnostics and external callers, but runtime planning asks the
    /// provider for a `CompactionWindow` instead of branching on this value.
    #[serde(default)]
    pub compaction_strategy: Option<ProviderCompactionStrategy>,
    pub supports_tool_result_media: bool,
    pub requires_non_empty_assistant_content: bool,
    pub tool_call_id_policy: ToolCallIdPolicy,
    pub max_input_tokens: u64,
    pub max_output_tokens: u64,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProviderCompactionStrategy {
    /// A first-class compaction endpoint (e.g. OpenAI Responses
    /// `/v1/responses/compact`) that returns encrypted content for safe
    /// reinjection. The runtime can compact aggressively because the
    /// provider preserves anchor invariants.
    Dedicated,
    /// In-band compaction via the regular completions endpoint
    /// (e.g. OpenRouter's responses passthrough). Lossy: the runtime
    /// only compacts the trailing window after the last cache breakpoint
    /// and wraps the result in explicit compaction tags so the model can
    /// distinguish it from authoritative system content.
    Inline,
}

impl Default for ProviderCapabilities {
    fn default() -> Self {
        Self {
            supports_tools: true,
            supports_streaming: true,
            supports_reasoning: false,
            supports_interleaved_reasoning: false,
            supports_images: false,
            supports_documents: false,
            supports_prompt_cache: false,
            supports_compaction: false,
            compaction_strategy: None,
            supports_tool_result_media: false,
            requires_non_empty_assistant_content: false,
            tool_call_id_policy: ToolCallIdPolicy::ProviderSupplied,
            max_input_tokens: 0,
            max_output_tokens: 0,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolCallIdPolicy {
    ProviderSupplied,
    RuntimeSynthesized,
    StableReplayNormalized,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ResolvedModel {
    pub role: ModelRole,
    pub id: ModelId,
    pub provider: ProviderName,
    pub provider_kind: ProviderKind,
    pub api_kind: ApiKind,
    pub model: String,
    pub max_input_tokens: Option<u32>,
    pub max_output_tokens: Option<u32>,
    pub reasoning: Option<ReasoningEffort>,
    #[serde(default)]
    pub tokens_per_minute: Option<u64>,
}

#[derive(
    Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord,
)]
#[serde(rename_all = "snake_case")]
pub enum MessageSignal {
    /// Compact first -- orientation commands, empty results, duplicate failures.
    VeryLow = 0,
    /// Low signal -- failed tool calls, stale reads.
    Low = 1,
    /// Default for most messages.
    Normal = 2,
    /// Active file reads and system guidance.
    High = 3,
    /// Assistant text or reasoning content.
    VeryHigh = 4,
    /// Never compact -- user messages.
    Anchor = 5,
}

#[derive(
    Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord,
)]
#[serde(rename_all = "snake_case")]
pub enum PruneSignalThreshold {
    VeryLow,
    Low,
    #[default]
    Normal,
    High,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct CompactionResult {
    /// Number of messages compacted into the raw prefix.
    pub compacted_count: usize,
    /// Human-readable summary for events and hooks.
    pub summary: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ContextPlan {
    pub prompt_segments: Vec<PromptSegment>,
    pub transcript_window: TranscriptWindow,
    #[serde(default)]
    pub compacted_prefix: Vec<Value>,
    pub file_views: Vec<FileViewSlice>,
    pub carried_summaries: Vec<SummarySlice>,
    pub elided_tool_results: Vec<ElisionMarker>,
    pub memory_items: Vec<MemoryItem>,
    pub tool_specs: Vec<ToolSpec>,
    pub observed_state: ObservedState,
    pub projected_input_tokens: u64,
    pub cache_boundary_hash: ContentHash,
    pub messages: Vec<Message>,
    pub estimated_tokens: u64,
    /// If the planner compacted messages this turn, the result is here.
    /// The caller should apply it to `SessionState` after using the plan.
    pub compaction: Option<CompactionResult>,
    /// When set, the codec should chain via `previous_response_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// Index into `messages` where new messages start (for chained requests).
    #[serde(default)]
    pub new_messages_start: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct AssembledPrompt {
    pub segments: Vec<PromptSegment>,
    pub transcript: Vec<Message>,
    pub ordered_segments: Vec<PromptSegment>,
    pub prefix_cache_key: String,
    pub rendered_prefix: String,
    pub rendered_transcript: String,
    pub rendered: String,
    /// Section boundaries that the assembler asks the codec to expose as
    /// cache breakpoints. Codecs that do not support explicit breakpoints
    /// (e.g. OpenAI Responses, which uses prefix-prefix caching) ignore
    /// this; codecs that do (Anthropic) emit `cache_control` on the last
    /// content block of each marked section.
    #[serde(default)]
    pub cache_breakpoints: CacheBreakpoints,
    /// Index into `ordered_segments` after which the system-prompt
    /// breakpoint applies. `None` when there are no system segments.
    #[serde(default)]
    pub system_segment_count: usize,
    /// Number of segments at the head of `ordered_segments` that belong
    /// to the skills section. Always immediately follows the system block.
    #[serde(default)]
    pub skill_segment_count: usize,
}

impl AssembledPrompt {
    /// Slice of segments that constitute the system-prompt section.
    #[must_use]
    pub fn system_segments(&self) -> &[PromptSegment] {
        let end = self.system_segment_count.min(self.ordered_segments.len());
        &self.ordered_segments[..end]
    }

    /// Slice of segments that constitute the skills section.
    #[must_use]
    pub fn skill_segments(&self) -> &[PromptSegment] {
        let start = self.system_segment_count.min(self.ordered_segments.len());
        let end = (start + self.skill_segment_count).min(self.ordered_segments.len());
        &self.ordered_segments[start..end]
    }

    /// Slice of segments that follow both the system and skills sections —
    /// hook-appended context, etc. These never receive a cache breakpoint
    /// because they may change turn-to-turn.
    #[must_use]
    pub fn append_segments(&self) -> &[PromptSegment] {
        let start =
            (self.system_segment_count + self.skill_segment_count).min(self.ordered_segments.len());
        &self.ordered_segments[start..]
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ProviderRequest {
    pub session_id: SessionId,
    pub turn_id: TurnId,
    pub model: ResolvedModel,
    pub prompt: AssembledPrompt,
    #[serde(default)]
    pub compacted_prefix: Vec<Value>,
    pub messages: Vec<Message>,
    pub tools: Vec<ToolSpec>,
    /// When set, the provider can chain onto the previous response instead of
    /// re-sending the full conversation history. The codec should send only
    /// messages after `new_messages_start` when this is present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// Index into `messages` where new (unseen-by-provider) messages begin.
    /// Only meaningful when `previous_response_id` is `Some`.
    #[serde(default)]
    pub new_messages_start: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ProviderCompactionRequest {
    pub session_id: SessionId,
    pub model: ResolvedModel,
    #[serde(default)]
    pub compacted_prefix: Vec<Value>,
    pub messages: Vec<Message>,
    pub tools: Vec<ToolSpec>,
    pub instructions: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ProviderCompactionResponse {
    pub output: Vec<Value>,
    pub usage: Usage,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SubagentResult {
    pub session_id: SessionId,
    pub output: String,
    pub usage: Usage,
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use super::*;

    #[test]
    fn message_roundtrip() {
        let message = Message::User(UserMessage::text("hello"));
        let encoded = serde_json::to_string(&message).expect("serialize message");
        let decoded: Message = serde_json::from_str(&encoded).expect("deserialize message");
        assert_eq!(decoded, message);
    }

    #[test]
    fn session_event_roundtrip() {
        let event = SessionEvent::new_committed(
            SessionId::new(),
            1,
            Delivery::Lossless,
            SessionEventPayload::TurnCompleted {
                turn_id: TurnId::new(),
                usage: Usage {
                    input_tokens: 10,
                    output_tokens: 5,
                    cache_creation_input_tokens: 0,
                    cache_read_input_tokens: 0,
                },
            },
        );
        let encoded = serde_json::to_string(&event).expect("serialize event");
        let decoded: SessionEvent = serde_json::from_str(&encoded).expect("deserialize event");
        assert_eq!(decoded, event);
    }

    #[test]
    fn pending_event_into_committed_preserves_fields() {
        let session_id = SessionId::from("session-42");
        let payload = SessionEventPayload::ContextCompacted {
            summary: "summary".to_owned(),
        };
        let pending = PendingEvent::new(session_id.clone(), Delivery::Lossless, payload.clone());

        let committed = pending.clone().into_committed(7);

        assert_eq!(committed.session_id, session_id);
        assert_eq!(committed.sequence(), 7);
        assert_eq!(committed.delivery, Delivery::Lossless);
        assert_eq!(committed.payload, payload);

        // PendingEvent is still unsequenced; we reject post-hoc mutation of
        // committed events by keeping the sequence field crate-private.
        let encoded = serde_json::to_string(&pending).expect("serialize pending");
        assert!(!encoded.contains("sequence"));
    }

    #[test]
    fn turn_roundtrip_preserves_model_overrides() {
        let turn = Turn::user("hello")
            .with_default_model("default")
            .with_subagent_model("subagent");

        let encoded = serde_json::to_string(&turn).expect("serialize turn");
        let decoded: Turn = serde_json::from_str(&encoded).expect("deserialize turn");

        assert_eq!(decoded, turn);
    }

    #[test]
    fn compacted_context_serializes_as_existing_prefix_array() {
        let context = CompactedContext::new(vec![
            serde_json::json!({"type": "reasoning", "encrypted_content": "summary"}),
        ]);

        let encoded = serde_json::to_string(&context).expect("serialize compacted context");
        assert!(encoded.starts_with('['));

        let decoded: CompactedContext =
            serde_json::from_str(&encoded).expect("deserialize compacted context");
        assert_eq!(decoded, context);

        let state: SessionState = serde_json::from_value(serde_json::json!({
            "messages": [],
            "compacted_prefix": [
                {"type": "reasoning", "encrypted_content": "summary"}
            ],
            "file_view_cache": {},
            "appended_prompt_segments": [],
            "pending_tool_calls": {},
            "usage_so_far": {
                "input_tokens": 0,
                "output_tokens": 0,
                "cache_creation_input_tokens": 0,
                "cache_read_input_tokens": 0
            },
            "summaries": [],
            "lineage": [],
            "fired_hook_ids": [],
            "pending_session_start_source": null,
            "pending_warning_messages": [],
            "messages_seen_by_provider": 0
        }))
        .expect("deserialize existing session state");
        assert_eq!(state.compacted_prefix.len(), 1);
    }

    #[test]
    fn compaction_window_preserves_latest_assistant_response_block() {
        let messages = vec![
            Message::User(UserMessage::text("first")),
            assistant_text("answer"),
            Message::User(UserMessage::text("follow up")),
        ];

        let window = CompactionWindow::preserve_latest_assistant_response_block(&messages);

        assert_eq!(window.eligible_messages.len(), 1);
        assert_eq!(window.preserved_messages.len(), 2);
        assert!(window.reserved_response_block);
    }

    #[test]
    fn compaction_window_preserves_through_latest_user() {
        let messages = vec![
            Message::User(UserMessage::text("first")),
            assistant_text("answer"),
            Message::User(UserMessage::text("follow up")),
            assistant_text("tail"),
        ];

        let window = CompactionWindow::preserve_through_latest_user(&messages);

        assert_eq!(window.preserved_messages.len(), 3);
        assert!(matches!(
            window.preserved_messages.last(),
            Some(Message::User(_))
        ));
        assert_eq!(window.eligible_messages.len(), 1);
        assert!(!window.reserved_response_block);
    }

    #[test]
    fn user_message_with_media_roundtrips() {
        let message = Message::User(UserMessage {
            id: MessageId::new(),
            created_at: Utc::now(),
            parts: vec![
                UserPart::Text {
                    text: "hello".to_owned(),
                },
                UserPart::Image {
                    media_type: "image/png".to_owned(),
                    data: Bytes::from_static(b"png"),
                },
                UserPart::Document {
                    media_type: "application/pdf".to_owned(),
                    data: Bytes::from_static(b"pdf"),
                },
            ],
        });

        let encoded = serde_json::to_string(&message).expect("serialize message");
        let decoded: Message = serde_json::from_str(&encoded).expect("deserialize message");
        assert_eq!(decoded, message);
    }

    #[test]
    fn stream_event_with_signature_roundtrips() {
        let event = StreamEvent::ThinkingEnd {
            id: BlockId::new(),
            signature: Some("sig-123".to_owned()),
        };

        let encoded = serde_json::to_string(&event).expect("serialize event");
        let decoded: StreamEvent = serde_json::from_str(&encoded).expect("deserialize event");
        assert_eq!(decoded, event);
    }

    fn assistant_text(text: &str) -> Message {
        Message::Assistant(AssistantMessage {
            id: MessageId::new(),
            created_at: Utc::now(),
            parts: vec![AssistantPart::Text {
                text: text.to_owned(),
            }],
            stop_reason: None,
            usage: None,
            replay_meta: ReplayMeta::default(),
        })
    }
}