causa-protocol 0.1.5

Causa — a minimal context kernel for Rust agents (facts, ports, adapters)
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
//! OpenAI Chat Completions translation for the context kernel.
//!
//! Pure functions from [`causa_kernel::ContextFrame`] to a Chat
//! Completions request body and back to [`causa_kernel::ModelOutput`].
//! Transport-free; the reqwest adapter in `causa-provider` owns HTTP.
//!
//! The renderer-independent policy (role mapping, empty-text skip,
//! no cross-block text join, tool id pairing, observation stringification) lives in
//! `super::context_frame`; this module only shapes the chat wire.
//!
//! # Chat-specific structural rules
//!
//! - `system` text segments stay in frame position as `role: "system"`
//!   messages (OpenAI carries system inline, unlike Anthropic's
//!   top-level parameter).
//! - A run of assistant text segments, tool call segments and own-format
//!   sealed parts coalesces into ONE assistant message (the exception to one
//!   item per block). The wire carries assistant content as a single string,
//!   so the run's texts concatenate in frame order with no separator. The
//!   message starts from the run's first sealed object (later ones are
//!   ignored), then `role`, `content` (only when non-empty) and
//!   `tool_calls` (only when non-empty) are written over it. A tool call
//!   with matching `wire` starts from its `fields` and writes `id`,
//!   `function.name` and `function.arguments`; the provider's arguments
//!   string is kept while it parses to the fact's value.
//! - Parsing a message emits, in order: one sealed item holding every
//!   message key other than `role`, `tool_calls` and a non-empty string
//!   `content` (`reasoning_content`, a null or empty `content`, unknown
//!   keys), when any remain; one text item for non-empty `content`; one
//!   tool-call item per call, with `wire.fields` the call minus `id` and
//!   `function.name`.
//! - Each tool result segment renders as its own `role: "tool"` message
//!   — `tool_call_id` pairing requires one message per call. There is no
//!   `is_error` flag on this wire; error information travels in the
//!   content.
//! - Media: Chat emits images only (`image/*`, via `image_url` for inline
//!   data URLs or remote URLs). Documents and unclassified media types never
//!   render and degrade to text placeholders.
//! - Tool-result media **hoists**: a tool message cannot carry images,
//!   so each result's attachments render as a user message immediately
//!   after the result group — one provenance text part naming the call,
//!   then the images (`image_url` parts with a data URL for inline
//!   payloads or a remote URL); placeholders degrade to text parts in
//!   the same message.
//! - One user `Message` block renders as one `role: "user"` message, its
//!   parts in order: a block that renders to a single text item keeps the
//!   string `content` form, anything else is a content array of `text` and
//!   `image_url` (data URL for inline payloads or remote URL) parts,
//!   with a degraded attachment as a `text` part. Adjacent user blocks
//!   stay separate messages: the block boundary is a fact boundary, and
//!   Chat accepts consecutive user messages. Assistant- and system-position
//!   media degrade to the shared placeholder text (the walk decides).
//! - Tool call arguments are a JSON *string* on the wire (encoded by the
//!   emitter, decoded by the shared `super::context_frame` codec);
//!   parsing rejects a non-JSON arguments string as `Undecodable`.
//! - Sealed `reasoning_content` is replayed by default: the run's sealed
//!   object becomes the assistant message, so a thinking-mode tool loop under
//!   an API that requires the field back (DeepSeek) keeps working.
//!   [`ChatRenderOptions::replay_reasoning_content`] turns that off; with it
//!   off the renderer removes the `reasoning_content` key from its own sealed
//!   items — skipping an item left empty, like one of another format — and
//!   changes nothing else. Other sealed message fields always replay.
//! - Tools: `tools` carries the frame's current tool state, the fold of its
//!   `ToolChange` blocks. Chat has no wire form for a change at a position,
//!   so a change rewrites `tools`.
//! - Output limits use `max_completion_tokens`, including reasoning tokens;
//!   [`ChatRenderOptions::max_tokens_field`] switches to the older
//!   `max_tokens` for a server that reads only that, and only the chosen
//!   field is written. No default limit is injected. Effort renders as
//!   `reasoning_effort`, exactly as given and beside any temperature. Which
//!   effort values and tools a model supports is the host's knowledge.

use serde_json::{Value, json};

use causa_kernel::{
    CacheDirective, ContextFrame, GenerationOptions, ModelInvokeError, ModelInvokeErrorKind,
    ModelItem, ModelOutput, ModelRef, ModelResponse, ReasoningPayload, ToolCallDraft,
};

use super::context_frame::{self, ResolvedMedia, Role, Segment};
use super::media::MediaSet;
use super::media::MediaSource;
use super::render_options::ChatRenderOptions;
use crate::Protocol;

