wiremux 0.11.9

Wiremux maps Chat Completions, Messages, Responses, Gemini, and Converse through one IR.
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
//! Item-centered IR and LossReport.

use std::collections::BTreeMap;

/// Protocol-neutral conversation. Hosts convert to/from their own types.
///
/// Build with [`IrRequest::new`]. Extra fields stay at their defaults.
///
/// ```
/// use wiremux::{IrItem, IrPart, IrRequest};
/// let req = IrRequest::new(
///     "gpt-4",
///     vec![IrItem::User {
///         parts: vec![IrPart::Text("Hi".into())],
///     }],
/// );
/// assert_eq!(req.model, "gpt-4");
/// assert!(req.tools.is_empty());
/// ```
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct IrRequest {
    pub model: String,
    pub items: Vec<IrItem>,
    pub tools: Vec<IrTool>,
    pub sampling: IrSampling,
}

impl IrRequest {
    /// Request with `model` and `items`. Tools and sampling are empty/default.
    ///
    /// Pass a string slice (`"gpt-4o"`). Do not write `model.into()`:
    /// hosts that also depend on `bytes` or `reqwest` see `E0283`.
    #[must_use]
    pub fn new(model: impl AsRef<str>, items: Vec<IrItem>) -> Self {
        Self {
            model: model.as_ref().to_owned(),
            items,
            tools: Vec::new(),
            sampling: IrSampling::default(),
        }
    }

    /// Set tools. For hosts that cannot use a struct literal.
    #[must_use]
    pub fn with_tools(mut self, tools: Vec<IrTool>) -> Self {
        self.tools = tools;
        self
    }

    /// Set sampling. For hosts that cannot use a struct literal.
    #[must_use]
    pub fn with_sampling(mut self, sampling: IrSampling) -> Self {
        self.sampling = sampling;
        self
    }
}

