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
// FoundationModels Swift FFI layer
// Provides C-compatible interface for Rust
//
// All @_cdecl functions use C calling convention and are safe to call from Rust.
// Memory management uses Unmanaged<AnyObject> for explicit retain/release.

import Foundation
import FoundationModels

// MARK: - Error Codes

enum FFIErrorCode: Int32 {
    case unknown = 0
    case modelNotAvailable = 1
    case generationFailed = 2
    case cancelled = 3
    case toolError = 4
    case invalidInput = 5
    case timeout = 6
    case unsupportedPlatform = 7
    case networkFailure = 8
    case quotaLimitReached = 9
    case serviceUnavailable = 10
    case contextSizeExceeded = 11
    case rateLimited = 12
    case guardrailViolation = 13
    case refusal = 14
    case unsupportedCapability = 15
    case unsupportedTranscriptContent = 16
    case unsupportedGenerationGuide = 17
    case unsupportedLanguageOrLocale = 18
    case assetsUnavailable = 19
    case concurrentRequests = 20
}

let tokenUsageUnavailableSentinel: Int64 = -2

// MARK: - Callback Types

/// Tool callback type - Rust side implements this
/// Parameters: userData, toolName, argumentsJson
/// Returns: resultJson (Rust-allocated, caller must free with fm_rust_string_free)
typealias ToolCallbackFn = @convention(c) (
    UnsafeMutableRawPointer?,
    UnsafePointer<CChar>?,
    UnsafePointer<CChar>?
) -> UnsafeMutablePointer<CChar>?

public typealias StreamChunkCallbackFn = @Sendable @convention(c) (
    UnsafeMutableRawPointer?,
    UnsafePointer<CChar>?
) -> Void
public typealias StreamDoneCallbackFn = @Sendable @convention(c) (UnsafeMutableRawPointer?) -> Void
public typealias StreamErrorCallbackFn = @Sendable @convention(c) (
    UnsafeMutableRawPointer?,
    Int32,
    UnsafePointer<CChar>?
) -> Void

/// The Rust caller keeps `userData` alive until the synchronous stream FFI
/// function returns. Bundling it with Sendable C function pointers makes that
/// lifetime contract explicit when the callbacks move into a detached task.
private struct StreamCallbackContext: @unchecked Sendable {
    let userData: UnsafeMutableRawPointer?
    let onChunk: StreamChunkCallbackFn
    let onDone: StreamDoneCallbackFn
    let onError: StreamErrorCallbackFn
}

// MARK: - Error Handling

/// Error info container for FFI
private final class ErrorInfo: @unchecked Sendable {
    let message: String
    let code: Int32
    var toolName: String?
    var toolArguments: String?

    init(message: String, code: Int32, toolName: String? = nil, toolArguments: String? = nil) {
        self.message = message
        self.code = code
        self.toolName = toolName
        self.toolArguments = toolArguments
    }
}

/// Gets the error code from an error object.
@_cdecl("fm_error_code")
public func fm_error_code(_ errorPtr: UnsafeMutableRawPointer) -> Int32 {
    let errorInfo = Unmanaged<AnyObject>.fromOpaque(errorPtr).takeUnretainedValue() as! ErrorInfo
    return errorInfo.code
}

/// Gets the error message from an error object. Caller frees with `fm_string_free`.
@_cdecl("fm_error_message")
public func fm_error_message(_ errorPtr: UnsafeMutableRawPointer) -> UnsafeMutablePointer<CChar>? {
    let errorInfo = Unmanaged<AnyObject>.fromOpaque(errorPtr).takeUnretainedValue() as! ErrorInfo
    return strdup(errorInfo.message)
}

/// Gets the tool name from a tool error (may be null). Caller frees with `fm_string_free`.
@_cdecl("fm_error_tool_name")
public func fm_error_tool_name(_ errorPtr: UnsafeMutableRawPointer) -> UnsafeMutablePointer<CChar>? {
    let errorInfo = Unmanaged<AnyObject>.fromOpaque(errorPtr).takeUnretainedValue() as! ErrorInfo
    guard let toolName = errorInfo.toolName else { return nil }
    return strdup(toolName)
}

/// Gets the tool arguments JSON from a tool error (may be null). Caller frees with `fm_string_free`.
@_cdecl("fm_error_tool_arguments")
public func fm_error_tool_arguments(_ errorPtr: UnsafeMutableRawPointer) -> UnsafeMutablePointer<CChar>? {
    let errorInfo = Unmanaged<AnyObject>.fromOpaque(errorPtr).takeUnretainedValue() as! ErrorInfo
    guard let args = errorInfo.toolArguments else { return nil }
    return strdup(args)
}

/// Frees an error object.
@_cdecl("fm_error_free")
public func fm_error_free(_ errorPtr: UnsafeMutableRawPointer?) {
    guard let errorPtr = errorPtr else { return }
    Unmanaged<AnyObject>.fromOpaque(errorPtr).release()
}

/// Creates an error object.
func createError(_ message: String, code: FFIErrorCode, toolName: String? = nil, toolArguments: String? = nil) -> UnsafeMutableRawPointer {
    let errorInfo = ErrorInfo(message: message, code: code.rawValue, toolName: toolName, toolArguments: toolArguments)
    return Unmanaged.passRetained(errorInfo as AnyObject).toOpaque()
}

/// Creates an error object from a Swift Error, extracting tool context if available.
private func createErrorFromException(_ error: Error, defaultCode: FFIErrorCode = .generationFailed) -> UnsafeMutableRawPointer {
    if let toolError = error as? ToolError {
        return createError(
            toolError.message,
            code: .toolError,
            toolName: toolError.toolName,
            toolArguments: toolError.toolArguments
        )
    } else if let timeoutError = error as? TimeoutError {
        return createError(timeoutError.message, code: .timeout)
    } else if let (code, message) = classifyPlatformError(error) {
        return createError(message, code: code)
    } else {
        return createError(error.localizedDescription, code: defaultCode)
    }
}

/// Maps platform error types onto stable FFI codes: PCC errors first, the
/// Foundation Models 27 taxonomy second, 26-era `GenerationError` cases third,
/// and the observed private bridge identity last.
func classifyPlatformError(_ error: Error) -> (FFIErrorCode, String)? {
    if error is CancellationError {
        return (.cancelled, "Operation cancelled")
    }
    return classifyPrivateCloudComputeError(error)
        ?? classifyLanguageModelError(error)
        ?? classifyLegacyGenerationError(error)
        ?? classifyObservedGenerativeFunctionsContextSizeError(error)
}

private let generativeFunctionsErrorDomain =
    "com.apple.GenerativeFunctionsFoundation.GenerativeError"
private let generativeFunctionsContextSizeExceededCode = 4_050_000

