iron-core 0.1.34

Core AgentIron loop, session state, and tool registry
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
use agent_client_protocol::schema::v1 as acp;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{btree_map::Entry, BTreeMap, BTreeSet, HashMap};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SessionId(pub u64);

impl SessionId {
    pub fn new() -> Self {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self(COUNTER.fetch_add(1, Ordering::SeqCst))
    }
}

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

impl std::fmt::Display for SessionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "session-{}", self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum StructuredMessage {
    User { content: Vec<ContentBlock> },
    Agent { content: Vec<ContentBlock> },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    Text { text: String },
    Image { data: String, mime_type: String },
    Resource { uri: String, name: Option<String> },
}

impl ContentBlock {
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    pub fn to_text(&self) -> Option<&str> {
        match self {
            ContentBlock::Text { text } => Some(text),
            _ => None,
        }
    }

    pub fn from_acp_content(block: &acp::ContentBlock) -> Self {
        match block {
            acp::ContentBlock::Text(tc) => ContentBlock::Text {
                text: tc.text.clone(),
            },
            acp::ContentBlock::Image(ic) => ContentBlock::Image {
                data: ic.data.clone(),
                mime_type: ic.mime_type.clone(),
            },
            acp::ContentBlock::ResourceLink(rl) => ContentBlock::Resource {
                uri: rl.uri.clone(),
                name: Some(rl.name.clone()),
            },
            _ => ContentBlock::Text {
                text: "[unsupported content]".into(),
            },
        }
    }
}

impl StructuredMessage {
    pub fn user_text(text: impl Into<String>) -> Self {
        Self::User {
            content: vec![ContentBlock::text(text)],
        }
    }

    pub fn agent_text(text: impl Into<String>) -> Self {
        Self::Agent {
            content: vec![ContentBlock::text(text)],
        }
    }

    pub fn text_content(&self) -> String {
        let blocks = match self {
            Self::User { content } => content,
            Self::Agent { content } => content,
        };
        blocks
            .iter()
            .filter_map(|b| b.to_text())
            .collect::<Vec<_>>()
            .join("")
    }

    pub fn is_user(&self) -> bool {
        matches!(self, Self::User { .. })
    }

    pub fn is_agent(&self) -> bool {
        matches!(self, Self::Agent { .. })
    }

    pub fn content_blocks(&self) -> &[ContentBlock] {
        match self {
            Self::User { content } => content,
            Self::Agent { content } => content,
        }
    }

    pub fn estimated_tokens(&self) -> usize {
        estimate_text_tokens(&self.text_content())
    }
}

fn estimate_text_tokens(text: &str) -> usize {
    (text.len() as f64 * 0.25).ceil() as usize
}

pub fn estimate_tool_call_tokens(tool_name: &str, arguments: &Value) -> usize {
    estimate_text_tokens(&format!("{}: {}", tool_name, arguments))
}

