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
1680
1681
1682
1683
1684
1685
1686
//! Durable, serializable session state and its lifecycle transitions.
//!
//! A [`DurableSession`] owns conversation messages, tool and script records,
//! timeline metadata, compacted summaries, model-switch history, and
//! session-scoped configuration. Transient work for an active turn belongs in
//! [`crate::ephemeral::EphemeralTurn`]. Provider usage establishes a token
//! baseline; newly appended visible content adds local deltas, while context
//! rewrites invalidate that baseline.
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};
/// Process-local numeric identity for a durable session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SessionId(
/// Numeric session identifier.
pub u64,
);
impl SessionId {
/// Allocates the next process-local session identifier.
///
/// Identifiers begin at one and are unique until the underlying counter
/// wraps. Deserializing an identifier does not advance the allocator.
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)
}
}
/// Structured user or agent content retained by a durable session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum StructuredMessage {
/// Content supplied by the user.
User {
/// Ordered content blocks in the message.
content: Vec<ContentBlock>,
},
/// Content produced by the agent.
Agent {
/// Ordered content blocks in the message.
content: Vec<ContentBlock>,
},
}
/// Serializable content retained in a structured message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
/// Plain text content.
Text {
/// Text payload.
text: String,
},
/// Encoded image content.
Image {
/// Encoded image data.
data: String,
/// Media type describing `data`.
mime_type: String,
},
/// Link to an external resource.
Resource {
/// Resource URI.
uri: String,
/// Optional display name.
name: Option<String>,
},
}
impl ContentBlock {
/// Creates a text content block.
pub fn text(text: impl Into<String>) -> Self {
Self::Text { text: text.into() }
}
/// Returns the text payload, or `None` for non-text content.
pub fn to_text(&self) -> Option<&str> {
match self {
ContentBlock::Text { text } => Some(text),
_ => None,
}
}
/// Converts an ACP content block into durable content.
///
/// ACP variants without a durable representation become the literal text
/// `[unsupported content]`.
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 {
/// Creates a user message containing one text block.
pub fn user_text(text: impl Into<String>) -> Self {
Self::User {
content: vec![ContentBlock::text(text)],
}
}
/// Creates an agent message containing one text block.
pub fn agent_text(text: impl Into<String>) -> Self {
Self::Agent {
content: vec![ContentBlock::text(text)],
}
}
/// Concatenates all text blocks, omitting images and resources.
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("")
}
/// Returns whether this is a user message.
pub fn is_user(&self) -> bool {
matches!(self, Self::User { .. })
}
/// Returns whether this is an agent message.
pub fn is_agent(&self) -> bool {
matches!(self, Self::Agent { .. })
}
/// Borrows the ordered content blocks regardless of message role.
pub fn content_blocks(&self) -> &[ContentBlock] {
match self {
Self::User { content } => content,
Self::Agent { content } => content,
}
}
/// Estimates text tokens at one token per four UTF-8 bytes, rounded up.
///
/// Non-text blocks do not contribute to this estimate.
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
}
/// Estimates tokens for a serialized tool name and argument payload.
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))
}
/// Ordered metadata linking durable messages, tools, and model switches.
///
/// `index` values are positions in the current timeline and may be rewritten
/// by compaction. `visible_id` values are stable user-facing range selectors.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TimelineEntry {
/// A user message retained in the session.
UserMessage {
/// Current zero-based timeline position.
index: u64,
/// Index into [`DurableSession::messages`].
message_index: usize,
/// Stable user-facing identifier used by compaction ranges.
#[serde(skip_serializing_if = "Option::is_none")]
visible_id: Option<String>,
/// Model active when the message was recorded.
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
},
/// An agent message retained in the session.
AgentMessage {
/// Current zero-based timeline position.
index: u64,
/// Index into [`DurableSession::messages`].
message_index: usize,
/// Stable user-facing identifier used by compaction ranges.
#[serde(skip_serializing_if = "Option::is_none")]
visible_id: Option<String>,
/// Model active when the message was recorded.
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
},
/// Start boundary of a tool-call lifecycle.
ToolCallStarted {
/// Current zero-based timeline position.
index: u64,
/// Provider-assigned tool-call identifier.
call_id: String,
/// Requested tool name.
tool_name: String,
/// Index into [`DurableSession::tool_records`].
tool_record_index: usize,
/// Stable user-facing identifier used by compaction ranges.
#[serde(skip_serializing_if = "Option::is_none")]
visible_id: Option<String>,
},
/// Terminal boundary of a tool-call lifecycle.
ToolCallTerminal {
/// Current zero-based timeline position.
index: u64,
/// Provider-assigned tool-call identifier.
call_id: String,
/// Requested tool name.
tool_name: String,
/// Terminal outcome represented by this boundary.
outcome: ToolTerminalOutcome,
/// Index into [`DurableSession::tool_records`].
tool_record_index: usize,
/// Stable user-facing identifier used by compaction ranges.
#[serde(skip_serializing_if = "Option::is_none")]
visible_id: Option<String>,
},
/// Metadata boundary recording an applied model switch.
///
/// This entry is excluded from provider transcripts.
ModelSwitched {
/// Current zero-based timeline position.
index: u64,
/// Model active before the switch.
from_model: String,
/// Model active after the switch.
to_model: String,
/// Provider active before the switch, if known.
#[serde(skip_serializing_if = "Option::is_none")]
from_provider: Option<String>,
/// Provider active after the switch, if known.
#[serde(skip_serializing_if = "Option::is_none")]
to_provider: Option<String>,
/// Whether context or capabilities were adapted for the target.
adapted: bool,
/// Optional stable user-facing identifier.
#[serde(skip_serializing_if = "Option::is_none")]
visible_id: Option<String>,
},
}
impl TimelineEntry {
/// Returns the entry's current timeline position.
pub fn index(&self) -> u64 {
match self {
Self::UserMessage { index, .. }
| Self::AgentMessage { index, .. }
| Self::ToolCallStarted { index, .. }
| Self::ToolCallTerminal { index, .. }
| Self::ModelSwitched { index, .. } => *index,
}
}
/// Borrows the stable user-facing identifier, when assigned.
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(),
}
}
/// Assigns or replaces the stable user-facing identifier.
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);
}
}
}
/// Returns the linked tool-record index for tool lifecycle entries.
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,
}
}
/// Returns whether this entry records a model switch.
pub fn is_model_switched(&self) -> bool {
matches!(self, Self::ModelSwitched { .. })
}
}
/// Terminal state represented by a tool timeline boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum ToolTerminalOutcome {
/// The tool returned successfully.
Completed,
/// Tool execution failed.
Failed,
/// Permission to run the tool was denied.
Denied,
/// The tool call was cancelled.
Cancelled,
}
/// Durable state and timeline links for one tool call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableToolRecord {
/// Provider-assigned call identifier.
pub call_id: String,
/// Requested tool name.
pub tool_name: String,
/// Arguments supplied to the tool.
pub arguments: Value,
/// Current lifecycle state.
pub status: ToolRecordStatus,
/// Terminal result or error payload, when available.
pub result: Option<Value>,
/// Timeline index at which the call was proposed or started.
pub timeline_started_index: Option<u64>,
/// Timeline index at which the call became terminal.
pub timeline_terminal_index: Option<u64>,
/// Script record that owns this child call, when linked.
pub parent_script_id: Option<String>,
}
/// Durable state for a script that may own multiple child tool calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableScriptRecord {
/// Stable script execution identifier.
pub script_id: String,
/// Tool call that launched the script.
pub parent_call_id: String,
/// Source text executed by the script tool.
pub script_source: String,
/// Optional script input payload.
pub input: Option<Value>,
/// Current script lifecycle state.
pub status: ScriptRecordStatus,
/// Successful or partial result payload.
pub result: Option<Value>,
/// Failure payload.
pub error: Option<Value>,
/// Tool-call identifiers launched by the script.
pub child_call_ids: Vec<String>,
}
/// Lifecycle state of a durable script execution.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ScriptRecordStatus {
/// Script execution is active.
Running,
/// Script and all relevant children completed successfully.
Completed,
/// Script produced a result while one or more children failed.
CompletedWithFailures,
/// Script execution failed.
Failed,
/// Script execution was cancelled.
Cancelled,
}
impl DurableScriptRecord {
/// Creates a running script record with no result, error, or children.
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(),
}
}
/// Marks the script completed and replaces its result and child list.
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;
}
/// Marks the script completed with child failures and stores its result.
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;
}
/// Marks the script failed and stores its error and child list.
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;
}
/// Marks the script cancelled without clearing prior result fields.
pub fn cancel(&mut self) {
self.status = ScriptRecordStatus::Cancelled;
}
/// Returns whether the script has reached any terminal state.
pub fn is_terminal(&self) -> bool {
matches!(
self.status,
ScriptRecordStatus::Completed
| ScriptRecordStatus::CompletedWithFailures
| ScriptRecordStatus::Failed
| ScriptRecordStatus::Cancelled
)
}
}
/// Lifecycle state of a durable tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ToolRecordStatus {
/// The call is recorded but awaits a permission decision.
PendingApproval,
/// Tool execution is active.
Running,
/// Tool execution returned successfully.
Completed,
/// Tool execution failed.
Failed,
/// Permission to execute was denied.
Denied,
/// The call was cancelled before normal completion.
Cancelled,
}
impl ToolRecordStatus {
/// Returns whether no further lifecycle transition is expected.
pub fn is_terminal(&self) -> bool {
matches!(
self,
Self::Completed | Self::Failed | Self::Denied | Self::Cancelled
)
}
/// Maps a terminal status to its timeline outcome.
///
/// Returns `None` for pending and running calls.
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,
}
}
}
/// Serializable owner of durable state for one agent session.
///
/// Messages and tool records are stored separately from their ordered
/// [`TimelineEntry`] links. Compaction may remove and reindex those stores while
/// preserving stable visible IDs for retained entries. [`Self::token_tracker`]
/// is runtime-only and is skipped during serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableSession {
/// Stable identity of this session.
pub id: SessionId,
/// Structured user and agent message storage referenced by the timeline.
pub messages: Vec<StructuredMessage>,
/// Tool lifecycle records referenced by tool timeline entries.
pub tool_records: Vec<DurableToolRecord>,
/// Ordered provider-facing history and model-switch metadata.
pub timeline: Vec<TimelineEntry>,
/// Script lifecycle records and their child tool links.
pub script_records: Vec<DurableScriptRecord>,
/// Explicit session instructions, excluding rendered profile identity.
pub instructions: Option<String>,
/// Optional serialized description of the session workspace scope.
pub workspace_scope: Option<String>,
/// Durable summaries that replace compacted context ranges.
#[serde(default)]
pub compressed_blocks: Vec<crate::context::models::CompressedBlock>,
/// Heuristic token count added since the last compaction reset.
#[serde(default)]
pub uncompacted_tokens: usize,
/// Resolved repository instructions included in prompt construction.
#[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.
#[serde(default)]
pub current_provider_slug: Option<String>,
/// Optional API key for the current managed provider.
///
/// Stored in a [`crate::secret::SecretString`] so the value is redacted from
/// debug output while still serializing for durable persistence and handoff.
#[serde(default)]
pub current_provider_api_key: Option<crate::secret::SecretString>,
/// History of applied model switches for this session.
#[serde(default)]
pub model_switch_history: Vec<crate::context::model_switch::ModelSwitchRecord>,
/// Tools hidden due to current-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>,
/// Runtime token baseline and accumulated provider usage.
///
/// This field is not serialized; a restored session starts without a
/// provider baseline and must use heuristic accounting until resynchronized.
#[serde(skip, default)]
pub token_tracker: crate::context::SessionTokenTracker,
}
impl DurableSession {
/// Creates an empty durable session with the supplied identity.
///
/// Visible timeline IDs begin at `m0001`, and token accounting starts with
/// no provider baseline.
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(),
}
}
/// Allocates the next stable visible timeline ID.
pub fn next_visible_id(&mut self) -> String {
let id = format!("m{:04}", self.next_visible_id);
self.next_visible_id += 1;
id
}
/// Appends a one-block user message and records its estimated token delta.
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);
}
/// Appends a structured user message and records its text token delta.
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);
}
/// Appends a one-block agent message and records its estimated token delta.
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);
}
/// Appends a structured agent message and records its text token delta.
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
/// [`Self::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
}
/// Records a tool call pending approval and accounts for its arguments.
///
/// Returns the new record's index. Use
/// [`Self::propose_tool_call_without_delta`] when provider usage ordering
/// requires the local token delta to be applied later.
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
}
/// Marks an existing call running or creates a new running call.
///
/// An existing record is selected by `call_id`; only its status changes and
/// no timeline entry or token delta is added. A new call receives a start
/// entry and contributes its estimated arguments to token accounting.
/// Returns the record index in either case.
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
}
/// Completes the first tool record matching `call_id`.
///
/// The result is stored, a terminal timeline entry is appended, and its
/// estimated token delta is recorded. An unknown ID is a no-op.
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);
}
}
/// Fails the first tool record matching `call_id`.
///
/// The error is stored as the record result, a terminal timeline entry is
/// appended, and its estimated token delta is recorded. An unknown ID is a
/// no-op.
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);
}
}
/// Denies the first tool record matching `call_id`.
///
/// A synthetic denial result and terminal timeline entry are added to the
/// provider-visible context. An unknown ID is a no-op.
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);
}
}
/// Cancels the first tool record matching `call_id` if it is non-terminal.
///
/// Cancellation adds a synthetic result and token delta. Unknown or
/// already terminal records are unchanged.
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");
}
}
/// Transitions every non-terminal tool record to `Cancelled`.
///
/// Each transition appends a terminal timeline result and token delta.
/// The returned IDs preserve tool-record order. Callers holding the shared
/// durable mutex can perform the whole operation without an await point.
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);
}
/// Appends an externally created compressed block and resets compaction age.
///
/// This helper does not remove source timeline entries. It resets
/// `uncompacted_tokens` and invalidates provider-baseline accounting because
/// adding the rendered block changes provider-visible context.
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();
}
/// Removes selected timeline positions and rebuilds referenced storage.
///
/// Retained messages and tool records are compacted into new vectors;
/// timeline indexes and tool boundary indexes are rewritten accordingly.
/// Script records are unaffected. Invalid positions are ignored, and a
/// nonempty request invalidates the provider token 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();
}
/// Resets the heuristic count of tokens added since compaction.
///
/// This does not alter provider baseline/delta accounting.
pub fn reset_uncompacted_tokens(&mut self) {
self.uncompacted_tokens = 0;
}
/// Returns whether no tool call is pending approval or running.
pub fn is_idle(&self) -> bool {
!self.tool_records.iter().any(|r| {
matches!(
r.status,
ToolRecordStatus::PendingApproval | ToolRecordStatus::Running
)
})
}
// -- Skill activation helpers --
/// Activates or replaces a session skill and invalidates token baseline.
///
/// Active skill instructions are provider-visible prompt content.
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();
}
/// Deactivates a named skill and invalidates token baseline.
pub fn deactivate_skill(&mut self, name: &str) {
self.skill_state.deactivate(name);
self.token_tracker.invalidate_baseline();
}
/// Returns active skill names in session-defined order.
pub fn list_active_skills(&self) -> Vec<&str> {
self.skill_state.active_names()
}
/// Renders all active skill instructions for prompt inclusion.
pub fn active_skill_instructions(&self) -> String {
self.skill_state.active_skill_instructions()
}
/// Returns whether a skill with `name` is active.
pub fn is_skill_active(&self, name: &str) -> bool {
self.skill_state.is_active(name)
}
/// Replaces the session snapshot of skills available for activation.
pub fn set_available_skills(&mut self, skills: Vec<crate::skill::LoadedSkill>) {
self.available_skills = skills;
}
/// Borrows the session snapshot of available skills.
pub fn list_available_skills(&self) -> &[crate::skill::LoadedSkill] {
&self.available_skills
}
/// Clones an available skill whose metadata ID matches `name`.
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 --
/// Borrows workspace roots active for the current turn.
pub fn active_workspace_roots(&self) -> &[std::path::PathBuf] {
&self.workspace_roots
}
/// Stages replacement workspace roots for the next turn boundary.
pub fn set_pending_workspace_roots(&mut self, roots: Vec<std::path::PathBuf>) {
self.pending_workspace_roots = Some(roots);
}
/// Discards workspace roots staged for the next turn boundary.
pub fn clear_pending_workspace_roots(&mut self) {
self.pending_workspace_roots = None;
}
/// Applies staged workspace roots at a turn boundary.
///
/// Returns whether roots were staged. Applying them invalidates provider
/// token accounting because workspace-derived prompt context may change.
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
}
}
/// Builds a provider transcript without stable visible-ID prefixes.
///
/// Model-switch entries are metadata and are omitted.
pub fn to_transcript(&self) -> iron_providers::Transcript {
self.to_transcript_with_visible_ids(false)
}
/// Builds a provider transcript from the ordered durable timeline.
///
/// When `include_visible_ids` is true, text messages are prefixed with
/// their stable IDs. Non-text message blocks are omitted, terminal tool
/// records become tool messages, and model-switch metadata is excluded.
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)
}
/// Returns whether the session has no messages or tool records.
///
/// Compressed blocks, scripts, and model-switch metadata do not affect this
/// predicate.
pub fn is_empty(&self) -> bool {
self.messages.is_empty() && self.tool_records.is_empty()
}
/// Replaces explicit session instructions and invalidates token baseline.
pub fn set_instructions(&mut self, instructions: impl Into<String>) {
self.instructions = Some(instructions.into());
self.token_tracker.invalidate_baseline();
}
/// Sets the profile identity, treating blank text as absent.
///
/// The rendered identity is provider-visible, so this invalidates token
/// baseline accounting.
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)),
}
}
/// Starts a durable script record linked to its launching tool call.
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));
}
/// Completes the first script record matching `script_id`.
///
/// An unknown ID is a no-op.
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);
}
}
/// Completes a matching script while recording child-call failures.
///
/// An unknown ID is a no-op.
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);
}
}
/// Fails the first script record matching `script_id`.
///
/// This convenience path records an empty child-call list. An unknown ID is
/// a no-op.
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());
}
}
/// Cancels the first script record matching `script_id`.
///
/// An unknown ID is a no-op.
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();
}
}
/// Links a child tool call to a script in both durable records.
///
/// Either side is updated independently when present. Existing child links
/// are not deduplicated.
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());
}
}
/// Enables or disables an MCP server for this session.
///
/// MCP tool definitions affect provider-visible context, so changing this
/// state invalidates token baseline accounting.
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();
}
/// Returns explicit MCP server enablement, or `None` when unset.
pub fn is_mcp_server_enabled(&self, server_id: &str) -> Option<bool> {
self.mcp_server_enablement.get(server_id).copied()
}
/// Returns IDs of MCP servers explicitly 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()
}
/// Enables or disables a plugin and invalidates token baseline accounting.
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();
}
/// Returns explicit plugin enablement, or `None` when unset.
pub fn is_plugin_enabled(&self, plugin_id: &str) -> Option<bool> {
self.plugin_enablement.is_enabled(plugin_id)
}
/// Returns IDs of plugins explicitly enabled for this session.
pub fn list_enabled_plugins(&self) -> Vec<String> {
self.plugin_enablement.list_enabled()
}
}
/// Shared, synchronously locked ownership of a [`DurableSession`].
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
);
}
}
}