/// macOS 27.0 beta 1 (26A5388g), with Xcode 27.0 beta 1 (27A5228h), was observed
/// throwing the private `GenerativeFunctionsFoundation.GenerativeError` when
/// the combined OCR, barcode reader, and Spotlight schemas exceeded the context
/// window. Blocking and streaming bridged it to this exact NSError domain/code.
/// This private identity is not guaranteed across Apple beta or runtime changes.
private func classifyObservedGenerativeFunctionsContextSizeError(
    _ error: Error
) -> (FFIErrorCode, String)? {
    let nsError = error as NSError
    guard nsError.domain == generativeFunctionsErrorDomain,
          nsError.code == generativeFunctionsContextSizeExceededCode
    else {
        return nil
    }
    return (.contextSizeExceeded, error.localizedDescription)
}

// MARK: - Legacy (Foundation Models 26) Error Classification

private protocol LegacyGenerationErrorClassifying {
    func classify(_ error: Error) -> (FFIErrorCode, String)?
}

private struct LegacyGenerationErrorClassifier: LegacyGenerationErrorClassifying {}

// The 26-era cases are deprecated on 27 SDKs. Implementing the classification
// inside an extension that is itself deprecated compiles without deprecation
// warnings; callers route through the non-deprecated protocol requirement.
@available(*, deprecated, message: "Bridges the deprecated Foundation Models 26 GenerationError cases")
extension LegacyGenerationErrorClassifier {
    func classify(_ error: Error) -> (FFIErrorCode, String)? {
        guard let generationError = error as? LanguageModelSession.GenerationError else {
            return nil
        }

        let base = generationError.errorDescription
        switch generationError {
        case .exceededContextWindowSize(let context):
            return (.contextSizeExceeded, base ?? context.debugDescription)
        case .assetsUnavailable(let context):
            return (.assetsUnavailable, base ?? context.debugDescription)
        case .guardrailViolation(let context):
            return (.guardrailViolation, base ?? context.debugDescription)
        case .unsupportedGuide(let context):
            return (.unsupportedGenerationGuide, base ?? context.debugDescription)
        case .unsupportedLanguageOrLocale(let context):
            return (.unsupportedLanguageOrLocale, base ?? context.debugDescription)
        case .decodingFailure(let context):
            return (.generationFailed, base ?? context.debugDescription)
        case .rateLimited(let context):
            return (.rateLimited, base ?? context.debugDescription)
        case .concurrentRequests(let context):
            return (.concurrentRequests, base ?? context.debugDescription)
        case .refusal(_, let context):
            return (.refusal, base ?? context.debugDescription)
        @unknown default:
            return (.generationFailed, generationError.localizedDescription)
        }
    }
}

/// Bridges 26-era `GenerationError` values thrown by macOS/iOS 26 runtimes.
func classifyLegacyGenerationError(_ error: Error) -> (FFIErrorCode, String)? {
    let classifier: any LegacyGenerationErrorClassifying = LegacyGenerationErrorClassifier()
    return classifier.classify(error)
}

func createGenerationErrorFromException(_ error: Error) -> UnsafeMutableRawPointer {
    createErrorFromException(error)
}

// MARK: - SystemLanguageModel

/// Type-erased language model storage shared by the Rust-facing FFI.
///
/// Foundation Models 26 only accepts `SystemLanguageModel`, while Foundation
/// Models 27 adds the public `LanguageModel` protocol and PCC model. Keeping the
/// concrete model inside closures lets this common source continue to compile
/// with the 26 SDK while a separate 27-only source supplies PCC closures.
final class LanguageModelBox: @unchecked Sendable {
    let systemModel: SystemLanguageModel?
    private let isAvailableHandler: () -> Bool
    private let availabilityHandler: () -> Int32
    private let sessionFactory: ([any Tool], Instructions?) -> LanguageModelSession
    private let transcriptSessionFactory: ([any Tool], Transcript) -> LanguageModelSession
    /// Returns quota usage as JSON; nil when the model has no quota concept.
    let quotaUsageJson: (() -> String?)?
    /// Returns the model context size in tokens; nil when unsupported.
    let contextSize: (() throws -> Int64)?

    init(
        systemModel: SystemLanguageModel? = nil,
        isAvailable: @escaping () -> Bool,
        availability: @escaping () -> Int32,
        makeSession: @escaping ([any Tool], Instructions?) -> LanguageModelSession,
        makeTranscriptSession: @escaping ([any Tool], Transcript) -> LanguageModelSession,
        quotaUsageJson: (() -> String?)? = nil,
        contextSize: (() throws -> Int64)? = nil
    ) {
        self.systemModel = systemModel
        isAvailableHandler = isAvailable
        availabilityHandler = availability
        sessionFactory = makeSession
        transcriptSessionFactory = makeTranscriptSession
        self.quotaUsageJson = quotaUsageJson
        self.contextSize = contextSize
    }

    var isAvailable: Bool { isAvailableHandler() }
    var availabilityCode: Int32 { availabilityHandler() }

    func makeSession(tools: [any Tool], instructions: Instructions?) -> LanguageModelSession {
        sessionFactory(tools, instructions)
    }

    func makeSession(tools: [any Tool], transcript: Transcript) -> LanguageModelSession {
        transcriptSessionFactory(tools, transcript)
    }
}

private func systemModelAvailabilityCode(_ model: SystemLanguageModel) -> Int32 {
    switch model.availability {
    case .available:
        return 0
    case .unavailable(.deviceNotEligible):
        return 1
    case .unavailable(.appleIntelligenceNotEnabled):
        return 2
    case .unavailable(.modelNotReady):
        return 3
    case .unavailable:
        return 4
    }
}

private func makeSystemLanguageModelBox() -> LanguageModelBox {
    let model = SystemLanguageModel.default
    return LanguageModelBox(
        systemModel: model,
        isAvailable: { model.isAvailable },
        availability: { systemModelAvailabilityCode(model) },
        makeSession: { tools, instructions in
            LanguageModelSession(model: model, tools: tools, instructions: instructions)
        },
        makeTranscriptSession: { tools, transcript in
            LanguageModelSession(model: model, tools: tools, transcript: transcript)
        },
        contextSize: systemModelContextSizeHandler(model)
    )
}

/// Creates the default SystemLanguageModel.
@_cdecl("fm_model_default")
public func fm_model_default(_ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?) -> UnsafeMutableRawPointer? {
    _ = errorOut
    let model = makeSystemLanguageModelBox()
    return Unmanaged.passRetained(model as AnyObject).toOpaque()
}

/// Checks if the model is available.
@_cdecl("fm_model_is_available")
public func fm_model_is_available(_ modelPtr: UnsafeMutableRawPointer) -> Bool {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox
    return model.isAvailable
}

/// Gets the availability status as an integer.
@_cdecl("fm_model_availability")
public func fm_model_availability(_ modelPtr: UnsafeMutableRawPointer) -> Int32 {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox
    return model.availabilityCode
}

/// Returns quota usage as a JSON string for models with a usage quota.
/// Sets `errorOut` and returns null for models without quota reporting.
@_cdecl("fm_model_pcc_quota_usage")
public func fm_model_pcc_quota_usage(
    _ modelPtr: UnsafeMutableRawPointer,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox
    guard let quotaUsageJson = model.quotaUsageJson else {
        errorOut?.pointee = createError(
            "Quota usage requires a PrivateCloudComputeLanguageModel on macOS/iOS 27.0 or later",
            code: .unsupportedPlatform
        )
        return nil
    }
    guard let json = quotaUsageJson() else {
        errorOut?.pointee = createError("Failed to encode quota usage", code: .unknown)
        return nil
    }
    return strdup(json)
}

