causa-protocol 0.0.1

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
//! 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 (source vocabulary, empty-text skip,
//! text joining, 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 and tool call segments coalesces
//!   into ONE assistant message. The wire carries assistant content as a
//!   single string, so text around tool calls joins in frame order; a
//!   run with no text omits `content`, a run with no calls omits
//!   `tool_calls`.
//! - 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.
//! - Tool-result media **hoists**: a tool message cannot carry images,
//!   so each result's attachments render as a user message immediately
//!   after it — one provenance text part naming the call, then the
//!   images (data-URL `image_url` parts); placeholders degrade to text
//!   parts in the same message.
//! - Media parts in user position render as `image_url` content-array
//!   messages (data URLs); 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 `Permanent`.
//! - `max_tokens` is optional for OpenAI (no default injected).

use serde_json::{Value, json};

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

use super::context_frame::{self, ResolvedMedia, Role, Segment};
use super::media::MediaSet;

/// A run of assistant text + tool call segments coalescing into one
/// assistant message.
struct AssistantRun {
    text: String,
    calls: Vec<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.
pub fn render_openai_chat_messages(
    frame: &ContextFrame,
    media: &MediaSet,
    tool_surface: &ToolSurface,
    generation: &GenerationOptions,
    model: &ModelRef,
    _cache: CacheDirective,
) -> Result<Value, ModelInvokeError> {
    let normalized = context_frame::normalize(frame, media);

    // 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;
    for segment in &normalized.segments {
        let closes_run = !matches!(
            segment,
            Segment::Text {
                role: Role::Assistant,
                ..
            } | Segment::ToolCall(_)
        );
        if closes_run && let Some(finished) = run.take() {
            messages.push(assistant_message(finished));
        }
        match segment {
            Segment::Text {
                role: Role::System,
                text,
            } => {
                messages.push(json!({"role": "system", "content": text}));
            }
            Segment::Text {
                role: Role::User,
                text,
            } => {
                messages.push(json!({"role": "user", "content": text}));
            }
            Segment::Media { role, media } => match (role, media) {
                (Role::System, ResolvedMedia::Placeholder(text)) => {
                    messages.push(json!({"role": "system", "content": text}));
                }
                (Role::Assistant, ResolvedMedia::Placeholder(text)) => {
                    // closes the open run, then a degraded assistant text
                    if let Some(finished) = run.take() {
                        messages.push(assistant_message(finished));
                    }
                    messages.push(json!({"role": "assistant", "content": text}));
                }
                (
                    _,
                    ResolvedMedia::Image {
                        media_type,
                        data_base64,
                    },
                ) => {
                    messages.push(json!({
                        "role": "user",
                        "content": [{"type": "image_url", "image_url": {"url": data_url(media_type, data_base64)}}],
                    }));
                }
                (_, ResolvedMedia::Placeholder(text)) => {
                    messages.push(json!({"role": "user", "content": text}));
                }
            },
            Segment::Text {
                role: Role::Assistant,
                text,
            } => match &mut run {
                Some(state) => {
                    state.text.push('\n');
                    state.text.push_str(text);
                }
                None => {
                    run = Some(AssistantRun {
                        text: text.clone(),
                        calls: Vec::new(),
                    })
                }
            },
            Segment::ToolCall(call) => {
                let wire_call = json!({
                    "id": call.wire_id,
                    "type": "function",
                    "function": {
                        "name": call.name,
                        "arguments": call.arguments.to_string(),
                    },
                });
                match &mut run {
                    Some(state) => state.calls.push(wire_call),
                    None => {
                        run = Some(AssistantRun {
                            text: String::new(),
                            calls: vec![wire_call],
                        })
                    }
                }
            }
            Segment::ToolResult {
                wire_id,
                content,
                media,
                ..
            } => {
                messages.push(json!({
                    "role": "tool",
                    "tool_call_id": wire_id,
                    "content": content,
                }));
                // A tool message cannot carry images: hoist the result's
                // media into a user message right after it, 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(|m| match m {
                        ResolvedMedia::Image {
                            media_type,
                            data_base64,
                        } => json!({
                            "type": "image_url",
                            "image_url": {"url": data_url(media_type, data_base64)},
                        }),
                        ResolvedMedia::Placeholder(text) => {
                            json!({"type": "text", "text": text})
                        }
                    }));
                    messages.push(json!({"role": "user", "content": parts}));
                }
            }
        }
    }
    if let Some(finished) = run.take() {
        messages.push(assistant_message(finished));
    }

    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["max_tokens"] = json!(max_tokens);
    }
    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_surface.definitions.is_empty() {
        body["tools"] = json!(context_frame::tool_definitions(
            tool_surface,
            context_frame::ToolShape::OpenAiChat
        ));
    }
    Ok(body)
}

