1use std::fmt;
9use std::str::FromStr;
10
11use mime::Mime;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use uuid::Uuid;
14
15const SHA256_HEX_LENGTH: usize = 64;
16const MAX_ARTIFACT_INSTRUCTION_CHARS: usize = 16_384;
17
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum ContentValueError {
21 #[error("artifact id cannot be nil")]
23 NilArtifactId,
24 #[error("artifact digest must use sha256:<64 lowercase or uppercase hexadecimal characters>")]
26 InvalidSha256Digest,
27 #[error("invalid artifact media type '{value}'")]
29 InvalidMediaType { value: String },
30 #[error("artifact instruction cannot be empty")]
32 EmptyArtifactInstruction,
33 #[error("artifact instruction exceeds {max_chars} characters")]
35 ArtifactInstructionTooLong { max_chars: usize },
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct ArtifactId(Uuid);
41
42impl ArtifactId {
43 pub fn parse(value: Uuid) -> Result<Self, ContentValueError> {
45 if value.is_nil() {
46 return Err(ContentValueError::NilArtifactId);
47 }
48 Ok(Self(value))
49 }
50
51 pub const fn as_uuid(self) -> Uuid {
53 self.0
54 }
55}
56
57impl fmt::Display for ArtifactId {
58 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59 self.0.fmt(formatter)
60 }
61}
62
63impl TryFrom<Uuid> for ArtifactId {
64 type Error = ContentValueError;
65
66 fn try_from(value: Uuid) -> Result<Self, Self::Error> {
67 Self::parse(value)
68 }
69}
70
71impl From<ArtifactId> for Uuid {
72 fn from(value: ArtifactId) -> Self {
73 value.as_uuid()
74 }
75}
76
77impl Serialize for ArtifactId {
78 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
79 where
80 S: Serializer,
81 {
82 self.0.serialize(serializer)
83 }
84}
85
86impl<'de> Deserialize<'de> for ArtifactId {
87 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
88 where
89 D: Deserializer<'de>,
90 {
91 let value = Uuid::deserialize(deserializer)?;
92 Self::parse(value).map_err(serde::de::Error::custom)
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
98pub struct Sha256Digest(String);
99
100impl Sha256Digest {
101 pub fn parse(value: &str) -> Result<Self, ContentValueError> {
103 let Some(hex) = value.strip_prefix("sha256:") else {
104 return Err(ContentValueError::InvalidSha256Digest);
105 };
106 if hex.len() != SHA256_HEX_LENGTH || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
107 return Err(ContentValueError::InvalidSha256Digest);
108 }
109 Ok(Self(format!("sha256:{}", hex.to_ascii_lowercase())))
110 }
111
112 pub fn as_str(&self) -> &str {
114 &self.0
115 }
116
117 pub fn hex(&self) -> &str {
119 self.0
120 .strip_prefix("sha256:")
121 .expect("validated digest always has the sha256 prefix")
122 }
123}
124
125impl fmt::Display for Sha256Digest {
126 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127 formatter.write_str(self.as_str())
128 }
129}
130
131impl FromStr for Sha256Digest {
132 type Err = ContentValueError;
133
134 fn from_str(value: &str) -> Result<Self, Self::Err> {
135 Self::parse(value)
136 }
137}
138
139impl Serialize for Sha256Digest {
140 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
141 where
142 S: Serializer,
143 {
144 serializer.serialize_str(self.as_str())
145 }
146}
147
148impl<'de> Deserialize<'de> for Sha256Digest {
149 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
150 where
151 D: Deserializer<'de>,
152 {
153 let value = String::deserialize(deserializer)?;
154 Self::parse(&value).map_err(serde::de::Error::custom)
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Hash)]
160pub struct MediaType(Mime);
161
162impl MediaType {
163 pub fn parse(value: &str) -> Result<Self, ContentValueError> {
165 let trimmed = value.trim();
166 let parsed = trimmed
167 .parse::<Mime>()
168 .map_err(|_| ContentValueError::InvalidMediaType {
169 value: value.to_owned(),
170 })?;
171 if parsed.type_() == mime::STAR || parsed.subtype() == mime::STAR {
172 return Err(ContentValueError::InvalidMediaType {
173 value: value.to_owned(),
174 });
175 }
176 Ok(Self(parsed))
177 }
178
179 pub fn as_mime(&self) -> &Mime {
181 &self.0
182 }
183
184 pub fn essence_str(&self) -> &str {
186 self.0.essence_str()
187 }
188}
189
190impl fmt::Display for MediaType {
191 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192 self.0.fmt(formatter)
193 }
194}
195
196impl FromStr for MediaType {
197 type Err = ContentValueError;
198
199 fn from_str(value: &str) -> Result<Self, Self::Err> {
200 Self::parse(value)
201 }
202}
203
204impl Serialize for MediaType {
205 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
206 where
207 S: Serializer,
208 {
209 serializer.collect_str(self)
210 }
211}
212
213impl<'de> Deserialize<'de> for MediaType {
214 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
215 where
216 D: Deserializer<'de>,
217 {
218 let value = String::deserialize(deserializer)?;
219 Self::parse(&value).map_err(serde::de::Error::custom)
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
225#[serde(transparent)]
226pub struct ArtifactSize(u64);
227
228impl ArtifactSize {
229 pub const fn new(bytes: u64) -> Self {
231 Self(bytes)
232 }
233
234 pub const fn bytes(self) -> u64 {
236 self.0
237 }
238}
239
240impl From<u64> for ArtifactSize {
241 fn from(value: u64) -> Self {
242 Self::new(value)
243 }
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
248pub struct ArtifactRef {
249 id: ArtifactId,
250 digest: Sha256Digest,
251 media_type: MediaType,
252 size: ArtifactSize,
253}
254
255impl ArtifactRef {
256 pub const fn new(
258 id: ArtifactId,
259 digest: Sha256Digest,
260 media_type: MediaType,
261 size: ArtifactSize,
262 ) -> Self {
263 Self {
264 id,
265 digest,
266 media_type,
267 size,
268 }
269 }
270
271 pub const fn id(&self) -> ArtifactId {
273 self.id
274 }
275
276 pub fn digest(&self) -> &Sha256Digest {
278 &self.digest
279 }
280
281 pub fn media_type(&self) -> &MediaType {
283 &self.media_type
284 }
285
286 pub const fn size(&self) -> ArtifactSize {
288 self.size
289 }
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
297#[serde(rename_all = "snake_case")]
298pub enum ArtifactInputSource {
299 UserAttachment,
300 TaskInput,
301 ToolResult,
302 SessionContext,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Hash)]
307pub struct ArtifactInstruction(String);
308
309impl ArtifactInstruction {
310 pub fn parse(value: &str) -> Result<Self, ContentValueError> {
312 let trimmed = value.trim();
313 if trimmed.is_empty() {
314 return Err(ContentValueError::EmptyArtifactInstruction);
315 }
316 if trimmed.chars().count() > MAX_ARTIFACT_INSTRUCTION_CHARS {
317 return Err(ContentValueError::ArtifactInstructionTooLong {
318 max_chars: MAX_ARTIFACT_INSTRUCTION_CHARS,
319 });
320 }
321 Ok(Self(trimmed.to_owned()))
322 }
323
324 pub fn as_str(&self) -> &str {
326 &self.0
327 }
328}
329
330impl fmt::Display for ArtifactInstruction {
331 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
332 formatter.write_str(self.as_str())
333 }
334}
335
336impl FromStr for ArtifactInstruction {
337 type Err = ContentValueError;
338
339 fn from_str(value: &str) -> Result<Self, Self::Err> {
340 Self::parse(value)
341 }
342}
343
344impl Serialize for ArtifactInstruction {
345 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
346 where
347 S: Serializer,
348 {
349 serializer.serialize_str(self.as_str())
350 }
351}
352
353impl<'de> Deserialize<'de> for ArtifactInstruction {
354 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
355 where
356 D: Deserializer<'de>,
357 {
358 let value = String::deserialize(deserializer)?;
359 Self::parse(&value).map_err(serde::de::Error::custom)
360 }
361}
362
363#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
365pub struct ArtifactInput {
366 artifact: ArtifactRef,
367 source: ArtifactInputSource,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 instruction: Option<ArtifactInstruction>,
370}
371
372impl ArtifactInput {
373 pub const fn new(artifact: ArtifactRef, source: ArtifactInputSource) -> Self {
375 Self {
376 artifact,
377 source,
378 instruction: None,
379 }
380 }
381
382 pub fn with_instruction(mut self, instruction: ArtifactInstruction) -> Self {
384 self.instruction = Some(instruction);
385 self
386 }
387
388 pub fn artifact(&self) -> &ArtifactRef {
389 &self.artifact
390 }
391
392 pub const fn source(&self) -> ArtifactInputSource {
393 self.source
394 }
395
396 pub fn instruction(&self) -> Option<&ArtifactInstruction> {
397 self.instruction.as_ref()
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 fn valid_id() -> Uuid {
406 Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").expect("valid fixture")
407 }
408
409 #[test]
410 fn artifact_id_rejects_nil_at_construction_and_deserialization() {
411 assert_eq!(
412 ArtifactId::parse(Uuid::nil()),
413 Err(ContentValueError::NilArtifactId)
414 );
415 assert!(serde_json::from_str::<ArtifactId>(&format!("\"{}\"", Uuid::nil())).is_err());
416 }
417
418 #[test]
419 fn digest_normalizes_hex_and_rejects_invalid_values() {
420 let digest =
421 Sha256Digest::parse(&format!("sha256:{}", "A".repeat(64))).expect("valid digest");
422 assert_eq!(digest.hex(), "a".repeat(64));
423 assert_eq!(digest.as_str(), format!("sha256:{}", "a".repeat(64)));
424 assert!(Sha256Digest::parse(&"a".repeat(64)).is_err());
425 assert!(Sha256Digest::parse(&format!("sha256:{}", "z".repeat(64))).is_err());
426 }
427
428 #[test]
429 fn media_type_is_concrete_and_normalized() {
430 let media_type = MediaType::parse(" image/png ").expect("valid MIME type");
431 assert_eq!(media_type.essence_str(), "image/png");
432 assert!(MediaType::parse("image/*").is_err());
433 assert!(MediaType::parse("not a mime type").is_err());
434 }
435
436 #[test]
437 fn artifact_reference_round_trip_preserves_validated_values() {
438 let reference = ArtifactRef::new(
439 ArtifactId::parse(valid_id()).expect("valid artifact id"),
440 Sha256Digest::parse(&format!("sha256:{}", "b".repeat(64))).expect("valid digest"),
441 MediaType::parse("image/png").expect("valid MIME type"),
442 ArtifactSize::new(42),
443 );
444
445 let encoded = serde_json::to_value(&reference).expect("serialize reference");
446 let decoded: ArtifactRef =
447 serde_json::from_value(encoded.clone()).expect("deserialize reference");
448
449 assert_eq!(decoded, reference);
450 assert_eq!(encoded["id"], valid_id().to_string());
451 assert_eq!(encoded["size"], 42);
452 }
453
454 #[test]
455 fn artifact_input_preserves_provenance_without_authority_fields() {
456 let reference = ArtifactRef::new(
457 ArtifactId::parse(valid_id()).expect("valid artifact id"),
458 Sha256Digest::parse(&format!("sha256:{}", "c".repeat(64))).expect("valid digest"),
459 MediaType::parse("image/png").expect("valid MIME type"),
460 ArtifactSize::new(42),
461 );
462 let input = ArtifactInput::new(reference, ArtifactInputSource::ToolResult)
463 .with_instruction(ArtifactInstruction::parse(" inspect the error ").unwrap());
464
465 let encoded = serde_json::to_value(&input).expect("serialize artifact input");
466 let decoded: ArtifactInput = serde_json::from_value(encoded.clone()).unwrap();
467
468 assert_eq!(decoded, input);
469 assert_eq!(encoded["source"], "tool_result");
470 assert_eq!(encoded["instruction"], "inspect the error");
471 assert!(encoded.get("org_id").is_none());
472 assert!(encoded.get("path").is_none());
473 assert!(encoded.get("bytes").is_none());
474 }
475
476 #[test]
477 fn artifact_instruction_rejects_empty_and_unbounded_values() {
478 assert_eq!(
479 ArtifactInstruction::parse(" "),
480 Err(ContentValueError::EmptyArtifactInstruction)
481 );
482 assert!(
483 ArtifactInstruction::parse(&"x".repeat(MAX_ARTIFACT_INSTRUCTION_CHARS + 1)).is_err()
484 );
485 }
486}