/// Returns the model context size in tokens.
/// Sets `errorOut` and returns -1 for models without context-size reporting.
@_cdecl("fm_model_context_size")
public func fm_model_context_size(
    _ modelPtr: UnsafeMutableRawPointer,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> Int64 {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox
    guard let contextSize = model.contextSize else {
        errorOut?.pointee = createError(
            "Context size reporting requires building with the macOS/iOS 26.4 SDK or later",
            code: .unsupportedPlatform
        )
        return -1
    }
    do {
        return try contextSize()
    } catch {
        errorOut?.pointee = createErrorFromException(error)
        return -1
    }
}

/// Frees a language model box.
@_cdecl("fm_model_free")
public func fm_model_free(_ modelPtr: UnsafeMutableRawPointer?) {
    guard let modelPtr = modelPtr else { return }
    Unmanaged<AnyObject>.fromOpaque(modelPtr).release()
}

// MARK: - Tool Definition from JSON

/// Tool definition parsed from Rust JSON
struct ToolDefinitionDTO: Decodable {
    let name: String
    let description: String
    let argumentsSchemaJson: String

    enum CodingKeys: String, CodingKey {
        case name
        case description
        case argumentsSchema
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        description = try container.decode(String.self, forKey: .description)
        // Decode argumentsSchema as raw JSON and re-encode to string for the description
        if let schemaValue = try? container.decode(AnyCodable.self, forKey: .argumentsSchema) {
            if let data = try? JSONEncoder().encode(schemaValue),
               let jsonStr = String(data: data, encoding: .utf8) {
                argumentsSchemaJson = jsonStr
            } else {
                argumentsSchemaJson = "{}"
            }
        } else {
            argumentsSchemaJson = "{}"
        }
    }
}

/// Helper for decoding arbitrary JSON values
private struct AnyCodable: Codable {
    let value: Any

    init(_ value: Any) {
        self.value = value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if container.decodeNil() {
            value = NSNull()
        } else if let bool = try? container.decode(Bool.self) {
            value = bool
        } else if let int = try? container.decode(Int.self) {
            value = int
        } else if let double = try? container.decode(Double.self) {
            value = double
        } else if let string = try? container.decode(String.self) {
            value = string
        } else if let array = try? container.decode([AnyCodable].self) {
            value = array.map { $0.value }
        } else if let dict = try? container.decode([String: AnyCodable].self) {
            value = dict.mapValues { $0.value }
        } else {
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode value")
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch value {
        case is NSNull:
            try container.encodeNil()
        case let bool as Bool:
            try container.encode(bool)
        case let int as Int:
            try container.encode(int)
        case let double as Double:
            try container.encode(double)
        case let string as String:
            try container.encode(string)
        case let array as [Any]:
            try container.encode(array.map { AnyCodable($0) })
        case let dict as [String: Any]:
            try container.encode(dict.mapValues { AnyCodable($0) })
        default:
            throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: container.codingPath, debugDescription: "Cannot encode value"))
        }
    }
}

private struct ToolError: Error, LocalizedError {
    let message: String
    let toolName: String?
    let toolArguments: String?

    init(message: String, toolName: String? = nil, toolArguments: String? = nil) {
        self.message = message
        self.toolName = toolName
        self.toolArguments = toolArguments
    }

    var errorDescription: String? { message }
}

private struct ToolResultDTO: Decodable {
    let success: Bool
    let content: String?
    let error: String?
}

// MARK: - Dynamic Tool Dispatcher

/// Releases the Rust-side `Arc<ToolCallbackData>` that `userData` points at.
///
/// Defined in Rust (`session.rs`) and linked into the same binary. Declared here
/// rather than passed as a function pointer so `fm_session_create`'s C signature
/// is unchanged.
@_silgen_name("fm_rust_tool_data_free")
func fm_rust_tool_data_free(_ userData: UnsafeMutableRawPointer?)

/// Stores tool context for callback dispatch
final class ToolDispatcher: @unchecked Sendable {
    let toolDefinitions: [ToolDefinitionDTO]
    let userData: UnsafeMutableRawPointer?
    let callback: ToolCallbackFn

    init(toolDefinitions: [ToolDefinitionDTO], userData: UnsafeMutableRawPointer?, callback: @escaping ToolCallbackFn) {
        self.toolDefinitions = toolDefinitions
        self.userData = userData
        self.callback = callback
    }

    /// Hands the Rust `Arc` clone back so it can be dropped.
    ///
    /// Rust transfers ownership of one strong reference into `userData` when the
    /// session is created. Without this the reference — and every `Arc<dyn Tool>`
    /// in its map — lived for the life of the process, once per tool-enabled
    /// session.
    deinit {
        fm_rust_tool_data_free(userData)
    }

    func callTool(name: String, argumentsJson: String) throws -> String {
        // Call Rust callback
        let resultPtr = name.withCString { namePtr in
            argumentsJson.withCString { argsPtr in
                callback(userData, namePtr, argsPtr)
            }
        }

        guard let resultPtr = resultPtr else {
            throw ToolError(message: "Tool callback returned null", toolName: name, toolArguments: argumentsJson)
        }

        // Parse result JSON
        let resultJson = String(cString: resultPtr)

        // Free the Rust-allocated string
        fm_rust_string_free(resultPtr)

        // Parse the result
        guard let resultData = resultJson.data(using: .utf8),
              let result = try? JSONDecoder().decode(ToolResultDTO.self, from: resultData) else {
            throw ToolError(message: "Failed to parse tool result JSON", toolName: name, toolArguments: argumentsJson)
        }

        if result.success {
            return result.content ?? ""
        } else {
            throw ToolError(message: result.error ?? "Unknown tool error", toolName: name, toolArguments: argumentsJson)
        }
    }
}

// MARK: - Generic Tool Bridge
//
// FoundationModels requires @Generable typed arguments for tools.
// We bridge dynamic Rust tools by creating a generic dispatcher tool that:
// 1. Accepts a tool name and JSON arguments from the model
// 2. Dispatches to the appropriate Rust callback
// 3. Returns the result to the model

/// Arguments for the generic tool dispatcher.
/// The model generates this structure to invoke a Rust-defined tool.
@Generable
struct GenericToolArgument: Sendable, Codable {
    let name: String
    let value: String
}

@Generable
struct GenericToolCallArguments: Sendable, Codable {
    /// The name of the tool to invoke (must match a registered Rust tool)
    let toolName: String

    /// Arguments for the tool as key/value pairs (values are JSON fragments)
    let arguments: [GenericToolArgument]

    enum CodingKeys: String, CodingKey {
        case toolName
        case toolNameSnake = "tool_name"
        case name
        case arguments
    }

    init(toolName: String, arguments: [GenericToolArgument]) {
        self.toolName = toolName
        self.arguments = arguments
    }