/// Materialize an assistant run: empty text is omitted (a calls-only
/// message carries no `content`), a text-only message carries no
/// `tool_calls` key.
fn assistant_message(run: AssistantRun) -> Value {
    let mut message = json!({"role": "assistant"});
    if !run.text.is_empty() {
        message["content"] = json!(run.text);
    }
    if !run.calls.is_empty() {
        message["tool_calls"] = json!(run.calls);
    }
    message
}

/// The inline data URL for a resolved image payload (`image_url` shape).
fn data_url(media_type: &str, data_base64: &str) -> String {
    format!("data:{media_type};base64,{data_base64}")
}

/// Parse an OpenAI Chat Completions response body into a kernel
/// [`ModelOutput`].
///
/// Unknown `finish_reason` values degrade to [`ModelStopReason::EndTurn`]
/// rather than inventing an interruption the provider did not report;
/// `reasoning_content` (the OpenAI-compatible reasoning extension) maps to
/// the reasoning envelope with no signature.
pub fn parse_openai_chat_response(value: &Value) -> Result<ModelOutput, ModelInvokeError> {
    fn permanent(message: impl Into<String>) -> ModelInvokeError {
        ModelInvokeError::new(ModelInvokeErrorKind::Permanent, message)
    }

    let choice = value
        .get("choices")
        .and_then(Value::as_array)
        .and_then(|c| c.first())
        .ok_or_else(|| permanent("missing choices[0]"))?;
    let message = choice
        .get("message")
        .ok_or_else(|| permanent("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(permanent("choices[0].message.content: expected a string")),
    };

    let mut tool_calls = Vec::new();
    if let Some(wire_calls) = message.get("tool_calls").and_then(Value::as_array) {
        for call in wire_calls {
            let id = call
                .get("id")
                .and_then(Value::as_str)
                .ok_or_else(|| permanent("tool_calls[]: missing `id` string"))?;
            let function = call
                .get("function")
                .ok_or_else(|| permanent("tool_calls[]: missing `function`"))?;
            let name = function
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| permanent("tool_calls[].function: missing `name` string"))?;
            // The wire carries arguments as a JSON string; an empty string
            // degrades to an empty object (shared OpenAI-family codec).
            let arguments = context_frame::decode_wire_arguments(function.get("arguments"))?;
            tool_calls.push(ToolCallDraft {
                tool_name: name.to_string(),
                arguments,
                provider_call_id: Some(id.to_string()),
            });
        }
    }

    let stop_reason = match choice.get("finish_reason") {
        Some(Value::String(s)) => match s.as_str() {
            "stop" => ModelStopReason::EndTurn,
            "tool_calls" => ModelStopReason::ToolUse,
            "length" => ModelStopReason::MaxTokens,
            "content_filter" => ModelStopReason::Refusal,
            _ => ModelStopReason::EndTurn,
        },
        None | Some(Value::Null) => return Err(permanent("missing choices[0].finish_reason")),
        Some(_) => return Err(permanent("choices[0].finish_reason: expected a string")),
    };

    let reasoning = message
        .get("reasoning_content")
        .and_then(Value::as_str)
        .map(|text| ReasoningPayload {
            text: text.to_string(),
            signature: None,
        });

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

    Ok(ModelOutput {
        response: ModelResponse {
            text: TextPayload::new(text),
            tool_calls,
        },
        usage,
        stop_reason,
        reasoning,
    })
}

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

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

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

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

    #[test]
    fn source_vocabulary_full_branch_coverage() {
        let f = frame(vec![
            text(0, "be terse", Some("system")),
            text(1, "model said", None),
            text(2, "user said", Some("user")),
            text(3, "replayed", Some("assistant")),
            text(4, "injected", Some("inject:note")),
            text(5, "unknown tag", Some("provider:gpt-x")),
        ]);
        let v = render(&f);
        let msgs = v["messages"].as_array().unwrap();
        // system stays inline as a message; assistant(None) / user /
        // assistant("assistant") / user("inject:note" + unknown merged)
        assert_eq!(msgs.len(), 5);
        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": "injected\nunknown tag"})
        );
    }

    #[test]
    fn tool_round_trip_pairing_and_assistant_merge() {
        let f = frame(vec![
            text(0, "reading now", None),
            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; id falls back to the kernel call_id
        assert_eq!(
            msgs[0],
            json!({
                "role": "assistant",
                "content": "reading now",
                "tool_calls": [
                    {"id": "toolu_a", "type": "function",
                     "function": {"name": "read", "arguments": "{\"path\":\"a\"}"}},
                    {"id": "kc2", "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": "kc2", "content": "{\"error\":\"boom\"}"})
        );
    }

    #[test]
    fn assistant_tool_calls_only_omits_empty_content() {
        let f = frame(vec![call(0, "kc1", Some("toolu_a"), "read", json!({}))]);
        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_join_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", None),
            call(1, "kc1", Some("toolu_a"), "read", json!({})),
            text(2, "second", None),
        ]);
        let v = render(&f);
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0]["role"], "assistant");
        assert_eq!(msgs[0]["content"], json!("first\nsecond"));
        assert_eq!(msgs[0]["tool_calls"].as_array().unwrap().len(), 1);

        // no calls in between: still one message, text joined
        let f = frame(vec![text(0, "a", None), text(1, "b", None)]);
        let v = render(&f);
        assert_eq!(
            v["messages"],
            json!([{"role": "assistant", "content": "a\nb"}])
        );
    }

    #[test]
    fn unpaired_tool_result_falls_back_to_kernel_call_id() {
        let f = frame(vec![result(
            0,
            "orphan",
            ToolResultStatus::Succeeded,
            json!("x"),
        )]);
        let v = render(&f);
        assert_eq!(v["messages"][0]["tool_call_id"], json!("orphan"));
    }

    #[test]
    fn tools_generation_and_byte_determinism() {
        let surface = ToolSurface::from_definitions(vec![ToolDefinition {
            name: "read".into(),
            description: "read a file".into(),
            parameters: json!({"type": "object"}),
        }]);
        let f = frame(vec![text(0, "hi", Some("user"))]);

        let generation = GenerationOptions {
            temperature: Some(0.5),
            max_tokens: None,
            ..GenerationOptions::default()
        };
        let v = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &surface,
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .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 {
            temperature: Some(0.5),
            max_tokens: Some(100),
            ..GenerationOptions::default()
        };
        let v2 = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &surface,
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .unwrap();
        assert_eq!(v2["max_tokens"], json!(100));
        let again = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &surface,
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .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", Some("user"))]);
        let generation = GenerationOptions {
            output_schema: Some(json!({"type": "object"})),
            ..GenerationOptions::default()
        };
        let v = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &ToolSurface::empty(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .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(),
            &ToolSurface::empty(),
            &generation,
            &ModelRef::new("gpt-test"),
            CacheDirective::StablePrefix,
        )
        .unwrap();
        assert_eq!(v, cached);
    }

    #[test]
    fn empty_frame_is_invalid_request() {
        let e = render_openai_chat_messages(
            &frame(vec![]),
            &MediaSet::new(),
            &ToolSurface::empty(),
            &GenerationOptions::default(),
            &ModelRef::new("m"),
            CacheDirective::None,
        )
        .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::new("image/png", "AAAA"));
        m
    }

    #[test]
    fn image_parts_render_as_image_url_messages() {
        let f = frame(vec![parts(
            0,
            vec![
                text_part("caption"),
                media_part("image/png", "asset-1"),
                text_part("after"),
            ],
            Some("user"),
        )]);
        let v = render_openai_chat_messages(
            &f,
            &resolved("asset-1"),
            &ToolSurface::empty(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .unwrap();
        // part boundaries preserved: each text part is its own message,
        // the image rides an array-content user message with a data URL
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(msgs[0], json!({"role": "user", "content": "caption"}));
        assert_eq!(
            msgs[1],
            json!({"role": "user", "content": [
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}
            ]})
        );
        assert_eq!(msgs[2], json!({"role": "user", "content": "after"}));
    }

    #[test]
    fn unresolved_media_degrades_to_the_deterministic_placeholder() {
        let f = frame(vec![parts(
            0,
            vec![media_part("image/png", "missing-asset")],
            Some("user"),
        )]);
        let v = render_openai_chat_messages(
            &f,
            &MediaSet::new(),
            &ToolSurface::empty(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .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::new("image/png", "AAAA"));
        media.insert("asset-2", MediaPayload::new("image/jpeg", "BBBB"));
        let v = render_openai_chat_messages(
            &f,
            &media,
            &ToolSurface::empty(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .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 hoisted_placeholders_stay_in_payload_order() {
        let f = frame(vec![result_with_media(
            0,
            "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::new("image/png", "AAAA"));
        media.insert("doc", MediaPayload::new("application/pdf", "BBBB"));
        let v = render_openai_chat_messages(
            &f,
            &media,
            &ToolSurface::empty(),
            &GenerationOptions::default(),
            &ModelRef::new("gpt-test"),
            CacheDirective::None,
        )
        .unwrap();
        let msgs = v["messages"].as_array().unwrap();
        assert_eq!(
            msgs[1]["content"],
            json!([
                {"type": "text", "text": "[tool result media for call kc1]"},
                {"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 -----------------------------------------------------------

    #[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.0, "Let me check.");
        assert_eq!(out.response.tool_calls.len(), 1);
        let tc = &out.response.tool_calls[0];
        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));
        let reasoning = out.reasoning.unwrap();
        assert_eq!(reasoning.text, "hmm");
        assert_eq!(reasoning.signature, None);
        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_degrades_to_end_turn() {
        for (wire, expected) in [
            ("stop", ModelStopReason::EndTurn),
            ("tool_calls", ModelStopReason::ToolUse),
            ("length", ModelStopReason::MaxTokens),
            ("content_filter", ModelStopReason::Refusal),
            ("some_new_reason", ModelStopReason::EndTurn),
        ] {
            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}"
            );
        }
    }

    #[test]
    fn missing_choices_or_finish_reason_is_permanent_error() {
        let e = parse_openai_chat_response(&json!({"choices": []})).unwrap_err();
        assert!(matches!(e.kind(), ModelInvokeErrorKind::Permanent));
        let e = parse_openai_chat_response(&json!({"choices": [{"message": {}}]})).unwrap_err();
        assert!(matches!(e.kind(), ModelInvokeErrorKind::Permanent));
        assert!(e.message.contains("finish_reason"));
    }

    #[test]
    fn malformed_arguments_string_is_permanent_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::Permanent));
        assert!(e.message.contains("arguments"));
    }

    #[test]
    fn empty_arguments_string_degrades_to_empty_object() {
        let v = json!({
            "choices": [{
                "message": {"tool_calls": [
                    {"id": "c1", "function": {"name": "list", "arguments": ""}},
                ]},
                "finish_reason": "tool_calls",
            }],
        });
        let out = parse_openai_chat_response(&v).unwrap();
        assert_eq!(out.response.tool_calls[0].arguments, json!({}));
    }
}