/// A run of assistant text + tool call segments coalescing into one
/// assistant message.
#[derive(Default)]
struct AssistantRun {
    text: String,
    calls: Vec<Value>,
    /// The first sealed message-level object of the run; later ones are
    /// ignored.
    sealed: Option<Value>,
}

/// Render a [`ContextFrame`] into an OpenAI Chat Completions request body.
/// Deterministic: identical inputs produce byte-identical JSON.
///
/// `cache` is accepted for interface parity and ignored: OpenAI-family
/// providers cache server-side, so the directive has no wire
/// representation on this protocol. `GenerationOptions::output_schema`
/// renders as `response_format` (structured output); schema validation
/// and corrective retry stay host-side. `options` carries the Chat-only
/// `reasoning_content` replay choice; see [`ChatRenderOptions`].
pub fn render_openai_chat_messages(
    frame: &ContextFrame,
    media: &MediaSet,
    generation: &GenerationOptions,
    model: &ModelRef,
    _cache: CacheDirective,
    options: &ChatRenderOptions,
) -> Result<Value, ModelInvokeError> {
    super::generation::validate_openai(generation)?;
    super::tool_history::validate_frame(frame)?;
    // Chat has no in-place form for a tool change: `tools` always carries
    // the frame's current tool state.
    let tool_plan = context_frame::plan_tools(frame, context_frame::ToolPlacement::Fold);
    let normalized = context_frame::normalize(
        frame,
        media,
        Protocol::OpenAiChatCompletions,
        tool_plan.in_place,
    );

    // A run of assistant text + tool call segments coalesces into one
    // assistant message; any other segment closes the open run.
    let mut messages: Vec<Value> = Vec::new();
    let mut run: Option<AssistantRun> = None;
    let mut result_media = Vec::new();
    let segments = &normalized.segments;
    let mut next = 0;
    while next < segments.len() {
        let segment = &segments[next];
        next += 1;
        // A whitespace-only assistant text part is omitted from the request
        // (as \`pi-ai\` does); the fact stays in the Context. This is a listed
        // exception to the round-trip property.
        if let Segment::Text {
            role: Role::Assistant,
            text,
            ..
        } = segment
            && context_frame::is_blank_text(text)
        {
            continue;
        }
        if !matches!(segment, Segment::ToolResult { .. }) {
            messages.append(&mut result_media);
        }
        let closes_run = !matches!(
            segment,
            Segment::Text {
                role: Role::Assistant,
                ..
            } | Segment::ToolCall(_)
                | Segment::Sealed(_)
        );
        if closes_run && let Some(finished) = run.take() {
            messages.extend(assistant_message(finished));
        }
        match segment {
            Segment::Text {
                role: Role::System,
                text,
                ..
            } => {
                messages.push(json!({"role": "system", "content": text}));
            }
            // One user block renders as one message, its parts in order.
            Segment::Text {
                role: Role::User, ..
            }
            | Segment::Media {
                role: Role::User, ..
            } => {
                let parts = context_frame::user_block_run(segments, next - 1);
                messages.push(user_message(&segments[next - 1..next - 1 + parts]));
                next += parts - 1;
            }
            Segment::Media {
                role,
                media: ResolvedMedia::Placeholder(text),
                ..
            } => {
                let role = if *role == Role::System {
                    "system"
                } else {
                    "assistant"
                };
                messages.push(json!({"role": role, "content": text}));
            }
            Segment::Media {
                media: ResolvedMedia::Image { .. },
                ..
            } => unreachable!("the walk renders images only in user position"),
            Segment::Media {
                media: ResolvedMedia::Document { .. },
                ..
            } => unreachable!("the capability table never emits documents for openai_chat"),
            Segment::Text {
                role: Role::Assistant,
                text,
                ..
            } => run
                .get_or_insert_with(AssistantRun::default)
                .text
                .push_str(text),
            Segment::Sealed(item) => {
                // With replay off, only `reasoning_content` is removed; other
                // sealed message fields still replay, and an item left empty
                // is skipped like one of another format.
                let item = if options.replay_reasoning_content {
                    Some(item.clone())
                } else {
                    without_reasoning_content(item)
                };
                if let Some(item) = item {
                    let state = run.get_or_insert_with(AssistantRun::default);
                    if state.sealed.is_none() {
                        state.sealed = Some(item);
                    }
                }
            }
            Segment::ToolCall(call) => {
                let mut wire_call = context_frame::residue_object(call.wire.as_ref());
                wire_call.entry("type").or_insert_with(|| json!("function"));
                wire_call.insert("id".into(), json!(call.wire_id));
                let mut function = match wire_call.remove("function") {
                    Some(Value::Object(function)) => function,
                    _ => serde_json::Map::new(),
                };
                function.insert("name".into(), json!(call.name));
                let arguments = context_frame::wire_arguments_string(
                    function.get("arguments"),
                    &call.arguments,
                );
                function.insert("arguments".into(), json!(arguments));
                wire_call.insert("function".into(), Value::Object(function));
                run.get_or_insert_with(AssistantRun::default)
                    .calls
                    .push(Value::Object(wire_call));
            }
            Segment::ToolResult {
                wire_id,
                content,
                notes,
                media,
                ..
            } => {
                messages.push(json!({
                    "role": "tool",
                    "tool_call_id": wire_id,
                    "content": context_frame::result_text_with_notes(content, notes),
                }));
                // A tool message cannot carry images: hoist the result's
                // media into a user message after the result group, provenance
                // first, one part per attachment in payload order.
                if !media.is_empty() {
                    let mut parts = vec![json!({
                        "type": "text",
                        "text": format!("[tool result media for call {wire_id}]"),
                    })];
                    parts.extend(media.iter().map(attachment_part));
                    result_media.push(json!({"role": "user", "content": parts}));
                }
            }
            // Never emitted under fold placement.
            Segment::ToolChange(_) => {}
        }
    }
    if let Some(finished) = run.take() {
        messages.extend(assistant_message(finished));
    }

    messages.append(&mut result_media);
    super::tool_history::validate_chat(&messages)?;

    if messages.is_empty() {
        return Err(ModelInvokeError::new(
            ModelInvokeErrorKind::InvalidRequest,
            "frame rendered to zero messages; nothing to send",
        ));
    }

    let mut body = json!({
        "model": model.0,
        "messages": messages,
    });
    if let Some(temperature) = generation.temperature {
        body["temperature"] = json!(temperature);
    }
    if let Some(max_tokens) = generation.max_tokens {
        body[options.max_tokens_field.field_name()] = json!(max_tokens);
    }
    if let Some(effort) = &generation.reasoning_effort {
        body["reasoning_effort"] = json!(effort);
    }
    if let Some(schema) = &generation.output_schema {
        body["response_format"] = json!({
            "type": "json_schema",
            "json_schema": {
                "name": super::OUTPUT_SCHEMA_NAME,
                "schema": schema,
                "strict": false,
            },
        });
    }
    if !tool_plan.tools.is_empty() {
        body["tools"] = json!(context_frame::tool_definitions(
            &tool_plan.tools,
            context_frame::ToolShape::OpenAiChat
        ));
    }
    super::generation::merge_extra_body(&mut body, generation);
    // The schema is the host's own value, not an object the adapter wrote:
    // the merge may add keys beside it and must not reach into it.
    if let Some(schema) = &generation.output_schema {
        body["response_format"]["json_schema"]["schema"] = schema.clone();
    }
    Ok(body)
}