    init(from decoder: Decoder) throws {
        if let container = try? decoder.container(keyedBy: CodingKeys.self) {
            toolName = decodeToolName(from: container)
            arguments = (try? container.decode([GenericToolArgument].self, forKey: .arguments)) ?? []
            return
        }

        if let single = try? decoder.singleValueContainer() {
            if let text = try? single.decode(String.self) {
                toolName = text
                arguments = []
                return
            }
        }

        toolName = ""
        arguments = []
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(toolName, forKey: .toolName)
        try container.encode(arguments, forKey: .arguments)
    }
}

private func decodeToolName(
    from container: KeyedDecodingContainer<GenericToolCallArguments.CodingKeys>
) -> String {
    if let value = try? container.decode(String.self, forKey: .toolName) {
        return value
    }
    if let value = try? container.decode(String.self, forKey: .toolNameSnake) {
        return value
    }
    if let value = try? container.decode(String.self, forKey: .name) {
        return value
    }
    return ""
}

private func buildArgumentsJson(
    _ arguments: [GenericToolArgument],
    stringProperties: Set<String>
) -> String {
    var dict: [String: Any] = [:]
    for arg in arguments {
        // The model may pad names with whitespace; match schema property
        // names the same way tool names are matched (trimmed).
        let name = arg.name.trimmingCharacters(in: .whitespacesAndNewlines)
        if stringProperties.contains(name) {
            // The schema declares this property as a string; parsing the value
            // as a JSON fragment would coerce "90210" to a number or "true" to
            // a boolean. Only unwrap an explicitly quoted JSON string.
            if let parsed = parseJsonFragment(arg.value) as? String {
                dict[name] = parsed
            } else {
                dict[name] = arg.value
            }
        } else if let parsed = parseJsonFragment(arg.value) {
            dict[name] = parsed
        } else {
            dict[name] = arg.value
        }
    }

    guard JSONSerialization.isValidJSONObject(dict),
          let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
          let text = String(data: data, encoding: .utf8) else {
        return "{}"
    }

    return text
}

/// Property names declared with `"type": "string"` in a tool's arguments schema.
private func stringPropertyNames(inSchemaJson schemaJson: String) -> Set<String> {
    guard let data = schemaJson.data(using: .utf8),
          let schema = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
          let properties = schema["properties"] as? [String: Any] else {
        return []
    }

    var names: Set<String> = []
    for (name, propertySchema) in properties {
        if let property = propertySchema as? [String: Any],
           property["type"] as? String == "string" {
            names.insert(name)
        }
    }
    return names
}

/// Property names listed in the schema's `"required"` array.
private func requiredPropertyNames(inSchemaJson schemaJson: String) -> [String] {
    guard let data = schemaJson.data(using: .utf8),
          let schema = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
          let required = schema["required"] as? [String] else {
        return []
    }
    return required
}

private func parseJsonFragment(_ text: String) -> Any? {
    guard let data = text.data(using: .utf8) else { return nil }
    return try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
}

/// Returns the byte-level suffix of a cumulative snapshot.
///
/// Swift `Character` boundaries can change when a later snapshot extends the
/// final grapheme (for example, `"e"` followed by `"e\u{301}"`). UTF-8
/// boundaries remain stable for that append-only case.
private func incrementalSuffix(of content: String, after previous: String) -> String? {
    guard content.utf8.starts(with: previous.utf8) else { return nil }
    return String(
        decoding: content.utf8.dropFirst(previous.utf8.count),
        as: UTF8.self
    )
}

/// Owns a tool-call continuation so task cancellation and the blocking Rust
/// callback can race without double-resuming it.
private final class ToolCallContinuationState: @unchecked Sendable {
    private let lock = NSLock()
    private var continuation: CheckedContinuation<String, Error>?
    private var isCancelled = false
    private var isCompleted = false

    /// Installs the continuation, returning false when cancellation won the race.
    func install(_ continuation: CheckedContinuation<String, Error>) -> Bool {
        lock.lock()
        if isCancelled || isCompleted {
            isCompleted = true
            lock.unlock()
            continuation.resume(throwing: CancellationError())
            return false
        }
        self.continuation = continuation
        lock.unlock()
        return true
    }

    func resume(with result: Result<String, Error>) {
        lock.lock()
        guard !isCompleted, let continuation else {
            lock.unlock()
            return
        }
        isCompleted = true
        self.continuation = nil
        lock.unlock()
        continuation.resume(with: result)
    }

    func cancel() {
        lock.lock()
        guard !isCompleted else {
            lock.unlock()
            return
        }
        isCancelled = true
        guard let continuation else {
            lock.unlock()
            return
        }
        isCompleted = true
        self.continuation = nil
        lock.unlock()
        continuation.resume(throwing: CancellationError())
    }
}

/// A bridge tool that dispatches to Rust-defined tools.
/// This is registered with FoundationModels and handles all dynamic tool calls.
final class GenericToolBridge: Tool, @unchecked Sendable {
    typealias Arguments = GenericToolCallArguments
    typealias Output = String

    private let dispatcher: ToolDispatcher
    private let toolDescriptions: String
    private let stringPropertiesByTool: [String: Set<String>]
    private let requiredPropertiesByTool: [String: [String]]

    /// Creates a bridge with the given dispatcher and tool descriptions for the schema.
    init(dispatcher: ToolDispatcher) {
        self.dispatcher = dispatcher
        // Build detailed description from tool definitions including schemas
        let descriptions = dispatcher.toolDefinitions.map { def in
            """
            Tool: \(def.name)
            Description: \(def.description)
            Arguments schema: \(def.argumentsSchemaJson)
            """
        }.joined(separator: "\n\n")
        self.toolDescriptions = descriptions

        var stringProperties: [String: Set<String>] = [:]
        var requiredProperties: [String: [String]] = [:]
        for def in dispatcher.toolDefinitions {
            stringProperties[def.name] = stringPropertyNames(inSchemaJson: def.argumentsSchemaJson)
            requiredProperties[def.name] = requiredPropertyNames(inSchemaJson: def.argumentsSchemaJson)
        }
        self.stringPropertiesByTool = stringProperties
        self.requiredPropertiesByTool = requiredProperties
    }

    var name: String { "invoke_tool" }

    var description: String {
        """
        Invokes a registered tool by name. You must provide:
        1. toolName: The exact name of the tool to call
        2. arguments: A list of {name, value} pairs for the tool arguments

        IMPORTANT: The value field must be a JSON fragment (e.g., "42", "true", "\"hello\"", or "{\"key\": 1}") as a string.

        Available tools and their argument schemas:

        \(toolDescriptions)

        Example usage for a weather tool:
        - toolName: "checkWeather"
        - arguments: [ { "name": "location", "value": "Tokyo, Japan" } ]
        """
    }