fn estimate_tool_result_tokens(tool_name: &str, result: &Value) -> usize {
    estimate_text_tokens(&format!("{}: {}", tool_name, result))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TimelineEntry {
    UserMessage {
        index: u64,
        message_index: usize,
        #[serde(skip_serializing_if = "Option::is_none")]
        visible_id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
    },
    AgentMessage {
        index: u64,
        message_index: usize,
        #[serde(skip_serializing_if = "Option::is_none")]
        visible_id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
    },
    ToolCallStarted {
        index: u64,
        call_id: String,
        tool_name: String,
        tool_record_index: usize,
        #[serde(skip_serializing_if = "Option::is_none")]
        visible_id: Option<String>,
    },
    ToolCallTerminal {
        index: u64,
        call_id: String,
        tool_name: String,
        outcome: ToolTerminalOutcome,
        tool_record_index: usize,
        #[serde(skip_serializing_if = "Option::is_none")]
        visible_id: Option<String>,
    },
    ModelSwitched {
        index: u64,
        from_model: String,
        to_model: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        from_provider: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        to_provider: Option<String>,
        adapted: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        visible_id: Option<String>,
    },
}

impl TimelineEntry {
    pub fn index(&self) -> u64 {
        match self {
            Self::UserMessage { index, .. }
            | Self::AgentMessage { index, .. }
            | Self::ToolCallStarted { index, .. }
            | Self::ToolCallTerminal { index, .. }
            | Self::ModelSwitched { index, .. } => *index,
        }
    }

    pub fn visible_id(&self) -> Option<&str> {
        match self {
            Self::UserMessage { visible_id, .. }
            | Self::AgentMessage { visible_id, .. }
            | Self::ToolCallStarted { visible_id, .. }
            | Self::ToolCallTerminal { visible_id, .. }
            | Self::ModelSwitched { visible_id, .. } => visible_id.as_deref(),
        }
    }

    pub fn set_visible_id(&mut self, id: String) {
        match self {
            Self::UserMessage { visible_id, .. }
            | Self::AgentMessage { visible_id, .. }
            | Self::ToolCallStarted { visible_id, .. }
            | Self::ToolCallTerminal { visible_id, .. }
            | Self::ModelSwitched { visible_id, .. } => {
                *visible_id = Some(id);
            }
        }
    }

    pub fn tool_record_index(&self) -> Option<usize> {
        match self {
            Self::ToolCallStarted {
                tool_record_index, ..
            }
            | Self::ToolCallTerminal {
                tool_record_index, ..
            } => Some(*tool_record_index),
            _ => None,
        }
    }

    pub fn is_model_switched(&self) -> bool {
        matches!(self, Self::ModelSwitched { .. })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum ToolTerminalOutcome {
    Completed,
    Failed,
    Denied,
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableToolRecord {
    pub call_id: String,
    pub tool_name: String,
    pub arguments: Value,
    pub status: ToolRecordStatus,
    pub result: Option<Value>,
    pub timeline_started_index: Option<u64>,
    pub timeline_terminal_index: Option<u64>,
    pub parent_script_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableScriptRecord {
    pub script_id: String,
    pub parent_call_id: String,
    pub script_source: String,
    pub input: Option<Value>,
    pub status: ScriptRecordStatus,
    pub result: Option<Value>,
    pub error: Option<Value>,
    pub child_call_ids: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ScriptRecordStatus {
    Running,
    Completed,
    CompletedWithFailures,
    Failed,
    Cancelled,
}

impl DurableScriptRecord {
    pub fn new(
        script_id: impl Into<String>,
        parent_call_id: impl Into<String>,
        script_source: impl Into<String>,
        input: Option<Value>,
    ) -> Self {
        Self {
            script_id: script_id.into(),
            parent_call_id: parent_call_id.into(),
            script_source: script_source.into(),
            input,
            status: ScriptRecordStatus::Running,
            result: None,
            error: None,
            child_call_ids: Vec::new(),
        }
    }

    pub fn complete(&mut self, result: Value, child_call_ids: Vec<String>) {
        self.status = ScriptRecordStatus::Completed;
        self.result = Some(result);
        self.child_call_ids = child_call_ids;
    }

    pub fn complete_with_failures(&mut self, result: Value, child_call_ids: Vec<String>) {
        self.status = ScriptRecordStatus::CompletedWithFailures;
        self.result = Some(result);
        self.child_call_ids = child_call_ids;
    }

    pub fn fail(&mut self, error: Value, child_call_ids: Vec<String>) {
        self.status = ScriptRecordStatus::Failed;
        self.error = Some(error);
        self.child_call_ids = child_call_ids;
    }

    pub fn cancel(&mut self) {
        self.status = ScriptRecordStatus::Cancelled;
    }

    pub fn is_terminal(&self) -> bool {
        matches!(
            self.status,
            ScriptRecordStatus::Completed
                | ScriptRecordStatus::CompletedWithFailures
                | ScriptRecordStatus::Failed
                | ScriptRecordStatus::Cancelled
        )
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ToolRecordStatus {
    PendingApproval,
    Running,
    Completed,
    Failed,
    Denied,
    Cancelled,
}

impl ToolRecordStatus {
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Denied | Self::Cancelled
        )
    }

    pub fn terminal_outcome(&self) -> Option<ToolTerminalOutcome> {
        match self {
            Self::Completed => Some(ToolTerminalOutcome::Completed),
            Self::Failed => Some(ToolTerminalOutcome::Failed),
            Self::Denied => Some(ToolTerminalOutcome::Denied),
            Self::Cancelled => Some(ToolTerminalOutcome::Cancelled),
            Self::PendingApproval | Self::Running => None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableSession {
    pub id: SessionId,
    pub messages: Vec<StructuredMessage>,
    pub tool_records: Vec<DurableToolRecord>,
    pub timeline: Vec<TimelineEntry>,
    pub script_records: Vec<DurableScriptRecord>,
    pub instructions: Option<String>,
    pub workspace_scope: Option<String>,
    #[serde(default)]
    pub compressed_blocks: Vec<crate::context::models::CompressedBlock>,
    #[serde(default)]
    pub uncompacted_tokens: usize,
    #[serde(default)]
    pub repo_instruction_payload: Option<crate::prompt::config::RepoInstructionPayload>,
    /// Session-scoped MCP server enablement state.
    /// Maps MCP server IDs to whether they are enabled for this session.
    #[serde(default)]
    pub mcp_server_enablement: HashMap<String, bool>,
    /// Session-scoped plugin enablement state.
    /// Maps plugin IDs to whether they are enabled for this session.
    /// NOTE: This is excluded from handoff bundles (see handoff.rs).
    #[serde(default)]
    pub plugin_enablement: crate::plugin::session::SessionPluginEnablement,
    /// Session-scoped skill activation state.
    #[serde(default)]
    pub skill_state: crate::skill::SessionSkillState,
    /// Session-scoped snapshot of skills available for activation.
    #[serde(default)]
    pub available_skills: Vec<crate::skill::LoadedSkill>,
    /// Counter for generating stable visible timeline IDs.
    #[serde(default)]
    pub next_visible_id: u64,
    /// Current model identifier for this session
    #[serde(default)]
    pub current_model: Option<String>,
    /// Provider slug when the session is using a managed provider
    /// (set by a managed model switch)
    #[serde(default)]
    pub current_provider_slug: Option<String>,
    /// Optional API key for the current managed provider
    #[serde(default)]
    pub current_provider_api_key: Option<String>,
    /// History of model switches for this session
    #[serde(default)]
    pub model_switch_history: Vec<crate::context::model_switch::ModelSwitchRecord>,
    /// Tools hidden due to model capability differences
    #[serde(default)]
    pub hidden_tools: Vec<String>,
    /// Session-scoped active workspace roots.
    #[serde(default)]
    pub workspace_roots: Vec<std::path::PathBuf>,
    /// Pending workspace roots to be applied at the next turn boundary.
    #[serde(default)]
    pub pending_workspace_roots: Option<Vec<std::path::PathBuf>>,
    /// The profile id last used for this session, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<crate::profile::AgentProfileId>,
    /// Profile identity prompt selected for this session, if any.
    /// Rendered in `## 1. Identity` instead of client/session injection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_identity: Option<String>,
    /// Session-effective snapshot of the profile's tool filter at setup time.
    /// `None` means the profile used `Inherit` (or no profile was selected).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_tool_filter: Option<crate::profile::ToolFilter>,
    /// Session-effective snapshot of the profile's approval posture at setup time.
    /// `None` means the profile used `PerTool` (or no profile was selected).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_approval: Option<crate::profile::AgentApproval>,
    /// Session-effective snapshot of the resolved provider context at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_provider_context:
        Option<crate::provider_credential::domain::ProviderPromptContext>,
    /// Session-effective snapshot of the resolved model at setup time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_model: Option<String>,
    /// Whether the session was created with a profile that is no longer available.
    /// Stored as a diagnostic; the session continues with its snapshot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_unavailable: Option<String>,
    #[serde(skip, default)]
    pub token_tracker: crate::context::SessionTokenTracker,
}

impl DurableSession {
    pub fn new(id: SessionId) -> Self {
        Self {
            id,
            messages: Vec::new(),
            tool_records: Vec::new(),
            timeline: Vec::new(),
            script_records: Vec::new(),
            instructions: None,
            workspace_scope: None,
            compressed_blocks: Vec::new(),
            uncompacted_tokens: 0,
            repo_instruction_payload: None,
            mcp_server_enablement: HashMap::new(),
            plugin_enablement: crate::plugin::session::SessionPluginEnablement::new(),
            skill_state: crate::skill::SessionSkillState::default(),
            available_skills: Vec::new(),
            next_visible_id: 1,
            current_model: None,
            current_provider_slug: None,
            current_provider_api_key: None,
            model_switch_history: Vec::new(),
            hidden_tools: Vec::new(),
            workspace_roots: Vec::new(),
            pending_workspace_roots: None,
            profile_id: None,
            profile_identity: None,
            effective_tool_filter: None,
            effective_approval: None,
            effective_provider_context: None,
            effective_model: None,
            profile_unavailable: None,
            token_tracker: crate::context::SessionTokenTracker::default(),
        }
    }

    pub fn next_visible_id(&mut self) -> String {
        let id = format!("m{:04}", self.next_visible_id);
        self.next_visible_id += 1;
        id
    }

    pub fn add_user_text(&mut self, text: impl Into<String>) {
        let msg = StructuredMessage::User {
            content: vec![ContentBlock::text(text)],
        };
        let tokens = msg.estimated_tokens();
        let message_index = self.messages.len();
        self.messages.push(msg);
        let timeline_index = self.timeline.len() as u64;
        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::UserMessage {
            index: timeline_index,
            message_index,
            visible_id: Some(visible_id),
            model: self.current_model.clone(),
        });
        self.uncompacted_tokens += tokens;
        self.token_tracker.add_delta(tokens);
    }

    pub fn add_user_message(&mut self, content: Vec<ContentBlock>) {
        let msg = StructuredMessage::User { content };
        let tokens = msg.estimated_tokens();
        let message_index = self.messages.len();
        self.messages.push(msg);
        let timeline_index = self.timeline.len() as u64;
        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::UserMessage {
            index: timeline_index,
            message_index,
            visible_id: Some(visible_id),
            model: self.current_model.clone(),
        });
        self.uncompacted_tokens += tokens;
        self.token_tracker.add_delta(tokens);
    }

    pub fn add_agent_text(&mut self, text: impl Into<String>) {
        let msg = StructuredMessage::Agent {
            content: vec![ContentBlock::text(text)],
        };
        let tokens = msg.estimated_tokens();
        let message_index = self.messages.len();
        self.messages.push(msg);
        let timeline_index = self.timeline.len() as u64;
        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::AgentMessage {
            index: timeline_index,
            message_index,
            visible_id: Some(visible_id),
            model: self.current_model.clone(),
        });
        self.uncompacted_tokens += tokens;
        self.token_tracker.add_delta(tokens);
    }

    pub fn add_agent_message(&mut self, content: Vec<ContentBlock>) {
        let msg = StructuredMessage::Agent { content };
        let tokens = msg.estimated_tokens();
        let message_index = self.messages.len();
        self.messages.push(msg);
        let timeline_index = self.timeline.len() as u64;
        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::AgentMessage {
            index: timeline_index,
            message_index,
            visible_id: Some(visible_id),
            model: self.current_model.clone(),
        });
        self.uncompacted_tokens += tokens;
        self.token_tracker.add_delta(tokens);
    }

    /// Create the durable record for a tool call without updating token
    /// tracking.  Callers that need the delta recorded immediately should use
    /// [`propose_tool_call`]; stream processing defers delta until after the
    /// usage event to avoid losing it when `ProviderEvent::Usage` resets the
    /// baseline.
    pub fn propose_tool_call_without_delta(
        &mut self,
        call_id: impl Into<String>,
        tool_name: impl Into<String>,
        arguments: Value,
    ) -> usize {
        let call_id = call_id.into();
        let tool_name = tool_name.into();
        let record_index = self.tool_records.len();
        let timeline_index = self.timeline.len() as u64;

        self.tool_records.push(DurableToolRecord {
            call_id: call_id.clone(),
            tool_name: tool_name.clone(),
            arguments,
            status: ToolRecordStatus::PendingApproval,
            result: None,
            timeline_started_index: Some(timeline_index),
            timeline_terminal_index: None,
            parent_script_id: None,
        });

        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::ToolCallStarted {
            index: timeline_index,
            call_id,
            tool_name,
            tool_record_index: record_index,
            visible_id: Some(visible_id),
        });

        record_index
    }

    pub fn propose_tool_call(
        &mut self,
        call_id: impl Into<String>,
        tool_name: impl Into<String>,
        arguments: Value,
    ) -> usize {
        let record_index = self.propose_tool_call_without_delta(call_id, tool_name, arguments);
        let tool_tokens = estimate_tool_call_tokens(
            &self.tool_records[record_index].tool_name,
            &self.tool_records[record_index].arguments,
        );
        self.uncompacted_tokens += tool_tokens;
        self.token_tracker.add_delta(tool_tokens);
        record_index
    }

    pub fn start_tool_call(
        &mut self,
        call_id: impl Into<String>,
        tool_name: impl Into<String>,
        arguments: Value,
    ) -> usize {
        let call_id = call_id.into();
        let tool_name = tool_name.into();

        let existing = self.tool_records.iter().position(|r| r.call_id == call_id);
        if let Some(i) = existing {
            let record = &mut self.tool_records[i];
            record.status = ToolRecordStatus::Running;
            return i;
        }

        let record_index = self.tool_records.len();
        let timeline_index = self.timeline.len() as u64;

        self.tool_records.push(DurableToolRecord {
            call_id: call_id.clone(),
            tool_name: tool_name.clone(),
            arguments,
            status: ToolRecordStatus::Running,
            result: None,
            timeline_started_index: Some(timeline_index),
            timeline_terminal_index: None,
            parent_script_id: None,
        });

        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::ToolCallStarted {
            index: timeline_index,
            call_id,
            tool_name,
            tool_record_index: record_index,
            visible_id: Some(visible_id),
        });

        let tool_tokens = estimate_tool_call_tokens(
            &self.tool_records[record_index].tool_name,
            &self.tool_records[record_index].arguments,
        );
        self.uncompacted_tokens += tool_tokens;
        self.token_tracker.add_delta(tool_tokens);

        record_index
    }

    pub fn complete_tool_call(&mut self, call_id: &str, result: Value) {
        let idx = self.tool_records.iter().position(|r| r.call_id == call_id);
        if let Some(i) = idx {
            let (call_id_owned, tool_name_owned) = {
                let record = &self.tool_records[i];
                (record.call_id.clone(), record.tool_name.clone())
            };

            let record = &mut self.tool_records[i];
            record.status = ToolRecordStatus::Completed;
            record.result = Some(result);
            let timeline_index = self.timeline.len() as u64;
            record.timeline_terminal_index = Some(timeline_index);
            let tool_name = record.tool_name.clone();
            let result_ref = record.result.as_ref().unwrap().clone();

            let visible_id = self.next_visible_id();
            self.timeline.push(TimelineEntry::ToolCallTerminal {
                index: timeline_index,
                call_id: call_id_owned,
                tool_name: tool_name_owned,
                outcome: ToolTerminalOutcome::Completed,
                tool_record_index: i,
                visible_id: Some(visible_id),
            });

            let result_tokens = estimate_tool_result_tokens(&tool_name, &result_ref);
            self.uncompacted_tokens += result_tokens;
            self.token_tracker.add_delta(result_tokens);
        }
    }

    pub fn fail_tool_call(&mut self, call_id: &str, error: Value) {
        let idx = self.tool_records.iter().position(|r| r.call_id == call_id);
        if let Some(i) = idx {
            let (call_id_owned, tool_name_owned) = {
                let record = &self.tool_records[i];
                (record.call_id.clone(), record.tool_name.clone())
            };

            let record = &mut self.tool_records[i];
            record.status = ToolRecordStatus::Failed;
            record.result = Some(error);
            let timeline_index = self.timeline.len() as u64;
            record.timeline_terminal_index = Some(timeline_index);
            let tool_name = record.tool_name.clone();
            let result_ref = record.result.as_ref().unwrap().clone();

            let visible_id = self.next_visible_id();
            self.timeline.push(TimelineEntry::ToolCallTerminal {
                index: timeline_index,
                call_id: call_id_owned,
                tool_name: tool_name_owned,
                outcome: ToolTerminalOutcome::Failed,
                tool_record_index: i,
                visible_id: Some(visible_id),
            });

            let result_tokens = estimate_tool_result_tokens(&tool_name, &result_ref);
            self.uncompacted_tokens += result_tokens;
            self.token_tracker.add_delta(result_tokens);
        }
    }

    pub fn deny_tool_call(&mut self, call_id: &str) {
        let idx = self.tool_records.iter().position(|r| r.call_id == call_id);
        if let Some(i) = idx {
            let (call_id_owned, tool_name_owned) = {
                let record = &self.tool_records[i];
                (record.call_id.clone(), record.tool_name.clone())
            };

            let record = &mut self.tool_records[i];
            record.status = ToolRecordStatus::Denied;
            record.result = Some(serde_json::json!({"error": "denied by user"}));
            let timeline_index = self.timeline.len() as u64;
            record.timeline_terminal_index = Some(timeline_index);
            let tool_name = record.tool_name.clone();
            let result_ref = record.result.as_ref().unwrap().clone();

            let visible_id = self.next_visible_id();
            self.timeline.push(TimelineEntry::ToolCallTerminal {
                index: timeline_index,
                call_id: call_id_owned,
                tool_name: tool_name_owned,
                outcome: ToolTerminalOutcome::Denied,
                tool_record_index: i,
                visible_id: Some(visible_id),
            });

            let result_tokens = estimate_tool_result_tokens(&tool_name, &result_ref);
            self.uncompacted_tokens += result_tokens;
            self.token_tracker.add_delta(result_tokens);
        }
    }

    pub fn cancel_tool_call(&mut self, call_id: &str) {
        let idx = self.tool_records.iter().position(|r| r.call_id == call_id);
        if let Some(i) = idx {
            self.cancel_record_at(i, "cancelled");
        }
    }

    /// Transition every non-terminal tool record (`Running` or
    /// `PendingApproval`) to `Cancelled` atomically under the durable mutex.
    ///
    /// Why: the cancel path previously exited without tying off records whose
    /// tool futures were still in flight, so a subsequent resume or status
    /// query would observe a permanently-`Running` record. Because this method
    /// does not await, holding the durable mutex for its duration is safe and
    /// makes the transition atomic with respect to other session writes.
    ///
    /// Returns the list of `call_id`s that were transitioned, for logging.
    pub fn cancel_running_tool_calls(&mut self, reason: &str) -> Vec<String> {
        let indices: Vec<usize> = self
            .tool_records
            .iter()
            .enumerate()
            .filter_map(|(i, r)| {
                if matches!(
                    r.status,
                    ToolRecordStatus::Running | ToolRecordStatus::PendingApproval
                ) {
                    Some(i)
                } else {
                    None
                }
            })
            .collect();

        let mut cancelled = Vec::with_capacity(indices.len());
        for i in indices {
            let call_id = self.tool_records[i].call_id.clone();
            self.cancel_record_at(i, reason);
            cancelled.push(call_id);
        }
        cancelled
    }

    fn cancel_record_at(&mut self, i: usize, reason: &str) {
        let (call_id_owned, tool_name_owned) = {
            let record = &self.tool_records[i];
            if matches!(
                record.status,
                ToolRecordStatus::Completed
                    | ToolRecordStatus::Failed
                    | ToolRecordStatus::Denied
                    | ToolRecordStatus::Cancelled
            ) {
                return;
            }
            (record.call_id.clone(), record.tool_name.clone())
        };

        let record = &mut self.tool_records[i];
        record.status = ToolRecordStatus::Cancelled;
        record.result = Some(serde_json::json!({"error": reason}));
        let timeline_index = self.timeline.len() as u64;
        record.timeline_terminal_index = Some(timeline_index);
        let tool_name = record.tool_name.clone();
        let result_ref = record.result.as_ref().unwrap().clone();

        let visible_id = self.next_visible_id();
        self.timeline.push(TimelineEntry::ToolCallTerminal {
            index: timeline_index,
            call_id: call_id_owned,
            tool_name: tool_name_owned,
            outcome: ToolTerminalOutcome::Cancelled,
            tool_record_index: i,
            visible_id: Some(visible_id),
        });

        let result_tokens = estimate_tool_result_tokens(&tool_name, &result_ref);
        self.uncompacted_tokens += result_tokens;
        self.token_tracker.add_delta(result_tokens);
    }

    pub fn apply_compression(&mut self, block: crate::context::models::CompressedBlock) {
        self.compressed_blocks.push(block);
        self.uncompacted_tokens = 0;
        self.token_tracker.invalidate_baseline();
    }

    pub fn remove_timeline_positions(&mut self, positions: &BTreeSet<usize>) {
        if positions.is_empty() {
            return;
        }

        let retained_entries = self
            .timeline
            .iter()
            .enumerate()
            .filter_map(|(idx, entry)| {
                if positions.contains(&idx) {
                    None
                } else {
                    Some(entry.clone())
                }
            })
            .collect::<Vec<_>>();

        let mut message_map = BTreeMap::new();
        let mut messages = Vec::new();
        for entry in &retained_entries {
            let old_message_index = match entry {
                TimelineEntry::UserMessage { message_index, .. }
                | TimelineEntry::AgentMessage { message_index, .. } => Some(*message_index),
                _ => None,
            };
            if let Some(old_index) = old_message_index {
                if let Entry::Vacant(entry) = message_map.entry(old_index) {
                    if let Some(message) = self.messages.get(old_index).cloned() {
                        let new_index = messages.len();
                        messages.push(message);
                        entry.insert(new_index);
                    }
                }
            }
        }

        let mut tool_record_map = BTreeMap::new();
        let mut tool_records = Vec::new();
        for entry in &retained_entries {
            if let Some(old_index) = entry.tool_record_index() {
                if let Entry::Vacant(entry) = tool_record_map.entry(old_index) {
                    if let Some(record) = self.tool_records.get(old_index).cloned() {
                        let new_index = tool_records.len();
                        tool_records.push(record);
                        entry.insert(new_index);
                    }
                }
            }
        }

        let mut timeline = Vec::new();
        for (new_index, entry) in retained_entries.into_iter().enumerate() {
            let index = new_index as u64;
            match entry {
                TimelineEntry::UserMessage {
                    message_index,
                    visible_id,
                    model,
                    ..
                } => {
                    if let Some(mapped) = message_map.get(&message_index).copied() {
                        timeline.push(TimelineEntry::UserMessage {
                            index,
                            message_index: mapped,
                            visible_id,
                            model,
                        });
                    }
                }
                TimelineEntry::AgentMessage {
                    message_index,
                    visible_id,
                    model,
                    ..
                } => {
                    if let Some(mapped) = message_map.get(&message_index).copied() {
                        timeline.push(TimelineEntry::AgentMessage {
                            index,
                            message_index: mapped,
                            visible_id,
                            model,
                        });
                    }
                }
                TimelineEntry::ToolCallStarted {
                    call_id,
                    tool_name,
                    tool_record_index,
                    visible_id,
                    ..
                } => {
                    if let Some(mapped) = tool_record_map.get(&tool_record_index).copied() {
                        timeline.push(TimelineEntry::ToolCallStarted {
                            index,
                            call_id,
                            tool_name,
                            tool_record_index: mapped,
                            visible_id,
                        });
                    }
                }
                TimelineEntry::ToolCallTerminal {
                    call_id,
                    tool_name,
                    outcome,
                    tool_record_index,
                    visible_id,
                    ..
                } => {
                    if let Some(mapped) = tool_record_map.get(&tool_record_index).copied() {
                        timeline.push(TimelineEntry::ToolCallTerminal {
                            index,
                            call_id,
                            tool_name,
                            outcome,
                            tool_record_index: mapped,
                            visible_id,
                        });
                    }
                }
                TimelineEntry::ModelSwitched {
                    from_model,
                    to_model,
                    from_provider,
                    to_provider,
                    adapted,
                    visible_id,
                    ..
                } => {
                    timeline.push(TimelineEntry::ModelSwitched {
                        index,
                        from_model,
                        to_model,
                        from_provider,
                        to_provider,
                        adapted,
                        visible_id,
                    });
                }
            }
        }

        for record in &mut tool_records {
            record.timeline_started_index = None;
            record.timeline_terminal_index = None;
        }
        for entry in &timeline {
            match entry {
                TimelineEntry::ToolCallStarted {
                    index,
                    tool_record_index,
                    ..
                } => tool_records[*tool_record_index].timeline_started_index = Some(*index),
                TimelineEntry::ToolCallTerminal {
                    index,
                    tool_record_index,
                    ..
                } => tool_records[*tool_record_index].timeline_terminal_index = Some(*index),
                _ => {}
            }
        }

        self.messages = messages;
        self.tool_records = tool_records;
        self.timeline = timeline;
        self.token_tracker.invalidate_baseline();
    }

    pub fn reset_uncompacted_tokens(&mut self) {
        self.uncompacted_tokens = 0;
    }

    pub fn is_idle(&self) -> bool {
        !self.tool_records.iter().any(|r| {
            matches!(
                r.status,
                ToolRecordStatus::PendingApproval | ToolRecordStatus::Running
            )
        })
    }

    // -- Skill activation helpers --

    pub fn activate_skill(
        &mut self,
        name: impl Into<String>,
        body: impl Into<String>,
        resources: Vec<crate::skill::SkillResourceEntry>,
    ) {
        let record = crate::skill::ActivatedSkillRecord {
            name: name.into(),
            body: body.into(),
            resources,
        };
        self.skill_state.activate(record);
        self.token_tracker.invalidate_baseline();
    }

    pub fn deactivate_skill(&mut self, name: &str) {
        self.skill_state.deactivate(name);
        self.token_tracker.invalidate_baseline();
    }

    pub fn list_active_skills(&self) -> Vec<&str> {
        self.skill_state.active_names()
    }

    pub fn active_skill_instructions(&self) -> String {
        self.skill_state.active_skill_instructions()
    }

    pub fn is_skill_active(&self, name: &str) -> bool {
        self.skill_state.is_active(name)
    }

    pub fn set_available_skills(&mut self, skills: Vec<crate::skill::LoadedSkill>) {
        self.available_skills = skills;
    }

    pub fn list_available_skills(&self) -> &[crate::skill::LoadedSkill] {
        &self.available_skills
    }

    pub fn load_available_skill(&self, name: &str) -> Option<crate::skill::LoadedSkill> {
        self.available_skills
            .iter()
            .find(|skill| skill.metadata.id == name)
            .cloned()
    }

    // -- Workspace root helpers --

    pub fn active_workspace_roots(&self) -> &[std::path::PathBuf] {
        &self.workspace_roots
    }

    pub fn set_pending_workspace_roots(&mut self, roots: Vec<std::path::PathBuf>) {
        self.pending_workspace_roots = Some(roots);
    }

    pub fn clear_pending_workspace_roots(&mut self) {
        self.pending_workspace_roots = None;
    }

    pub fn apply_pending_workspace_roots(&mut self) -> bool {
        if let Some(roots) = self.pending_workspace_roots.take() {
            self.workspace_roots = roots;
            self.token_tracker.invalidate_baseline();
            true
        } else {
            false
        }
    }

    pub fn to_transcript(&self) -> iron_providers::Transcript {
        self.to_transcript_with_visible_ids(false)
    }

    pub fn to_transcript_with_visible_ids(
        &self,
        include_visible_ids: bool,
    ) -> iron_providers::Transcript {
        let mut provider_messages = Vec::new();

        for entry in &self.timeline {
            match entry {
                TimelineEntry::UserMessage { message_index, .. } => {
                    if let Some(StructuredMessage::User { content }) =
                        self.messages.get(*message_index)
                    {
                        let text = content
                            .iter()
                            .filter_map(|b| b.to_text())
                            .collect::<Vec<_>>()
                            .join("");
                        provider_messages.push(iron_providers::Message::User {
                            content: render_with_visible_id(entry, text, include_visible_ids),
                        });
                    }
                }
                TimelineEntry::AgentMessage { message_index, .. } => {
                    if let Some(StructuredMessage::Agent { content }) =
                        self.messages.get(*message_index)
                    {
                        let text = content
                            .iter()
                            .filter_map(|b| b.to_text())
                            .collect::<Vec<_>>()
                            .join("");
                        provider_messages.push(iron_providers::Message::Assistant {
                            content: render_with_visible_id(entry, text, include_visible_ids),
                        });
                    }
                }
                TimelineEntry::ToolCallStarted {
                    tool_record_index, ..
                } => {
                    if let Some(record) = self.tool_records.get(*tool_record_index) {
                        provider_messages.push(iron_providers::Message::AssistantToolCall {
                            call_id: record.call_id.clone(),
                            tool_name: record.tool_name.clone(),
                            arguments: record.arguments.clone(),
                        });
                    }
                }
                TimelineEntry::ToolCallTerminal {
                    tool_record_index, ..
                } => {
                    if let Some(record) = self.tool_records.get(*tool_record_index) {
                        if record.status.is_terminal() {
                            let result = record
                                .result
                                .clone()
                                .unwrap_or(serde_json::json!({"error": "no result"}));
                            provider_messages.push(iron_providers::Message::Tool {
                                call_id: record.call_id.clone(),
                                tool_name: record.tool_name.clone(),
                                result,
                            });
                        }
                    }
                }
                TimelineEntry::ModelSwitched { .. } => {
                    // Model switches are metadata, not provider-facing messages.
                    // They are intentionally excluded from the transcript sent to
                    // inference providers to avoid confusing the model with synthetic
                    // boundary markers. Switch history is available via
                    // DurableSession::model_switch_history for client-side rendering.
                }
            }
        }

        iron_providers::Transcript::with_messages(provider_messages)
    }

    pub fn is_empty(&self) -> bool {
        self.messages.is_empty() && self.tool_records.is_empty()
    }

    pub fn set_instructions(&mut self, instructions: impl Into<String>) {
        self.instructions = Some(instructions.into());
        self.token_tracker.invalidate_baseline();
    }

    pub fn set_profile_identity(&mut self, identity: impl Into<String>) {
        let value = identity.into();
        if value.trim().is_empty() {
            self.profile_identity = None;
        } else {
            self.profile_identity = Some(value);
        }
        self.token_tracker.invalidate_baseline();
    }

    /// Combine rendered identity and explicit session instructions for token
    /// accounting. This mirrors system prompt rendering: a missing or blank
    /// profile identity still renders the core fallback identity in Section 1.
    pub fn instruction_text_for_estimate(&self) -> Option<String> {
        let identity = self
            .profile_identity
            .as_deref()
            .filter(|identity| !identity.trim().is_empty())
            .unwrap_or(crate::prompt::system::DEFAULT_RENDERED_IDENTITY);

        match self.instructions.as_deref() {
            None => Some(identity.to_string()),
            Some(instructions) => Some(format!("{}\n\n{}", identity, instructions)),
        }
    }

    pub fn record_script_start(
        &mut self,
        script_id: impl Into<String>,
        call_id: impl Into<String>,
        source: impl Into<String>,
        input: Option<Value>,
    ) {
        self.script_records
            .push(DurableScriptRecord::new(script_id, call_id, source, input));
    }

    pub fn record_script_complete(
        &mut self,
        script_id: &str,
        result: Value,
        child_call_ids: Vec<String>,
    ) {
        if let Some(rec) = self
            .script_records
            .iter_mut()
            .find(|r| r.script_id == script_id)
        {
            rec.complete(result, child_call_ids);
        }
    }

    pub fn record_script_complete_with_failures(
        &mut self,
        script_id: &str,
        result: Value,
        child_call_ids: Vec<String>,
    ) {
        if let Some(rec) = self
            .script_records
            .iter_mut()
            .find(|r| r.script_id == script_id)
        {
            rec.complete_with_failures(result, child_call_ids);
        }
    }

    pub fn record_script_failed(&mut self, script_id: &str, error: Value) {
        if let Some(rec) = self
            .script_records
            .iter_mut()
            .find(|r| r.script_id == script_id)
        {
            rec.fail(error, Vec::new());
        }
    }

    pub fn record_script_cancelled(&mut self, script_id: &str) {
        if let Some(rec) = self
            .script_records
            .iter_mut()
            .find(|r| r.script_id == script_id)
        {
            rec.cancel();
        }
    }

    pub fn link_child_to_script(&mut self, script_id: &str, child_call_id: &str) {
        if let Some(rec) = self
            .script_records
            .iter_mut()
            .find(|r| r.script_id == script_id)
        {
            rec.child_call_ids.push(child_call_id.to_string());
        }
        if let Some(tool_rec) = self
            .tool_records
            .iter_mut()
            .find(|r| r.call_id == child_call_id)
        {
            tool_rec.parent_script_id = Some(script_id.to_string());
        }
    }

    /// Enable or disable an MCP server for this session.
    pub fn set_mcp_server_enabled(&mut self, server_id: impl Into<String>, enabled: bool) {
        self.mcp_server_enablement.insert(server_id.into(), enabled);
        self.token_tracker.invalidate_baseline();
    }

    /// Check if an MCP server is enabled for this session.
    /// Returns None if not explicitly set.
    pub fn is_mcp_server_enabled(&self, server_id: &str) -> Option<bool> {
        self.mcp_server_enablement.get(server_id).copied()
    }

    /// Get list of MCP server IDs that are enabled for this session.
    pub fn list_enabled_mcp_servers(&self) -> Vec<String> {
        self.mcp_server_enablement
            .iter()
            .filter(|&(_, enabled)| *enabled)
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Enable or disable a plugin for this session.
    pub fn set_plugin_enabled(&mut self, plugin_id: impl Into<String>, enabled: bool) {
        self.plugin_enablement.set_enabled(plugin_id, enabled);
        self.token_tracker.invalidate_baseline();
    }

    /// Check if a plugin is enabled for this session.
    /// Returns None if not explicitly set.
    pub fn is_plugin_enabled(&self, plugin_id: &str) -> Option<bool> {
        self.plugin_enablement.is_enabled(plugin_id)
    }

    /// Get list of plugin IDs that are enabled for this session.
    pub fn list_enabled_plugins(&self) -> Vec<String> {
        self.plugin_enablement.list_enabled()
    }
}

pub type SharedDurableSession = std::sync::Arc<parking_lot::Mutex<DurableSession>>;

fn render_with_visible_id(
    entry: &TimelineEntry,
    text: String,
    include_visible_ids: bool,
) -> String {
    if include_visible_ids {
        if let Some(id) = entry.visible_id() {
            return format!("<{}>\n{}", id, text);
        }
    }
    text
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fresh_session() -> DurableSession {
        DurableSession::new(SessionId(1))
    }

    #[test]
    fn cancel_running_transitions_running_and_pending() {
        let mut s = fresh_session();
        s.start_tool_call("a", "tool_a", serde_json::json!({}));
        s.start_tool_call("b", "tool_b", serde_json::json!({}));
        // Flip b to PendingApproval via request_tool_approval if exposed,
        // otherwise set directly for the test.
        s.tool_records[1].status = ToolRecordStatus::PendingApproval;

        let cancelled = s.cancel_running_tool_calls("cancelled");
        assert_eq!(cancelled.len(), 2);
        assert!(cancelled.contains(&"a".to_string()));
        assert!(cancelled.contains(&"b".to_string()));

        for record in &s.tool_records {
            assert!(matches!(record.status, ToolRecordStatus::Cancelled));
            assert!(record.timeline_terminal_index.is_some());
        }
    }

    #[test]
    fn cancel_running_skips_already_terminal_records() {
        let mut s = fresh_session();
        s.start_tool_call("done", "t", serde_json::json!({}));
        s.complete_tool_call("done", serde_json::json!({"ok": true}));

        s.start_tool_call("running", "t", serde_json::json!({}));

        let cancelled = s.cancel_running_tool_calls("cancelled");
        assert_eq!(cancelled, vec!["running".to_string()]);

        // Completed record unchanged.
        let done = s.tool_records.iter().find(|r| r.call_id == "done").unwrap();
        assert!(matches!(done.status, ToolRecordStatus::Completed));
    }

    #[test]
    fn cancel_running_with_no_running_is_noop() {
        let mut s = fresh_session();
        let cancelled = s.cancel_running_tool_calls("cancelled");
        assert!(cancelled.is_empty());
    }

    #[test]
    fn cancel_running_leaves_no_running_records_after() {
        let mut s = fresh_session();
        for i in 0..5 {
            s.start_tool_call(format!("c{}", i), "t", serde_json::json!({}));
        }
        s.cancel_running_tool_calls("cancelled");
        for record in &s.tool_records {
            assert!(
                !matches!(
                    record.status,
                    ToolRecordStatus::Running | ToolRecordStatus::PendingApproval
                ),
                "record {} left in non-terminal state after cancel",
                record.call_id
            );
        }
    }
}