/// Materialize an assistant run. The message starts from the run's sealed
/// message-level object when it has one; `role`, `content` (the run's texts
/// concatenated with no separator, only when non-empty) and `tool_calls`
/// (only when non-empty) are written over it. Without a sealed object, empty
/// text is omitted (a calls-only message carries no `content`) and a
/// text-only message carries no `tool_calls` key.
///
/// `None` when the result would carry neither a `content` key nor
/// `tool_calls`: a run whose only text was whitespace (omitted above) leaves
/// just the sealed residue, and an assistant message with neither is not a
/// valid Chat message, so the whole message is omitted like the text was.
fn assistant_message(run: AssistantRun) -> Option<Value> {
    let mut message = context_frame::residue_object(run.sealed.as_ref());
    message.insert("role".into(), json!("assistant"));
    if !run.text.is_empty() {
        message.insert("content".into(), json!(run.text));
    }
    if !run.calls.is_empty() {
        message.insert("tool_calls".into(), json!(run.calls));
    }
    (message.contains_key("content") || message.contains_key("tool_calls"))
        .then_some(Value::Object(message))
}

/// The sealed Chat object without its `reasoning_content` key; `None` when
/// that leaves it empty. A non-object sealed item is returned unchanged.
fn without_reasoning_content(item: &Value) -> Option<Value> {
    let Value::Object(map) = item else {
        return Some(item.clone());
    };
    let mut map = map.clone();
    map.remove("reasoning_content");
    (!map.is_empty()).then_some(Value::Object(map))
}

/// One user block's text and media segments as one user message. A block
/// that renders to a single text item keeps the string `content` form;
/// anything else is a content array in part order.
fn user_message(parts: &[Segment]) -> Value {
    let mut items: Vec<Value> = parts
        .iter()
        .filter_map(|segment| match segment {
            Segment::Text { text, .. } => Some(json!({"type": "text", "text": text})),
            Segment::Media { media, .. } => Some(attachment_part(media)),
            _ => None,
        })
        .collect();
    if let [item] = items.as_mut_slice()
        && item["type"] == "text"
    {
        return json!({"role": "user", "content": item["text"].take()});
    }
    json!({"role": "user", "content": items})
}