    func call(arguments: GenericToolCallArguments) async throws -> String {
        let toolName = arguments.toolName.trimmingCharacters(in: .whitespacesAndNewlines)
        if toolName.isEmpty {
            throw ToolError(message: "Missing tool name")
        }
        // The model sometimes omits required arguments; feed the omission back
        // as the tool output so it can retry with the full set instead of the
        // tool silently running on defaults.
        let provided = Set(
            arguments.arguments.map { $0.name.trimmingCharacters(in: .whitespacesAndNewlines) }
        )
        let missing = (requiredPropertiesByTool[toolName] ?? []).filter { !provided.contains($0) }
        if !missing.isEmpty {
            return """
            Error: missing required argument(s) \(missing.joined(separator: ", ")) for tool \
            "\(toolName)". Call the tool again providing every required argument.
            """
        }

        let argsJson = buildArgumentsJson(
            arguments.arguments,
            stringProperties: stringPropertiesByTool[toolName] ?? []
        )
        // callTool blocks in synchronous Rust user code; run it on a Dispatch
        // thread so it cannot starve the cooperative pool (a Rust tool that
        // re-enters this library needs a pool thread to make progress).
        let dispatcher = self.dispatcher
        let continuationState = ToolCallContinuationState()
        return try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                guard continuationState.install(continuation) else { return }
                DispatchQueue.global(qos: .userInitiated).async {
                    let result: Result<String, Error>
                    do {
                        result = .success(
                            try dispatcher.callTool(name: toolName, argumentsJson: argsJson)
                        )
                    } catch {
                        result = .failure(error)
                    }
                    continuationState.resume(with: result)
                }
            }
        } onCancel: {
            // The synchronous Rust callback cannot be forcibly stopped, but
            // the generation must not remain suspended waiting for it.
            continuationState.cancel()
        }
    }
}

/// Parses tool definitions from JSON
func parseToolDefinitions(_ toolsJson: UnsafePointer<CChar>?) throws -> [ToolDefinitionDTO] {
    guard let toolsJson = toolsJson else { return [] }

    let jsonString = String(cString: toolsJson)
    guard let jsonData = jsonString.data(using: .utf8) else {
        throw ToolDefinitionError(message: "Invalid UTF-8 in tools JSON")
    }

    do {
        return try JSONDecoder().decode([ToolDefinitionDTO].self, from: jsonData)
    } catch {
        throw ToolDefinitionError(message: "Failed to decode tools JSON: \(error.localizedDescription)")
    }
}

private struct ToolDefinitionError: Error {
    let message: String
}

// MARK: - Session State

/// Session state container for FFI with tools support
final class SessionState: @unchecked Sendable {
    let session: LanguageModelSession
    let toolDispatcher: ToolDispatcher?
    private var currentTask: Task<Void, Never>?
    private let lock = NSLock()
    private var lastResponseUsageJsonStorage: String?

    init(session: LanguageModelSession, toolDispatcher: ToolDispatcher? = nil) {
        self.session = session
        self.toolDispatcher = toolDispatcher
    }

    /// Records per-response usage; nil clears it (fallback builds/runtimes).
    func setLastResponseUsage(_ json: String?) {
        lock.lock()
        defer { lock.unlock() }
        lastResponseUsageJsonStorage = json
    }

    var lastResponseUsageJson: String? {
        lock.lock()
        defer { lock.unlock() }
        return lastResponseUsageJsonStorage
    }

    func setTask(_ task: Task<Void, Never>?) {
        lock.lock()
        defer { lock.unlock() }
        currentTask = task
    }

    /// Claims successful completion before a concurrent cancellation can
    /// target the task. Returns false when cancellation already won the race.
    func finishCurrentTask() -> Bool {
        lock.lock()
        defer { lock.unlock() }
        guard let task = currentTask else { return false }
        currentTask = nil
        return !task.isCancelled
    }

    /// Creates a detached task and registers it while holding the lock, so a
    /// concurrent `fm_session_cancel` cannot slip between creation and
    /// registration and be lost.
    @discardableResult
    func beginTrackedTask(_ operation: @escaping @Sendable () async -> Void) -> Task<Void, Never> {
        lock.lock()
        defer { lock.unlock() }
        let task = Task.detached { await operation() }
        currentTask = task
        return task
    }

    func cancelCurrentTask() {
        lock.lock()
        defer { lock.unlock() }
        currentTask?.cancel()
        currentTask = nil
    }
}

// MARK: - Session Creation

/// Creates a new session with optional instructions, tools, and tool callback.
///
/// Tools are bridged through a GenericToolBridge that allows FoundationModels to
/// invoke Rust-defined tools dynamically. The model calls `invoke_tool` with the
/// tool name and JSON arguments, which dispatches to the appropriate Rust callback.
@_cdecl("fm_session_create")
public func fm_session_create(
    _ modelPtr: UnsafeMutableRawPointer,
    _ instructions: UnsafePointer<CChar>?,
    _ toolsJson: UnsafePointer<CChar>?,
    _ builtinToolsJson: UnsafePointer<CChar>?,
    _ userData: UnsafeMutableRawPointer?,
    _ toolCallback: @escaping @convention(c) (UnsafeMutableRawPointer?, UnsafePointer<CChar>?, UnsafePointer<CChar>?) -> UnsafeMutablePointer<CChar>?,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutableRawPointer? {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox

    // Parse built-in system tool names
    let builtinToolNames: [String]
    if let builtinToolsJson {
        let jsonString = String(cString: builtinToolsJson)
        guard let jsonData = jsonString.data(using: .utf8),
              let names = try? JSONDecoder().decode([String].self, from: jsonData)
        else {
            errorOut?.pointee = createError("Invalid built-in tools JSON", code: .invalidInput)
            return nil
        }
        builtinToolNames = names
    } else {
        builtinToolNames = []
    }
    guard let builtinTools = makeBuiltinTools(builtinToolNames, errorOut: errorOut) else {
        return nil
    }

    // Parse instructions
    let instructionsValue: Instructions?
    if let instructions = instructions {
        instructionsValue = Instructions(String(cString: instructions))
    } else {
        instructionsValue = nil
    }

    // Parse tool definitions and create dispatcher + bridge
    let toolDefinitions: [ToolDefinitionDTO]
    do {
        toolDefinitions = try parseToolDefinitions(toolsJson)
    } catch let parseError as ToolDefinitionError {
        if let errorOut = errorOut {
            errorOut.pointee = createError(parseError.message, code: .invalidInput)
        }
        return nil
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createError(
                "Failed to decode tools JSON: \(error.localizedDescription)",
                code: .invalidInput
            )
        }
        return nil
    }
    // INVARIANT: every fallible step must precede ToolDispatcher construction.
    // Rust reclaims the userData Arc when this function returns nil, and the
    // dispatcher's deinit reclaims it again — an error return after this point
    // would double-free.
    let toolDispatcher: ToolDispatcher?
    let toolBridge: GenericToolBridge?

    if !toolDefinitions.isEmpty {
        let dispatcher = ToolDispatcher(toolDefinitions: toolDefinitions, userData: userData, callback: toolCallback)
        toolDispatcher = dispatcher
        toolBridge = GenericToolBridge(dispatcher: dispatcher)
    } else {
        toolDispatcher = nil
        toolBridge = nil
    }

    let sessionTools: [any Tool] = (toolBridge.map { [$0] } ?? []) + builtinTools
    let session = model.makeSession(tools: sessionTools, instructions: instructionsValue)

    let state = SessionState(session: session, toolDispatcher: toolDispatcher)
    return Unmanaged.passRetained(state as AnyObject).toOpaque()
}

