fm-rs 0.3.0

Rust bindings for Apple's FoundationModels.framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
//! Session management for `FoundationModels`.
//!
//! A session maintains conversation context between requests.

use std::collections::{HashMap, HashSet};
use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::ptr::{self, NonNull};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::context::{ContextLimit, ContextUsage, context_usage_from_transcript};
use crate::error::{Error, Result};
use crate::ffi::{self, SwiftPtr};
use crate::model::{LanguageModel, error_from_parts, error_from_swift};
use crate::options::{GenerationOptions, ReasoningLevel};
use crate::tool::{Tool, ToolResult, tools_to_json};

/// Type alias for the tool map used in sessions.
type ToolMapInner = HashMap<String, Arc<dyn Tool>>;

/// Callback data shared between the session and tool callbacks.
///
/// Lifetime is reference-counted from both sides: the `Session` holds one
/// strong reference and Swift's `ToolDispatcher` holds another. Any in-flight
/// callback runs inside a dispatcher method, so ARC keeps this alive for the
/// duration of every callback — no additional handshake is needed.
struct ToolCallbackData {
    tools: Mutex<ToolMapInner>,
}

/// Release the [`ToolCallbackData`] strong reference handed to Swift.
///
/// `Session::create_internal` gives Swift ownership of one `Arc` clone via
/// `Arc::into_raw`, so something has to give it back. `ToolDispatcher.deinit`
/// calls this when the dispatcher is deallocated.
///
/// # Safety
///
/// `user_data` must be null, or a pointer from `Arc::into_raw` on an
/// `Arc<ToolCallbackData>` that has not already been reclaimed. Swift calls
/// this exactly once per dispatcher, from `deinit`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fm_rust_tool_data_free(user_data: *mut c_void) {
    if user_data.is_null() {
        return;
    }
    // Drops the dispatcher's strong reference — the only one on the success
    // path — freeing the allocation and every `Arc<dyn Tool>` in its map.
    // A user tool's Drop may panic; catch it rather than unwinding into
    // Swift's deinit, which would abort the process.
    let data = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(data)));
}

/// Response returned by the model.
#[derive(Debug, Clone)]
pub struct Response {
    content: String,
    usage: Option<SessionUsage>,
}

impl Response {
    /// Creates a response, optionally carrying per-response token usage.
    pub(crate) fn with_usage(content: String, usage: Option<SessionUsage>) -> Self {
        Self { content, usage }
    }

    /// Returns exact token usage for this response (Foundation Models 27).
    ///
    /// `None` on pre-27 build SDKs or runtimes, or when the framework did
    /// not report usage for this response.
    pub fn usage(&self) -> Option<SessionUsage> {
        self.usage
    }

    /// Gets the text content of the response.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Converts the response into its text content.
    pub fn into_content(self) -> String {
        self.content
    }
}

impl AsRef<str> for Response {
    fn as_ref(&self) -> &str {
        &self.content
    }
}

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

/// A session that interacts with a language model.
///
/// A session maintains state between requests, allowing for multi-turn conversations.
/// You can reuse the same session for multiple prompts or create a new one each time.
///
/// Dropping a session requests cooperative cancellation. A Rust tool callback
/// that is already queued or running may continue until it returns; its
/// dispatcher-owned callback context remains valid for that duration.
///
/// # Example
///
/// ```rust,no_run
/// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
///
/// let model = SystemLanguageModel::new()?;
/// let session = Session::new(&model)?;
///
/// let response = session.respond("Hello!", &GenerationOptions::default())?;
/// println!("{}", response.content());
/// # Ok::<(), fm_rs::Error>(())
/// ```
pub struct Session {
    ptr: NonNull<c_void>,
}

/// Apple's built-in system tools for sessions (Foundation Models 27).
///
/// These tools run inside the framework; unlike [`Tool`] implementations,
/// they never call back into Rust. All use Apple's default configuration.
///
/// For reliable image-tool invocation, assign attachments a label with
/// [`Attachment::with_label`] and reference that exact label in the prompt.
/// Without an explicit label, the model may request an image label that does
/// not exist and the tool call fails.
///
/// ```rust,no_run
/// use fm_rs::{Attachment, GenerationOptions, Session, SystemLanguageModel, SystemTool};
///
/// let model = SystemLanguageModel::new()?;
/// let session = Session::builder(&model)
///     .system_tool(SystemTool::BarcodeReader)
///     .build()?;
///
/// let response = session.respond_with_attachments(
///     "Read the barcode in the attached image labeled \"qr\" and report its payload.",
///     &[Attachment::file("qr.png").with_label("qr")],
///     &GenerationOptions::default(),
/// )?;
/// println!("{}", response.content());
/// # Ok::<(), fm_rs::Error>(())
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SystemTool {
    /// Vision text recognition over image attachments.
    ///
    /// Label attachments with [`Attachment::with_label`] and reference the
    /// label in the prompt (see the enum-level example).
    Ocr,
    /// Vision barcode and QR-code reading over image attachments.
    ///
    /// Label attachments with [`Attachment::with_label`] and reference the
    /// label in the prompt (see the enum-level example).
    BarcodeReader,
    /// Core Spotlight semantic search over the device index.
    SpotlightSearch,
}

impl SystemTool {
    fn ffi_name(self) -> &'static str {
        match self {
            SystemTool::Ocr => "ocr",
            SystemTool::BarcodeReader => "barcodeReader",
            SystemTool::SpotlightSearch => "spotlightSearch",
        }
    }
}

/// Builder combining instructions, custom tools, and built-in system tools.
///
/// ```rust,no_run
/// use fm_rs::{Session, SystemLanguageModel, SystemTool};
///
/// let model = SystemLanguageModel::new()?;
/// let session = Session::builder(&model)
///     .instructions("Describe attached images and read any text in them.")
///     .system_tool(SystemTool::Ocr)
///     .build()?;
/// # Ok::<(), fm_rs::Error>(())
/// ```
pub struct SessionBuilder<'m, M: LanguageModel + ?Sized> {
    model: &'m M,
    instructions: Option<String>,
    tools: Vec<Arc<dyn Tool>>,
    system_tools: Vec<SystemTool>,
}

impl<M: LanguageModel + ?Sized> SessionBuilder<'_, M> {
    /// Sets the session instructions.
    #[must_use]
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// Adds a Rust-implemented tool.
    #[must_use]
    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Adds a built-in system tool (Foundation Models 27).
    ///
    /// Session creation fails with [`crate::Error::UnsupportedPlatform`] on
    /// pre-27 build SDKs or runtimes.
    #[must_use]
    pub fn system_tool(mut self, tool: SystemTool) -> Self {
        self.system_tools.push(tool);
        self
    }

    /// Builds the session.
    pub fn build(self) -> Result<Session> {
        Session::create_internal(
            self.model,
            self.instructions.as_deref(),
            &self.tools,
            &self.system_tools,
        )
    }
}

