causa_protocol/translation/media.rs
1//! Render-side media vocabulary: the resolved payload shape, coarse media
2//! kinds, and the resolution table the renderers consume. Facts never carry
3//! bytes or URLs — this is the only shape media takes on the render path, built
4//! by the gateway's injected resolver (causa-provider) right before translation.
5//!
6//! Media payloads are classified into [`MediaKind`]s. What renders to the wire
7//! depends on each protocol's rendering capabilities:
8//!
9//! - **Anthropic Messages**: emits images (`image/*`) and documents
10//! (`application/pdf`) in user messages and tool results, either as inline
11//! base64 bytes or as remote `http`/`https` URLs.
12//! - **OpenAI Chat Completions** and **Responses**: emit images only (`image/*`),
13//! either as inline base64 bytes or as remote `http`/`https` URLs; documents
14//! never render and degrade to text placeholders.
15//!
16//! Any unsupported combination, unclassified media type, unsupported or empty
17//! URL, empty payload, or unresolvable reference degrades to a deterministic
18//! text placeholder (`[media: {type} {reference}]`, or
19//! `[media: {type} {name} {reference}]` when named), decided once in the
20//! shared walk.
21
22use std::collections::HashMap;
23
24use causa_kernel::MediaRef;
25
26/// The coarse media kind of a payload or reference.
27///
28/// Exhaustive on purpose: each protocol's rendering capabilities and the
29/// gateway are total over it, so a new kind is a breaking change.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum MediaKind {
32 /// An image payload (e.g. `image/png`, `image/jpeg`).
33 Image,
34 /// A document payload (e.g. `application/pdf`).
35 Document,
36}
37
38impl MediaKind {
39 /// Classifies an IANA media type into a [`MediaKind`].
40 ///
41 /// Any parameter after `;` is dropped, whitespace is trimmed, and the
42 /// comparison is case-insensitive. Any type with an `image/` prefix and
43 /// a non-empty subtype maps to [`MediaKind::Image`], `application/pdf`
44 /// maps to [`MediaKind::Document`], and all other types return `None`.
45 pub fn of(media_type: &str) -> Option<Self> {
46 let base = media_type.split(';').next().unwrap_or("").trim();
47 if let Some(prefix) = base.get(..6)
48 && prefix.eq_ignore_ascii_case("image/")
49 && base.len() > 6
50 {
51 return Some(Self::Image);
52 }
53 if base.eq_ignore_ascii_case("application/pdf") {
54 return Some(Self::Document);
55 }
56 None
57 }
58}
59
60/// The source data of a resolved media payload: inline base64 bytes or a
61/// remote URL.
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum MediaSource {
65 /// Inline media bytes represented as a base64-encoded string.
66 Inline {
67 /// Base64-encoded media bytes.
68 data_base64: String,
69 },
70 /// A remote media location addressed by URL.
71 ///
72 /// When paired with a supported media type and protocol capability, a URL
73 /// with an `http` or `https` scheme and non-empty remainder renders
74 /// directly to the wire; any other URL, scheme, or unsupported media type
75 /// degrades to the deterministic text placeholder.
76 Url(String),
77}
78
79/// Resolved media payload for one [`MediaRef`], carrying either inline
80/// base64-encoded bytes or a remote URL. Render-side only: produced by the
81/// host's `MediaResolver`, consumed by the renderers, never persisted.
82#[derive(Debug, Clone, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct MediaPayload {
85 /// IANA media type of the payload (e.g. `image/png`).
86 pub media_type: String,
87 /// The source data of the media payload.
88 pub source: MediaSource,
89}
90
91impl MediaPayload {
92 /// Wraps a media type and a [`MediaSource`].
93 pub fn new(media_type: impl Into<String>, source: MediaSource) -> Self {
94 Self {
95 media_type: media_type.into(),
96 source,
97 }
98 }
99
100 /// Wraps a media type and inline base64-encoded bytes.
101 pub fn inline(media_type: impl Into<String>, data_base64: impl Into<String>) -> Self {
102 Self {
103 media_type: media_type.into(),
104 source: MediaSource::Inline {
105 data_base64: data_base64.into(),
106 },
107 }
108 }
109
110 /// Wraps a media type and a remote URL.
111 pub fn url(media_type: impl Into<String>, url: impl Into<String>) -> Self {
112 Self {
113 media_type: media_type.into(),
114 source: MediaSource::Url(url.into()),
115 }
116 }
117}
118
119/// Resolution table for one render pass: durable
120/// [`MediaRef::reference`](MediaRef) → payload. The gateway builds it
121/// from the frame's media references before calling a renderer; the
122/// same reference resolves identically in batch and stream rendering.
123/// A reference absent here renders as the deterministic placeholder.
124#[derive(Debug, Clone, Default)]
125pub struct MediaSet {
126 by_reference: HashMap<String, MediaPayload>,
127}
128
129impl MediaSet {
130 /// An empty table — every reference degrades to its placeholder.
131 pub fn new() -> Self {
132 Self::default()
133 }
134
135 /// Register the payload for a reference. Later inserts win.
136 pub fn insert(&mut self, reference: impl Into<String>, payload: MediaPayload) {
137 self.by_reference.insert(reference.into(), payload);
138 }
139
140 /// The payload registered for this reference's `reference` key, if
141 /// the resolver produced one.
142 pub fn get(&self, r: &MediaRef) -> Option<&MediaPayload> {
143 self.by_reference.get(&r.reference)
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn media_kind_classification() {
153 // Exact matches
154 assert_eq!(MediaKind::of("image/png"), Some(MediaKind::Image));
155 assert_eq!(MediaKind::of("image/jpeg"), Some(MediaKind::Image));
156 assert_eq!(MediaKind::of("application/pdf"), Some(MediaKind::Document));
157
158 // Case insensitivity
159 assert_eq!(MediaKind::of("IMAGE/PNG"), Some(MediaKind::Image));
160 assert_eq!(MediaKind::of("APPLICATION/PDF"), Some(MediaKind::Document));
161 assert_eq!(MediaKind::of("Application/Pdf"), Some(MediaKind::Document));
162
163 // Parameters after semicolon
164 assert_eq!(
165 MediaKind::of("application/pdf; x=y"),
166 Some(MediaKind::Document)
167 );
168 assert_eq!(
169 MediaKind::of("image/jpeg; charset=utf-8"),
170 Some(MediaKind::Image)
171 );
172 assert_eq!(
173 MediaKind::of("application/pdf;version=1.7"),
174 Some(MediaKind::Document)
175 );
176
177 // Trimming whitespace
178 assert_eq!(
179 MediaKind::of(" application/pdf "),
180 Some(MediaKind::Document)
181 );
182 assert_eq!(
183 MediaKind::of(" image/png ; foo=bar "),
184 Some(MediaKind::Image)
185 );
186
187 // Non-matches: distinct types or invalid prefixes
188 assert_eq!(MediaKind::of("application/pdfx"), None);
189 assert_eq!(MediaKind::of("application/zip"), None);
190 assert_eq!(MediaKind::of("text/plain"), None);
191 assert_eq!(MediaKind::of("image"), None);
192 assert_eq!(MediaKind::of("image/"), None);
193 assert_eq!(MediaKind::of(""), None);
194 }
195}