/// Creates a session from a transcript JSON string.
@_cdecl("fm_session_from_transcript")
public func fm_session_from_transcript(
    _ modelPtr: UnsafeMutableRawPointer,
    _ transcriptJson: UnsafePointer<CChar>,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutableRawPointer? {
    let model = Unmanaged<AnyObject>.fromOpaque(modelPtr).takeUnretainedValue() as! LanguageModelBox
    let jsonString = String(cString: transcriptJson)

    guard let jsonData = jsonString.data(using: .utf8) else {
        if let errorOut = errorOut {
            errorOut.pointee = createError("Invalid UTF-8 in transcript JSON", code: .invalidInput)
        }
        return nil
    }

    do {
        let transcript = try JSONDecoder().decode(Transcript.self, from: jsonData)
        let session = model.makeSession(tools: [], transcript: transcript)
        let state = SessionState(session: session)
        return Unmanaged.passRetained(state as AnyObject).toOpaque()
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createError("Failed to decode transcript: \(error.localizedDescription)", code: .invalidInput)
        }
        return nil
    }
}

/// Frees a session.
@_cdecl("fm_session_free")
public func fm_session_free(_ sessionPtr: UnsafeMutableRawPointer?) {
    guard let sessionPtr = sessionPtr else { return }
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeRetainedValue() as! SessionState
    state.cancelCurrentTask()
}

/// Takes an extra retain on the session state so a cancellation handle can
/// outlive the owning session without dangling.
@_cdecl("fm_session_retain")
public func fm_session_retain(_ sessionPtr: UnsafeMutableRawPointer) {
    _ = Unmanaged<AnyObject>.fromOpaque(sessionPtr).retain()
}

/// Releases a reference taken with `fm_session_retain`. Unlike
/// `fm_session_free`, this does not cancel any in-flight task.
@_cdecl("fm_session_release")
public func fm_session_release(_ sessionPtr: UnsafeMutableRawPointer?) {
    guard let sessionPtr = sessionPtr else { return }
    Unmanaged<AnyObject>.fromOpaque(sessionPtr).release()
}

// MARK: - Session Respond (Blocking)

/// Sends a prompt and blocks until response is ready.
@_cdecl("fm_session_respond")
public func fm_session_respond(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let options = parseGenerationOptions(optionsJson)

    do {
        let (content, usageJson) = try AsyncWaiter.wait(session: state) {
            let response = try await state.session.respond(to: promptString, options: options)
            return (response.content, responseUsageJson(response))
        }

        state.setLastResponseUsage(usageJson)
        return strdup(content)
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createErrorFromException(error)
        }
        return nil
    }
}

/// Sends a prompt and blocks until response is ready, with a timeout in milliseconds.
@_cdecl("fm_session_respond_with_timeout")
public func fm_session_respond_with_timeout(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ timeoutMs: UInt64,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let options = parseGenerationOptions(optionsJson)

    do {
        let (content, usageJson) = try AsyncWaiter.wait(session: state, timeoutMs: timeoutMs) {
            let response = try await state.session.respond(to: promptString, options: options)
            return (response.content, responseUsageJson(response))
        }

        state.setLastResponseUsage(usageJson)
        return strdup(content)
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createErrorFromException(error)
        }
        return nil
    }
}

// MARK: - Session Streaming

/// Starts streaming a response.
///
/// Tool invocations during streaming are handled through the GenericToolBridge
/// registered during session creation, not through a separate callback.
@_cdecl("fm_session_stream")
public func fm_session_stream(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ userData: UnsafeMutableRawPointer?,
    _ onChunk: @escaping StreamChunkCallbackFn,
    _ onDone: @escaping StreamDoneCallbackFn,
    _ onError: @escaping StreamErrorCallbackFn
) {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let options = parseGenerationOptions(optionsJson)

    // Streaming records no per-response usage; clear any value left by a
    // previous blocking response so fm_session_last_response_usage cannot
    // return stale data.
    state.setLastResponseUsage(nil)

    let callbackQueue = DispatchQueue(label: "fm.ffi.callbacks", qos: .userInteractive)
    let callbacks = StreamCallbackContext(
        userData: userData,
        onChunk: onChunk,
        onDone: onDone,
        onError: onError
    )
    let semaphore = DispatchSemaphore(value: 0)

    state.beginTrackedTask {
        do {
            let stream = state.session.streamResponse(to: promptString, options: options)

            // The framework yields cumulative snapshots; emit only the newly
            // generated suffix so Rust callers receive incremental chunks.
            var emittedContent = ""

            for try await partialResponse in stream {
                let content = partialResponse.content
                let delta: String
                if let suffix = incrementalSuffix(of: content, after: emittedContent) {
                    delta = suffix
                } else {
                    // The snapshot was rewritten rather than extended; emit it
                    // whole rather than losing the revision.
                    delta = content
                }
                emittedContent = content

                if !delta.isEmpty {
                    callbackQueue.sync {
                        delta.withCString { ptr in
                            callbacks.onChunk(callbacks.userData, ptr)
                        }
                    }
                }

                if Task.isCancelled {
                    callbackQueue.sync {
                        "Cancelled".withCString { ptr in
                            callbacks.onError(
                                callbacks.userData,
                                FFIErrorCode.cancelled.rawValue,
                                ptr
                            )
                        }
                    }
                    semaphore.signal()
                    return
                }
            }

            let completed = state.finishCurrentTask()
            callbackQueue.sync {
                if completed {
                    callbacks.onDone(callbacks.userData)
                } else {
                    "Cancelled".withCString { ptr in
                        callbacks.onError(callbacks.userData, FFIErrorCode.cancelled.rawValue, ptr)
                    }
                }
            }
        } catch {
            callbackQueue.sync {
                // Extract tool error context if available
                let (errorCode, errorMessage): (Int32, String)
                if let toolError = error as? ToolError {
                    // Include tool context in the error message for streaming
                    var msg = toolError.message
                    if let name = toolError.toolName {
                        msg += " [tool: \(name)]"
                    }
                    errorCode = FFIErrorCode.toolError.rawValue
                    errorMessage = msg
                } else if let (code, message) = classifyPlatformError(error) {
                    errorCode = code.rawValue
                    errorMessage = message
                } else {
                    errorCode = FFIErrorCode.generationFailed.rawValue
                    errorMessage = error.localizedDescription
                }
                errorMessage.withCString { ptr in
                    callbacks.onError(callbacks.userData, errorCode, ptr)
                }
            }
        }

        semaphore.signal()
    }

    semaphore.wait()
    state.setTask(nil)
}

/// Cancels an ongoing stream operation.
@_cdecl("fm_session_cancel")
public func fm_session_cancel(_ sessionPtr: UnsafeMutableRawPointer) {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    state.cancelCurrentTask()
}