impl Session {
    /// Creates a session builder for combining instructions, tools, and
    /// built-in system tools.
    pub fn builder<M: LanguageModel + ?Sized>(model: &M) -> SessionBuilder<'_, M> {
        SessionBuilder {
            model,
            instructions: None,
            tools: Vec::new(),
            system_tools: Vec::new(),
        }
    }

    /// Creates a new session with the given model.
    pub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self> {
        Self::create_internal(model, None, &[], &[])
    }

    /// Creates a new session with instructions.
    ///
    /// Instructions define the model's behavior and role.
    pub fn with_instructions<M: LanguageModel + ?Sized>(
        model: &M,
        instructions: &str,
    ) -> Result<Self> {
        Self::create_internal(model, Some(instructions), &[], &[])
    }

    /// Creates a new session with tools.
    ///
    /// Tools allow the model to call external functions during generation.
    pub fn with_tools<M: LanguageModel + ?Sized>(
        model: &M,
        tools: &[Arc<dyn Tool>],
    ) -> Result<Self> {
        Self::create_internal(model, None, tools, &[])
    }

    /// Creates a new session with both instructions and tools.
    pub fn with_instructions_and_tools<M: LanguageModel + ?Sized>(
        model: &M,
        instructions: &str,
        tools: &[Arc<dyn Tool>],
    ) -> Result<Self> {
        Self::create_internal(model, Some(instructions), tools, &[])
    }

    /// Creates a session from a transcript JSON string.
    ///
    /// This allows restoring a previous conversation.
    /// Note: Restored sessions do not have tools - use `with_tools` for new sessions.
    pub fn from_transcript<M: LanguageModel + ?Sized>(
        model: &M,
        transcript_json: &str,
    ) -> Result<Self> {
        let transcript_c = CString::new(transcript_json)?;
        let mut error: SwiftPtr = ptr::null_mut();

        let ptr = unsafe {
            ffi::fm_session_from_transcript(
                model.raw_model_ptr(),
                transcript_c.as_ptr(),
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        NonNull::new(ptr).map(|ptr| Self { ptr }).ok_or_else(|| {
            Error::InternalError(
                "Session creation from transcript returned null without error. \
                 The transcript JSON may be malformed or incompatible."
                    .to_string(),
            )
        })
    }

    /// Internal helper to create a session.
    fn create_internal<M: LanguageModel + ?Sized>(
        model: &M,
        instructions: Option<&str>,
        tools: &[Arc<dyn Tool>],
        system_tools: &[SystemTool],
    ) -> Result<Self> {
        let instructions_c = instructions.map(CString::new).transpose()?;
        let instructions_ptr = instructions_c.as_ref().map_or(ptr::null(), |s| s.as_ptr());

        // Serialize built-in system tool names for FFI
        let system_tools_json = system_tools_json(system_tools)?;
        let system_tools_ptr = system_tools_json
            .as_ref()
            .map_or(ptr::null(), |s| s.as_ptr());

        // Build tool map and serialize for FFI
        let mut tool_map = HashMap::new();
        let tools_json = if tools.is_empty() {
            None
        } else {
            let tool_refs: Vec<&dyn Tool> = tools.iter().map(std::convert::AsRef::as_ref).collect();
            for tool in tools {
                // Key by the trimmed name: tools_to_json advertises trimmed
                // names, and Swift trims what the model produces before
                // dispatching.
                tool_map.insert(tool.name().trim().to_string(), Arc::clone(tool));
            }
            let json_str = tools_to_json(&tool_refs)?;
            Some(CString::new(json_str)?)
        };
        let tools_ptr = tools_json.as_ref().map_or(ptr::null(), |s| s.as_ptr());

        // Transfer one strong reference to Swift's ToolDispatcher, which
        // reclaims it in deinit via fm_rust_tool_data_free.
        let user_data = if tools.is_empty() {
            ptr::null_mut()
        } else {
            Arc::into_raw(Arc::new(ToolCallbackData {
                tools: Mutex::new(tool_map),
            })) as *mut c_void
        };

        let mut error: SwiftPtr = ptr::null_mut();

        let ptr = unsafe {
            ffi::fm_session_create(
                model.raw_model_ptr(),
                instructions_ptr,
                tools_ptr,
                system_tools_ptr,
                user_data,
                session_tool_callback,
                &raw mut error,
            )
        };

        if !error.is_null() {
            // Clean up leaked Arc if we allocated it
            if !user_data.is_null() {
                let _ = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
            }
            return Err(error_from_swift(error));
        }

        NonNull::new(ptr).map(|ptr| Self { ptr }).ok_or_else(|| {
            // Clean up leaked Arc if we allocated it
            if !user_data.is_null() {
                let _ = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
            }
            Error::InternalError(
                "Session creation returned null without error. \
                 Check model availability and instructions validity."
                    .to_string(),
            )
        })
    }

    /// Sends a prompt and waits for the complete response.
    ///
    /// This method blocks until the model finishes generating.
    pub fn respond(&self, prompt: &str, options: &GenerationOptions) -> Result<Response> {
        let prompt_c = CString::new(prompt)?;
        let options_json = options.to_json();
        let options_c = CString::new(options_json)?;

        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError("Received null response".to_string()));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |e| {
                Error::GenerationError(format!("Invalid UTF-8 in response: {e}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Sends a prompt with Foundation Models 27 extended reasoning.
    ///
    /// Extended reasoning is a Foundation Models 27 `ContextOptions` request.
    /// The framework decides whether the session's model honors the level;
    /// models without the capability report a typed error. On an older build
    /// SDK or runtime, this returns [`Error::UnsupportedPlatform`].
    pub fn respond_with_reasoning(
        &self,
        prompt: &str,
        options: &GenerationOptions,
        reasoning_level: ReasoningLevel,
    ) -> Result<Response> {
        let prompt_c = CString::new(prompt)?;
        let options_c = CString::new(options.to_json())?;
        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_with_reasoning(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                reasoning_level.as_ffi_code(),
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError(
                "Received null reasoning response".to_string(),
            ));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |error| {
                Error::GenerationError(format!("Invalid UTF-8 in reasoning response: {error}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Sends a prompt with extended reasoning and waits up to `timeout`.
    ///
    /// If `timeout` is zero, this behaves like
    /// [`respond_with_reasoning`](Self::respond_with_reasoning).
    /// Positive sub-millisecond timeouts are rounded up to one millisecond.
    ///
    /// Timeout cancellation is cooperative: the abandoned generation may keep
    /// running in the background, in which case new requests report
    /// [`Error::ConcurrentRequests`] until it finishes, and an
    /// already-dispatched tool call may still run (side effects included)
    /// after this method has returned [`Error::Timeout`].
    pub fn respond_with_reasoning_timeout(
        &self,
        prompt: &str,
        options: &GenerationOptions,
        reasoning_level: ReasoningLevel,
        timeout: Duration,
    ) -> Result<Response> {
        if timeout.is_zero() {
            return self.respond_with_reasoning(prompt, options, reasoning_level);
        }

        let timeout_ms = timeout_millis(timeout)?;
        let prompt_c = CString::new(prompt)?;
        let options_c = CString::new(options.to_json())?;
        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_with_reasoning_timeout(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                reasoning_level.as_ffi_code(),
                timeout_ms,
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError(
                "Received null reasoning response".to_string(),
            ));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |error| {
                Error::GenerationError(format!("Invalid UTF-8 in reasoning response: {error}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Sends a prompt and waits for the complete response, with a timeout.
    ///
    /// If `timeout` is zero, this behaves like [`respond`](Self::respond).
    /// Positive sub-millisecond timeouts are rounded up to one millisecond.
    ///
    /// Timeout cancellation is cooperative: the abandoned generation may keep
    /// running in the background, in which case new requests report
    /// [`Error::ConcurrentRequests`] until it finishes, and an
    /// already-dispatched tool call may still run (side effects included)
    /// after this method has returned [`Error::Timeout`].
    pub fn respond_with_timeout(
        &self,
        prompt: &str,
        options: &GenerationOptions,
        timeout: Duration,
    ) -> Result<Response> {
        if timeout.is_zero() {
            return self.respond(prompt, options);
        }

        let timeout_ms = timeout_millis(timeout)?;

        let prompt_c = CString::new(prompt)?;
        let options_json = options.to_json();
        let options_c = CString::new(options_json)?;

        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_with_timeout(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                timeout_ms,
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError("Received null response".to_string()));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |e| {
                Error::GenerationError(format!("Invalid UTF-8 in response: {e}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Sends a prompt and streams the response.
    ///
    /// The `on_chunk` callback is called for each text chunk as it arrives.
    /// Chunks are incremental: concatenating every chunk yields the full
    /// response. This method blocks until streaming is complete.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    ///
    /// session.stream_response("Tell me a story", &GenerationOptions::default(), |chunk| {
    ///     print!("{}", chunk);
    /// })?;
    /// # Ok::<(), fm_rs::Error>(())
    /// ```
    pub fn stream_response<F>(
        &self,
        prompt: &str,
        options: &GenerationOptions,
        on_chunk: F,
    ) -> Result<()>
    where
        F: FnMut(&str) + Send,
    {
        let prompt_c = CString::new(prompt)?;
        let options_json = options.to_json();
        let options_c = CString::new(options_json)?;

        // Create callback state
        let state = Box::new(StreamState {
            session_ptr: self.ptr,
            on_chunk: Mutex::new(Box::new(on_chunk)),
            error: Mutex::new(None),
        });
        let state_ptr = Box::into_raw(state).cast::<c_void>();

        unsafe {
            ffi::fm_session_stream(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                state_ptr,
                stream_chunk_callback,
                stream_done_callback,
                stream_error_callback,
            );
        }

        // Reclaim the state and check for errors
        let state = unsafe { Box::from_raw(state_ptr.cast::<StreamState>()) };
        let error = state.error.lock().map_err(|_| Error::PoisonError)?;
        if let Some((code, message)) = error.as_ref() {
            return Err(error_from_parts(*code, message.clone()));
        }

        Ok(())
    }

    /// Sends a prompt with image attachments and blocks until the response
    /// is ready (Foundation Models 27 multimodal prompting).
    ///
    /// The on-device model accepts images for description, extraction, and
    /// classification; the framework handles scaling and color conversion.
    /// With no attachments this behaves like [`respond`](Self::respond).
    /// Requires a 27 build SDK and runtime; otherwise returns
    /// [`Error::UnsupportedPlatform`]. Models without the image capability
    /// report [`Error::UnsupportedCapability`].
    pub fn respond_with_attachments(
        &self,
        prompt: &str,
        attachments: &[Attachment<'_>],
        options: &GenerationOptions,
    ) -> Result<Response> {
        if attachments.is_empty() {
            return self.respond(prompt, options);
        }

        let (specs_json, buffers, buffer_lens) = attachment_specs(attachments)?;
        let buffer_count = c_int::try_from(buffers.len())
            .map_err(|_| Error::InvalidInput("Too many attachments".to_string()))?;

        let prompt_c = CString::new(prompt)?;
        let options_c = CString::new(options.to_json())?;
        let specs_c = CString::new(specs_json)?;
        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_with_attachments(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                options_c.as_ptr(),
                specs_c.as_ptr(),
                buffers.as_ptr(),
                buffer_lens.as_ptr(),
                buffer_count,
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError(
                "Received null multimodal response".to_string(),
            ));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |error| {
                Error::GenerationError(format!("Invalid UTF-8 in multimodal response: {error}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Returns exact cumulative token usage for this session.
    ///
    /// Foundation Models 27 reports authoritative input, cached-input,
    /// output, and reasoning token counts across all requests in this
    /// session. To measure a single request, snapshot before and after and
    /// use [`SessionUsage::delta_since`]. Per-response usage is bridged into
    /// [`Response::usage`] on blocking response paths; per-response usage for
    /// streaming remains unsupported. On older build SDKs or runtimes this
    /// returns [`Error::UnsupportedPlatform`]; use [`crate::estimate_tokens`]
    /// there instead.
    pub fn usage(&self) -> Result<SessionUsage> {
        let mut error: SwiftPtr = ptr::null_mut();
        let json_ptr = unsafe { ffi::fm_session_usage(self.ptr.as_ptr(), &raw mut error) };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if json_ptr.is_null() {
            return Err(Error::InternalError(
                "Session usage returned null without an error".to_string(),
            ));
        }

        let json = unsafe {
            let json = CStr::from_ptr(json_ptr).to_string_lossy().into_owned();
            ffi::fm_string_free(json_ptr);
            json
        };

        session_usage_from_json(&json)
    }

    /// Replaces this session's transcript (Foundation Models 27).
    ///
    /// The JSON must be a Foundation Models `Transcript`, such as one
    /// returned by [`transcript_json`](Self::transcript_json) and edited. Fails while
    /// the session is responding. On older build SDKs or runtimes this
    /// returns [`Error::UnsupportedPlatform`]; there, create a new session
    /// with [`Session::from_transcript`] instead.
    pub fn set_transcript(&self, transcript_json: &str) -> Result<()> {
        let transcript_c = CString::new(transcript_json)?;
        let mut error: SwiftPtr = ptr::null_mut();

        let replaced = unsafe {
            ffi::fm_session_set_transcript(self.ptr.as_ptr(), transcript_c.as_ptr(), &raw mut error)
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if replaced {
            Ok(())
        } else {
            Err(Error::InternalError(
                "Transcript replacement failed without an error".to_string(),
            ))
        }
    }

    /// Sets or clears how the transcript is repaired after a failed request
    /// (Foundation Models 27).
    ///
    /// `None` restores the framework default. On older build SDKs or
    /// runtimes this returns [`Error::UnsupportedPlatform`].
    pub fn set_transcript_error_handling_policy(
        &self,
        policy: Option<TranscriptErrorHandlingPolicy>,
    ) -> Result<()> {
        let code = match policy {
            None => 0,
            Some(TranscriptErrorHandlingPolicy::RevertTranscript) => 1,
            Some(TranscriptErrorHandlingPolicy::PreserveTranscript) => 2,
        };
        let mut error: SwiftPtr = ptr::null_mut();

        let applied = unsafe {
            ffi::fm_session_set_transcript_error_policy(self.ptr.as_ptr(), code, &raw mut error)
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if applied {
            Ok(())
        } else {
            Err(Error::InternalError(
                "Transcript policy update failed without an error".to_string(),
            ))
        }
    }

    /// Fetches the usage recorded for the most recent completed response.
    ///
    /// Returns `None` on pre-27 build SDKs or runtimes, or when no blocking
    /// response has completed yet. Unreadable payloads also map to `None`;
    /// [`Response::usage`] documents this as "not reported".
    fn fetch_last_response_usage(&self) -> Option<SessionUsage> {
        let json_ptr = unsafe { ffi::fm_session_last_response_usage(self.ptr.as_ptr()) };
        if json_ptr.is_null() {
            return None;
        }

        let json = unsafe {
            let json = CStr::from_ptr(json_ptr).to_string_lossy().into_owned();
            ffi::fm_string_free(json_ptr);
            json
        };

        session_usage_from_json(&json).ok()
    }

    /// Cancels the in-flight generation (blocking or streaming), if any.
    ///
    /// Every generation method blocks the calling thread and `Session` is not
    /// `Sync`, so this cannot be reached while a request is in flight. To
    /// cancel from another thread, obtain a [`CancellationHandle`] via
    /// [`cancellation_handle`](Self::cancellation_handle) before starting.
    pub fn cancel(&self) {
        unsafe {
            ffi::fm_session_cancel(self.ptr.as_ptr());
        }
    }

    /// Returns a thread-safe handle that can cancel this session's in-flight
    /// generation from another thread.
    ///
    /// The handle holds its own reference to the underlying Swift session, so
    /// it remains safe to use (as a no-op) after the `Session` is dropped.
    /// It is session-scoped rather than generation-scoped: [`cancel`](CancellationHandle::cancel)
    /// targets whichever generation is in flight when it is called. A delayed
    /// call intended for an earlier generation can therefore cancel a later
    /// one; coordinate its lifetime with the operation it is meant to cancel.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fm_rs::{GenerationOptions, Session, SystemLanguageModel};
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    /// let handle = session.cancellation_handle();
    ///
    /// let canceller = std::thread::spawn(move || {
    ///     std::thread::sleep(std::time::Duration::from_millis(100));
    ///     handle.cancel();
    /// });
    ///
    /// let result = session.stream_response(
    ///     "Tell me a very long story",
    ///     &GenerationOptions::default(),
    ///     |chunk| print!("{chunk}"),
    /// );
    /// assert!(matches!(result, Err(fm_rs::Error::Cancelled(_))));
    /// canceller.join().expect("canceller thread panicked");
    /// # Ok::<(), fm_rs::Error>(())
    /// ```
    pub fn cancellation_handle(&self) -> CancellationHandle {
        unsafe { ffi::fm_session_retain(self.ptr.as_ptr()) };
        CancellationHandle { ptr: self.ptr }
    }

    /// Checks if the session is currently generating a response.
    pub fn is_responding(&self) -> bool {
        unsafe { ffi::fm_session_is_responding(self.ptr.as_ptr()) }
    }

    /// Gets the session transcript as a JSON string.
    ///
    /// This can be used to persist and restore conversations.
    pub fn transcript_json(&self) -> Result<String> {
        let mut error: SwiftPtr = ptr::null_mut();
        let ptr = unsafe { ffi::fm_session_get_transcript(self.ptr.as_ptr(), &raw mut error) };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if ptr.is_null() {
            return Err(Error::InternalError(
                "Transcript retrieval returned null without error. \
                 The session may be in an invalid state."
                    .to_string(),
            ));
        }

        unsafe {
            take_swift_string(ptr, |e| {
                Error::InternalError(format!("Invalid UTF-8 in transcript: {e}"))
            })
        }
    }

    /// Estimates current context usage based on the session transcript.
    pub fn context_usage(&self, limit: &ContextLimit) -> Result<ContextUsage> {
        let transcript_json = self.transcript_json()?;
        context_usage_from_transcript(&transcript_json, limit)
    }

    /// Returns an error if the estimated context usage exceeds the configured limit.
    pub fn ensure_context_within(&self, limit: &ContextLimit) -> Result<()> {
        let usage = self.context_usage(limit)?;
        if usage.over_limit {
            return Err(Error::InvalidInput(format!(
                "Estimated context usage {} exceeds configured limit {} (reserved: {})",
                usage.estimated_tokens, usage.max_tokens, usage.reserved_response_tokens
            )));
        }
        Ok(())
    }

    /// Prewarms the model with an optional prompt prefix.
    ///
    /// This can reduce latency for the first response.
    pub fn prewarm(&self, prompt_prefix: Option<&str>) -> Result<()> {
        let prefix_c = prompt_prefix.map(CString::new).transpose()?;
        let prefix_ptr = prefix_c.as_ref().map_or(ptr::null(), |s| s.as_ptr());

        unsafe {
            ffi::fm_session_prewarm(self.ptr.as_ptr(), prefix_ptr);
        }

        Ok(())
    }

    /// Sends a prompt and returns a structured JSON response.
    ///
    /// The schema is a JSON Schema that describes the expected output format.
    /// The model is instructed to produce JSON that matches the schema.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
    /// use serde::Deserialize;
    /// use serde_json::json;
    ///
    /// #[derive(Deserialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    ///
    /// let schema = json!({
    ///     "type": "object",
    ///     "properties": {
    ///         "name": { "type": "string" },
    ///         "age": { "type": "integer" }
    ///     },
    ///     "required": ["name", "age"]
    /// });
    ///
    /// let json_str = session.respond_json(
    ///     "Generate a fictional person",
    ///     &schema,
    ///     &GenerationOptions::default()
    /// )?;
    ///
    /// let person: Person = serde_json::from_str(&json_str)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn respond_json(
        &self,
        prompt: &str,
        schema: &serde_json::Value,
        options: &GenerationOptions,
    ) -> Result<String> {
        let prompt_c = CString::new(prompt)?;
        let schema_json = serde_json::to_string(schema)?;
        let schema_c = CString::new(schema_json)?;
        let options_json = options.to_json();
        let options_c = CString::new(options_json)?;

        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_json(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                schema_c.as_ptr(),
                options_c.as_ptr(),
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError(
                "Received null response from JSON generation".to_string(),
            ));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |e| {
                Error::GenerationError(format!("Invalid UTF-8 in JSON response: {e}"))
            })
        }?;

        Ok(content)
    }

    /// Sends a prompt and returns a structured JSON response with a timeout.
    ///
    /// The response content contains the extracted JSON string. On Foundation Models 27,
    /// [`Response::usage`] also exposes the framework's per-response token usage when
    /// available. If `timeout` is zero, this uses the same path as
    /// [`respond_json`](Self::respond_json). Positive sub-millisecond timeouts are rounded up
    /// to one millisecond, the finest resolution supported by the Swift bridge.
    ///
    /// The timeout bounds only the caller's wait. On expiry, the bridge requests cooperative
    /// task cancellation and returns [`Error::Timeout`]; it cannot force Foundation Models
    /// framework work to stop immediately. While the abandoned generation drains, new
    /// requests report [`Error::ConcurrentRequests`], and an already-dispatched tool call
    /// may still run (side effects included) after this method has returned.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::time::Duration;
    ///
    /// use fm_rs::{GenerationOptions, Session, SystemLanguageModel};
    /// use serde_json::json;
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    /// let schema = json!({
    ///     "type": "object",
    ///     "properties": { "answer": { "type": "string" } },
    ///     "required": ["answer"]
    /// });
    ///
    /// let response = session.respond_json_with_timeout(
    ///     "Answer briefly",
    ///     &schema,
    ///     &GenerationOptions::default(),
    ///     Duration::from_secs(30),
    /// )?;
    /// let json: serde_json::Value = serde_json::from_str(response.content())?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn respond_json_with_timeout(
        &self,
        prompt: &str,
        schema: &serde_json::Value,
        options: &GenerationOptions,
        timeout: Duration,
    ) -> Result<Response> {
        let Some(timeout_ms) = json_timeout_millis(timeout)? else {
            let content = self.respond_json(prompt, schema, options)?;
            return Ok(Response::with_usage(
                content,
                self.fetch_last_response_usage(),
            ));
        };

        let prompt_c = CString::new(prompt)?;
        let schema_c = CString::new(serde_json::to_string(schema)?)?;
        let options_c = CString::new(options.to_json())?;
        let mut error: SwiftPtr = ptr::null_mut();

        let response_ptr = unsafe {
            ffi::fm_session_respond_json_with_timeout(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                schema_c.as_ptr(),
                options_c.as_ptr(),
                timeout_ms,
                &raw mut error,
            )
        };

        if !error.is_null() {
            return Err(error_from_swift(error));
        }

        if response_ptr.is_null() {
            return Err(Error::GenerationError(
                "Received null response from JSON generation".to_string(),
            ));
        }

        let content = unsafe {
            take_swift_string(response_ptr, |error| {
                Error::GenerationError(format!("Invalid UTF-8 in JSON response: {error}"))
            })
        }?;

        Ok(Response::with_usage(
            content,
            self.fetch_last_response_usage(),
        ))
    }

    /// Sends a prompt and returns a deserialized structured response.
    ///
    /// This is a convenience method that calls `respond_json` and deserializes
    /// the result into the specified type.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
    /// use serde::Deserialize;
    /// use serde_json::json;
    ///
    /// #[derive(Deserialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    ///
    /// let schema = json!({
    ///     "type": "object",
    ///     "properties": {
    ///         "name": { "type": "string" },
    ///         "age": { "type": "integer" }
    ///     },
    ///     "required": ["name", "age"]
    /// });
    ///
    /// let person: Person = session.respond_structured(
    ///     "Generate a fictional person",
    ///     &schema,
    ///     &GenerationOptions::default()
    /// )?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn respond_structured<T: serde::de::DeserializeOwned>(
        &self,
        prompt: &str,
        schema: &serde_json::Value,
        options: &GenerationOptions,
    ) -> Result<T> {
        let json_str = self.respond_json(prompt, schema, options)?;
        serde_json::from_str(&json_str)
            .map_err(|e| Error::InvalidInput(format!("Failed to deserialize response: {e}")))
    }

    /// Sends a prompt and returns a deserialized structured response using a derived schema.
    ///
    /// This uses the [`crate::Generable`] implementation to obtain the JSON schema.
    pub fn respond_structured_gen<T>(&self, prompt: &str, options: &GenerationOptions) -> Result<T>
    where
        T: crate::Generable + serde::de::DeserializeOwned,
    {
        self.respond_structured(prompt, &T::schema(), options)
    }

    /// Streams a structured JSON response.
    ///
    /// Unlike [`stream_response`](Self::stream_response), `on_chunk` receives
    /// the *cumulative* partial JSON generated so far on each call, not an
    /// incremental delta — render each snapshot in place rather than
    /// concatenating them. Partial snapshots may not be valid JSON until
    /// streaming completes.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
    /// use serde_json::json;
    ///
    /// let model = SystemLanguageModel::new()?;
    /// let session = Session::new(&model)?;
    ///
    /// let schema = json!({
    ///     "type": "object",
    ///     "properties": {
    ///         "items": { "type": "array", "items": { "type": "string" } }
    ///     }
    /// });
    ///
    /// session.stream_json(
    ///     "List 5 programming languages",
    ///     &schema,
    ///     &GenerationOptions::default(),
    ///     |chunk| {
    ///         print!("{chunk}");
    ///     }
    /// )?;
    /// # Ok::<(), fm_rs::Error>(())
    /// ```
    pub fn stream_json<F>(
        &self,
        prompt: &str,
        schema: &serde_json::Value,
        options: &GenerationOptions,
        on_chunk: F,
    ) -> Result<()>
    where
        F: FnMut(&str) + Send,
    {
        let prompt_c = CString::new(prompt)?;
        let schema_json = serde_json::to_string(schema)?;
        let schema_c = CString::new(schema_json)?;
        let options_json = options.to_json();
        let options_c = CString::new(options_json)?;

        // Create callback state
        let state = Box::new(StreamState {
            session_ptr: self.ptr,
            on_chunk: Mutex::new(Box::new(on_chunk)),
            error: Mutex::new(None),
        });
        let state_ptr = Box::into_raw(state).cast::<c_void>();

        unsafe {
            ffi::fm_session_stream_json(
                self.ptr.as_ptr(),
                prompt_c.as_ptr(),
                schema_c.as_ptr(),
                options_c.as_ptr(),
                state_ptr,
                stream_chunk_callback,
                stream_done_callback,
                stream_error_callback,
            );
        }

        // Reclaim the state and check for errors
        let state = unsafe { Box::from_raw(state_ptr.cast::<StreamState>()) };
        let error = state.error.lock().map_err(|_| Error::PoisonError)?;
        if let Some((code, message)) = error.as_ref() {
            return Err(error_from_parts(*code, message.clone()));
        }

        Ok(())
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        unsafe {
            ffi::fm_session_free(self.ptr.as_ptr());
        }

        // Swift's ToolDispatcher owns the ToolCallbackData reference (via
        // Arc::into_raw) and reclaims it in deinit; any in-flight tool
        // callback runs inside a dispatcher method, so the data outlives
        // every callback.
    }
}

// SAFETY: Session is a wrapper around a Swift object that uses
// DispatchQueue for thread safety internally.
unsafe impl Send for Session {}

// Note: Session is NOT Sync because streaming callbacks use internal mutable state.
// To cancel or observe an in-flight generation from another thread, use
// Session::cancellation_handle().

/// Thread-safe handle for cancelling a [`Session`]'s in-flight generation.
///
/// Created via [`Session::cancellation_handle`]. Holds its own reference to
/// the Swift session, so it may outlive the `Session`; cancelling after the
/// session is gone is a no-op. The handle is session-scoped, so a delayed
/// cancellation targets whichever generation is active at call time, not
/// necessarily the generation that was active when the handle was created.
pub struct CancellationHandle {
    ptr: NonNull<c_void>,
}

impl CancellationHandle {
    /// Cancels the session's in-flight generation, if any.
    ///
    /// Covers blocking (`respond*`) and streaming calls alike; a cancelled
    /// call returns [`Error::Cancelled`]. Cancellation is cooperative, so the
    /// framework may finish a small amount of work before observing it. This
    /// targets the current generation at call time; discard or otherwise
    /// coordinate stale handles before starting a later generation.
    pub fn cancel(&self) {
        unsafe { ffi::fm_session_cancel(self.ptr.as_ptr()) };
    }

    /// Returns whether the session is currently generating a response.
    pub fn is_responding(&self) -> bool {
        unsafe { ffi::fm_session_is_responding(self.ptr.as_ptr()) }
    }
}

impl Drop for CancellationHandle {
    fn drop(&mut self) {
        unsafe { ffi::fm_session_release(self.ptr.as_ptr()) };
    }
}

// SAFETY: the handle only calls into Swift entry points that guard their
// state with a lock (cancelCurrentTask) or read a framework-owned property
// (isResponding); the retained reference keeps the pointee alive.
unsafe impl Send for CancellationHandle {}
unsafe impl Sync for CancellationHandle {}

/// Type alias for the chunk callback function.
type ChunkCallbackFn<'a> = dyn FnMut(&str) + Send + 'a;

/// An image input for Foundation Models 27 multimodal prompting.
///
/// Create one from a file path or from encoded image bytes (PNG, JPEG,
/// HEIC, ...), then pass it to [`Session::respond_with_attachments`]. Label
/// attachments so prompts can reference specific images by name.
#[derive(Debug, Clone)]
pub struct Attachment<'a> {
    source: AttachmentSource<'a>,
    label: Option<String>,
}

#[derive(Debug, Clone)]
enum AttachmentSource<'a> {
    File(std::path::PathBuf),
    ImageBytes(&'a [u8]),
}

fn system_tools_json(system_tools: &[SystemTool]) -> Result<Option<CString>> {
    if system_tools.is_empty() {
        return Ok(None);
    }

    let mut seen = HashSet::with_capacity(system_tools.len());
    let mut names = Vec::with_capacity(system_tools.len());
    for tool in system_tools {
        if !seen.insert(*tool) {
            return Err(Error::InvalidInput(format!(
                "Duplicate built-in system tool: {}",
                tool.ffi_name()
            )));
        }
        names.push(tool.ffi_name());
    }

    Ok(Some(CString::new(serde_json::to_string(&names)?)?))
}

impl<'a> Attachment<'a> {
    /// Creates an image attachment from a file on disk.
    pub fn file(path: impl Into<std::path::PathBuf>) -> Attachment<'static> {
        Attachment {
            source: AttachmentSource::File(path.into()),
            label: None,
        }
    }

    /// Creates an image attachment from encoded image bytes.
    pub fn image_bytes(bytes: &'a [u8]) -> Attachment<'a> {
        Attachment {
            source: AttachmentSource::ImageBytes(bytes),
            label: None,
        }
    }

    /// Labels the attachment so prompts can reference it by name.
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }
}

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AttachmentSpec<'a> {
    kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    buffer_index: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    label: Option<&'a str>,
}

type AttachmentBuffers = (String, Vec<*const u8>, Vec<usize>);

/// Serializes attachments to a JSON spec plus parallel byte-buffer arrays.
fn attachment_specs(attachments: &[Attachment<'_>]) -> Result<AttachmentBuffers> {
    let mut specs = Vec::with_capacity(attachments.len());
    let mut buffers = Vec::new();
    let mut buffer_lens = Vec::new();

    for attachment in attachments {
        let label = attachment.label.as_deref();
        match &attachment.source {
            AttachmentSource::File(path) => {
                let path = path.to_str().ok_or_else(|| {
                    Error::InvalidInput(format!(
                        "Attachment path is not valid UTF-8: {}",
                        path.display()
                    ))
                })?;
                specs.push(AttachmentSpec {
                    kind: "file",
                    path: Some(path),
                    buffer_index: None,
                    label,
                });
            }
            AttachmentSource::ImageBytes(bytes) => {
                specs.push(AttachmentSpec {
                    kind: "data",
                    path: None,
                    buffer_index: Some(buffers.len()),
                    label,
                });
                buffers.push(bytes.as_ptr());
                buffer_lens.push(bytes.len());
            }
        }
    }

    let json = serde_json::to_string(&specs)?;
    Ok((json, buffers, buffer_lens))
}

/// Exact cumulative token usage reported by a Foundation Models 27 session.
///
/// Returned by [`Session::usage`]. Unlike [`crate::estimate_tokens`], these
/// counts are authoritative and include prompt caching and
/// extended-reasoning accounting.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionUsage {
    /// Total input tokens across all requests in this session.
    pub input_tokens: u64,
    /// Input tokens that were served from the prompt cache.
    pub cached_input_tokens: u64,
    /// Total output tokens across all responses in this session.
    pub output_tokens: u64,
    /// Output tokens spent on extended reasoning.
    pub reasoning_tokens: u64,
}

impl SessionUsage {
    /// Returns the usage consumed since an earlier snapshot of this session.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if any counter went backwards, which
    /// indicates the snapshots came from different sessions or were taken
    /// out of order.
    pub fn delta_since(&self, earlier: &SessionUsage) -> Result<SessionUsage> {
        let sub = |now: u64, before: u64, field: &str| {
            now.checked_sub(before).ok_or_else(|| {
                Error::InvalidInput(format!(
                    "Usage {field} went backwards ({now} < {before}); snapshots must come \
                     from the same session in order"
                ))
            })
        };

        Ok(SessionUsage {
            input_tokens: sub(self.input_tokens, earlier.input_tokens, "input_tokens")?,
            cached_input_tokens: sub(
                self.cached_input_tokens,
                earlier.cached_input_tokens,
                "cached_input_tokens",
            )?,
            output_tokens: sub(self.output_tokens, earlier.output_tokens, "output_tokens")?,
            reasoning_tokens: sub(
                self.reasoning_tokens,
                earlier.reasoning_tokens,
                "reasoning_tokens",
            )?,
        })
    }
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[expect(
    clippy::struct_field_names,
    reason = "the _tokens suffix maps to the FFI JSON keys and mirrors Apple's usage terminology"
)]
struct SessionUsageDto {
    input_tokens: i64,
    cached_input_tokens: i64,
    output_tokens: i64,
    reasoning_tokens: i64,
}

fn session_usage_from_json(json: &str) -> Result<SessionUsage> {
    let dto: SessionUsageDto = serde_json::from_str(json)
        .map_err(|error| Error::InternalError(format!("Invalid session usage JSON: {error}")))?;

    let count = |value: i64, field: &str| {
        u64::try_from(value).map_err(|_| {
            Error::InternalError(format!("Session usage {field} was negative: {value}"))
        })
    };

    Ok(SessionUsage {
        input_tokens: count(dto.input_tokens, "inputTokens")?,
        cached_input_tokens: count(dto.cached_input_tokens, "cachedInputTokens")?,
        output_tokens: count(dto.output_tokens, "outputTokens")?,
        reasoning_tokens: count(dto.reasoning_tokens, "reasoningTokens")?,
    })
}

/// How a session repairs its transcript after a failed request
/// (Foundation Models 27).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranscriptErrorHandlingPolicy {
    /// Remove the failed request from the transcript.
    RevertTranscript,
    /// Keep the failed request in the transcript.
    PreserveTranscript,
}

/// Internal state for streaming callbacks.
struct StreamState<'a> {
    session_ptr: NonNull<c_void>,
    on_chunk: Mutex<Box<ChunkCallbackFn<'a>>>,
    error: Mutex<Option<(c_int, String)>>,
}

/// Callback invoked when a chunk arrives during streaming.
extern "C" fn stream_chunk_callback(user_data: *mut c_void, chunk: *const c_char) {
    if user_data.is_null() || chunk.is_null() {
        return;
    }

    let state = unsafe { &*(user_data as *const StreamState) };
    let chunk_str = unsafe { CStr::from_ptr(chunk).to_string_lossy() };

    // A panic here would unwind into Swift and abort the process; convert it
    // into a stream error instead. The poisoned mutex suppresses the user
    // callback for any chunks that arrive after the panic.
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        if let Ok(mut on_chunk) = state.on_chunk.lock() {
            on_chunk(&chunk_str);
        }
    }))
    .is_err();

    if panicked && let Ok(mut error) = state.error.lock() {
        error.get_or_insert((
            ffi::ErrorCode::Unknown as c_int,
            "Stream chunk callback panicked".to_string(),
        ));
    }
    if panicked {
        // Stop generation promptly; the error callback below preserves the
        // more specific callback-panic error already recorded above.
        unsafe { ffi::fm_session_cancel(state.session_ptr.as_ptr()) };
    }
}

/// Callback invoked when streaming is done.
extern "C" fn stream_done_callback(_user_data: *mut c_void) {
    // Nothing to do - state cleanup happens in stream_response
}

/// Callback invoked on error during streaming.
extern "C" fn stream_error_callback(user_data: *mut c_void, code: c_int, message: *const c_char) {
    if user_data.is_null() {
        return;
    }

    let state = unsafe { &*(user_data as *const StreamState) };
    let msg = if message.is_null() {
        "Streaming error occurred (no message provided by Swift)".to_string()
    } else {
        unsafe { CStr::from_ptr(message).to_string_lossy().into_owned() }
    };

    if let Ok(mut error) = state.error.lock() {
        error.get_or_insert((code, msg));
    }
}

/// Callback invoked when a tool needs to be called during session operations.
/// This is used by Swift's `FFITool` to call back into Rust.
extern "C" fn session_tool_callback(
    user_data: *mut c_void,
    tool_name: *const c_char,
    arguments_json: *const c_char,
) -> *mut c_char {
    if user_data.is_null() || tool_name.is_null() {
        let result = ToolResult::error("Invalid callback parameters");
        return string_to_c(result.to_json());
    }

    // user_data is a raw pointer to Arc<ToolCallbackData> (from Arc::into_raw)
    // SAFETY: Swift's ToolDispatcher holds a strong reference to this Arc and
    // is the object invoking this callback, so ARC keeps the data alive for
    // the duration of the call. We must NOT consume the Arc here - just
    // borrow it.
    let callback_data = unsafe { &*(user_data as *const ToolCallbackData) };

    let name = unsafe { CStr::from_ptr(tool_name).to_string_lossy().into_owned() };
    let args_str = if arguments_json.is_null() {
        "{}".to_string()
    } else {
        unsafe {
            CStr::from_ptr(arguments_json)
                .to_string_lossy()
                .into_owned()
        }
    };

    // Parse arguments (with a best-effort auto-close for truncated JSON)
    let arguments: serde_json::Value = match parse_tool_arguments(&args_str) {
        Ok(v) => v,
        Err(message) => {
            let result = ToolResult::error(message);
            return string_to_c(result.to_json());
        }
    };

    // Find and call the tool
    let Ok(tools) = callback_data.tools.lock() else {
        let result = ToolResult::error("Failed to acquire tool lock");
        return string_to_c(result.to_json());
    };

    let Some(tool) = tools.get(&name).map(Arc::clone) else {
        let result = ToolResult::error(format!("Unknown tool: {name}"));
        return string_to_c(result.to_json());
    };

    // Release the lock before calling the tool (it might take a while)
    drop(tools);

    // Invoke the tool. A panic here would unwind into Swift and abort the
    // process; report it as a tool error so the model (and caller) can react.
    let result =
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| tool.call(arguments))) {
            Ok(Ok(output)) => ToolResult::success(output),
            Ok(Err(e)) => ToolResult::error(e.to_string()),
            Err(_) => ToolResult::error(format!("Tool '{name}' panicked")),
        };

    string_to_c(result.to_json())
}

/// Copies a Swift-allocated (`strdup`) C string and always frees it, even
/// when the contents are not valid UTF-8.
///
/// # Safety
///
/// `ptr` must be a non-null, NUL-terminated allocation owned by the caller
/// and freeable with `fm_string_free`.
unsafe fn take_swift_string(
    ptr: *mut c_char,
    make_error: impl FnOnce(std::str::Utf8Error) -> Error,
) -> Result<String> {
    let converted = unsafe { CStr::from_ptr(ptr) }.to_str().map(str::to_owned);
    unsafe { ffi::fm_string_free(ptr) };
    converted.map_err(make_error)
}

/// Helper to convert a Rust string to a C string that can be freed by Swift.
fn string_to_c(s: String) -> *mut c_char {
    match CString::new(s) {
        Ok(cs) => cs.into_raw(),
        Err(_) => ptr::null_mut(),
    }
}

fn parse_tool_arguments(input: &str) -> std::result::Result<serde_json::Value, String> {
    match serde_json::from_str(input) {
        Ok(value) => Ok(value),
        Err(err) => {
            if let Some(fixed) = autoclose_json(input) {
                match serde_json::from_str(&fixed) {
                    Ok(value) => Ok(value),
                    Err(fixed_err) => Err(format!(
                        "Failed to parse arguments: {err}; attempted fix: {fixed_err}"
                    )),
                }
            } else {
                Err(format!("Failed to parse arguments: {err}"))
            }
        }
    }
}

fn timeout_millis(timeout: Duration) -> Result<u64> {
    let milliseconds = u64::try_from(timeout.as_millis()).map_err(|_| {
        Error::InvalidInput("Timeout is too large to represent in milliseconds".to_string())
    })?;

    if timeout.is_zero() {
        Ok(0)
    } else {
        Ok(milliseconds.max(1))
    }
}

fn json_timeout_millis(timeout: Duration) -> Result<Option<u64>> {
    if timeout.is_zero() {
        Ok(None)
    } else {
        timeout_millis(timeout).map(Some)
    }
}

/// Maximum input size for `autoclose_json` to prevent resource exhaustion (1 MB).
const AUTOCLOSE_JSON_MAX_SIZE: usize = 1024 * 1024;

fn autoclose_json(input: &str) -> Option<String> {
    // Limit input size to prevent resource exhaustion attacks
    if input.len() > AUTOCLOSE_JSON_MAX_SIZE {
        return None;
    }

    let mut stack: Vec<char> = Vec::new();
    let mut in_string = false;
    let mut escape = false;

    for ch in input.chars() {
        if in_string {
            if escape {
                escape = false;
                continue;
            }
            if ch == '\\' {
                escape = true;
                continue;
            }
            if ch == '"' {
                in_string = false;
            }
            continue;
        }

        match ch {
            '"' => in_string = true,
            '{' => stack.push('}'),
            '[' => stack.push(']'),
            '}' if stack.pop() != Some('}') => return None,
            ']' if stack.pop() != Some(']') => return None,
            _ => {}
        }
    }

    if in_string || stack.is_empty() {
        return None;
    }

    let mut out = input.to_string();
    while let Some(close) = stack.pop() {
        out.push(close);
    }
    Some(out)
}

#[cfg(test)]
mod tests {
    use std::ffi::{CString, c_void};
    use std::ptr::NonNull;
    use std::sync::Mutex;
    use std::time::Duration;

    use crate::error::Error;
    use crate::session::{
        Attachment, Response, SessionUsage, StreamState, SystemTool, attachment_specs,
        json_timeout_millis, session_usage_from_json, stream_error_callback, system_tools_json,
        timeout_millis,
    };

    #[test]
    fn test_response() {
        let response = Response::with_usage("Hello, world!".to_string(), None);
        assert_eq!(response.content(), "Hello, world!");
        assert_eq!(response.as_ref(), "Hello, world!");
        assert_eq!(format!("{response}"), "Hello, world!");
        assert_eq!(response.into_content(), "Hello, world!");
    }

    #[test]
    fn stream_error_callback_preserves_an_existing_callback_error() {
        let mut state = StreamState {
            session_ptr: NonNull::dangling(),
            on_chunk: Mutex::new(Box::new(|_: &str| {})),
            error: Mutex::new(Some((
                crate::ffi::ErrorCode::Unknown as i32,
                "Stream chunk callback panicked".to_string(),
            ))),
        };
        let message = CString::new("Cancelled").expect("literal has no NUL");

        stream_error_callback(
            std::ptr::from_mut(&mut state).cast::<c_void>(),
            crate::ffi::ErrorCode::Cancelled as i32,
            message.as_ptr(),
        );

        let error = state.error.lock().expect("stream error mutex should lock");
        assert_eq!(
            error.as_ref().map(|(_, message)| message.as_str()),
            Some("Stream chunk callback panicked")
        );
    }

    #[test]
    fn timeout_millis_rejects_values_larger_than_u64() {
        let timeout = Duration::from_secs(u64::MAX);
        assert!(matches!(
            timeout_millis(timeout),
            Err(Error::InvalidInput(_))
        ));
    }

    #[test]
    fn timeout_millis_preserves_zero_and_rounds_positive_sub_millisecond_values_up() {
        assert!(matches!(timeout_millis(Duration::ZERO), Ok(0)));

        for timeout in [
            Duration::from_nanos(1),
            Duration::from_micros(500),
            Duration::from_micros(999),
        ] {
            assert!(matches!(timeout_millis(timeout), Ok(1)));
        }

        assert!(matches!(timeout_millis(Duration::from_millis(1)), Ok(1)));
    }

    const _: fn(
        &crate::Session,
        &str,
        &serde_json::Value,
        &crate::GenerationOptions,
        Duration,
    ) -> crate::Result<Response> = crate::Session::respond_json_with_timeout;

    #[test]
    fn respond_json_with_timeout_zero_selects_existing_json_path() {
        assert!(matches!(json_timeout_millis(Duration::ZERO), Ok(None)));
    }

    #[test]
    fn respond_json_with_timeout_rounds_positive_sub_millisecond_values_up() {
        for timeout in [
            Duration::from_nanos(1),
            Duration::from_micros(500),
            Duration::from_micros(999),
        ] {
            assert!(matches!(json_timeout_millis(timeout), Ok(Some(1))));
        }

        assert!(matches!(
            json_timeout_millis(Duration::from_millis(1)),
            Ok(Some(1))
        ));
    }

    #[test]
    fn respond_json_with_timeout_reuses_timeout_overflow_error() {
        let timeout = Duration::from_secs(u64::MAX);
        assert!(matches!(
            json_timeout_millis(timeout),
            Err(Error::InvalidInput(_))
        ));
    }

    #[test]
    fn session_usage_should_parse_all_counters() {
        let usage = session_usage_from_json(
            r#"{"inputTokens":120,"cachedInputTokens":48,"outputTokens":64,"reasoningTokens":16}"#,
        )
        .expect("session usage JSON should parse");

        assert_eq!(usage.input_tokens, 120);
        assert_eq!(usage.cached_input_tokens, 48);
        assert_eq!(usage.output_tokens, 64);
        assert_eq!(usage.reasoning_tokens, 16);
    }

    #[test]
    fn session_usage_should_reject_negative_counters() {
        let err = session_usage_from_json(
            r#"{"inputTokens":-1,"cachedInputTokens":0,"outputTokens":0,"reasoningTokens":0}"#,
        )
        .expect_err("negative token counts should fail");
        assert!(matches!(err, Error::InternalError(_)));
    }

    #[test]
    fn session_usage_should_reject_invalid_json() {
        let err = session_usage_from_json("not json").expect_err("invalid JSON should fail");
        assert!(matches!(err, Error::InternalError(_)));
    }

    #[test]
    fn response_should_expose_optional_usage() {
        let usage = SessionUsage {
            input_tokens: 10,
            cached_input_tokens: 1,
            output_tokens: 5,
            reasoning_tokens: 0,
        };
        let response = Response::with_usage("ok".to_string(), Some(usage));
        assert_eq!(response.usage(), Some(usage));

        let response = Response::with_usage("ok".to_string(), None);
        assert_eq!(response.usage(), None);
    }

    #[test]
    fn session_usage_delta_should_subtract_counters() {
        let earlier = SessionUsage {
            input_tokens: 100,
            cached_input_tokens: 40,
            output_tokens: 50,
            reasoning_tokens: 10,
        };
        let later = SessionUsage {
            input_tokens: 180,
            cached_input_tokens: 90,
            output_tokens: 75,
            reasoning_tokens: 30,
        };

        let delta = later
            .delta_since(&earlier)
            .expect("in-order snapshots should subtract");
        assert_eq!(delta.input_tokens, 80);
        assert_eq!(delta.cached_input_tokens, 50);
        assert_eq!(delta.output_tokens, 25);
        assert_eq!(delta.reasoning_tokens, 20);
    }

    #[test]
    fn session_usage_delta_should_reject_backwards_counters() {
        let earlier = SessionUsage {
            input_tokens: 100,
            cached_input_tokens: 0,
            output_tokens: 0,
            reasoning_tokens: 0,
        };
        let later = SessionUsage {
            input_tokens: 50,
            cached_input_tokens: 0,
            output_tokens: 0,
            reasoning_tokens: 0,
        };

        let err = later
            .delta_since(&earlier)
            .expect_err("backwards counters should fail");
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    #[test]
    fn attachment_specs_should_index_buffers_and_keep_labels() {
        let bytes = [0_u8, 1, 2, 3];
        let attachments = [
            Attachment::file("/tmp/photo.png").with_label("photo"),
            Attachment::image_bytes(&bytes),
        ];

        let (json, buffers, buffer_lens) =
            attachment_specs(&attachments).expect("attachment specs should serialize");

        assert_eq!(
            json,
            r#"[{"kind":"file","path":"/tmp/photo.png","label":"photo"},{"kind":"data","bufferIndex":0}]"#
        );
        assert_eq!(buffers, vec![bytes.as_ptr()]);
        assert_eq!(buffer_lens, vec![bytes.len()]);
    }

    #[test]
    fn attachment_specs_should_reject_non_utf8_paths() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let path = std::path::PathBuf::from(OsString::from_vec(vec![0x66, 0x6f, 0x80]));
        let attachments = [Attachment::file(path)];
        let err = attachment_specs(&attachments).expect_err("non-UTF-8 path should fail");
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    #[test]
    fn system_tools_should_reject_duplicates() {
        let err = system_tools_json(&[SystemTool::Ocr, SystemTool::Ocr])
            .expect_err("duplicate built-in tools should fail");
        assert!(matches!(err, Error::InvalidInput(_)));
    }
}