/// One media attachment as a user content item: an `image_url` part with a
/// data URL (inline) or remote URL, or the placeholder as a `text` part.
fn attachment_part(media: &ResolvedMedia) -> Value {
    match media {
        ResolvedMedia::Image { media_type, source } => {
            let url = match source {
                MediaSource::Inline { data_base64 } => {
                    format!("data:{media_type};base64,{data_base64}")
                }
                MediaSource::Url(u) => u.clone(),
            };
            json!({
                "type": "image_url",
                "image_url": {"url": url},
            })
        }
        ResolvedMedia::Document { .. } => {
            unreachable!("the capability table never emits documents for openai_chat")
        }
        ResolvedMedia::Placeholder(text) => json!({"type": "text", "text": text}),
    }
}

/// Parse an OpenAI Chat Completions response body into a kernel
/// [`ModelOutput`].
///
/// A `finish_reason` the kernel has no meaning for maps to
/// [`causa_kernel::ModelStopReason::Unrecognized`] rather than being guessed, and the raw
/// wire value is preserved on [`ModelOutput::raw_stop_reason`]. The mapping
/// table is shared with the streaming decoder, so batch and streaming cannot
/// disagree. `reasoning_content` (the OpenAI-compatible reasoning extension)
/// is kept as a sealed message-level item — so the renderer can send it back
/// — and additionally maps to the reasoning observation, which is
/// display-only.
pub fn parse_openai_chat_response(value: &Value) -> Result<ModelOutput, ModelInvokeError> {
    fn undecodable(message: impl Into<String>) -> ModelInvokeError {
        ModelInvokeError::new(ModelInvokeErrorKind::Undecodable, message)
    }

    let choices = value
        .get("choices")
        .and_then(Value::as_array)
        .ok_or_else(|| undecodable("missing choices[0]"))?;
    // One output holds one answer. Returning the first of several would
    // drop the rest while the usage still counts them.
    if choices.len() > 1 {
        return Err(undecodable("more than one choice; one is supported"));
    }
    let choice = choices
        .first()
        .ok_or_else(|| undecodable("missing choices[0]"))?;
    let message = choice
        .get("message")
        .ok_or_else(|| undecodable("missing choices[0].message"))?;

    let text = match message.get("content") {
        None | Some(Value::Null) => String::new(),
        Some(Value::String(s)) => s.clone(),
        Some(_) => return Err(undecodable("choices[0].message.content: expected a string")),
    };

    let mut items: Vec<ModelItem> = Vec::new();
    // Message-level keys the facts do not hold (`reasoning_content`, a null
    // or empty `content`, and anything unknown) travel as one sealed item,
    // first, so the renderer can rebuild the message around it.
    let mut residue = message.as_object().cloned().unwrap_or_default();
    residue.remove("role");
    residue.remove("tool_calls");
    if !text.is_empty() {
        residue.remove("content");
    }
    if !residue.is_empty() {
        items.push(context_frame::sealed_item(
            Protocol::OpenAiChatCompletions,
            Value::Object(residue),
        ));
    }
    if !text.is_empty() {
        items.push(ModelItem::text(text));
    }

    let raw_stop_reason = match crate::translation::stop_reason::chat_raw(choice) {
        Some(raw) => raw.to_owned(),
        None if choice.get("finish_reason").is_some_and(|v| !v.is_null()) => {
            return Err(undecodable("choices[0].finish_reason: expected a string"));
        }
        None => return Err(undecodable("missing choices[0].finish_reason")),
    };
    let stop_reason = crate::translation::stop_reason::chat(&raw_stop_reason);

    if let Some(wire_calls) = message.get("tool_calls").and_then(Value::as_array) {
        for (position, call) in wire_calls.iter().enumerate() {
            let id = call
                .get("id")
                .and_then(Value::as_str)
                .ok_or_else(|| undecodable("tool_calls[]: missing `id` string"))?;
            let function = call
                .get("function")
                .ok_or_else(|| undecodable("tool_calls[]: missing `function`"))?;
            let name = function
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| undecodable("tool_calls[].function: missing `name` string"))?;
            // Completed calls require a complete JSON-encoded argument value.
            // The token limit can stop the response inside the last call.
            let cut_off = stop_reason == causa_kernel::ModelStopReason::MaxTokens
                && position + 1 == wire_calls.len();
            let Some(arguments) =
                context_frame::decode_wire_arguments(function.get("arguments"), cut_off)?
            else {
                continue;
            };
            // The entry minus `id` and `function.name`: `type`, `index` and
            // the raw `function.arguments` string stay.
            let mut fields = context_frame::without_keys(call, &["id"]);
            if let Some(function) = fields.get_mut("function").and_then(Value::as_object_mut) {
                function.remove("name");
            }
            items.push({
                let mut item = ModelItem::tool_call(
                    ToolCallDraft::new(name.to_string(), arguments)
                        .with_provider_call_id(id.to_string()),
                );
                item.wire = Some(context_frame::wire_meta(
                    Protocol::OpenAiChatCompletions,
                    fields,
                ));
                item
            });
        }
    }

    let reasoning = message
        .get("reasoning_content")
        .and_then(Value::as_str)
        .map(|text| ReasoningPayload::new(text.to_string()));

    let usage = value
        .get("usage")
        .filter(|v| v.is_object())
        .map(crate::translation::usage::model_usage_from_openai_chat);

    Ok({
        let mut output = ModelOutput::new(ModelResponse { items }, stop_reason);
        output.usage = usage;
        output.raw_stop_reason = Some(raw_stop_reason);
        output.reasoning = reasoning;
        output
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use causa_kernel::{
        ModelItemContent, ModelStopReason, ModelUsage, ToolDefinition, ToolResultStatus,
    };

    use crate::translation::media::{MediaPayload, MediaSet};
    use crate::translation::test_support::{
        call, frame, label_id, media_part, parts, result, result_with_media, text, text_part,
        text_with_source, with_tools,
    };

    fn render(frame: &ContextFrame) -> Value {
        render_openai_chat_messages(
            frame,
            &MediaSet::new(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap()
    }

    // --- rendering ---------------------------------------------------------

    #[test]
    fn role_mapping_and_source_independence() {
        let f = frame(vec![
            text(0, "be terse", Role::System),
            text(1, "model said", Role::Assistant),
            text(2, "user said", Role::User),
            text(3, "replayed", Role::Assistant),
            // source set to "system" but role is User: role wins, source ignored
            text_with_source(4, "user override", Role::User, Some("system")),
            // source absent and role is User: renders as user
            text(5, "user no source", Role::User),
        ]);
        let v = render(&f);
        let msgs = v["messages"].as_array().unwrap();
        // system stays inline as a message; assistant / user /
        // assistant / user / user:
        // user texts are never joined across block seams
        assert_eq!(msgs.len(), 6);
        assert_eq!(msgs[0], json!({"role": "system", "content": "be terse"}));
        assert_eq!(
            msgs[1],
            json!({"role": "assistant", "content": "model said"})
        );
        assert_eq!(msgs[2], json!({"role": "user", "content": "user said"}));
        assert_eq!(msgs[3], json!({"role": "assistant", "content": "replayed"}));
        assert_eq!(msgs[4], json!({"role": "user", "content": "user override"}));
        assert_eq!(
            msgs[5],
            json!({"role": "user", "content": "user no source"})
        );
    }

    #[test]
    fn tool_round_trip_pairing_and_assistant_merge() {
        let fallback_id = call(2, "kc2", None, "list", json!({})).id().0.to_string();
        let f = frame(vec![
            text(0, "reading now", Role::Assistant),
            call(1, "kc1", Some("toolu_a"), "read", json!({"path": "a"})),
            call(2, "kc2", None, "list", json!({})),
            result(3, "kc1", ToolResultStatus::Succeeded, json!("file-a")),
            result(4, "kc2", ToolResultStatus::Failed, json!({"error": "boom"})),
        ]);
        let v = render(&f);
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(msgs.len(), 3);
        // text + both calls merge into ONE assistant message; arguments
        // serialize to a JSON string; an unnamed call falls back to its
        // declaration BlockId UUID.
        assert_eq!(
            msgs[0],
            json!({
                "role": "assistant",
                "content": "reading now",
                "tool_calls": [
                    {"id": "toolu_a", "type": "function",
                     "function": {"name": "read", "arguments": "{\"path\":\"a\"}"}},
                    {"id": fallback_id, "type": "function",
                     "function": {"name": "list", "arguments": "{}"}},
                ],
            })
        );
        // each result is its own role:"tool" message with paired ids
        assert_eq!(
            msgs[1],
            json!({"role": "tool", "tool_call_id": "toolu_a", "content": "file-a"})
        );
        assert_eq!(
            msgs[2],
            json!({"role": "tool", "tool_call_id": fallback_id, "content": "{\"error\":\"boom\"}"})
        );
    }

    #[test]
    fn assistant_tool_calls_only_omits_empty_content() {
        let f = frame(vec![
            call(0, "kc1", Some("toolu_a"), "read", json!({})),
            result(1, "kc1", ToolResultStatus::Succeeded, json!("ok")),
        ]);
        let v = render(&f);
        assert_eq!(
            v["messages"][0],
            json!({
                "role": "assistant",
                "tool_calls": [
                    {"id": "toolu_a", "type": "function",
                     "function": {"name": "read", "arguments": "{}"}},
                ],
            })
        );
        assert!(v["messages"][0].get("content").is_none());
    }

    #[test]
    fn adjacent_assistant_texts_concatenate_into_one_message() {
        // Assistant text runs coalesce across calls too — the wire
        // carries assistant content as a single string.
        let f = frame(vec![
            text(0, "first", Role::Assistant),
            call(1, "kc1", Some("toolu_a"), "read", json!({})),
            text(2, "second", Role::Assistant),
            result(3, "kc1", ToolResultStatus::Succeeded, json!("ok")),
        ]);
        let v = render(&f);
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(msgs.len(), 2);
        assert_eq!(msgs[0]["role"], "assistant");
        assert_eq!(msgs[0]["content"], json!("firstsecond"));
        assert_eq!(msgs[0]["tool_calls"].as_array().unwrap().len(), 1);

        // no calls in between: still one message, texts concatenated with
        // no separator
        let f = frame(vec![
            text(0, "a", Role::Assistant),
            text(1, "b", Role::Assistant),
        ]);
        let v = render(&f);
        assert_eq!(
            v["messages"],
            json!([{"role": "assistant", "content": "ab"}])
        );
    }

    #[test]
    fn unpaired_tool_result_is_invalid_before_http() {
        let f = frame(vec![result(
            0,
            "orphan",
            ToolResultStatus::Succeeded,
            json!("x"),
        )]);
        let error = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &GenerationOptions::default(),
            &ModelRef::new("test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap_err();
        assert_eq!(error.kind, ModelInvokeErrorKind::InvalidRequest);
    }

    #[test]
    fn tools_generation_and_byte_determinism() {
        let surface = vec![ToolDefinition::new(
            "read",
            "read a file",
            json!({"type": "object"}),
        )];
        let f = frame(vec![text(0, "hi", Role::User)]);

        let generation = GenerationOptions::default().with_temperature(0.5);
        let v = render_openai_chat_messages(
            &with_tools(&f, &surface),
            &MediaSet::new(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(v["model"], json!("gpt-test"));
        assert_eq!(v["temperature"], json!(0.5));
        // OpenAI does not require max_tokens; None stays absent
        assert!(v.get("max_tokens").is_none());
        assert_eq!(
            v["tools"],
            json!([{
                "type": "function",
                "function": {"name": "read", "description": "read a file", "parameters": {"type": "object"}},
            }])
        );

        let generation = GenerationOptions::default()
            .with_temperature(0.5)
            .with_max_tokens(100);
        let v2 = render_openai_chat_messages(
            &with_tools(&f, &surface),
            &MediaSet::new(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(v2["max_completion_tokens"], json!(100));
        let again = render_openai_chat_messages(
            &with_tools(&f, &surface),
            &MediaSet::new(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(
            serde_json::to_string(&v2).unwrap(),
            serde_json::to_string(&again).unwrap()
        );
    }

    #[test]
    fn output_schema_maps_and_cache_directive_is_a_noop() {
        let f = frame(vec![text(0, "hi", Role::User)]);
        let generation = GenerationOptions::default().with_output_schema(json!({"type": "object"}));
        let v = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(
            v["response_format"],
            json!({
                "type": "json_schema",
                "json_schema": {
                    "name": "response",
                    "schema": {"type": "object"},
                    "strict": false,
                },
            })
        );
        // the cache directive has no wire representation on this protocol
        let cached = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::StablePrefix,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(v, cached);
    }

    #[test]
    fn empty_frame_is_invalid_request() {
        let e = render_openai_chat_messages(
            &frame(vec![]),
            &MediaSet::new(),
            &GenerationOptions::default(),
            &ModelRef::new("m"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap_err();
        assert!(matches!(e.kind, ModelInvokeErrorKind::InvalidRequest));
    }

    // --- media -------------------------------------------------------------

    use causa_kernel::MediaRef;

    fn resolved(reference: &str) -> MediaSet {
        let mut m = MediaSet::new();
        m.insert(reference, MediaPayload::inline("image/png", "AAAA"));
        m
    }

    #[test]
    fn one_user_block_renders_as_one_message() {
        let f = frame(vec![
            parts(
                0,
                vec![
                    text_part("caption"),
                    media_part("image/png", "asset-1"),
                    text_part("after"),
                ],
                Role::User,
            ),
            parts(1, vec![text_part("first"), text_part("second")], Role::User),
            text(2, "alone", Role::User),
            parts(3, vec![media_part("image/png", "asset-1")], Role::User),
        ]);
        let v = render_openai_chat_messages(
            &f,
            &resolved("asset-1"),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        // part boundaries are content items inside the block's one message;
        // adjacent user blocks stay separate messages, and a single text
        // part keeps the string form
        assert_eq!(
            v["messages"],
            json!([
                {"role": "user", "content": [
                    {"type": "text", "text": "caption"},
                    {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
                    {"type": "text", "text": "after"},
                ]},
                {"role": "user", "content": [
                    {"type": "text", "text": "first"},
                    {"type": "text", "text": "second"},
                ]},
                {"role": "user", "content": "alone"},
                {"role": "user", "content": [
                    {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
                ]},
            ])
        );
    }

    #[test]
    fn url_image_parts_render_as_image_url_in_user_position() {
        let f = frame(vec![parts(
            0,
            vec![
                text_part("caption"),
                media_part("image/png", "asset-1"),
                text_part("after"),
            ],
            Role::User,
        )]);
        let mut media = MediaSet::new();
        media.insert(
            "asset-1",
            MediaPayload::url("image/png", "https://example.com/pic.png"),
        );
        let v = render_openai_chat_messages(
            &f,
            &media,
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(
            v["messages"][0]["content"],
            json!([
                {"type": "text", "text": "caption"},
                {"type": "image_url", "image_url": {"url": "https://example.com/pic.png"}},
                {"type": "text", "text": "after"},
            ])
        );
    }

    #[test]
    fn unresolved_media_degrades_to_the_deterministic_placeholder() {
        let f = frame(vec![parts(
            0,
            vec![media_part("image/png", "missing-asset")],
            Role::User,
        )]);
        let v = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        assert_eq!(
            v["messages"][0],
            json!({"role": "user", "content": "[media: image/png missing-asset]"})
        );
    }

    #[test]
    fn tool_result_media_hoists_into_a_user_message_with_provenance() {
        let f = frame(vec![
            call(0, "kc1", Some("call_1"), "render", json!({})),
            result_with_media(
                1,
                "kc1",
                ToolResultStatus::Succeeded,
                json!("chart ready"),
                vec![
                    MediaRef::new("image/png", "asset-1"),
                    MediaRef::new("image/png", "asset-2"),
                ],
            ),
        ]);
        let mut media = MediaSet::new();
        media.insert("asset-1", MediaPayload::inline("image/png", "AAAA"));
        media.insert("asset-2", MediaPayload::inline("image/jpeg", "BBBB"));
        let v = render_openai_chat_messages(
            &f,
            &media,
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        let msgs = v["messages"].as_array().unwrap();
        // tool message stays text-only; media hoists right after it
        assert_eq!(msgs[1]["role"], "tool");
        assert_eq!(msgs[2]["role"], "user");
        assert_eq!(
            msgs[2]["content"],
            json!([
                {"type": "text", "text": "[tool result media for call call_1]"},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
                {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,BBBB"}},
            ])
        );
    }

    #[test]
    fn tool_result_url_media_hoists_into_a_user_message() {
        let f = frame(vec![
            call(0, "kc1", Some("call_1"), "render", json!({})),
            result_with_media(
                1,
                "kc1",
                ToolResultStatus::Succeeded,
                json!("chart ready"),
                vec![MediaRef::new("image/png", "asset-1")],
            ),
        ]);
        let mut media = MediaSet::new();
        media.insert(
            "asset-1",
            MediaPayload::url("image/png", "https://example.com/chart.png"),
        );
        let v = render_openai_chat_messages(
            &f,
            &media,
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(msgs[1]["role"], "tool");
        assert_eq!(msgs[2]["role"], "user");
        assert_eq!(
            msgs[2]["content"],
            json!([
                {"type": "text", "text": "[tool result media for call call_1]"},
                {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}},
            ])
        );
    }

    #[test]
    fn hoisted_placeholders_stay_in_payload_order() {
        let fallback_id = label_id("kc1").0.to_string();
        let f = frame(vec![
            call(0, "kc1", None, "render", json!({})),
            result_with_media(
                1,
                "kc1",
                ToolResultStatus::Succeeded,
                json!("mixed"),
                vec![
                    MediaRef::new("image/png", "good"),
                    MediaRef::new("image/png", "missing"),
                    MediaRef::new("application/pdf", "doc"),
                ],
            ),
        ]);
        let mut media = MediaSet::new();
        media.insert("good", MediaPayload::inline("image/png", "AAAA"));
        media.insert("doc", MediaPayload::inline("application/pdf", "BBBB"));
        let v = render_openai_chat_messages(
            &f,
            &media,
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
            &ChatRenderOptions::default(),
        )
        .unwrap();
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(
            msgs[2]["content"],
            json!([
                {"type": "text", "text": format!("[tool result media for call {fallback_id}]")},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
                {"type": "text", "text": "[media: image/png missing]"},
                // resolved but non-image: degraded, never inlined
                {"type": "text", "text": "[media: application/pdf doc]"},
            ])
        );
    }

    // --- parsing -----------------------------------------------------------

    /// The stored value of every sealed part of a response, in item order.
    fn sealed_items(out: &ModelOutput) -> Vec<Value> {
        out.response
            .items
            .iter()
            .flat_map(|item| match &item.content {
                ModelItemContent::Parts(parts) => parts
                    .iter()
                    .filter_map(|part| match part {
                        causa_kernel::ContentPart::Sealed(sealed) => Some(sealed.item.clone()),
                        _ => None,
                    })
                    .collect::<Vec<_>>(),
                _ => Vec::new(),
            })
            .collect()
    }

    #[test]
    fn parse_full_message_shape_with_provider_id_passthrough() {
        let v = json!({
            "choices": [{
                "message": {
                    "role": "assistant",
                    "content": "Let me check.",
                    "tool_calls": [{
                        "id": "call_9",
                        "type": "function",
                        "function": {"name": "read", "arguments": "{\"path\": \"a\"}"},
                    }],
                    "reasoning_content": "hmm",
                },
                "finish_reason": "tool_calls",
            }],
            "usage": {
                "prompt_tokens": 100,
                "completion_tokens": 20,
                "prompt_tokens_details": {"cached_tokens": 11},
                "completion_tokens_details": {"reasoning_tokens": 5},
            },
        });
        let out = parse_openai_chat_response(&v).unwrap();
        assert_eq!(out.response.text(), "Let me check.");
        assert_eq!(out.response.tool_calls().count(), 1);
        let tc = &out.response.tool_calls().next().unwrap();
        assert_eq!(tc.tool_name, "read");
        assert_eq!(tc.arguments, json!({"path": "a"}));
        assert_eq!(tc.provider_call_id.as_deref(), Some("call_9"));
        assert!(matches!(out.stop_reason, ModelStopReason::ToolUse));
        // The message residue, `reasoning_content` included, is sealed material
        // so the renderer can send it back verbatim.
        assert_eq!(
            sealed_items(&out),
            vec![json!({"reasoning_content": "hmm"})]
        );
        let reasoning = out.reasoning.unwrap();
        assert_eq!(reasoning.text, "hmm");
        let u: ModelUsage = out.usage.unwrap();
        assert_eq!((u.input_tokens, u.output_tokens), (100, 20));
        assert_eq!(u.cache_read_tokens, Some(11));
        assert_eq!(u.cache_write_tokens, None);
        assert_eq!(u.reasoning_tokens, Some(5));
    }

    #[test]
    fn finish_reason_mapping_full_and_unknown_is_unrecognized() {
        for (wire, expected) in [
            ("stop", ModelStopReason::EndTurn),
            ("end", ModelStopReason::EndTurn),
            ("tool_calls", ModelStopReason::ToolUse),
            ("function_call", ModelStopReason::ToolUse),
            ("length", ModelStopReason::MaxTokens),
            ("content_filter", ModelStopReason::Refusal),
            // An unknown value is reported as what it is, never guessed.
            ("some_new_reason", ModelStopReason::Unrecognized),
        ] {
            let v = json!({"choices": [{"message": {"content": ""}, "finish_reason": wire}]});
            let out = parse_openai_chat_response(&v).unwrap();
            assert_eq!(
                std::mem::discriminant(&out.stop_reason),
                std::mem::discriminant(&expected),
                "finish_reason = {wire}"
            );
            assert_eq!(out.raw_stop_reason.as_deref(), Some(wire));
        }
    }

    #[test]
    fn missing_choices_or_finish_reason_is_undecodable_error() {
        let e = parse_openai_chat_response(&json!({"choices": []})).unwrap_err();
        assert!(matches!(e.kind, ModelInvokeErrorKind::Undecodable));
        let e = parse_openai_chat_response(&json!({"choices": [{"message": {}}]})).unwrap_err();
        assert!(matches!(e.kind, ModelInvokeErrorKind::Undecodable));
        assert!(e.message.contains("finish_reason"));
        // Present but not a string is reported as such, not as missing.
        let e =
            parse_openai_chat_response(&json!({"choices": [{"message": {}, "finish_reason": 7}]}))
                .unwrap_err();
        assert!(matches!(e.kind, ModelInvokeErrorKind::Undecodable));
        assert!(e.message.contains("expected a string"));
    }

    #[test]
    fn malformed_arguments_string_is_undecodable_error() {
        let v = json!({
            "choices": [{
                "message": {"content": null, "tool_calls": [
                    {"id": "c1", "function": {"name": "read", "arguments": "{not json"}},
                ]},
                "finish_reason": "tool_calls",
            }],
        });
        let e = parse_openai_chat_response(&v).unwrap_err();
        assert!(matches!(e.kind, ModelInvokeErrorKind::Undecodable));
        assert!(e.message.contains("arguments"));
    }

    #[test]
    fn empty_arguments_string_is_undecodable_error() {
        let v = json!({
            "choices": [{
                "message": {"tool_calls": [
                    {"id": "c1", "function": {"name": "list", "arguments": ""}},
                ]},
                "finish_reason": "tool_calls",
            }],
        });
        let error = parse_openai_chat_response(&v).unwrap_err();
        assert_eq!(error.kind, ModelInvokeErrorKind::Undecodable);
    }
}