/// Returns the usage recorded for the most recent completed response, or
/// null when none has been recorded (pre-27 SDKs/runtimes, or no blocking
/// response has finished yet). Caller frees with `fm_string_free`.
@_cdecl("fm_session_last_response_usage")
public func fm_session_last_response_usage(
    _ sessionPtr: UnsafeMutableRawPointer
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    guard let json = state.lastResponseUsageJson else { return nil }
    return strdup(json)
}

/// Checks if the session is currently responding.
@_cdecl("fm_session_is_responding")
public func fm_session_is_responding(_ sessionPtr: UnsafeMutableRawPointer) -> Bool {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    return state.session.isResponding
}

// MARK: - Transcript

/// Gets the session transcript as JSON.
@_cdecl("fm_session_get_transcript")
public func fm_session_get_transcript(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let transcript = state.session.transcript

    do {
        let encoder = JSONEncoder()
        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
        let data = try encoder.encode(transcript)
        guard let jsonString = String(data: data, encoding: .utf8) else {
            if let errorOut = errorOut {
                errorOut.pointee = createError("Failed to encode transcript", code: .unknown)
            }
            return nil
        }
        return strdup(jsonString)
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createError(
                "Failed to encode transcript: \(error.localizedDescription)",
                code: .unknown
            )
        }
        return nil
    }
}

/// Prewarms the model with an optional prompt prefix.
@_cdecl("fm_session_prewarm")
public func fm_session_prewarm(_ sessionPtr: UnsafeMutableRawPointer, _ promptPrefix: UnsafePointer<CChar>?) {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let prefix = promptPrefix.map { String(cString: $0) }

    Task.detached {
        if let prefix = prefix {
            state.session.prewarm(promptPrefix: Prompt(prefix))
        } else {
            state.session.prewarm()
        }
    }
}

// MARK: - Generation Options

/// Parses generation options from JSON string.
func parseGenerationOptions(_ optionsJson: UnsafePointer<CChar>?) -> GenerationOptions {
    guard let optionsJson = optionsJson else {
        return GenerationOptions()
    }

    let jsonString = String(cString: optionsJson)
    guard let jsonData = jsonString.data(using: .utf8) else {
        return GenerationOptions()
    }

    do {
        let decoded = try JSONDecoder().decode(GenerationOptionsDTO.self, from: jsonData)

        // Note: seed is not supported in current GenerationOptions API
        return makeGenerationOptions(
            sampling: decoded.sampling,
            temperature: decoded.temperature,
            maximumResponseTokens: decoded.maximumResponseTokens,
            toolCallingMode: decoded.toolCallingMode
        )
    } catch {
        return GenerationOptions()
    }
}

/// DTO for parsing generation options from JSON.
private struct GenerationOptionsDTO: Decodable {
    var temperature: Double?
    var sampling: String?
    var maximumResponseTokens: UInt32?
    var seed: UInt64?
    var toolCallingMode: String?
}

// MARK: - Structured (JSON) Response

private func structuredPrompt(_ prompt: String, schema: String) -> String {
    """
    \(prompt)

    IMPORTANT: You must respond with valid JSON that matches this schema exactly:
    \(schema)

    Output only the JSON object, with no additional text, markdown formatting, or explanation.
    """
}

private func respondJson(
    state: SessionState,
    prompt: String,
    schema: String,
    options: GenerationOptions,
    timeoutMs: UInt64? = nil
) throws -> String {
    let formattedPrompt = structuredPrompt(prompt, schema: schema)
    let operation: @Sendable () async throws -> (String, String?) = {
        let response = try await state.session.respond(to: formattedPrompt, options: options)
        return (response.content, responseUsageJson(response))
    }

    let result: (content: String, usageJson: String?)
    if let timeoutMs = timeoutMs {
        result = try AsyncWaiter.wait(session: state, timeoutMs: timeoutMs, operation)
    } else {
        result = try AsyncWaiter.wait(session: state, operation)
    }

    state.setLastResponseUsage(result.usageJson)
    return extractJson(from: result.content)
}

/// Sends a prompt and returns a JSON response matching the provided schema.
/// The schema is used to instruct the model to output valid JSON. On success,
/// fm_session_last_response_usage exposes this response's usage when available.
@_cdecl("fm_session_respond_json")
public func fm_session_respond_json(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ schemaJson: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let schemaString = String(cString: schemaJson)
    let options = parseGenerationOptions(optionsJson)

    do {
        let jsonContent = try respondJson(
            state: state,
            prompt: promptString,
            schema: schemaString,
            options: options
        )
        return strdup(jsonContent)
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createErrorFromException(error)
        }
        return nil
    }
}

/// Sends a prompt and returns a JSON response matching the provided schema,
/// waiting at most timeoutMs milliseconds. On success,
/// fm_session_last_response_usage exposes this response's usage when available.
/// A zero timeout expires immediately. Rust callers that request the legacy
/// no-timeout path use fm_session_respond_json instead.
@_cdecl("fm_session_respond_json_with_timeout")
public func fm_session_respond_json_with_timeout(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ schemaJson: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ timeoutMs: UInt64,
    _ errorOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>?
) -> UnsafeMutablePointer<CChar>? {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let schemaString = String(cString: schemaJson)
    let options = parseGenerationOptions(optionsJson)

    do {
        let jsonContent = try respondJson(
            state: state,
            prompt: promptString,
            schema: schemaString,
            options: options,
            timeoutMs: timeoutMs
        )
        return strdup(jsonContent)
    } catch {
        if let errorOut = errorOut {
            errorOut.pointee = createErrorFromException(error)
        }
        return nil
    }
}

/// Streams a JSON response matching the provided schema.
@_cdecl("fm_session_stream_json")
public func fm_session_stream_json(
    _ sessionPtr: UnsafeMutableRawPointer,
    _ prompt: UnsafePointer<CChar>,
    _ schemaJson: UnsafePointer<CChar>,
    _ optionsJson: UnsafePointer<CChar>?,
    _ userData: UnsafeMutableRawPointer?,
    _ onChunk: @escaping StreamChunkCallbackFn,
    _ onDone: @escaping StreamDoneCallbackFn,
    _ onError: @escaping StreamErrorCallbackFn
) {
    let state = Unmanaged<AnyObject>.fromOpaque(sessionPtr).takeUnretainedValue() as! SessionState
    let promptString = String(cString: prompt)
    let schemaString = String(cString: schemaJson)
    let options = parseGenerationOptions(optionsJson)

    let formattedPrompt = structuredPrompt(promptString, schema: schemaString)

    // Streaming records no per-response usage; clear any value left by a
    // previous blocking response so fm_session_last_response_usage cannot
    // return stale data.
    state.setLastResponseUsage(nil)

    let callbackQueue = DispatchQueue(label: "fm.ffi.callbacks.json", qos: .userInteractive)
    let callbacks = StreamCallbackContext(
        userData: userData,
        onChunk: onChunk,
        onDone: onDone,
        onError: onError
    )
    let semaphore = DispatchSemaphore(value: 0)

    state.beginTrackedTask {
        do {
            let stream = state.session.streamResponse(to: formattedPrompt, options: options)

            for try await partialResponse in stream {
                let content = partialResponse.content
                callbackQueue.sync {
                    content.withCString { ptr in
                        callbacks.onChunk(callbacks.userData, ptr)
                    }
                }

                if Task.isCancelled {
                    callbackQueue.sync {
                        "Cancelled".withCString { ptr in
                            callbacks.onError(
                                callbacks.userData,
                                FFIErrorCode.cancelled.rawValue,
                                ptr
                            )
                        }
                    }
                    semaphore.signal()
                    return
                }
            }

            let completed = state.finishCurrentTask()
            callbackQueue.sync {
                if completed {
                    callbacks.onDone(callbacks.userData)
                } else {
                    "Cancelled".withCString { ptr in
                        callbacks.onError(callbacks.userData, FFIErrorCode.cancelled.rawValue, ptr)
                    }
                }
            }
        } catch {
            callbackQueue.sync {
                let (errorCode, errorMessage): (Int32, String)
                if let (code, message) = classifyPlatformError(error) {
                    errorCode = code.rawValue
                    errorMessage = message
                } else {
                    errorCode = FFIErrorCode.generationFailed.rawValue
                    errorMessage = error.localizedDescription
                }
                errorMessage.withCString { ptr in
                    callbacks.onError(callbacks.userData, errorCode, ptr)
                }
            }
        }

        semaphore.signal()
    }

    semaphore.wait()
    state.setTask(nil)
}