impl Default for IrRequest {
    fn default() -> Self {
        Self::new(String::new(), Vec::new())
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct IrSampling {
    pub temperature: Option<f32>,
    pub top_p: Option<f32>,
    /// Messages `top_k`. Gemini `generationConfig.topK`.
    /// Chat Completions, Responses, and Converse drop.
    pub top_k: Option<u32>,
    /// Host max output tokens.
    ///
    /// Chat Completions encode may write `max_completion_tokens` and omit
    /// temperature (`LossReport`) for o1/o3/o4/gpt-5; decode accepts either key.
    /// Chat omits logprobs for gpt-5, gpt-5-mini, and gpt-5-nano, and for
    /// gpt-5.1 and gpt-5.2 unless reasoning effort is none. Responses does
    /// the same for temperature, top_p, and top_logprobs.
    pub max_tokens: Option<u32>,
    /// Chat omits stop for o3 and o4-mini.
    pub stop: Vec<String>,
    pub tool_choice: IrToolChoice,
    pub parallel_tool_calls: Option<bool>,
    /// Chat Completions and Responses `store`. Gemini emits request-root
    /// `store`. Messages drops.
    pub store: Option<bool>,
    pub previous_response_id: Option<String>,
    pub cache: IrCache,
    /// Client asked for SSE. Grok TUI always sets this.
    pub stream: Option<bool>,
    /// Gemini `thinkingConfig.includeThoughts`; Messages `thinking.type`;
    /// Responses `reasoning.summary` (`auto` when true). Chat Completions drops.
    pub include_thoughts: Option<bool>,
    /// Gemini `thinkingConfig.thinkingBudget` (decode and encode).
    /// Messages encode emits this as `thinking.budget_tokens` when
    /// `max_reasoning_tokens` is unset. Messages decode leaves this `None`
    /// and writes `budget_tokens` into `max_reasoning_tokens`.
    pub thinking_budget: Option<u32>,
    /// Dialect effort string (`low`, `high`, `xhigh`). Not a host enum.
    /// Gemini encode emits `thinkingConfig.thinkingLevel` (lowercase;
    /// `xhigh` / `x-high` degrade to `high`). Converse encode emits
    /// `outputConfig.effort` (`low`/`medium`/`high`/`xhigh`/`max`;
    /// `x-high` degrades to `xhigh`).
    pub reasoning_effort: Option<String>,
    /// Host cap on reasoning tokens.
    ///
    /// Messages decode writes `thinking.budget_tokens` here
    /// (`thinking_budget` stays `None`). Messages encode emits this as
    /// `thinking.budget_tokens`. Gemini encode emits it as
    /// `thinkingConfig.thinkingBudget` when `thinking_budget` is unset.
    /// Chat Completions and Responses have no emit slot.
    pub max_reasoning_tokens: Option<u32>,
    /// JSON schema for structured output when the dialect has a slot.
    pub json_schema: Option<serde_json::Value>,
    /// Optional schema name (Responses `text.format.name` / Chat json_schema.name /
    /// Converse `outputConfig.textFormat.structure.jsonSchema.name`).
    pub json_schema_name: Option<String>,
    /// Chat `response_format.json_schema.description`, Responses
    /// `text.format.description`, and Converse
    /// `outputConfig.textFormat.structure.jsonSchema.description`.
    /// Gemini and Messages drop when set.
    pub json_schema_description: Option<String>,
    /// Chat Completions `response_format.json_schema.strict`.
    /// Other dests drop when `Some`.
    pub json_schema_strict: Option<bool>,
    /// Unconstrained JSON object mode (Chat `response_format.type=json_object`,
    /// Responses `text.format.type=json_object`, Gemini `responseMimeType=
    /// application/json` without a schema). `json_schema` wins when both are set.
    pub json_object: Option<bool>,
    /// Responses `include`. Empty by default. Encode writes this list and
    /// omits the field when it is empty. It does not add
    /// `reasoning.encrypted_content`. Other dests drop a non-empty list.
    pub include: Vec<String>,
    /// OpenAI / Codex `prompt_cache_key`. Chat Completions and Responses
    /// emit it. Messages and Gemini drop.
    pub prompt_cache_key: Option<String>,
    /// Chat Completions and Responses `prompt_cache_retention`
    /// (`24h` / `in_memory`). Distinct from Messages `IrCache.retention`.
    /// Gemini, Messages, and Converse drop.
    pub prompt_cache_retention: Option<String>,
    /// Chat / Responses `prompt_cache_options.mode` (`implicit` / `explicit`).
    pub prompt_cache_mode: Option<String>,
    /// Chat / Responses `prompt_cache_options.ttl` (`30m`). Distinct from Messages IrCache.retention.
    pub prompt_cache_ttl: Option<String>,
    /// Chat / Responses `top_logprobs` (0-20).
    pub top_logprobs: Option<u32>,
    /// Chat / Responses `moderation.model`.
    pub moderation_model: Option<String>,
    /// Chat / Responses `moderation.policy.input.mode` (`score` / `block`).
    pub moderation_input: Option<String>,
    /// Chat / Responses `moderation.policy.output.mode`.
    pub moderation_output: Option<String>,
    /// Chat / Responses `stream_options.include_obfuscation`.
    pub include_obfuscation: Option<bool>,
    /// Chat Completions and Responses `user`. Messages, Gemini, and
    /// Converse drop.
    pub user: Option<String>,
    /// Chat Completions `verbosity` and Responses `text.verbosity`
    /// (`low` / `medium` / `high`). Gemini, Messages, and Converse drop.
    pub verbosity: Option<String>,
    /// Chat Completions and Responses `safety_identifier`.
    /// Distinct from `user`. Gemini, Messages, and Converse drop.
    pub safety_identifier: Option<String>,
    /// Chat Completions and Responses `metadata` string map.
    /// Messages `metadata.user_id` stays on `user`. Gemini and Converse drop.
    pub metadata: BTreeMap<String, String>,
    /// Chat Completions `frequency_penalty`. Gemini `generationConfig.frequencyPenalty`.
    /// Messages, Responses, and Converse drop.
    pub frequency_penalty: Option<f32>,
    /// Chat Completions `presence_penalty`. Gemini `generationConfig.presencePenalty`.
    /// Messages, Responses, and Converse drop.
    pub presence_penalty: Option<f32>,
    /// Chat Completions `seed`. Gemini `generationConfig.seed`.
    /// Messages, Responses, and Converse drop.
    pub seed: Option<i64>,
    /// Chat Completions `n`. Gemini `generationConfig.candidateCount`.
    /// Messages, Responses, and Converse drop.
    pub n: Option<u32>,
    /// OpenAI / Codex `service_tier` (`flex`, `priority`, `auto`).
    /// Chat Completions and Responses emit it. Converse emits
    /// `serviceTier.type` (`flex` / `priority` / `reserved` /
    /// `default`; `auto` degrades to `default`). Gemini emits
    /// request-root `serviceTier` (`flex` / `priority` / `standard`;
    /// `default` / `auto` degrade to `standard`). Messages drops.
    pub service_tier: Option<String>,
    /// Dest Chat `modalities` (`text` / `audio`). Dest Gemini
    /// `generationConfig.responseModalities` (`TEXT` / `AUDIO` / `IMAGE`).
    /// Dest Messages, dest Responses, and dest Converse drop.
    /// Dest Chat drops `image`.
    pub output_modalities: Vec<String>,
    /// Dest Chat `audio.voice` (string or object `id`). Dest Gemini
    /// `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName`.
    /// Dest Messages, dest Responses, and dest Converse drop.
    pub audio_voice: Option<String>,
    /// Dest Chat `audio.format`. Dest Gemini speechConfig has no format
    /// (Chat encode defaults to `wav` when emitting `audio`). Dest
    /// Messages, dest Responses, and dest Converse drop.
    pub audio_format: Option<String>,
    /// Dest Chat `logprobs` boolean. Dest Gemini
    /// `generationConfig.responseLogprobs`. Distinct from `top_logprobs`.
    /// Dest Messages, dest Responses, and dest Converse drop.
    pub logprobs: Option<bool>,
    /// Dest Chat `logit_bias` token-id to bias (-100..100). Dest Responses,
    /// dest Gemini, dest Messages, and dest Converse drop.
    pub logit_bias: BTreeMap<String, f64>,
    /// Dest Chat `prediction` object (`type` + `content`). Dest Responses,
    /// dest Gemini, dest Messages, and dest Converse drop.
    pub prediction: Option<serde_json::Value>,
    /// Dest Chat `web_search_options` object. Dest Responses, dest Gemini,
    /// dest Messages, and dest Converse drop.
    pub web_search_options: Option<serde_json::Value>,
    /// Messages request `inference_geo`. Chat, Responses, Gemini, and Converse drop.
    pub inference_geo: Option<String>,
    /// Converse `performanceConfig.latency` (`standard` or `optimized`).
    /// Chat, Messages, Responses, and Gemini drop.
    pub performance_latency: Option<String>,
    /// Messages request `diagnostics.previous_message_id`. Chat, Responses, Gemini, and Converse drop.
    pub previous_message_id: Option<String>,
    /// Converse `additionalModelResponseFieldPaths`.
    /// Chat, Messages, Responses, and Gemini drop.
    pub response_field_paths: Vec<String>,
    /// Converse `additionalModelRequestFields`.
    /// Chat, Messages, Responses, and Gemini drop.
    pub additional_request_fields: Option<serde_json::Value>,
    /// Converse `promptVariables`.
    /// Chat, Messages, Responses, and Gemini drop.
    pub prompt_variables: Option<serde_json::Value>,
    /// Converse `guardrailConfig`.
    /// Chat, Messages, Responses, and Gemini drop.
    pub guardrail: Option<serde_json::Value>,
    /// Messages request `container` (string id or object). Null and other
    /// types decode as absent. Chat, Responses, Gemini, and Converse drop.
    pub container: Option<serde_json::Value>,
    /// Messages request `context_management` object. Chat, Responses,
    /// Gemini, and Converse drop.
    pub context_management: Option<serde_json::Value>,
    /// Messages request `mcp_servers` array. Chat, Responses, Gemini,
    /// and Converse drop.
    pub mcp_servers: Option<serde_json::Value>,
    /// Gemini `generationConfig.mediaResolution`
    /// (`MEDIA_RESOLUTION_LOW`, `MEDIA_RESOLUTION_MEDIUM`,
    /// `MEDIA_RESOLUTION_HIGH`). Chat, Messages, Responses, and
    /// Converse drop.
    pub media_resolution: Option<String>,
    /// Gemini `generationConfig.imageConfig` (`aspectRatio`, `imageSize`).
    /// Chat, Messages, Responses, and Converse drop.
    pub image_config: Option<serde_json::Value>,
    /// Gemini `generationConfig.audioTranscriptionConfig`.
    /// Chat, Messages, Responses, and Converse drop.
    pub audio_transcription_config: Option<serde_json::Value>,
    /// Gemini `generationConfig.translationConfig`.
    /// Chat, Messages, Responses, and Converse drop.
    pub translation_config: Option<serde_json::Value>,
    /// Gemini `generationConfig.enableAffectiveDialog`.
    /// Chat, Messages, Responses, and Converse drop.
    pub affective_dialog: Option<bool>,
    /// Gemini `generationConfig.enableEnhancedCivicAnswers`.
    /// Chat, Messages, Responses, and Converse drop.
    pub enhanced_civic_answers: Option<bool>,
    /// Gemini `generationConfig.speechConfig` when it uses
    /// `multiSpeakerVoiceConfig`. A single `voiceConfig` stays on
    /// `audio_voice`. Chat, Messages, Responses, and Converse drop.
    pub multi_speaker_speech: Option<serde_json::Value>,
    /// Gemini request-root `cachedContent` (`cachedContents/{id}`).
    /// Chat, Messages, Responses, and Converse drop.
    pub cached_content: Option<String>,
    /// Gemini request-root `safetySettings` array.
    /// Chat, Messages, Responses, and Converse drop.
    pub safety_settings: Option<serde_json::Value>,
    /// Gemini request-root `labels` object.
    /// Chat, Messages, Responses, and Converse drop.
    pub request_labels: Option<serde_json::Value>,
    /// Responses request `truncation` (`auto`, `disabled`, or a vendor
    /// token). Empty is absent. Chat, Messages, Gemini, and Converse drop.
    pub truncation: Option<String>,
    /// Responses request `max_tool_calls`. `0` is a real cap.
    /// Chat, Messages, Gemini, and Converse drop.
    pub max_tool_calls: Option<u32>,
    /// Responses request `background`. `false` is explicit foreground and
    /// is preserved. Chat, Messages, Gemini, and Converse drop.
    pub background: Option<bool>,
    /// Responses request `conversation`: a non-empty string id or an
    /// object. Numbers, arrays, null, and empty strings are absent.
    /// Chat, Messages, Gemini, and Converse drop.
    pub conversation: Option<serde_json::Value>,
    /// Responses request `context_management` array (compaction).
    /// Distinct from the Messages `context_management` object.
    /// Chat, Messages, Gemini, and Converse drop.
    pub responses_context_management: Option<serde_json::Value>,
    /// Messages request `thinking` when `type` is `adaptive` or
    /// `between_tools`, including `display`. `enabled` and `disabled`
    /// stay on `include_thoughts`. Chat, Responses, Gemini, and
    /// Converse drop.
    pub messages_thinking: Option<serde_json::Value>,
}

impl IrSampling {
    /// Build sampling by mutating defaults.
    ///
    /// External crates cannot use struct literals on this type.
    pub fn patch(update: impl FnOnce(&mut Self)) -> Self {
        let mut sampling = Self::default();
        update(&mut sampling);
        sampling
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum IrToolChoice {
    #[default]
    Auto,
    None,
    Required,
    Named(String),
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct IrCache {
    pub enabled: bool,
    /// "5m" or "1h" when the target dialect has a TTL slot.
    pub retention: Option<String>,
    /// Skip `cache_control` when [`estimate_prompt_tokens`] is below this floor.
    /// `None` or `0` means no floor.
    pub min_cacheable_tokens: Option<u32>,
}

impl IrCache {
    /// Enabled cache with no TTL and no token floor.
    #[must_use]
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Self::default()
        }
    }

    /// Set Messages-style TTL (`5m` / `1h`).
    ///
    /// Pass a string slice (`"5m"`). Do not write `retention.into()`.
    #[must_use]
    pub fn with_retention(mut self, retention: impl AsRef<str>) -> Self {
        self.retention = Some(retention.as_ref().to_owned());
        self
    }

    /// Skip `cache_control` below this estimated prompt-token floor.
    #[must_use]
    pub fn with_min_cacheable_tokens(mut self, tokens: u32) -> Self {
        self.min_cacheable_tokens = Some(tokens);
        self
    }
}

/// One conversation turn.
///
/// `System`, `Developer`, and `Assistant` name every field.
/// `#[non_exhaustive]` does not let an outside crate skip one.
/// A 0.11.1 literal that omits the fields below does not compile.
///
/// ```
/// use wiremux::{IrItem, IrPart};
/// let system = IrItem::System {
///     text: "You are concise.".into(),
///     prompt_cache_breakpoint: None,
///     content_parts: vec![],
/// };
/// let developer = IrItem::Developer {
///     text: "Prefer short answers.".into(),
///     prompt_cache_breakpoint: None,
///     content_parts: vec![],
/// };
/// let assistant = IrItem::Assistant {
///     parts: vec![IrPart::Text("Hi".into())],
///     phase: None,
/// };
/// let image = IrPart::ImageUrl {
///     url: "https://example.com/a.png".into(),
///     detail: None,
///     bucket_owner: None,
///     file_id: None,
/// };
/// assert!(matches!(system, IrItem::System { prompt_cache_breakpoint: None, .. }));
/// assert!(matches!(
///     developer,
///     IrItem::Developer { content_parts, .. } if content_parts.is_empty()
/// ));
/// assert!(matches!(assistant, IrItem::Assistant { phase: None, .. }));
/// assert!(matches!(
///     image,
///     IrPart::ImageUrl { file_id: None, bucket_owner: None, .. }
/// ));
/// ```
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum IrItem {
    System {
        text: String,
        /// Chat system `prompt_cache_breakpoint` mode.
        /// Set when that role is one text part carrying the marker.
        /// Other wires keep `text` and record that the marker has no slot.
        prompt_cache_breakpoint: Option<String>,
        /// Ordered parts when a multi-part role must keep a breakpoint.
        /// Empty means `text` and `prompt_cache_breakpoint` are the whole role.
        /// Messages, Gemini, and Converse send the text parts from this
        /// list and drop image, document, audio, and raw parts.
        content_parts: Vec<IrPart>,
    },
    /// Converse system `cachePoint`. Other wires drop it.
    /// It stays between the system texts that surround it.
    SystemCache {
        raw: serde_json::Value,
    },
    /// Converse system `guardContent`. Other wires drop it.
    /// Once present, the guardrail assesses only these blocks.
    SystemGuard {
        raw: serde_json::Value,
    },
    /// Chat Completions `developer` degrades to this on Messages.
    Developer {
        text: String,
        /// Chat developer `prompt_cache_breakpoint` mode.
        /// Set when that role is one text part carrying the marker.
        /// Other wires keep `text` and record that the marker has no slot.
        prompt_cache_breakpoint: Option<String>,
        /// Ordered parts when a multi-part role must keep a breakpoint.
        /// Empty means `text` and `prompt_cache_breakpoint` are the whole role.
        /// Messages, Gemini, and Converse send the text parts from this
        /// list and drop image, document, audio, and raw parts.
        content_parts: Vec<IrPart>,
    },
    User {
        parts: Vec<IrPart>,
    },
    Assistant {
        parts: Vec<IrPart>,
        /// Responses assistant `phase` (`commentary` or `final_answer`).
        /// A later Responses turn must send it again. Other wires drop it.
        /// User messages never carry it.
        phase: Option<String>,
    },
    FunctionCall {
        call_id: String,
        name: String,
        arguments: String,
        /// Gemini `thoughtSignature` on the same functionCall part.
        thought_signature: Option<String>,
    },
    /// Chat `type: custom` and Responses `custom_tool_call`.
    /// Messages, Converse, and Gemini have no custom-tool frame, so
    /// those encoders reuse the function tool and keep this name and input.
    /// `responses_item` is the original Responses object so same-wire
    /// keeps `id`, `namespace`, `status`, `created_by`, and `caller`.
    CustomToolCall {
        call_id: String,
        name: String,
        input: String,
        responses_item: Option<serde_json::Value>,
    },
    FunctionOutput {
        call_id: String,
        /// Joined text. Images and other blocks live in `parts`.
        output: String,
        parts: Vec<IrPart>,
        is_error: bool,
    },
    Reasoning {
        encrypted: Option<String>,
        summary: Option<String>,
        raw: Option<serde_json::Value>,
    },
    HostedToolCall {
        kind: String,
        raw: serde_json::Value,
    },
    Unknown {
        type_name: String,
        raw: serde_json::Value,
    },
}

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum IrPart {
    Text(String),
    /// Chat `image_url`. `detail` is `low`, `high`, or `auto`.
    /// `bucket_owner` is the Converse S3 account id.
    /// `file_id` is the Responses `input_image.file_id`.
    /// Chat, Messages, Converse, and Gemini have no slot for it.
    /// Other dest wires keep the URL and drop `detail` and `bucket_owner`.
    ImageUrl {
        url: String,
        detail: Option<String>,
        bucket_owner: Option<String>,
        file_id: Option<String>,
    },
    ImageBase64 {
        media_type: String,
        data: String,
    },
    /// Messages replay needs a nonempty signature. Responses remaps
    /// signed thinking to a reasoning item. Unsigned thinking is dropped
    /// on Messages, Responses, and Chat Completions.
    Thinking {
        text: String,
        signature: Option<String>,
    },
    /// Dialect-native block (Anthropic `redacted_thinking`).
    Raw {
        type_name: String,
        raw: serde_json::Value,
    },
    /// Messages `document`, Chat/Responses `file`/`input_file`,
    /// Gemini PDF `inlineData`/`fileData`, Converse `document`.
    /// `citations_enabled` and `context` are kept on Messages and Converse.
    /// Chat and Gemini drop them.
    Document {
        source: IrDocumentSource,
        media_type: String,
        name: Option<String>,
        /// Messages `citations.enabled`. `None` omits the object.
        citations_enabled: Option<bool>,
        /// Messages document `context`.
        context: Option<String>,
    },
    /// Chat `input_audio` and Gemini `inlineData` with `audio/*`.
    Audio {
        data: String,
        format: String,
    },
    /// Chat and Responses `prompt_cache_breakpoint` on `inner`.
    /// Other wires keep `inner` and record that the marker has no slot.
    /// `mode` is the breakpoint mode. The API documents `explicit`.
    PromptCacheBreakpoint {
        mode: String,
        inner: Box<IrPart>,
    },
}

/// Where a document payload lives.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum IrDocumentSource {
    Base64(String),
    /// Messages PlainTextSource `data`. The string is the document text, not base64.
    Text(String),
    Url(String),
    /// Converse `s3Location`. `bucket_owner` is the AWS account id when the
    /// request included `bucketOwner`.
    S3 {
        uri: String,
        bucket_owner: Option<String>,
    },
    FileId(String),
}

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum IrTool {
    Function {
        name: String,
        description: String,
        parameters: serde_json::Value,
        /// Chat Completions and Responses `strict`. Other dests drop when `Some`.
        strict: Option<bool>,
    },
    Namespace {
        name: String,
        raw: serde_json::Value,
    },
    Hosted {
        kind: String,
        raw: serde_json::Value,
    },
    Unknown {
        type_name: String,
        raw: serde_json::Value,
    },
    /// Converse `toolConfig.tools` cachePoint. Other wires drop it.
    /// It stays between the tool specs that surround it.
    CachePoint { raw: serde_json::Value },
}

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum IrStreamEvent {
    TextDelta {
        text: String,
    },
    /// Dest Chat `delta.refusal` / `message.refusal`, dest Responses
    /// `response.refusal.delta` / output content `{ "type": "refusal" }`,
    /// dest Messages complete `stop_details.explanation`, dest Messages
    /// STREAM `message_delta.delta.stop_details.explanation`, and dest
    /// Gemini `candidates[].finishMessage`.
    RefusalDelta {
        text: String,
    },
    ReasoningDelta {
        text: String,
    },
    ReasoningSignature {
        signature: String,
    },
    ToolCallStart {
        id: String,
        name: String,
        /// Gemini `thoughtSignature` bound to this function call.
        thought_signature: Option<String>,
        /// Parallel tool-call slot. Chat Completions `tool_calls[].index`.
        /// Other dialects use a block/output index or 0.
        index: u32,
    },
    ToolCallArgDelta {
        delta: String,
        /// Same slot as the matching [`Self::ToolCallStart`].
        index: u32,
    },
    ToolCallEnd,
    /// Dest Chat `message.annotations` url_citation and dest Responses
    /// `response.output_text.annotation.added`.
    AnnotationAdded {
        annotation: serde_json::Value,
    },
    /// Dest Gemini `candidates[].groundingMetadata.searchEntryPoint.renderedContent`.
    /// HTML a Grounding with Google Search client must display.
    /// Other wires omit it. `webSearchQueries` stays dropped.
    SearchEntryPoint {
        rendered_content: String,
    },
    /// Dest Chat `message.audio.data` and dest Responses `response.audio.delta`.
    AudioDelta {
        data: String,
    },
    /// Generated image bytes. Dest Gemini `inlineData` with `image/*`,
    /// dest Chat `image_url` data URL, dest Messages image block,
    /// dest Responses `output_image`, and dest Converse `image`.
    ImageDelta {
        media_type: String,
        data: String,
    },
    /// Dest Chat `message.audio.transcript` and dest Responses
    /// `response.audio.transcript.delta`.
    AudioTranscriptDelta {
        text: String,
    },
    /// Dest Chat `tool_calls[].type=custom` and dest Responses
    /// `custom_tool_call` output item.
    CustomToolCallStart {
        id: String,
        name: String,
        index: u32,
    },
    /// Dest Chat custom tool `custom.input` and dest Responses
    /// `response.custom_tool_call_input.delta`.
    CustomToolCallInputDelta {
        delta: String,
        index: u32,
    },
    /// Dest Chat STREAM `choices[].logprobs.content` and dest Responses
    /// `response.output_text.delta.logprobs`. Dest Gemini
    /// `candidates[].logprobsResult` is one list, so encode appends
    /// `refusal` tokens there. Dest Responses logprobs is one array and
    /// gets the same append.
    /// `refusal` is Chat `logprobs.refusal`. Other wires do not have that key.
    Logprobs {
        content: serde_json::Value,
        /// Chat `logprobs.refusal`. Other wires do not have that key.
        refusal: Option<serde_json::Value>,
    },
    /// Dest Chat `created` and dest Responses `created_at` (unix seconds).
    Created {
        unix: i64,
    },
    /// Dest Chat `service_tier`, dest Responses `service_tier`, and dest
    /// Messages `usage.service_tier`.
    ServiceTier {
        tier: String,
    },
    /// Dest Chat `metadata` and dest Responses `metadata` string map.
    Metadata {
        metadata: BTreeMap<String, String>,
    },
    /// Dest Chat `moderation.input` / `moderation.output` (Chat-shaped
    /// `moderation_results` or `error`) and dest Responses the same keys.
    Moderation {
        input: Option<serde_json::Value>,
        output: Option<serde_json::Value>,
    },
    /// Messages response `diagnostics.cache_miss_reason`. Other wires omit it.
    Diagnostics {
        cache_miss_reason: serde_json::Value,
    },
    /// Messages response `container`. Other wires omit it.
    Container {
        value: serde_json::Value,
    },
    /// Messages response `context_management`. Other wires omit it.
    ContextManagement {
        value: serde_json::Value,
    },
    /// Messages response `stop_sequence`. Other wires omit it.
    StopSequence {
        text: String,
    },
    /// Exclusive buckets: prompt excludes cache
    /// read, completion excludes reasoning. Encoders re-inflate inclusive
    /// wire totals for Chat and Responses.
    /// `audio_tokens` is dest Chat `prompt_tokens_details.audio_tokens`
    /// and dest Gemini `promptTokensDetails` modality AUDIO. It is a
    /// subset of prompt, not subtracted from `prompt_tokens`. Dest Chat
    /// has no `image_tokens`; Gemini IMAGE details are an official Drop.
    /// `completion_audio_tokens` is dest Chat
    /// `completion_tokens_details.audio_tokens` and dest Gemini
    /// `candidatesTokensDetails` modality AUDIO. It is a subset of
    /// completion, not subtracted from `completion_tokens`.
    /// Messages response `usage.inference_geo`. Other wires omit it.
    Usage {
        prompt_tokens: u32,
        completion_tokens: u32,
        cache_read_tokens: u32,
        cache_write_tokens: u32,
        reasoning_tokens: u32,
        audio_tokens: u32,
        completion_audio_tokens: u32,
        /// Messages response `usage.inference_geo`. Other wires omit it.
        inference_geo: Option<String>,
    },
    /// Mapped stop reason. `vendor` is the original Gemini token when the
    /// mapped word is not that token (`MALFORMED_FUNCTION_CALL`, `SAFETY`).
    /// Other wires leave `vendor` empty. Unknown Gemini `finishReason`
    /// values stay in `reason` and are not rewritten to `stop`.
    FinishReason {
        reason: String,
        vendor: Option<String>,
    },
    Protocol {
        item_type: String,
        payload: serde_json::Value,
    },
    Unknown {
        event: String,
        raw: serde_json::Value,
    },
    Done,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct LossReport {
    pub events: Vec<LossEvent>,
}

impl LossReport {
    /// Append a loss event.
    pub fn record(
        &mut self,
        path: impl Into<String>,
        action: LossAction,
        detail: impl Into<String>,
    ) {
        self.events.push(LossEvent {
            path: path.into(),
            action,
            detail: detail.into(),
        });
    }

    /// Events whose action is not [`LossAction::Preserve`], in record order.
    #[must_use]
    pub fn lossy(&self) -> Vec<LossEvent> {
        self.events
            .iter()
            .filter(|event| event.action != LossAction::Preserve)
            .cloned()
            .collect()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct LossEvent {
    pub path: String,
    pub action: LossAction,
    pub detail: String,
}

impl std::fmt::Display for LossEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let action = match self.action {
            LossAction::Preserve => "preserve",
            LossAction::Degrade => "degrade",
            LossAction::Drop => "drop",
            LossAction::HardError => "harderror",
        };
        write!(f, "{action} {}: {}", self.path, self.detail)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LossAction {
    Preserve,
    Degrade,
    Drop,
    HardError,
}

/// Estimate prompt tokens as `chars / 4` for the Messages cache floor.
///
/// Counts system and developer text, user and assistant text, signed
/// thinking text, image bytes, document text, and document base64.
/// An image URL, a document URL, and a document file id count as at
/// least 4096 characters (1024 tokens) so a short handle still meets
/// the shipped Messages floor. A longer handle counts its own length.
/// Titles, context, function-call names and arguments, custom-tool
/// names and inputs, function-output text and parts, reasoning text
/// that becomes a thinking block, and function-tool names,
/// descriptions, and parameters also count.
///
/// Unsigned thinking is not replayed, so that text is not counted.
/// Whitespace-only text parts are omitted. Audio is dropped. A custom
/// tool's `responses_item` is the same input again, so it is not
/// counted. A reasoning or thinking signature is not prompt text.
/// Image detail is dropped. Hosted items and unknown raw JSON stay out
/// so a short prompt is not treated as long. Inline image and document
/// bytes that Messages rewrites from a raw part are counted.
#[must_use]
pub fn estimate_prompt_tokens(req: &IrRequest) -> u32 {
    crate::map::messages_cache_floor_tokens(req)
}

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

    #[test]
    fn ir_request_holds_system_user_and_function_tool() {
        let req = IrRequest {
            model: "gpt-4".into(),
            items: vec![
                IrItem::System {
                    text: "You are helpful.".into(),
                    prompt_cache_breakpoint: None,
                    content_parts: vec![],
                },
                IrItem::User {
                    parts: vec![IrPart::Text("Hi".into())],
                },
            ],
            tools: vec![IrTool::Function {
                name: "lookup".into(),
                description: "Look up a term.".into(),
                parameters: serde_json::json!({"type": "object"}),
                strict: None,
            }],
            sampling: IrSampling::default(),
        };

        assert_eq!(req.model, "gpt-4");
        assert_eq!(req.items.len(), 2);
        assert!(matches!(req.items[0], IrItem::System { .. }));
        assert!(matches!(
            &req.items[1],
            IrItem::User { parts } if parts == &[IrPart::Text("Hi".into())]
        ));
        assert_eq!(req.tools.len(), 1);
        assert!(matches!(
            &req.tools[0],
            IrTool::Function { name, description, .. }
                if name == "lookup" && description == "Look up a term."
        ));
        assert!(matches!(req.sampling.tool_choice, IrToolChoice::Auto));
    }

    #[test]
    fn loss_report_records_all_actions() {
        let mut report = LossReport::default();
        report.record("items[0]", LossAction::Preserve, "kept as-is");
        report.record("items[1]", LossAction::Degrade, "developer to system");
        report.record("sampling.store", LossAction::Drop, "no slot");
        report.record("tools[0]", LossAction::HardError, "namespace");

        assert_eq!(
            report.events,
            [
                LossEvent {
                    path: "items[0]".into(),
                    action: LossAction::Preserve,
                    detail: "kept as-is".into(),
                },
                LossEvent {
                    path: "items[1]".into(),
                    action: LossAction::Degrade,
                    detail: "developer to system".into(),
                },
                LossEvent {
                    path: "sampling.store".into(),
                    action: LossAction::Drop,
                    detail: "no slot".into(),
                },
                LossEvent {
                    path: "tools[0]".into(),
                    action: LossAction::HardError,
                    detail: "namespace".into(),
                },
            ]
        );
    }

    #[test]
    fn ir_tool_namespace_is_first_class() {
        let tool = IrTool::Namespace {
            name: "apply_patch".into(),
            raw: serde_json::json!({"type": "namespace"}),
        };
        assert!(matches!(
            &tool,
            IrTool::Namespace { name, .. } if name == "apply_patch"
        ));
        assert!(!matches!(tool, IrTool::Function { .. }));
    }

    #[test]
    fn ir_item_developer_is_distinct_from_system() {
        let system = IrItem::System {
            text: "rules".into(),
            prompt_cache_breakpoint: None,
            content_parts: vec![],
        };
        let developer = IrItem::Developer {
            text: "rules".into(),
            prompt_cache_breakpoint: None,
            content_parts: vec![],
        };
        assert_ne!(system, developer);
        assert!(matches!(system, IrItem::System { .. }));
        assert!(matches!(developer, IrItem::Developer { .. }));
    }

    #[test]
    fn estimate_prompt_tokens_counts_developer_text() {
        let req = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Developer {
                text: "x".repeat(5000),
                prompt_cache_breakpoint: None,
                content_parts: vec![],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&req) >= 1024,
            "5000 developer chars must meet a 1024-token floor"
        );
    }

    #[test]
    fn estimate_prompt_tokens_counts_function_output() {
        let req = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::FunctionOutput {
                call_id: "c1".into(),
                output: "x".repeat(5000),
                parts: Vec::new(),
                is_error: false,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&req) >= 1024,
            "5000 tool-result chars must meet a 1024-token floor"
        );
    }

    #[test]
    fn estimate_prompt_tokens_counts_signed_thinking_not_unsigned() {
        let signed = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Assistant {
                phase: None,
                parts: vec![IrPart::Thinking {
                    text: "x".repeat(5000),
                    signature: Some("sig".into()),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&signed) >= 1024,
            "5000 signed thinking chars must meet a 1024-token floor"
        );

        let unsigned = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![
                    IrPart::Text("hi".into()),
                    IrPart::Thinking {
                        text: "x".repeat(5000),
                        signature: None,
                    },
                ],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&unsigned) < 1024,
            "unsigned thinking is not replayed and must stay under the floor"
        );

        let blank_signature = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Assistant {
                phase: None,
                parts: vec![IrPart::Thinking {
                    text: "x".repeat(5000),
                    signature: Some(String::new()),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&blank_signature) < 1024,
            "an empty thinking signature is unsigned and must stay under the floor"
        );

        let signature_only = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Assistant {
                phase: None,
                parts: vec![IrPart::Thinking {
                    text: "hi".into(),
                    signature: Some("y".repeat(5000)),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&signature_only) < 1024,
            "a thinking signature is not prompt text"
        );
    }

    #[test]
    fn estimate_prompt_tokens_counts_images_documents_and_tool_result_parts() {
        let long = "x".repeat(5000);
        let image = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::ImageBase64 {
                    media_type: "image/png".into(),
                    data: long.clone(),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&image) >= 1024,
            "5000 image bytes must meet a 1024-token floor"
        );

        let image_url = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::ImageUrl {
                    url: long.clone(),
                    detail: Some("y".repeat(5000)),
                    bucket_owner: None,
                    file_id: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&image_url) >= 1024,
            "a long image URL must meet a 1024-token floor"
        );
        let detail_only = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::ImageUrl {
                    url: "https://cdn.example/a.png".into(),
                    detail: Some(long.clone()),
                    bucket_owner: None,
                    file_id: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&detail_only) >= 1024,
            "a normal image URL meets a 1024-token floor"
        );
        let url_only = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::ImageUrl {
                    url: "https://cdn.example/a.png".into(),
                    detail: None,
                    bucket_owner: None,
                    file_id: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert_eq!(
            estimate_prompt_tokens(&detail_only),
            estimate_prompt_tokens(&url_only),
            "image detail is dropped"
        );
        let file_id = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::FileId("file_abc".into()),
                    media_type: "application/pdf".into(),
                    name: None,
                    citations_enabled: None,
                    context: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&file_id) >= 1024,
            "a file id meets a 1024-token floor"
        );
        let short_base64 = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::Base64("0123456789".into()),
                    media_type: "application/pdf".into(),
                    name: None,
                    citations_enabled: None,
                    context: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&short_base64) < 1024,
            "short document base64 stays under the floor"
        );

        let document_text = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::Text(long.clone()),
                    media_type: "text/plain".into(),
                    name: None,
                    citations_enabled: None,
                    context: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&document_text) >= 1024,
            "5000 document text chars must meet a 1024-token floor"
        );

        let document_base64 = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::Base64(long.clone()),
                    media_type: "application/pdf".into(),
                    name: None,
                    citations_enabled: None,
                    context: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&document_base64) >= 1024,
            "5000 document base64 chars must meet a 1024-token floor"
        );

        let document_url = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::Url(long.clone()),
                    media_type: "application/pdf".into(),
                    name: None,
                    citations_enabled: None,
                    context: None,
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&document_url) >= 1024,
            "a long document URL must meet a 1024-token floor"
        );

        let document_context = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Document {
                    source: IrDocumentSource::FileId("file-short".into()),
                    media_type: "text/plain".into(),
                    name: None,
                    citations_enabled: None,
                    context: Some(long.clone()),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&document_context) >= 1024,
            "document context Messages writes must meet a 1024-token floor"
        );

        let tool_image = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::FunctionOutput {
                call_id: "c1".into(),
                output: String::new(),
                parts: vec![IrPart::ImageBase64 {
                    media_type: "image/png".into(),
                    data: long.clone(),
                }],
                is_error: false,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&tool_image) >= 1024,
            "a tool-result image must meet a 1024-token floor"
        );

        let tool_text = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::FunctionOutput {
                call_id: "c1".into(),
                output: String::new(),
                parts: vec![IrPart::Text(long.clone())],
                is_error: false,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&tool_text) >= 1024,
            "tool-result text Messages writes must meet a 1024-token floor"
        );

        let raw_image = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Raw {
                    type_name: "inline".into(),
                    raw: serde_json::json!({
                        "inlineData": {
                            "mimeType": "image/png",
                            "data": long,
                        }
                    }),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&raw_image) >= 1024,
            "inline image bytes Messages writes must meet a 1024-token floor"
        );

        let hinted_pdf = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Raw {
                    type_name: "inline".into(),
                    raw: serde_json::json!({
                        "inlineData": {
                            "mimeType": "application/pdf",
                            "data": "y".repeat(5000),
                        },
                        "mediaResolution": { "level": "media_resolution_high" }
                    }),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&hinted_pdf) >= 1024,
            "a media-hint PDF Messages writes must meet a 1024-token floor"
        );
    }

    #[test]
    fn estimate_prompt_tokens_skips_text_messages_does_not_send() {
        let long = "x".repeat(5000);
        let whitespace = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Text(" \n".repeat(2500))],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&whitespace) < 1024,
            "whitespace-only text is omitted and must stay under the floor"
        );

        let audio = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Audio {
                    data: long.clone(),
                    format: "mp3".into(),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&audio) < 1024,
            "audio has no Messages slot and must stay under the floor"
        );

        let raw_json = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Unknown {
                type_name: "redacted_thinking".into(),
                raw: serde_json::json!({
                    "type": "redacted_thinking",
                    "data": long.clone(),
                }),
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&raw_json) < 1024,
            "unknown raw JSON must not meet the floor"
        );

        let hosted = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::HostedToolCall {
                kind: "web_search".into(),
                raw: serde_json::json!({ "query": long }),
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&hosted) < 1024,
            "hosted raw JSON must not meet the floor"
        );

        let raw_part = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Raw {
                    type_name: "redacted_thinking".into(),
                    raw: serde_json::json!({
                        "type": "redacted_thinking",
                        "data": long.clone(),
                    }),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&raw_part) < 1024,
            "a raw Messages block is not prompt text"
        );

        let raw_audio = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Raw {
                    type_name: "inline".into(),
                    raw: serde_json::json!({
                        "inlineData": {
                            "mimeType": "audio/mp3",
                            "data": long,
                        },
                        "mediaResolution": { "level": "media_resolution_high" }
                    }),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&raw_audio) < 1024,
            "audio bytes inside a raw part must stay under the floor"
        );

        let hinted_blank = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::User {
                parts: vec![IrPart::Raw {
                    type_name: "inline".into(),
                    raw: serde_json::json!({
                        "text": " \n".repeat(2500),
                        "mediaResolution": { "level": "media_resolution_high" }
                    }),
                }],
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&hinted_blank) < 1024,
            "whitespace inside a hinted raw part must stay under the floor"
        );
    }

    #[test]
    fn estimate_prompt_tokens_counts_custom_tool_input_not_responses_item() {
        let long = "x".repeat(5000);
        let counted = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::CustomToolCall {
                call_id: "c1".into(),
                name: "lookup".into(),
                input: long.clone(),
                responses_item: None,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&counted) >= 1024,
            "5000 custom-tool input chars must meet a 1024-token floor"
        );

        let wrapper_only = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::CustomToolCall {
                call_id: "c1".into(),
                name: "lookup".into(),
                input: "{}".into(),
                responses_item: Some(serde_json::json!({ "input": long })),
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&wrapper_only) < 1024,
            "responses_item must not double-count the custom-tool input"
        );
    }

    #[test]
    fn estimate_prompt_tokens_counts_reasoning_summary_not_signature() {
        let long = "x".repeat(5000);
        let summary = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Reasoning {
                encrypted: Some("y".repeat(5000)),
                summary: Some(long.clone()),
                raw: None,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&summary) >= 1024,
            "5000 reasoning-summary chars must meet a 1024-token floor"
        );

        let signature_only = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Reasoning {
                encrypted: Some(long.clone()),
                summary: None,
                raw: None,
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&signature_only) < 1024,
            "a reasoning signature must not meet the floor by itself"
        );

        let raw_thinking = IrRequest {
            model: "claude".into(),
            items: vec![IrItem::Reasoning {
                encrypted: None,
                summary: None,
                raw: Some(serde_json::json!({
                    "type": "thinking",
                    "thinking": long,
                    "signature": "y".repeat(5000),
                })),
            }],
            tools: vec![],
            sampling: IrSampling::default(),
        };
        assert!(
            estimate_prompt_tokens(&raw_thinking) >= 1024,
            "a raw thinking string must meet a 1024-token floor"
        );
    }

    #[test]
    fn new_and_retention_take_str_next_to_bytes() {
        let _owned = bytes::Bytes::from_static(b"x");
        let req = IrRequest::new("gpt-4o", vec![]).with_sampling(IrSampling::patch(|s| {
            s.cache = IrCache::enabled().with_retention("5m");
        }));
        assert_eq!(req.model, "gpt-4o");
        assert_eq!(req.sampling.cache.retention.as_deref(), Some("5m"));
        let owned = IrRequest::new(String::from("gpt-4o"), vec![]);
        assert_eq!(owned.model, "gpt-4o");
    }
}