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
use crate::error::{Error, Result};
use crate::types::{ChatRequest, Message, Part, ProviderStateFormat, Role, ToolResult, ToolSpec};
/// The provider-facing protocol we are preparing a request for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
/// The OpenAI Chat Completions API.
OpenAiChat,
/// The OpenAI Responses API.
OpenAiResponses,
/// The Anthropic Messages API.
AnthropicMessages,
/// The Google Gemini `generateContent` API.
GeminiGenerateContent,
}
impl Protocol {
/// The provider state format used to tag reasoning and other opaque
/// state carried by this protocol.
pub fn provider_state_format(self) -> ProviderStateFormat {
match self {
Self::OpenAiChat => ProviderStateFormat::OpenAiChat,
Self::OpenAiResponses => ProviderStateFormat::OpenAiResponses,
Self::AnthropicMessages => ProviderStateFormat::AnthropicMessages,
Self::GeminiGenerateContent => ProviderStateFormat::GeminiGenerateContent,
}
}
}
/// Roles that are safe to send to a provider adapter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExternalRole {
System,
/// Instruction message kept at its position in the history.
///
/// Produced only under [`SystemPlacement::FirstToTopRestInPlace`] on the
/// OpenAI protocols. Strict OpenAI-compatible endpoints that reject a
/// `developer` role should keep [`SystemPlacement::MergeIntoTop`].
Developer,
User,
Assistant,
Tool,
}
/// What to do with a tool result that has no matching assistant tool call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrphanToolResultPolicy {
/// Remove it. This is the safest default for a strict provider API.
Drop,
/// Turn it into a user message. Useful when debugging messy histories.
DowngradeToUser,
/// Stop normalization and return an error.
Error,
}
/// What to do when an assistant tool call has no result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingToolResultPolicy {
/// Add an error result so that tool calls are always paired.
Synthesize,
/// Remove the tool call from the assistant message.
DropToolCall,
/// Stop normalization and return an error.
Error,
}
/// How `System`/`Developer` messages are placed by normalization.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SystemPlacement {
/// Merge every system/developer message into the top-level system text
/// (rendered as a leading system entry or `instructions`).
#[default]
MergeIntoTop,
/// The first `System` message becomes the top-level system text; later
/// `System` and `Developer` messages stay at their position in the
/// history, preserving prefix-cache-friendly runtime injections for
/// endpoints that accept instruction messages inline (OpenAI Chat
/// Completions and OpenAI Responses). Other protocols ignore the policy
/// and keep [`Self::MergeIntoTop`] semantics.
FirstToTopRestInPlace,
}
/// Rules used by the normalization layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizeOptions {
/// The provider protocol that will receive the normalized request.
pub protocol: Protocol,
/// `Developer` is not understood by every provider, so downgrade it to
/// `System` by default.
pub developer_to_system: bool,
/// Unknown/custom roles are downgraded to `User` by default.
pub custom_to_user: bool,
/// Policy for tool results that reference no pending assistant tool
/// call. See [`OrphanToolResultPolicy`] for the available choices.
pub orphan_tool_result: OrphanToolResultPolicy,
/// Policy for assistant tool calls that never received a tool result.
/// See [`MissingToolResultPolicy`] for the available choices.
pub missing_tool_result: MissingToolResultPolicy,
/// Anthropic and Gemini require user/model turns to alternate. OpenAI does
/// not require this, so its adapter keeps the original message boundaries.
pub merge_adjacent_same_role: bool,
/// How system/developer messages are placed; see [`SystemPlacement`].
pub system_placement: SystemPlacement,
/// Keep reasoning state produced by a different provider protocol.
///
/// This is disabled by default because signatures and encrypted reasoning
/// tokens are provider-specific and cannot be safely translated.
pub preserve_foreign_reasoning: bool,
}
impl NormalizeOptions {
/// Build options with sensible defaults for `protocol`.
///
/// Role downgrades, orphan-result dropping, and missing-result
/// synthesis are enabled; strict same-role merging is enabled only for
/// protocols that require alternating turns (Anthropic and Gemini).
pub fn for_protocol(protocol: Protocol) -> Self {
let merge_adjacent_same_role = matches!(
protocol,
Protocol::AnthropicMessages | Protocol::GeminiGenerateContent
);
Self {
protocol,
developer_to_system: true,
custom_to_user: true,
orphan_tool_result: OrphanToolResultPolicy::Drop,
missing_tool_result: MissingToolResultPolicy::Synthesize,
merge_adjacent_same_role,
preserve_foreign_reasoning: false,
system_placement: SystemPlacement::MergeIntoTop,
}
}
}
/// A provider-facing message after role downgrade and tool-pair repair.
#[derive(Debug, Clone, PartialEq)]
pub struct NormalizedMessage {
/// The downgraded role, safe to send to a provider adapter.
pub role: ExternalRole,
/// Content parts belonging to this message, already repaired.
pub parts: Vec<Part>,
}
/// A provider-facing conversation.
#[derive(Debug, Clone, PartialEq)]
pub struct NormalizedChat {
/// Anthropic, Gemini and OpenAI Responses accept system instructions
/// outside the normal message list. OpenAI Chat can prepend this as a
/// system message.
pub system: Option<String>,
/// Every normalized message, in order.
pub messages: Vec<NormalizedMessage>,
/// Tool specifications passed through from the request unchanged.
pub tools: Vec<ToolSpec>,
}
/// A human-readable trace of every repair made at the boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizeAction {
/// A `Developer` role message was downgraded to `System` or `User`.
DowngradedDeveloper,
/// A custom role was downgraded to a provider-safe role.
DowngradedCustomRole {
/// The original custom role name.
role: String,
},
/// A tool call arrived without an id and was assigned a generated one.
AssignedToolCallId {
/// Name of the tool being called.
name: String,
/// The generated call id.
id: String,
},
/// A tool result was missing a call id, which was filled in from the
/// matching pending tool call.
FilledToolResultId {
/// Name of the tool the result belongs to.
name: String,
/// The call id assigned to the result.
id: String,
},
/// A tool result carried a call id that did not match the call it was
/// paired with, so the id was rewritten to the pending call's id. This only
/// happens when the call's id was generated by this normalization run.
ReconciledToolResultId {
/// Name of the tool the result belongs to.
name: String,
/// The id the result arrived with.
from: String,
/// The id of the call the result was paired with.
to: String,
},
/// A tool call stored on a non-tool message was rendered as literal text.
/// The structured call is gone; only the text survives to the provider.
FlattenedToolCallIntoText {
/// Name of the tool that was called.
name: String,
},
/// A tool result stored on a non-tool message was rendered as literal text
/// inside that message, keeping the message's original role.
FlattenedToolResultIntoText {
/// Name of the tool that produced the result.
name: String,
},
/// A tool result had no matching assistant tool call and was handled
/// according to [`OrphanToolResultPolicy`] (dropped or downgraded).
DroppedOrphanToolResult {
/// Name of the tool the orphaned result belonged to.
name: String,
},
/// An assistant tool call never received a result, so an error result
/// was synthesized per [`MissingToolResultPolicy::Synthesize`].
SynthesizedMissingToolResult {
/// Id of the unpaired tool call.
call_id: String,
/// Name of the tool being called.
name: String,
},
/// An assistant tool call never received a result, so the call itself
/// was removed per [`MissingToolResultPolicy::DropToolCall`].
DroppedUnpairedToolCall {
/// Id of the removed tool call.
call_id: String,
/// Name of the tool being called.
name: String,
},
/// Reasoning state produced by a different protocol was dropped. See
/// [`NormalizeOptions::preserve_foreign_reasoning`].
DroppedForeignReasoning {
/// Format of the state that was dropped.
format: ProviderStateFormat,
/// Format expected by the target protocol.
expected: ProviderStateFormat,
},
/// A tool call carrying provider state from a different protocol had
/// that state cleared.
DroppedForeignToolState {
/// Format of the state that was dropped.
format: ProviderStateFormat,
/// Format expected by the target protocol.
expected: ProviderStateFormat,
},
/// A text part carrying provider state from a different protocol had
/// that state cleared.
DroppedForeignTextState {
/// Format of the state that was dropped.
format: ProviderStateFormat,
/// Format expected by the target protocol.
expected: ProviderStateFormat,
},
/// A provider-specific item from a different protocol was dropped.
DroppedForeignProviderItem {
/// Format of the item that was dropped.
format: ProviderStateFormat,
/// Format expected by the target protocol.
expected: ProviderStateFormat,
},
/// Reasoning was dropped because only assistant messages may carry it.
DroppedReasoningFromNonAssistant {
/// The role of the message that contained the reasoning.
role: ExternalRole,
},
/// Two adjacent messages with the same role were merged into one.
MergedAdjacent {
/// The role of the merged messages.
role: ExternalRole,
},
}
/// Details about normalization. Callers can log this while learning.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NormalizeReport {
/// Every repair action recorded during normalization, in order.
pub actions: Vec<NormalizeAction>,
}
impl NormalizeReport {
/// Returns `true` when normalization made no repairs.
pub fn is_clean(&self) -> bool {
self.actions.is_empty()
}
/// Aggregate repair counts without role names, tool names, call ids, or
/// message content.
///
/// This is the form used by [`crate::AuditEvent`] so enabling operational
/// diagnostics never leaks conversation context.
pub fn stats(&self) -> NormalizeStats {
let mut stats = NormalizeStats::default();
for action in &self.actions {
stats.total += 1;
match action {
NormalizeAction::DowngradedDeveloper => stats.downgraded_developer += 1,
NormalizeAction::DowngradedCustomRole { .. } => {
stats.downgraded_custom_role += 1;
}
NormalizeAction::AssignedToolCallId { .. } => stats.assigned_tool_call_id += 1,
NormalizeAction::FilledToolResultId { .. } => stats.filled_tool_result_id += 1,
NormalizeAction::ReconciledToolResultId { .. } => {
stats.reconciled_tool_result_id += 1;
}
NormalizeAction::FlattenedToolCallIntoText { .. } => {
stats.flattened_tool_call += 1;
}
NormalizeAction::FlattenedToolResultIntoText { .. } => {
stats.flattened_tool_result += 1;
}
NormalizeAction::DroppedOrphanToolResult { .. } => {
stats.dropped_orphan_tool_result += 1;
}
NormalizeAction::SynthesizedMissingToolResult { .. } => {
stats.synthesized_missing_tool_result += 1;
}
NormalizeAction::DroppedUnpairedToolCall { .. } => {
stats.dropped_unpaired_tool_call += 1;
}
NormalizeAction::DroppedForeignReasoning { .. } => {
stats.dropped_foreign_reasoning += 1;
}
NormalizeAction::DroppedForeignToolState { .. } => {
stats.dropped_foreign_tool_state += 1;
}
NormalizeAction::DroppedForeignTextState { .. } => {
stats.dropped_foreign_text_state += 1;
}
NormalizeAction::DroppedForeignProviderItem { .. } => {
stats.dropped_foreign_provider_item += 1;
}
NormalizeAction::DroppedReasoningFromNonAssistant { .. } => {
stats.dropped_reasoning_from_non_assistant += 1;
}
NormalizeAction::MergedAdjacent { .. } => stats.merged_adjacent += 1,
}
}
stats
}
}
/// Context-free aggregate of normalization repairs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NormalizeStats {
/// Total number of repairs recorded.
pub total: u32,
/// Number of `Developer` roles downgraded.
pub downgraded_developer: u32,
/// Number of custom roles downgraded.
pub downgraded_custom_role: u32,
/// Number of tool call ids that were generated.
pub assigned_tool_call_id: u32,
/// Number of tool results that had a missing call id filled in.
pub filled_tool_result_id: u32,
/// Number of tool results whose conflicting call id was rewritten to the
/// id of the call they were paired with.
pub reconciled_tool_result_id: u32,
/// Number of tool calls flattened into literal text on a non-tool message.
pub flattened_tool_call: u32,
/// Number of tool results flattened into literal text on a non-tool message.
pub flattened_tool_result: u32,
/// Number of orphan tool results dropped.
pub dropped_orphan_tool_result: u32,
/// Number of missing tool results that were synthesized.
pub synthesized_missing_tool_result: u32,
/// Number of unpaired tool calls dropped.
pub dropped_unpaired_tool_call: u32,
/// Number of reasoning parts with foreign provider state dropped.
pub dropped_foreign_reasoning: u32,
/// Number of tool calls whose foreign provider state was cleared.
pub dropped_foreign_tool_state: u32,
/// Number of text parts whose foreign provider state was cleared.
pub dropped_foreign_text_state: u32,
/// Number of provider items from a foreign protocol dropped.
pub dropped_foreign_provider_item: u32,
/// Number of reasoning parts dropped from non-assistant messages.
pub dropped_reasoning_from_non_assistant: u32,
/// Number of adjacent same-role message merges performed.
pub merged_adjacent: u32,
}
impl NormalizeStats {
/// Returns `true` when no repairs were recorded.
pub const fn is_clean(self) -> bool {
self.total == 0
}
}
#[derive(Debug, Clone)]
struct PendingCall {
id: String,
name: String,
message_index: usize,
fulfilled: bool,
/// True when the id was generated by this normalization run because the
/// stored assistant tool call carried no id. Such ids cannot match a result
/// that keeps a real provider id, so they accept a name-based fallback.
synthetic: bool,
native: bool,
}
/// Normalize a request using the default rules for a protocol.
///
/// # Errors
///
/// Returns an error for invalid histories, unsupported tool representations,
/// or when a configured tool-result policy rejects a malformed history.
pub fn normalize(
request: &ChatRequest,
protocol: Protocol,
) -> Result<(NormalizedChat, NormalizeReport)> {
normalize_with_options(request, NormalizeOptions::for_protocol(protocol))
}
/// Normalize a request with explicit rules.
///
/// The output is intentionally boring: only `System`, `Developer`, `User`,
/// `Assistant` and `Tool` can reach an adapter, and every `ToolCall` is
/// paired with a `ToolResult`. `Developer` appears only under
/// [`SystemPlacement::FirstToTopRestInPlace`] on the OpenAI protocols.
///
/// # Errors
///
/// Returns an error if [`NormalizeOptions::orphan_tool_result`] or
/// [`NormalizeOptions::missing_tool_result`] is set to an `Error` policy
/// and the corresponding malformed history is encountered.
pub fn normalize_with_options(
request: &ChatRequest,
options: NormalizeOptions,
) -> Result<(NormalizedChat, NormalizeReport)> {
if request.messages.iter().any(|message| {
message.role != Role::Assistant
&& message
.parts
.iter()
.any(|part| matches!(part, Part::NativeToolCall(_)))
}) {
return Err(Error::Normalize(
"tool_identity_conflict: native calls require assistant role".into(),
));
}
if !request.tool_declarations.is_empty() {
let mut declarations: Vec<_> = request
.tools
.iter()
.cloned()
.map(|tool| crate::types::ToolDeclaration::Tool { tool: tool.into() })
.collect();
declarations.extend(request.tool_declarations.iter().cloned());
crate::types::validate_tool_declarations(&declarations)?;
if options.protocol != Protocol::OpenAiResponses {
return Err(Error::Unsupported(format!(
"unsupported_tool_representation: native tool declarations require Responses, got {:?}",
options.protocol
)));
}
}
let expected_reasoning_format = options.protocol.provider_state_format();
let occupied_call_ids = request
.messages
.iter()
.flat_map(|message| &message.parts)
.filter_map(|part| match part {
Part::ToolCall(call) => call.id.clone(),
Part::NativeToolCall(call) => Some(call.call_id.clone()),
_ => None,
})
.collect();
let mut normalizer = Normalizer {
options,
report: NormalizeReport::default(),
system: Vec::new(),
messages: Vec::new(),
pending_calls: Vec::new(),
next_call_id: 1,
occupied_call_ids,
seen_call_ids: std::collections::HashSet::new(),
seen_native_ids: std::collections::HashSet::new(),
expected_reasoning_format,
top_taken: false,
};
for message in &request.messages {
normalizer.push(message)?;
}
normalizer.finish_pending_calls()?;
normalizer.merge_adjacent_messages();
Ok((
NormalizedChat {
system: normalizer.join_system(),
messages: normalizer.messages,
tools: request.tools.clone(),
},
normalizer.report,
))
}
struct Normalizer {
options: NormalizeOptions,
report: NormalizeReport,
system: Vec<String>,
messages: Vec<NormalizedMessage>,
pending_calls: Vec<PendingCall>,
next_call_id: u64,
occupied_call_ids: std::collections::HashSet<String>,
seen_call_ids: std::collections::HashSet<String>,
seen_native_ids: std::collections::HashSet<String>,
expected_reasoning_format: ProviderStateFormat,
/// True once a system message has claimed the top-level slot under
/// `SystemPlacement::FirstToTopRestInPlace`.
top_taken: bool,
}
impl Normalizer {
fn push(&mut self, message: &Message) -> Result<()> {
match &message.role {
Role::System => {
if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace
&& self.top_taken
{
self.place_in_place(message, ExternalRole::System);
return Ok(());
}
if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace {
self.top_taken = true;
}
self.push_system(message);
Ok(())
}
Role::Developer => {
if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace {
self.place_in_place(message, ExternalRole::Developer);
return Ok(());
}
self.report
.actions
.push(NormalizeAction::DowngradedDeveloper);
if self.options.developer_to_system {
self.push_system(message);
} else {
self.push_user(message);
}
Ok(())
}
Role::Custom(role) => {
self.report
.actions
.push(NormalizeAction::DowngradedCustomRole { role: role.clone() });
if self.options.custom_to_user {
self.push_user(message);
} else {
self.push_system(message);
}
Ok(())
}
Role::User => {
self.finish_pending_calls()?;
self.push_user(message);
Ok(())
}
Role::Assistant => {
self.finish_pending_calls()?;
self.push_assistant(message)
}
Role::Tool => self.push_tool(message),
}
}
fn push_system(&mut self, message: &Message) {
self.report_non_assistant_reasoning(ExternalRole::System, &message.parts);
let text = text_parts_joined(&message.parts);
if !text.is_empty() {
self.system.push(text);
}
}
fn place_in_place(&mut self, message: &Message, role: ExternalRole) {
self.report_non_assistant_reasoning(role.clone(), &message.parts);
let parts = normalize_non_tool_parts(&message.parts, &mut self.report);
if !parts.is_empty() {
self.messages.push(NormalizedMessage { role, parts });
}
}
fn push_user(&mut self, message: &Message) {
self.report_non_assistant_reasoning(ExternalRole::User, &message.parts);
let parts = normalize_non_tool_parts(&message.parts, &mut self.report);
if !parts.is_empty() {
self.messages.push(NormalizedMessage {
role: ExternalRole::User,
parts,
});
}
}
fn push_assistant(&mut self, message: &Message) -> Result<()> {
let pending_start = self.pending_calls.len();
let mut parts = Vec::new();
for part in &message.parts {
match part {
Part::Text {
text,
provider_state,
} => {
let text = text.clone();
let mut provider_state = provider_state.clone();
if !self.options.preserve_foreign_reasoning
&& let Some(state) = &provider_state
&& state.format != self.expected_reasoning_format
{
self.report
.actions
.push(NormalizeAction::DroppedForeignTextState {
format: state.format.clone(),
expected: self.expected_reasoning_format.clone(),
});
provider_state = None;
}
parts.push(Part::Text {
text,
provider_state,
});
}
Part::ImageUrl { .. } | Part::Image { .. } => parts.push(part.clone()),
Part::Reasoning(reasoning) => {
if !self.options.preserve_foreign_reasoning
&& let Some(state) = &reasoning.state
&& state.format != self.expected_reasoning_format
{
self.report
.actions
.push(NormalizeAction::DroppedForeignReasoning {
format: state.format.clone(),
expected: self.expected_reasoning_format.clone(),
});
continue;
}
parts.push(Part::Reasoning(reasoning.clone()));
}
Part::ToolCall(call) => {
let mut call = call.clone();
if !self.options.preserve_foreign_reasoning
&& let Some(state) = &call.provider_state
&& state.format != self.expected_reasoning_format
{
self.report
.actions
.push(NormalizeAction::DroppedForeignToolState {
format: state.format.clone(),
expected: self.expected_reasoning_format.clone(),
});
call.provider_state = None;
}
let mut synthetic_id = false;
if call.id.is_none() {
let id = loop {
let id = format!("call_{}", self.next_call_id);
self.next_call_id += 1;
if self.occupied_call_ids.insert(id.clone()) {
break id;
}
};
call.id = Some(id.clone());
synthetic_id = true;
self.report
.actions
.push(NormalizeAction::AssignedToolCallId {
name: call.name.clone(),
id: id.clone(),
});
}
let id = call.id.clone().expect("id was assigned above");
if id.trim().is_empty() || !self.seen_call_ids.insert(id.clone()) {
return Err(Error::Normalize(
"tool call IDs must be non-empty and unique".into(),
));
}
self.pending_calls.push(PendingCall {
id: id.clone(),
name: call.name.clone(),
// Patched to the real slot once this message is pushed.
message_index: usize::MAX,
fulfilled: false,
synthetic: synthetic_id,
native: false,
});
parts.push(Part::ToolCall(call));
}
Part::NativeToolCall(call) => {
if self.options.protocol != Protocol::OpenAiResponses {
return Err(Error::Unsupported("unsupported_tool_representation: native tool history requires Responses".into()));
}
call.validate_completed()?;
if !self.seen_call_ids.insert(call.call_id.clone()) {
return Err(Error::Normalize(
"tool_identity_conflict: duplicate call_id".into(),
));
}
self.seen_native_ids.insert(call.call_id.clone());
self.pending_calls.push(PendingCall {
id: call.call_id.clone(),
name: call.name.clone(),
message_index: usize::MAX,
fulfilled: false,
synthetic: false,
native: true,
});
parts.push(part.clone());
}
Part::ToolResult(result) => {
// A result inside an assistant message is malformed.
self.handle_orphan_tool_result(result)?;
}
Part::ProviderItem(item) => {
if item.provider_state.format == ProviderStateFormat::OpenAiResponses
&& matches!(
item.provider_state
.data
.get("type")
.and_then(serde_json::Value::as_str),
Some(
"custom_tool_call"
| "function_call"
| "custom_tool_call_output"
| "function_call_output"
)
)
{
return Err(Error::Normalize("unsupported_tool_representation: client tool calls and results must use typed parts".into()));
}
if self.options.preserve_foreign_reasoning
|| item.provider_state.format == self.expected_reasoning_format
{
parts.push(part.clone());
} else {
self.report
.actions
.push(NormalizeAction::DroppedForeignProviderItem {
format: item.provider_state.format.clone(),
expected: self.expected_reasoning_format.clone(),
});
}
}
}
}
if !parts.is_empty() {
let message_index = self.messages.len();
self.messages.push(NormalizedMessage {
role: ExternalRole::Assistant,
parts,
});
for pending in &mut self.pending_calls[pending_start..] {
pending.message_index = message_index;
}
}
Ok(())
}
fn push_tool(&mut self, message: &Message) -> Result<()> {
self.report_non_assistant_reasoning(ExternalRole::Tool, &message.parts);
let mut accepted = Vec::new();
for part in &message.parts {
let Part::ToolResult(result) = part else {
continue;
};
let Some(index) = self.find_pending_call(result) else {
if self.pending_calls.iter().any(|call| call.native)
|| result
.call_id
.as_ref()
.is_some_and(|id| self.seen_native_ids.contains(id))
{
return Err(Error::Normalize(
"orphan_tool_result: native history requires explicit call_id pairing"
.into(),
));
}
self.handle_orphan_tool_result(result)?;
continue;
};
let pending = &mut self.pending_calls[index];
pending.fulfilled = true;
let call_id = pending.id.clone();
let name = pending.name.clone();
let mut result = result.clone();
let previous_id = result.call_id.clone();
if previous_id.as_deref() != Some(call_id.as_str()) {
result.call_id = Some(call_id.clone());
self.report.actions.push(match previous_id {
None => NormalizeAction::FilledToolResultId {
name: result.name.clone(),
id: call_id.clone(),
},
Some(previous) => NormalizeAction::ReconciledToolResultId {
name: result.name.clone(),
from: previous,
to: call_id.clone(),
},
});
}
result.name = name;
accepted.push(Part::ToolResult(result));
}
if !accepted.is_empty() {
self.messages.push(NormalizedMessage {
role: ExternalRole::Tool,
parts: accepted,
});
}
Ok(())
}
fn report_non_assistant_reasoning(&mut self, role: ExternalRole, parts: &[Part]) {
if parts.iter().any(|part| matches!(part, Part::Reasoning(_))) {
self.report
.actions
.push(NormalizeAction::DroppedReasoningFromNonAssistant { role });
}
}
fn find_pending_call(&self, result: &ToolResult) -> Option<usize> {
if let Some(call_id) = &result.call_id {
if let Some(index) = self
.pending_calls
.iter()
.position(|call| call.id == *call_id && !call.fulfilled)
{
return Some(index);
}
if self.seen_native_ids.contains(call_id)
|| self
.pending_calls
.iter()
.any(|call| call.native && !call.fulfilled)
{
return None;
}
// An explicit id is the identity, so it never borrows another call's
// slot by name. The single exception is a call whose id this run
// invented: it cannot equal the real provider id the result carries.
return self
.pending_calls
.iter()
.position(|call| call.synthetic && call.name == result.name && !call.fulfilled);
}
self.pending_calls
.iter()
.position(|call| !call.native && call.name == result.name && !call.fulfilled)
}
fn handle_orphan_tool_result(&mut self, result: &ToolResult) -> Result<()> {
match self.options.orphan_tool_result {
OrphanToolResultPolicy::Drop => {
self.report
.actions
.push(NormalizeAction::DroppedOrphanToolResult {
name: result.name.clone(),
});
Ok(())
}
OrphanToolResultPolicy::DowngradeToUser => {
self.messages.push(NormalizedMessage {
role: ExternalRole::User,
parts: vec![Part::text(format!(
"Orphan tool result from `{}`: {}",
result.name, result.content
))],
});
Ok(())
}
OrphanToolResultPolicy::Error => Err(Error::Normalize(format!(
"tool result `{}` has no matching assistant tool call",
result.name
))),
}
}
fn finish_pending_calls(&mut self) -> Result<()> {
let missing: Vec<(String, String, usize)> = self
.pending_calls
.iter()
.filter(|call| !call.fulfilled)
.map(|call| (call.id.clone(), call.name.clone(), call.message_index))
.collect();
if missing.is_empty() {
self.pending_calls.clear();
return Ok(());
}
if self
.pending_calls
.iter()
.any(|call| call.native && !call.fulfilled)
{
return Err(Error::Normalize(
"tool_call_incomplete: native tool result missing".into(),
));
}
match self.options.missing_tool_result {
MissingToolResultPolicy::Synthesize => {
let mut results = Vec::new();
for (call_id, name, _) in missing {
self.report
.actions
.push(NormalizeAction::SynthesizedMissingToolResult {
call_id: call_id.clone(),
name: name.clone(),
});
results.push(Part::ToolResult(ToolResult::error(
Some(call_id),
name,
"missing tool result",
)));
}
self.messages.push(NormalizedMessage {
role: ExternalRole::Tool,
parts: results,
});
self.pending_calls.clear();
Ok(())
}
MissingToolResultPolicy::DropToolCall => {
for (call_id, name, message_index) in missing {
if let Some(message) = self.messages.get_mut(message_index) {
message.parts.retain(|part| {
!matches!(
part,
Part::ToolCall(call)
if call.id.as_deref() == Some(call_id.as_str())
)
});
}
self.report
.actions
.push(NormalizeAction::DroppedUnpairedToolCall { call_id, name });
}
// Dropping the last part can leave an assistant message with no
// content, which strict providers reject outright.
self.messages.retain(|message| !message.parts.is_empty());
self.pending_calls.clear();
Ok(())
}
MissingToolResultPolicy::Error => Err(Error::Normalize(format!(
"{} assistant tool call(s) have no matching tool result",
self.pending_calls.iter().filter(|c| !c.fulfilled).count()
))),
}
}
fn merge_adjacent_messages(&mut self) {
if !self.options.merge_adjacent_same_role {
return;
}
let mut merged: Vec<NormalizedMessage> = Vec::with_capacity(self.messages.len());
for message in self.messages.drain(..) {
if let Some(last) = merged.last_mut()
&& last.role == message.role
{
last.parts.extend(message.parts);
self.report.actions.push(NormalizeAction::MergedAdjacent {
role: last.role.clone(),
});
} else {
merged.push(message);
}
}
self.messages = merged;
}
fn join_system(&self) -> Option<String> {
if self.system.is_empty() {
None
} else {
Some(self.system.join("\n\n"))
}
}
}
fn text_parts_joined(parts: &[Part]) -> String {
parts
.iter()
.filter_map(|part| match part {
Part::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
fn normalize_non_tool_parts(parts: &[Part], report: &mut NormalizeReport) -> Vec<Part> {
parts
.iter()
.filter_map(|part| match part {
Part::Text { text, .. } => Some(Part::text(text)),
Part::ImageUrl { .. } | Part::Image { .. } => Some(part.clone()),
Part::Reasoning(_) => None,
Part::ToolCall(call) => {
report
.actions
.push(NormalizeAction::FlattenedToolCallIntoText {
name: call.name.clone(),
});
Some(Part::text(format!(
"Unpaired tool call `{}` with arguments {}",
call.name, call.arguments
)))
}
Part::NativeToolCall(_) => None,
Part::ToolResult(result) => {
report
.actions
.push(NormalizeAction::FlattenedToolResultIntoText {
name: result.name.clone(),
});
Some(Part::text(format!(
"Orphan tool result from `{}`: {}",
result.name, result.content
)))
}
Part::ProviderItem(_) => None,
})
.collect()
}