/// Extracts JSON from a response that might contain markdown code blocks or extra text.
private func extractJson(from content: String) -> String {
    let trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)

    // Check for markdown code block
    if trimmed.hasPrefix("```") {
        // Find the end of the opening fence
        if let startRange = trimmed.range(of: "\n") {
            let afterFence = trimmed[startRange.upperBound...]
            // Find closing fence
            if let endRange = afterFence.range(of: "```") {
                return String(afterFence[..<endRange.lowerBound]).trimmingCharacters(in: .whitespacesAndNewlines)
            }
        }
    }

    // Check if it starts with { or [ (already JSON) - extract balanced JSON
    if trimmed.hasPrefix("{") {
        return extractBalancedJson(from: trimmed, open: "{", close: "}")
    }
    if trimmed.hasPrefix("[") {
        return extractBalancedJson(from: trimmed, open: "[", close: "]")
    }

    // Try to find JSON object or array in the content - use whichever comes first
    let objectStart = trimmed.firstIndex(of: "{")
    let arrayStart = trimmed.firstIndex(of: "[")

    if let obj = objectStart, let arr = arrayStart {
        // Both found - use whichever comes first
        if obj <= arr {
            return extractBalancedJson(from: String(trimmed[obj...]), open: "{", close: "}")
        } else {
            return extractBalancedJson(from: String(trimmed[arr...]), open: "[", close: "]")
        }
    } else if let obj = objectStart {
        return extractBalancedJson(from: String(trimmed[obj...]), open: "{", close: "}")
    } else if let arr = arrayStart {
        return extractBalancedJson(from: String(trimmed[arr...]), open: "[", close: "]")
    }

    // Return as-is
    return trimmed
}

/// Extracts a balanced JSON structure (object or array) from the start of a string.
/// Handles nested structures and strings with escaped characters.
private func extractBalancedJson(from content: String, open: Character, close: Character) -> String {
    var depth = 0
    var inString = false
    var escapeNext = false
    var endIndex = content.startIndex
    var index = content.startIndex

    while index < content.endIndex {
        let char = content[index]
        defer { index = content.index(after: index) }

        if escapeNext {
            escapeNext = false
            continue
        }

        if char == "\\" && inString {
            escapeNext = true
            continue
        }

        if char == "\"" {
            inString = !inString
            continue
        }

        if !inString {
            if char == open {
                depth += 1
            } else if char == close {
                depth -= 1
                if depth == 0 {
                    endIndex = content.index(after: index)
                    break
                }
            }
        }
    }

    // If we found a balanced structure, return it; otherwise return original
    if depth == 0 && endIndex > content.startIndex {
        return String(content[..<endIndex])
    }
    return content
}

// MARK: - String Helpers

/// Frees a string allocated by the Swift layer (strdup).
@_cdecl("fm_string_free")
public func fm_string_free(_ s: UnsafeMutablePointer<CChar>?) {
    guard let s = s else { return }
    free(s)
}

// fm_rust_string_free is exported by Rust (src/lib.rs) and linked at build time.
// Swift calls this to properly deallocate strings returned from Rust callbacks.
// Declaration for Swift to call the Rust-exported function:
@_silgen_name("fm_rust_string_free")
private func fm_rust_string_free(_ s: UnsafeMutablePointer<CChar>?)

// MARK: - Async Helpers

/// Helper for synchronously running Swift async code.
///
/// Pass `session:` for session-bound generations so the task is registered
/// with the `SessionState` and `fm_session_cancel` can reach it.
final class AsyncWaiter {
    private final class AsyncState<T: Sendable>: @unchecked Sendable {
        var result: Result<T, Error>?
        let semaphore = DispatchSemaphore(value: 0)
    }

    private static func launch<T: Sendable>(
        _ operation: @escaping @Sendable () async throws -> T,
        session: SessionState?,
        into state: AsyncState<T>
    ) -> Task<Void, Never> {
        let body: @Sendable () async -> Void = {
            do {
                let value = try await operation()
                state.result = .success(value)
            } catch {
                state.result = .failure(error)
            }
            state.semaphore.signal()
        }
        if let session {
            return session.beginTrackedTask(body)
        }
        return Task.detached(operation: body)
    }

    private static func takeResult<T: Sendable>(
        _ state: AsyncState<T>,
        session: SessionState?
    ) throws -> T {
        session?.setTask(nil)
        switch state.result {
        case .success(let value):
            return value
        case .failure(let error):
            throw error
        case .none:
            throw TimeoutError(message: "No result available")
        }
    }

    static func wait<T: Sendable>(
        session: SessionState? = nil,
        _ operation: @escaping @Sendable () async throws -> T
    ) throws -> T {
        let state = AsyncState<T>()
        _ = launch(operation, session: session, into: state)
        state.semaphore.wait()
        return try takeResult(state, session: session)
    }

    static func wait<T: Sendable>(
        session: SessionState? = nil,
        timeoutMs: UInt64,
        _ operation: @escaping @Sendable () async throws -> T
    ) throws -> T {
        let state = AsyncState<T>()
        let task = launch(operation, session: session, into: state)

        let timeoutMsInt = timeoutMs > UInt64(Int.max) ? Int.max : Int(timeoutMs)
        if state.semaphore.wait(timeout: .now() + .milliseconds(timeoutMsInt)) == .timedOut {
            // Leave the cancelled task registered: it may drain for a while,
            // and fm_session_cancel remains able to target it.
            task.cancel()
            throw TimeoutError(message: "Timed out after \(timeoutMs) ms")
        }

        return try takeResult(state, session: session)
    }
}

private struct TimeoutError: Error {
    let message: String
}