agent_stream_kit/
data.rs

1use std::{collections::BTreeMap, sync::Arc};
2
3#[cfg(feature = "image")]
4use photon_rs::PhotonImage;
5
6use serde::{
7    Deserialize, Deserializer, Serialize, Serializer,
8    ser::{SerializeMap, SerializeSeq},
9};
10
11use super::error::AgentError;
12
13const IMAGE_BASE64_PREFIX: &str = "data:image/png;base64,";
14
15#[derive(Debug, Clone, PartialEq, Serialize)]
16pub struct AgentData {
17    pub kind: String,
18    pub value: AgentValue,
19}
20
21impl AgentData {
22    pub fn unit() -> Self {
23        Self {
24            kind: "unit".to_string(),
25            value: AgentValue::unit(),
26        }
27    }
28
29    pub fn boolean(value: bool) -> Self {
30        AgentData {
31            kind: "boolean".to_string(),
32            value: AgentValue::boolean(value),
33        }
34    }
35
36    pub fn integer(value: i64) -> Self {
37        AgentData {
38            kind: "integer".to_string(),
39            value: AgentValue::integer(value),
40        }
41    }
42
43    pub fn number(value: f64) -> Self {
44        AgentData {
45            kind: "number".to_string(),
46            value: AgentValue::number(value),
47        }
48    }
49
50    pub fn string(value: impl Into<String>) -> Self {
51        AgentData {
52            kind: "string".to_string(),
53            value: AgentValue::string(value.into()),
54        }
55    }
56
57    #[cfg(feature = "image")]
58    pub fn image(value: PhotonImage) -> Self {
59        AgentData {
60            kind: "image".to_string(),
61            value: AgentValue::image(value),
62        }
63    }
64
65    pub fn object(value: AgentValueMap<String, AgentValue>) -> Self {
66        AgentData {
67            kind: "object".to_string(),
68            value: AgentValue::object(value),
69        }
70    }
71
72    pub fn object_with_kind(
73        kind: impl Into<String>,
74        value: AgentValueMap<String, AgentValue>,
75    ) -> Self {
76        AgentData {
77            kind: kind.into(),
78            value: AgentValue::object(value),
79        }
80    }
81
82    pub fn array(kind: impl Into<String>, value: Vec<AgentValue>) -> Self {
83        AgentData {
84            kind: kind.into(),
85            value: AgentValue::array(value),
86        }
87    }
88
89    pub fn from_value(value: AgentValue) -> Self {
90        let kind = value.kind();
91        AgentData { kind, value }
92    }
93
94    pub fn from_json_with_kind(
95        kind: impl Into<String>,
96        value: serde_json::Value,
97    ) -> Result<Self, AgentError> {
98        let kind: String = kind.into();
99        let value = AgentValue::from_kind_json(&kind, value)?;
100        Ok(Self { kind, value })
101    }
102
103    pub fn from_json(json_value: serde_json::Value) -> Result<Self, AgentError> {
104        let value = AgentValue::from_json(json_value)?;
105        Ok(AgentData {
106            kind: value.kind(),
107            value,
108        })
109    }
110
111    /// Create AgentData from any Serialize with automatic kind inference
112    pub fn from_serialize<T: Serialize>(value: &T) -> Result<Self, AgentError> {
113        let json_value = serde_json::to_value(value)
114            .map_err(|e| AgentError::InvalidValue(format!("Failed to serialize: {}", e)))?;
115        Self::from_json(json_value)
116    }
117
118    /// Create AgentData from any Serialize with custom kind
119    pub fn from_serialize_with_kind<T: Serialize>(
120        kind: impl Into<String>,
121        value: &T,
122    ) -> Result<Self, AgentError> {
123        let json_value = serde_json::to_value(value)
124            .map_err(|e| AgentError::InvalidValue(format!("Failed to serialize: {}", e)))?;
125        Self::from_json_with_kind(kind, json_value)
126    }
127
128    /// Convert AgentData to a Deserialize
129    pub fn to_deserialize<T: for<'de> Deserialize<'de>>(&self) -> Result<T, AgentError> {
130        let json_value = self.value.to_json();
131        serde_json::from_value(json_value)
132            .map_err(|e| AgentError::InvalidValue(format!("Failed to deserialize: {}", e)))
133    }
134
135    #[allow(unused)]
136    pub fn is_unit(&self) -> bool {
137        self.kind == "unit"
138    }
139
140    #[allow(unused)]
141    pub fn is_boolean(&self) -> bool {
142        self.kind == "boolean"
143    }
144
145    #[allow(unused)]
146    pub fn is_integer(&self) -> bool {
147        self.kind == "integer"
148    }
149
150    #[allow(unused)]
151    pub fn is_number(&self) -> bool {
152        self.kind == "number"
153    }
154
155    #[allow(unused)]
156    pub fn is_string(&self) -> bool {
157        self.kind == "string"
158    }
159
160    #[cfg(feature = "image")]
161    #[allow(unused)]
162    pub fn is_image(&self) -> bool {
163        self.kind == "image"
164    }
165
166    #[allow(unused)]
167    pub fn is_object(&self) -> bool {
168        if let AgentValue::Object(_) = &self.value {
169            true
170        } else {
171            false
172        }
173    }
174
175    #[allow(unused)]
176    pub fn is_array(&self) -> bool {
177        if let AgentValue::Array(_) = &self.value {
178            true
179        } else {
180            false
181        }
182    }
183
184    #[allow(unused)]
185    pub fn as_bool(&self) -> Option<bool> {
186        self.value.as_bool()
187    }
188
189    #[allow(unused)]
190    pub fn as_i64(&self) -> Option<i64> {
191        self.value.as_i64()
192    }
193
194    #[allow(unused)]
195    pub fn as_f64(&self) -> Option<f64> {
196        self.value.as_f64()
197    }
198
199    pub fn as_str(&self) -> Option<&str> {
200        self.value.as_str()
201    }
202
203    #[cfg(feature = "image")]
204    #[allow(unused)]
205    pub fn as_image(&self) -> Option<&PhotonImage> {
206        self.value.as_image()
207    }
208
209    pub fn as_object(&self) -> Option<&AgentValueMap<String, AgentValue>> {
210        self.value.as_object()
211    }
212
213    #[allow(unused)]
214    pub fn as_array(&self) -> Option<&Vec<AgentValue>> {
215        self.value.as_array()
216    }
217
218    #[allow(unused)]
219    pub fn get(&self, key: &str) -> Option<&AgentValue> {
220        self.value.get(key)
221    }
222
223    #[allow(unused)]
224    pub fn get_bool(&self, key: &str) -> Option<bool> {
225        self.value.get_bool(key)
226    }
227
228    #[allow(unused)]
229    pub fn get_i64(&self, key: &str) -> Option<i64> {
230        self.value.get_i64(key)
231    }
232
233    #[allow(unused)]
234    pub fn get_f64(&self, key: &str) -> Option<f64> {
235        self.value.get_f64(key)
236    }
237
238    #[allow(unused)]
239    pub fn get_str(&self, key: &str) -> Option<&str> {
240        self.value.get_str(key)
241    }
242
243    #[cfg(feature = "image")]
244    #[allow(unused)]
245    pub fn get_image(&self, key: &str) -> Option<&PhotonImage> {
246        self.value.get_image(key)
247    }
248
249    #[allow(unused)]
250    pub fn get_object(&self, key: &str) -> Option<&AgentValueMap<String, AgentValue>> {
251        self.value.get_object(key)
252    }
253
254    #[allow(unused)]
255    pub fn get_array(&self, key: &str) -> Option<&Vec<AgentValue>> {
256        self.value.get_array(key)
257    }
258}
259
260impl<'de> Deserialize<'de> for AgentData {
261    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
262    where
263        D: Deserializer<'de>,
264    {
265        let json_value = serde_json::Value::deserialize(deserializer)?;
266        let serde_json::Value::Object(obj) = json_value else {
267            return Err(serde::de::Error::custom("not a JSON object"));
268        };
269        let Some(kind) = obj.get("kind").and_then(|k| k.as_str()) else {
270            return Err(serde::de::Error::custom("missing kind"));
271        };
272        let Some(value) = obj.get("value") else {
273            return Err(serde::de::Error::custom("Missing value"));
274        };
275        AgentData::from_json_with_kind(kind, value.to_owned()).map_err(|e| {
276            serde::de::Error::custom(format!("Failed to deserialize AgentData: {}", e))
277        })
278    }
279}
280
281#[derive(Debug, Clone)]
282pub enum AgentValue {
283    // Primitive types stored directly
284    Unit,
285    Boolean(bool),
286    Integer(i64),
287    Number(f64),
288
289    // Larger data structures use reference counting
290    String(Arc<String>),
291
292    #[cfg(feature = "image")]
293    Image(Arc<PhotonImage>),
294
295    // Recursive data structures
296    Array(Arc<Vec<AgentValue>>),
297    Object(Arc<AgentValueMap<String, AgentValue>>),
298}
299
300pub type AgentValueMap<S, T> = BTreeMap<S, T>;
301
302impl AgentValue {
303    pub fn unit() -> Self {
304        AgentValue::Unit
305    }
306
307    pub fn boolean(value: bool) -> Self {
308        AgentValue::Boolean(value)
309    }
310
311    pub fn integer(value: i64) -> Self {
312        AgentValue::Integer(value)
313    }
314
315    pub fn number(value: f64) -> Self {
316        AgentValue::Number(value)
317    }
318
319    pub fn string(value: impl Into<String>) -> Self {
320        AgentValue::String(Arc::new(value.into()))
321    }
322
323    #[cfg(feature = "image")]
324    pub fn image(value: PhotonImage) -> Self {
325        AgentValue::Image(Arc::new(value))
326    }
327
328    #[cfg(feature = "image")]
329    pub fn image_arc(value: Arc<PhotonImage>) -> Self {
330        AgentValue::Image(value)
331    }
332
333    pub fn object(value: AgentValueMap<String, AgentValue>) -> Self {
334        AgentValue::Object(Arc::new(value))
335    }
336
337    pub fn array(value: Vec<AgentValue>) -> Self {
338        AgentValue::Array(Arc::new(value))
339    }
340
341    pub fn boolean_default() -> Self {
342        AgentValue::Boolean(false)
343    }
344
345    pub fn integer_default() -> Self {
346        AgentValue::Integer(0)
347    }
348
349    pub fn number_default() -> Self {
350        AgentValue::Number(0.0)
351    }
352
353    pub fn string_default() -> Self {
354        AgentValue::String(Arc::new(String::new()))
355    }
356
357    #[cfg(feature = "image")]
358    pub fn image_default() -> Self {
359        AgentValue::Image(Arc::new(PhotonImage::new(vec![0u8, 0u8, 0u8, 0u8], 1, 1)))
360    }
361
362    pub fn array_default() -> Self {
363        AgentValue::Array(Arc::new(Vec::new()))
364    }
365
366    pub fn object_default() -> Self {
367        AgentValue::Object(Arc::new(AgentValueMap::new()))
368    }
369
370    pub fn from_json(value: serde_json::Value) -> Result<Self, AgentError> {
371        match value {
372            serde_json::Value::Null => Ok(AgentValue::Unit),
373            serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
374            serde_json::Value::Number(n) => {
375                if let Some(i) = n.as_i64() {
376                    Ok(AgentValue::Integer(i))
377                } else if let Some(f) = n.as_f64() {
378                    Ok(AgentValue::Number(f))
379                } else {
380                    // This case should not happen, but handle it gracefully
381                    Ok(AgentValue::Integer(0))
382                }
383            }
384            serde_json::Value::String(s) => {
385                #[cfg(feature = "image")]
386                if s.starts_with(IMAGE_BASE64_PREFIX) {
387                    let img =
388                        PhotonImage::new_from_base64(&s.trim_start_matches(IMAGE_BASE64_PREFIX));
389                    Ok(AgentValue::Image(Arc::new(img)))
390                } else {
391                    Ok(AgentValue::String(Arc::new(s)))
392                }
393                #[cfg(not(feature = "image"))]
394                Ok(AgentValue::String(Arc::new(s)))
395            }
396            serde_json::Value::Array(arr) => {
397                let mut agent_arr = Vec::new();
398                for v in arr {
399                    agent_arr.push(AgentValue::from_json(v)?);
400                }
401                Ok(AgentValue::array(agent_arr))
402            }
403            serde_json::Value::Object(obj) => {
404                let mut map = AgentValueMap::new();
405                for (k, v) in obj {
406                    map.insert(k, AgentValue::from_json(v)?);
407                }
408                Ok(AgentValue::object(map))
409            }
410        }
411    }
412
413    pub fn from_kind_json(kind: &str, value: serde_json::Value) -> Result<Self, AgentError> {
414        match kind {
415            "unit" => {
416                if let serde_json::Value::Array(a) = value {
417                    Ok(AgentValue::Array(Arc::new(
418                        a.into_iter().map(|_| AgentValue::Unit).collect(),
419                    )))
420                } else {
421                    Ok(AgentValue::Unit)
422                }
423            }
424            "boolean" => match value {
425                serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
426                serde_json::Value::Array(a) => {
427                    let mut agent_arr = Vec::new();
428                    for v in a {
429                        if let serde_json::Value::Bool(b) = v {
430                            agent_arr.push(AgentValue::Boolean(b));
431                        } else {
432                            return Err(AgentError::InvalidArrayValue("boolean".into()));
433                        }
434                    }
435                    Ok(AgentValue::Array(Arc::new(agent_arr)))
436                }
437                _ => Err(AgentError::InvalidValue("boolean".into())),
438            },
439            "integer" => match value {
440                serde_json::Value::Number(n) => {
441                    if let Some(i) = n.as_i64() {
442                        Ok(AgentValue::Integer(i))
443                    } else if let Some(f) = n.as_f64() {
444                        Ok(AgentValue::Integer(f as i64))
445                    } else {
446                        Err(AgentError::InvalidValue("integer".into()))
447                    }
448                }
449                serde_json::Value::Array(a) => {
450                    let mut agent_arr = Vec::new();
451                    for n in a {
452                        if let Some(i) = n.as_i64() {
453                            agent_arr.push(AgentValue::Integer(i));
454                        } else if let Some(f) = n.as_f64() {
455                            agent_arr.push(AgentValue::Integer(f as i64));
456                        } else {
457                            return Err(AgentError::InvalidArrayValue("integer".into()));
458                        }
459                    }
460                    Ok(AgentValue::Array(Arc::new(agent_arr)))
461                }
462                _ => Err(AgentError::InvalidValue("integer".into())),
463            },
464            "number" => match value {
465                serde_json::Value::Number(n) => {
466                    if let Some(f) = n.as_f64() {
467                        Ok(AgentValue::Number(f))
468                    } else if let Some(i) = n.as_i64() {
469                        Ok(AgentValue::Number(i as f64))
470                    } else {
471                        Err(AgentError::InvalidValue("number".into()))
472                    }
473                }
474                serde_json::Value::Array(a) => {
475                    let mut agent_arr = Vec::new();
476                    for n in a {
477                        if let Some(f) = n.as_f64() {
478                            agent_arr.push(AgentValue::Number(f));
479                        } else if let Some(i) = n.as_i64() {
480                            agent_arr.push(AgentValue::Number(i as f64));
481                        } else {
482                            return Err(AgentError::InvalidArrayValue("number".into()));
483                        }
484                    }
485                    Ok(AgentValue::Array(Arc::new(agent_arr)))
486                }
487                _ => Err(AgentError::InvalidValue("number".into())),
488            },
489            "string" => match value {
490                serde_json::Value::String(s) => Ok(AgentValue::string(s)),
491                serde_json::Value::Array(a) => {
492                    let mut agent_arr = Vec::new();
493                    for v in a {
494                        if let serde_json::Value::String(s) = v {
495                            agent_arr.push(AgentValue::string(s));
496                        } else {
497                            return Err(AgentError::InvalidArrayValue("string".into()));
498                        }
499                    }
500                    Ok(AgentValue::Array(Arc::new(agent_arr)))
501                }
502                _ => Err(AgentError::InvalidValue("string".into())),
503            },
504            #[cfg(feature = "image")]
505            "image" => match value {
506                serde_json::Value::String(s) => Ok(AgentValue::Image(Arc::new(
507                    PhotonImage::new_from_base64(&s.trim_start_matches(IMAGE_BASE64_PREFIX)),
508                ))),
509                serde_json::Value::Array(a) => {
510                    let mut agent_arr = Vec::new();
511                    for v in a {
512                        if let serde_json::Value::String(s) = v {
513                            agent_arr.push(AgentValue::image(PhotonImage::new_from_base64(
514                                &s.trim_start_matches(IMAGE_BASE64_PREFIX),
515                            )));
516                        } else {
517                            return Err(AgentError::InvalidArrayValue("image".into()));
518                        }
519                    }
520                    Ok(AgentValue::Array(Arc::new(agent_arr)))
521                }
522                _ => Err(AgentError::InvalidValue("image".into())),
523            },
524            _ => match value {
525                serde_json::Value::Null => Ok(AgentValue::Unit),
526                serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
527                serde_json::Value::Number(n) => {
528                    if let Some(i) = n.as_i64() {
529                        Ok(AgentValue::Integer(i))
530                    } else if let Some(f) = n.as_f64() {
531                        Ok(AgentValue::Number(f))
532                    } else {
533                        Err(AgentError::InvalidValue("number".into()))
534                    }
535                }
536                serde_json::Value::String(s) => Ok(AgentValue::string(s)),
537                serde_json::Value::Array(a) => {
538                    let mut agent_arr = Vec::new();
539                    for v in a {
540                        let agent_v = AgentValue::from_kind_json(kind, v)?;
541                        agent_arr.push(agent_v);
542                    }
543                    Ok(AgentValue::Array(Arc::new(agent_arr)))
544                }
545                serde_json::Value::Object(obj) => {
546                    let mut map = AgentValueMap::new();
547                    for (k, v) in obj {
548                        map.insert(k.clone(), AgentValue::from_json(v)?);
549                    }
550                    Ok(AgentValue::object(map))
551                }
552            },
553        }
554    }
555
556    pub fn to_json(&self) -> serde_json::Value {
557        match self {
558            AgentValue::Unit => serde_json::Value::Null,
559            AgentValue::Boolean(b) => (*b).into(),
560            AgentValue::Integer(i) => (*i).into(),
561            AgentValue::Number(n) => (*n).into(),
562            AgentValue::String(s) => s.as_str().into(),
563            #[cfg(feature = "image")]
564            AgentValue::Image(img) => img.get_base64().into(),
565            AgentValue::Object(o) => {
566                let mut map = serde_json::Map::new();
567                for (k, v) in o.iter() {
568                    map.insert(k.clone(), v.to_json());
569                }
570                serde_json::Value::Object(map)
571            }
572            AgentValue::Array(a) => {
573                let arr: Vec<serde_json::Value> = a.iter().map(|v| v.to_json()).collect();
574                serde_json::Value::Array(arr)
575            }
576        }
577    }
578
579    /// Create AgentValue from Serialize
580    pub fn from_serialize<T: Serialize>(value: &T) -> Result<Self, AgentError> {
581        let json_value = serde_json::to_value(value)
582            .map_err(|e| AgentError::InvalidValue(format!("Failed to serialize: {}", e)))?;
583        Self::from_json(json_value)
584    }
585
586    /// Convert AgentValue to a Deserialize
587    pub fn to_deserialize<T: for<'de> Deserialize<'de>>(&self) -> Result<T, AgentError> {
588        let json_value = self.to_json();
589        serde_json::from_value(json_value)
590            .map_err(|e| AgentError::InvalidValue(format!("Failed to deserialize: {}", e)))
591    }
592
593    #[allow(unused)]
594    pub fn is_unit(&self) -> bool {
595        matches!(self, AgentValue::Unit)
596    }
597
598    #[allow(unused)]
599    pub fn is_boolean(&self) -> bool {
600        matches!(self, AgentValue::Boolean(_))
601    }
602
603    #[allow(unused)]
604    pub fn is_integer(&self) -> bool {
605        matches!(self, AgentValue::Integer(_))
606    }
607
608    #[allow(unused)]
609    pub fn is_number(&self) -> bool {
610        matches!(self, AgentValue::Number(_))
611    }
612
613    #[allow(unused)]
614    pub fn is_string(&self) -> bool {
615        matches!(self, AgentValue::String(_))
616    }
617
618    #[cfg(feature = "image")]
619    #[allow(unused)]
620    pub fn is_image(&self) -> bool {
621        matches!(self, AgentValue::Image(_))
622    }
623
624    #[allow(unused)]
625    pub fn is_array(&self) -> bool {
626        matches!(self, AgentValue::Array(_))
627    }
628
629    #[allow(unused)]
630    pub fn is_object(&self) -> bool {
631        matches!(self, AgentValue::Object(_))
632    }
633
634    pub fn as_bool(&self) -> Option<bool> {
635        match self {
636            AgentValue::Boolean(b) => Some(*b),
637            _ => None,
638        }
639    }
640
641    pub fn as_i64(&self) -> Option<i64> {
642        match self {
643            AgentValue::Integer(i) => Some(*i),
644            AgentValue::Number(n) => Some(*n as i64),
645            _ => None,
646        }
647    }
648
649    pub fn as_f64(&self) -> Option<f64> {
650        match self {
651            AgentValue::Integer(i) => Some(*i as f64),
652            AgentValue::Number(n) => Some(*n),
653            _ => None,
654        }
655    }
656
657    pub fn as_str(&self) -> Option<&str> {
658        match self {
659            AgentValue::String(s) => Some(s),
660            _ => None,
661        }
662    }
663
664    #[cfg(feature = "image")]
665    pub fn as_image(&self) -> Option<&PhotonImage> {
666        match self {
667            AgentValue::Image(img) => Some(img),
668            _ => None,
669        }
670    }
671
672    pub fn as_object(&self) -> Option<&AgentValueMap<String, AgentValue>> {
673        match self {
674            AgentValue::Object(o) => Some(o),
675            _ => None,
676        }
677    }
678
679    pub fn as_array(&self) -> Option<&Vec<AgentValue>> {
680        match self {
681            AgentValue::Array(a) => Some(a),
682            _ => None,
683        }
684    }
685
686    #[allow(unused)]
687    pub fn get(&self, key: &str) -> Option<&AgentValue> {
688        self.as_object().and_then(|o| o.get(key))
689    }
690
691    #[allow(unused)]
692    pub fn get_bool(&self, key: &str) -> Option<bool> {
693        self.get(key).and_then(|v| v.as_bool())
694    }
695
696    #[allow(unused)]
697    pub fn get_i64(&self, key: &str) -> Option<i64> {
698        self.get(key).and_then(|v| v.as_i64())
699    }
700
701    #[allow(unused)]
702    pub fn get_f64(&self, key: &str) -> Option<f64> {
703        self.get(key).and_then(|v| v.as_f64())
704    }
705
706    #[allow(unused)]
707    pub fn get_str(&self, key: &str) -> Option<&str> {
708        self.get(key).and_then(|v| v.as_str())
709    }
710
711    #[cfg(feature = "image")]
712    #[allow(unused)]
713    pub fn get_image(&self, key: &str) -> Option<&PhotonImage> {
714        self.get(key).and_then(|v| v.as_image())
715    }
716
717    #[allow(unused)]
718    pub fn get_object(&self, key: &str) -> Option<&AgentValueMap<String, AgentValue>> {
719        self.get(key).and_then(|v| v.as_object())
720    }
721
722    #[allow(unused)]
723    pub fn get_array(&self, key: &str) -> Option<&Vec<AgentValue>> {
724        self.get(key).and_then(|v| v.as_array())
725    }
726
727    pub fn kind(&self) -> String {
728        match self {
729            AgentValue::Unit => "unit".to_string(),
730            AgentValue::Boolean(_) => "boolean".to_string(),
731            AgentValue::Integer(_) => "integer".to_string(),
732            AgentValue::Number(_) => "number".to_string(),
733            AgentValue::String(_) => "string".to_string(),
734            #[cfg(feature = "image")]
735            AgentValue::Image(_) => "image".to_string(),
736            AgentValue::Object(_) => "object".to_string(),
737            AgentValue::Array(arr) => {
738                if arr.is_empty() {
739                    "array".to_string()
740                } else {
741                    arr[0].kind()
742                }
743            }
744        }
745    }
746}
747
748impl Default for AgentValue {
749    fn default() -> Self {
750        AgentValue::Unit
751    }
752}
753
754impl PartialEq for AgentValue {
755    fn eq(&self, other: &Self) -> bool {
756        match (self, other) {
757            (AgentValue::Unit, AgentValue::Unit) => true,
758            (AgentValue::Boolean(b1), AgentValue::Boolean(b2)) => b1 == b2,
759            (AgentValue::Integer(i1), AgentValue::Integer(i2)) => i1 == i2,
760            (AgentValue::Number(n1), AgentValue::Number(n2)) => n1 == n2,
761            (AgentValue::String(s1), AgentValue::String(s2)) => s1 == s2,
762            #[cfg(feature = "image")]
763            (AgentValue::Image(i1), AgentValue::Image(i2)) => {
764                i1.get_width() == i2.get_width()
765                    && i1.get_height() == i2.get_height()
766                    && i1.get_raw_pixels() == i2.get_raw_pixels()
767            }
768            (AgentValue::Object(o1), AgentValue::Object(o2)) => o1 == o2,
769            (AgentValue::Array(a1), AgentValue::Array(a2)) => a1 == a2,
770            _ => false,
771        }
772    }
773}
774
775impl Serialize for AgentValue {
776    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
777    where
778        S: Serializer,
779    {
780        match self {
781            AgentValue::Unit => serializer.serialize_none(),
782            AgentValue::Boolean(b) => serializer.serialize_bool(*b),
783            AgentValue::Integer(i) => serializer.serialize_i64(*i),
784            AgentValue::Number(n) => serializer.serialize_f64(*n),
785            AgentValue::String(s) => serializer.serialize_str(s),
786            #[cfg(feature = "image")]
787            AgentValue::Image(img) => serializer.serialize_str(&img.get_base64()),
788            AgentValue::Object(o) => {
789                let mut map = serializer.serialize_map(Some(o.len()))?;
790                for (k, v) in o.iter() {
791                    map.serialize_entry(k, v)?;
792                }
793                map.end()
794            }
795            AgentValue::Array(a) => {
796                let mut seq = serializer.serialize_seq(Some(a.len()))?;
797                for e in a.iter() {
798                    seq.serialize_element(e)?;
799                }
800                seq.end()
801            }
802        }
803    }
804}
805
806impl<'de> Deserialize<'de> for AgentValue {
807    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
808    where
809        D: Deserializer<'de>,
810    {
811        let value = serde_json::Value::deserialize(deserializer)?;
812        AgentValue::from_json(value).map_err(|e| {
813            serde::de::Error::custom(format!("Failed to deserialize AgentValue: {}", e))
814        })
815    }
816}
817
818impl From<()> for AgentValue {
819    fn from(_: ()) -> Self {
820        AgentValue::unit()
821    }
822}
823
824impl From<bool> for AgentValue {
825    fn from(value: bool) -> Self {
826        AgentValue::boolean(value)
827    }
828}
829
830impl From<i32> for AgentValue {
831    fn from(value: i32) -> Self {
832        AgentValue::integer(value as i64)
833    }
834}
835
836impl From<i64> for AgentValue {
837    fn from(value: i64) -> Self {
838        AgentValue::integer(value)
839    }
840}
841
842impl From<f64> for AgentValue {
843    fn from(value: f64) -> Self {
844        AgentValue::number(value)
845    }
846}
847
848impl From<String> for AgentValue {
849    fn from(value: String) -> Self {
850        AgentValue::string(value)
851    }
852}
853
854impl From<&str> for AgentValue {
855    fn from(value: &str) -> Self {
856        AgentValue::string(value)
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    use super::*;
863    use serde_json::json;
864
865    #[test]
866    fn test_agent_data_new_constructors() {
867        // Test all the constructor methods
868        let unit_data = AgentData::unit();
869        assert_eq!(unit_data.kind, "unit");
870        assert_eq!(unit_data.value, AgentValue::Unit);
871
872        let bool_data = AgentData::boolean(true);
873        assert_eq!(bool_data.kind, "boolean");
874        assert_eq!(bool_data.value, AgentValue::Boolean(true));
875
876        let int_data = AgentData::integer(42);
877        assert_eq!(int_data.kind, "integer");
878        assert_eq!(int_data.value, AgentValue::Integer(42));
879
880        let num_data = AgentData::number(3.14);
881        assert_eq!(num_data.kind, "number");
882        assert!(matches!(num_data.value, AgentValue::Number(_)));
883        if let AgentValue::Number(num) = num_data.value {
884            assert!((num - 3.14).abs() < f64::EPSILON);
885        }
886
887        let str_data = AgentData::string("hello".to_string());
888        assert_eq!(str_data.kind, "string");
889        assert!(matches!(str_data.value, AgentValue::String(_)));
890        assert_eq!(str_data.as_str().unwrap(), "hello");
891
892        let text_data = AgentData::string("multiline\ntext\n\n".to_string());
893        assert_eq!(text_data.kind, "string");
894        assert!(matches!(text_data.value, AgentValue::String(_)));
895        assert_eq!(text_data.as_str().unwrap(), "multiline\ntext\n\n");
896
897        #[cfg(feature = "image")]
898        {
899            let img_data = AgentData::image(PhotonImage::new(vec![0u8, 0u8, 0u8, 0u8], 1, 1));
900            assert_eq!(img_data.kind, "image");
901            assert!(matches!(img_data.value, AgentValue::Image(_)));
902            assert_eq!(img_data.as_image().unwrap().get_width(), 1);
903            assert_eq!(img_data.as_image().unwrap().get_height(), 1);
904            assert_eq!(
905                img_data.as_image().unwrap().get_raw_pixels(),
906                vec![0u8, 0u8, 0u8, 0u8]
907            );
908        }
909
910        let obj_val = [
911            ("key1".to_string(), AgentValue::string("string1")),
912            ("key2".to_string(), AgentValue::integer(2)),
913        ];
914        let obj_data = AgentData::object(obj_val.clone().into());
915        assert_eq!(obj_data.kind, "object");
916        assert!(matches!(obj_data.value, AgentValue::Object(_)));
917        assert_eq!(obj_data.as_object().unwrap(), &obj_val.into());
918    }
919
920    #[test]
921    fn test_agent_data_from_kind_value() {
922        // Test creating AgentData from kind and JSON value
923        let unit_data = AgentData::from_json_with_kind("unit", json!(null)).unwrap();
924        assert_eq!(unit_data.kind, "unit");
925        assert_eq!(unit_data.value, AgentValue::Unit);
926
927        let bool_data = AgentData::from_json_with_kind("boolean", json!(true)).unwrap();
928        assert_eq!(bool_data.kind, "boolean");
929        assert_eq!(bool_data.value, AgentValue::Boolean(true));
930
931        let int_data = AgentData::from_json_with_kind("integer", json!(42)).unwrap();
932        assert_eq!(int_data.kind, "integer");
933        assert_eq!(int_data.value, AgentValue::Integer(42));
934
935        let int_data = AgentData::from_json_with_kind("integer", json!(3.14)).unwrap();
936        assert_eq!(int_data.kind, "integer");
937        assert_eq!(int_data.value, AgentValue::Integer(3));
938
939        let num_data = AgentData::from_json_with_kind("number", json!(3.14)).unwrap();
940        assert_eq!(num_data.kind, "number");
941        assert_eq!(num_data.value, AgentValue::number(3.14));
942
943        let num_data = AgentData::from_json_with_kind("number", json!(3)).unwrap();
944        assert_eq!(num_data.kind, "number");
945        assert_eq!(num_data.value, AgentValue::number(3.0));
946
947        let str_data = AgentData::from_json_with_kind("string", json!("hello")).unwrap();
948        assert_eq!(str_data.kind, "string");
949        assert_eq!(str_data.value, AgentValue::string("hello"));
950
951        let str_data = AgentData::from_json_with_kind("string", json!("hello\nworld\n\n")).unwrap();
952        assert_eq!(str_data.kind, "string");
953        assert_eq!(str_data.value, AgentValue::string("hello\nworld\n\n"));
954
955        let text_data =
956            AgentData::from_json_with_kind("string", json!("hello\nworld\n\n")).unwrap();
957        assert_eq!(text_data.kind, "string");
958        assert_eq!(text_data.value, AgentValue::string("hello\nworld\n\n"));
959
960        #[cfg(feature = "image")]
961        {
962            let img_data = AgentData::from_json_with_kind("image",
963        json!("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==")).unwrap();
964            assert_eq!(img_data.kind, "image");
965            assert!(matches!(img_data.value, AgentValue::Image(_)));
966            assert_eq!(img_data.as_image().unwrap().get_width(), 1);
967            assert_eq!(img_data.as_image().unwrap().get_height(), 1);
968            assert_eq!(
969                img_data.as_image().unwrap().get_raw_pixels(),
970                vec![0u8, 0u8, 0u8, 0u8]
971            );
972        }
973
974        let obj_data =
975            AgentData::from_json_with_kind("object", json!({"key1": "string1", "key2": 2}))
976                .unwrap();
977        assert_eq!(obj_data.kind, "object");
978        assert_eq!(
979            obj_data.value,
980            AgentValue::object(
981                [
982                    ("key1".to_string(), AgentValue::string("string1")),
983                    ("key2".to_string(), AgentValue::integer(2)),
984                ]
985                .into()
986            )
987        );
988
989        // Test custom object kind
990        let obj_data = AgentData::from_json_with_kind(
991            "custom_type".to_string(),
992            json!({"foo": "hi", "bar": 3}),
993        )
994        .unwrap();
995        assert_eq!(obj_data.kind, "custom_type");
996        assert_eq!(
997            obj_data.value,
998            AgentValue::object(
999                [
1000                    ("foo".to_string(), AgentValue::string("hi")),
1001                    ("bar".to_string(), AgentValue::integer(3)),
1002                ]
1003                .into()
1004            )
1005        );
1006
1007        // Test array values
1008        let array_data = AgentData::from_json_with_kind("unit", json!([null, null])).unwrap();
1009        assert_eq!(array_data.kind, "unit");
1010        assert_eq!(
1011            array_data.value,
1012            AgentValue::array(vec![AgentValue::unit(), AgentValue::unit(),])
1013        );
1014
1015        let array_data = AgentData::from_json_with_kind("boolean", json!([true, false])).unwrap();
1016        assert_eq!(array_data.kind, "boolean");
1017        assert_eq!(
1018            array_data.value,
1019            AgentValue::array(vec![AgentValue::boolean(true), AgentValue::boolean(false),])
1020        );
1021
1022        let array_data = AgentData::from_json_with_kind("integer", json!([1, 2.1, 3.0])).unwrap();
1023        assert_eq!(array_data.kind, "integer");
1024        assert_eq!(
1025            array_data.value,
1026            AgentValue::array(vec![
1027                AgentValue::integer(1),
1028                AgentValue::integer(2),
1029                AgentValue::integer(3),
1030            ])
1031        );
1032
1033        let array_data = AgentData::from_json_with_kind("number", json!([1.0, 2.1, 3])).unwrap();
1034        assert_eq!(array_data.kind, "number");
1035        assert_eq!(
1036            array_data.value,
1037            AgentValue::array(vec![
1038                AgentValue::number(1.0),
1039                AgentValue::number(2.1),
1040                AgentValue::number(3.0),
1041            ])
1042        );
1043
1044        let array_data =
1045            AgentData::from_json_with_kind("string", json!(["test", "hello\nworld\n", ""]))
1046                .unwrap();
1047        assert_eq!(array_data.kind, "string");
1048        assert_eq!(
1049            array_data.value,
1050            AgentValue::array(vec![
1051                AgentValue::string("test"),
1052                AgentValue::string("hello\nworld\n"),
1053                AgentValue::string(""),
1054            ])
1055        );
1056
1057        let array_data =
1058            AgentData::from_json_with_kind("string", json!(["test", "hello\nworld\n", ""]))
1059                .unwrap();
1060        assert_eq!(array_data.kind, "string");
1061        assert_eq!(
1062            array_data.value,
1063            AgentValue::array(vec![
1064                AgentValue::string("test"),
1065                AgentValue::string("hello\nworld\n"),
1066                AgentValue::string(""),
1067            ])
1068        );
1069
1070        let array_data = AgentData::from_json_with_kind(
1071            "object",
1072            json!([{"key1":"test","key2":1}, {"key1":"test2","key2":"hi"}, {}]),
1073        )
1074        .unwrap();
1075        assert_eq!(array_data.kind, "object");
1076        assert_eq!(
1077            array_data.value,
1078            AgentValue::array(vec![
1079                AgentValue::object(
1080                    [
1081                        ("key1".to_string(), AgentValue::string("test")),
1082                        ("key2".to_string(), AgentValue::integer(1)),
1083                    ]
1084                    .into()
1085                ),
1086                AgentValue::object(
1087                    [
1088                        ("key1".to_string(), AgentValue::string("test2")),
1089                        ("key2".to_string(), AgentValue::string("hi")),
1090                    ]
1091                    .into()
1092                ),
1093                AgentValue::object(AgentValueMap::default()),
1094            ])
1095        );
1096
1097        let array_data = AgentData::from_json_with_kind(
1098            "custom",
1099            json!([{"key1":"test","key2":1}, {"key1":"test2","key2":"hi"}, {}]),
1100        )
1101        .unwrap();
1102        assert_eq!(array_data.kind, "custom");
1103        assert_eq!(
1104            array_data.value,
1105            AgentValue::array(vec![
1106                AgentValue::object(
1107                    [
1108                        ("key1".to_string(), AgentValue::string("test")),
1109                        ("key2".to_string(), AgentValue::integer(1)),
1110                    ]
1111                    .into()
1112                ),
1113                AgentValue::object(
1114                    [
1115                        ("key1".to_string(), AgentValue::string("test2")),
1116                        ("key2".to_string(), AgentValue::string("hi")),
1117                    ]
1118                    .into()
1119                ),
1120                AgentValue::object(AgentValueMap::default()),
1121            ])
1122        );
1123    }
1124
1125    #[test]
1126    fn test_agent_data_from_json_value() {
1127        // Test automatic kind inference from JSON values
1128        let unit_data = AgentData::from_json(json!(null)).unwrap();
1129        assert_eq!(unit_data.kind, "unit");
1130        assert_eq!(unit_data.value, AgentValue::Unit);
1131
1132        let bool_data = AgentData::from_json(json!(true)).unwrap();
1133        assert_eq!(bool_data.kind, "boolean");
1134        assert_eq!(bool_data.value, AgentValue::Boolean(true));
1135
1136        let int_data = AgentData::from_json(json!(42)).unwrap();
1137        assert_eq!(int_data.kind, "integer");
1138        assert_eq!(int_data.value, AgentValue::Integer(42));
1139
1140        let num_data = AgentData::from_json(json!(3.14)).unwrap();
1141        assert_eq!(num_data.kind, "number");
1142        assert_eq!(num_data.value, AgentValue::number(3.14));
1143
1144        let str_data = AgentData::from_json(json!("hello")).unwrap();
1145        assert_eq!(str_data.kind, "string");
1146        assert_eq!(str_data.value, AgentValue::string("hello"));
1147
1148        let str_data = AgentData::from_json(json!("hello\nworld\n\n")).unwrap();
1149        assert_eq!(str_data.kind, "string");
1150        assert_eq!(str_data.value, AgentValue::string("hello\nworld\n\n"));
1151
1152        #[cfg(feature = "image")]
1153        {
1154            let image_data = AgentData::from_json(json!(
1155            "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg=="
1156        ))
1157        .unwrap();
1158            assert_eq!(image_data.kind, "image");
1159            assert!(matches!(image_data.value, AgentValue::Image(_)));
1160            assert_eq!(image_data.as_image().unwrap().get_width(), 1);
1161            assert_eq!(image_data.as_image().unwrap().get_height(), 1);
1162            assert_eq!(
1163                image_data.as_image().unwrap().get_raw_pixels(),
1164                vec![0u8, 0u8, 0u8, 0u8]
1165            );
1166        }
1167
1168        let obj_data = AgentData::from_json(json!({"key1": "string1", "key2": 2})).unwrap();
1169        assert_eq!(obj_data.kind, "object");
1170        assert_eq!(
1171            obj_data.value,
1172            AgentValue::object(
1173                [
1174                    ("key1".to_string(), AgentValue::string("string1")),
1175                    ("key2".to_string(), AgentValue::integer(2)),
1176                ]
1177                .into()
1178            )
1179        );
1180
1181        // Test array values
1182        let array_data = AgentData::from_json(json!([null, null])).unwrap();
1183        assert_eq!(array_data.kind, "unit");
1184        assert_eq!(
1185            array_data.value,
1186            AgentValue::array(vec![AgentValue::unit(), AgentValue::unit(),])
1187        );
1188
1189        let array_data = AgentData::from_json(json!([true, false])).unwrap();
1190        assert_eq!(array_data.kind, "boolean");
1191        assert_eq!(
1192            array_data.value,
1193            AgentValue::array(vec![AgentValue::boolean(true), AgentValue::boolean(false),])
1194        );
1195
1196        let array_data = AgentData::from_json(json!([1, 2, 3])).unwrap();
1197        assert_eq!(array_data.kind, "integer");
1198        assert_eq!(
1199            array_data.value,
1200            AgentValue::array(vec![
1201                AgentValue::integer(1),
1202                AgentValue::integer(2),
1203                AgentValue::integer(3),
1204            ])
1205        );
1206
1207        let array_data = AgentData::from_json(json!([1.0, 2.1, 3.2])).unwrap();
1208        assert_eq!(array_data.kind, "number");
1209        assert_eq!(
1210            array_data.value,
1211            AgentValue::array(vec![
1212                AgentValue::number(1.0),
1213                AgentValue::number(2.1),
1214                AgentValue::number(3.2),
1215            ])
1216        );
1217
1218        let array_data = AgentData::from_json(json!(["test", "hello\nworld\n", ""])).unwrap();
1219        assert_eq!(array_data.kind, "string");
1220        assert_eq!(
1221            array_data.value,
1222            AgentValue::array(vec![
1223                AgentValue::string("test"),
1224                AgentValue::string("hello\nworld\n"),
1225                AgentValue::string(""),
1226            ])
1227        );
1228
1229        let array_data = AgentData::from_json(
1230            json!([{"key1":"test","key2":1}, {"key1":"test2","key2":"hi"}, {}]),
1231        )
1232        .unwrap();
1233        assert_eq!(array_data.kind, "object");
1234        assert_eq!(
1235            array_data.value,
1236            AgentValue::array(vec![
1237                AgentValue::object(
1238                    [
1239                        ("key1".to_string(), AgentValue::string("test")),
1240                        ("key2".to_string(), AgentValue::integer(1)),
1241                    ]
1242                    .into()
1243                ),
1244                AgentValue::object(
1245                    [
1246                        ("key1".to_string(), AgentValue::string("test2")),
1247                        ("key2".to_string(), AgentValue::string("hi")),
1248                    ]
1249                    .into()
1250                ),
1251                AgentValue::object(AgentValueMap::default()),
1252            ])
1253        );
1254    }
1255
1256    #[test]
1257    fn test_agent_data_accessor_methods() {
1258        // Test accessor methods
1259        let str_data = AgentData::string("hello".to_string());
1260        assert_eq!(str_data.as_str().unwrap(), "hello");
1261        assert!(str_data.as_object().is_none());
1262
1263        let obj_val = [
1264            ("key1".to_string(), AgentValue::string("string1")),
1265            ("key2".to_string(), AgentValue::integer(2)),
1266        ];
1267        let obj_data = AgentData::object(obj_val.clone().into());
1268        assert!(obj_data.as_str().is_none());
1269        assert_eq!(obj_data.as_object().unwrap(), &obj_val.into());
1270    }
1271
1272    #[test]
1273    fn test_agent_data_serialization() {
1274        // Test unit serialization
1275        {
1276            let data = AgentData::unit();
1277            assert_eq!(
1278                serde_json::to_string(&data).unwrap(),
1279                r#"{"kind":"unit","value":null}"#
1280            );
1281        }
1282
1283        // Test Boolean serialization
1284        {
1285            let data = AgentData::boolean(true);
1286            assert_eq!(
1287                serde_json::to_string(&data).unwrap(),
1288                r#"{"kind":"boolean","value":true}"#
1289            );
1290
1291            let data = AgentData::boolean(false);
1292            assert_eq!(
1293                serde_json::to_string(&data).unwrap(),
1294                r#"{"kind":"boolean","value":false}"#
1295            );
1296        }
1297
1298        // Test Integer serialization
1299        {
1300            let data = AgentData::integer(42);
1301            assert_eq!(
1302                serde_json::to_string(&data).unwrap(),
1303                r#"{"kind":"integer","value":42}"#
1304            );
1305        }
1306
1307        // Test Number serialization
1308        {
1309            let data = AgentData::number(3.14);
1310            assert_eq!(
1311                serde_json::to_string(&data).unwrap(),
1312                r#"{"kind":"number","value":3.14}"#
1313            );
1314
1315            let data = AgentData::number(3.0);
1316            assert_eq!(
1317                serde_json::to_string(&data).unwrap(),
1318                r#"{"kind":"number","value":3.0}"#
1319            );
1320        }
1321
1322        // Test String serialization
1323        {
1324            let data = AgentData::string("Hello, world!");
1325            assert_eq!(
1326                serde_json::to_string(&data).unwrap(),
1327                r#"{"kind":"string","value":"Hello, world!"}"#
1328            );
1329
1330            let data = AgentData::string("hello\nworld\n\n");
1331            assert_eq!(
1332                serde_json::to_string(&data).unwrap(),
1333                r#"{"kind":"string","value":"hello\nworld\n\n"}"#
1334            );
1335        }
1336
1337        // Test Image serialization
1338        #[cfg(feature = "image")]
1339        {
1340            let data = AgentData::image(PhotonImage::new(vec![0u8, 0u8, 0u8, 0u8], 1, 1));
1341            assert_eq!(
1342                serde_json::to_string(&data).unwrap(),
1343                r#"{"kind":"image","value":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg=="}"#
1344            );
1345        }
1346
1347        // Test Object serialization
1348        {
1349            let data = AgentData::object(
1350                [
1351                    ("key1".to_string(), AgentValue::string("string1")),
1352                    ("key2".to_string(), AgentValue::integer(2)),
1353                ]
1354                .into(),
1355            );
1356            assert_eq!(
1357                serde_json::to_string(&data).unwrap(),
1358                r#"{"kind":"object","value":{"key1":"string1","key2":2}}"#
1359            );
1360        }
1361
1362        // Test custom object serialization
1363        {
1364            let data = AgentData::object_with_kind(
1365                "custom",
1366                [
1367                    ("key1".to_string(), AgentValue::string("test")),
1368                    ("key2".to_string(), AgentValue::integer(3)),
1369                ]
1370                .into(),
1371            );
1372            assert_eq!(
1373                serde_json::to_string(&data).unwrap(),
1374                r#"{"kind":"custom","value":{"key1":"test","key2":3}}"#
1375            );
1376        }
1377
1378        // Test Array serialization
1379        {
1380            let data = AgentData::array("unit", vec![AgentValue::unit(), AgentValue::unit()]);
1381            assert_eq!(
1382                serde_json::to_string(&data).unwrap(),
1383                r#"{"kind":"unit","value":[null,null]}"#
1384            );
1385
1386            let data = AgentData::array(
1387                "boolean",
1388                vec![AgentValue::boolean(false), AgentValue::boolean(true)],
1389            );
1390            assert_eq!(
1391                serde_json::to_string(&data).unwrap(),
1392                r#"{"kind":"boolean","value":[false,true]}"#
1393            );
1394
1395            let data = AgentData::array(
1396                "integer",
1397                vec![
1398                    AgentValue::integer(1),
1399                    AgentValue::integer(2),
1400                    AgentValue::integer(3),
1401                ],
1402            );
1403            assert_eq!(
1404                serde_json::to_string(&data).unwrap(),
1405                r#"{"kind":"integer","value":[1,2,3]}"#
1406            );
1407
1408            let data = AgentData::array(
1409                "number",
1410                vec![
1411                    AgentValue::number(1.0),
1412                    AgentValue::number(2.1),
1413                    AgentValue::number(3.2),
1414                ],
1415            );
1416            assert_eq!(
1417                serde_json::to_string(&data).unwrap(),
1418                r#"{"kind":"number","value":[1.0,2.1,3.2]}"#
1419            );
1420
1421            let data = AgentData::array(
1422                "string",
1423                vec![
1424                    AgentValue::string("test"),
1425                    AgentValue::string("hello\nworld\n"),
1426                    AgentValue::string(""),
1427                ],
1428            );
1429            assert_eq!(
1430                serde_json::to_string(&data).unwrap(),
1431                r#"{"kind":"string","value":["test","hello\nworld\n",""]}"#
1432            );
1433
1434            let data = AgentData::array(
1435                "object",
1436                vec![
1437                    AgentValue::object(
1438                        [
1439                            ("key1".to_string(), AgentValue::string("test")),
1440                            ("key2".to_string(), AgentValue::integer(1)),
1441                        ]
1442                        .into(),
1443                    ),
1444                    AgentValue::object(
1445                        [
1446                            ("key1".to_string(), AgentValue::string("test2")),
1447                            ("key2".to_string(), AgentValue::string("hi")),
1448                        ]
1449                        .into(),
1450                    ),
1451                    AgentValue::object(AgentValueMap::default()),
1452                ],
1453            );
1454            assert_eq!(
1455                serde_json::to_string(&data).unwrap(),
1456                r#"{"kind":"object","value":[{"key1":"test","key2":1},{"key1":"test2","key2":"hi"},{}]}"#
1457            );
1458
1459            let data = AgentData::array(
1460                "custom",
1461                vec![
1462                    AgentValue::object(
1463                        [
1464                            ("key1".to_string(), AgentValue::string("test")),
1465                            ("key2".to_string(), AgentValue::integer(1)),
1466                        ]
1467                        .into(),
1468                    ),
1469                    AgentValue::object(
1470                        [
1471                            ("key1".to_string(), AgentValue::string("test2")),
1472                            ("key2".to_string(), AgentValue::string("hi")),
1473                        ]
1474                        .into(),
1475                    ),
1476                    AgentValue::object(AgentValueMap::default()),
1477                ],
1478            );
1479            assert_eq!(
1480                serde_json::to_string(&data).unwrap(),
1481                r#"{"kind":"custom","value":[{"key1":"test","key2":1},{"key1":"test2","key2":"hi"},{}]}"#
1482            );
1483        }
1484    }
1485
1486    #[test]
1487    fn test_agent_data_deserialization() {
1488        // Test unit deserialization
1489        {
1490            let deserialized: AgentData =
1491                serde_json::from_str(r#"{"kind":"unit","value":null}"#).unwrap();
1492            assert_eq!(deserialized, AgentData::unit());
1493        }
1494
1495        // Test Boolean deserialization
1496        {
1497            let deserialized: AgentData =
1498                serde_json::from_str(r#"{"kind":"boolean","value":false}"#).unwrap();
1499            assert_eq!(deserialized, AgentData::boolean(false));
1500
1501            let deserialized: AgentData =
1502                serde_json::from_str(r#"{"kind":"boolean","value":true}"#).unwrap();
1503            assert_eq!(deserialized, AgentData::boolean(true));
1504        }
1505
1506        // Test Integer deserialization
1507        {
1508            let deserialized: AgentData =
1509                serde_json::from_str(r#"{"kind":"integer","value":123}"#).unwrap();
1510            assert_eq!(deserialized, AgentData::integer(123));
1511        }
1512
1513        // Test Number deserialization
1514        {
1515            let deserialized: AgentData =
1516                serde_json::from_str(r#"{"kind":"number","value":3.14}"#).unwrap();
1517            assert_eq!(deserialized, AgentData::number(3.14));
1518
1519            let deserialized: AgentData =
1520                serde_json::from_str(r#"{"kind":"number","value":3.0}"#).unwrap();
1521            assert_eq!(deserialized, AgentData::number(3.0));
1522        }
1523
1524        // Test String deserialization
1525        {
1526            let deserialized: AgentData =
1527                serde_json::from_str(r#"{"kind":"string","value":"Hello, world!"}"#).unwrap();
1528            assert_eq!(deserialized, AgentData::string("Hello, world!"));
1529
1530            let deserialized: AgentData =
1531                serde_json::from_str(r#"{"kind":"string","value":"hello\nworld\n\n"}"#).unwrap();
1532            assert_eq!(deserialized, AgentData::string("hello\nworld\n\n"));
1533        }
1534
1535        // Test Image deserialization
1536        #[cfg(feature = "image")]
1537        {
1538            let deserialized: AgentData = serde_json::from_str(
1539                r#"{"kind":"image","value":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg=="}"#,
1540            )
1541            .unwrap();
1542            assert_eq!(deserialized.kind, "image");
1543            assert!(matches!(deserialized.value, AgentValue::Image(_)));
1544        }
1545
1546        // Test Object deserialization
1547        {
1548            let deserialized: AgentData =
1549                serde_json::from_str(r#"{"kind":"object","value":{"key1":"test","key2":3}}"#)
1550                    .unwrap();
1551            assert_eq!(
1552                deserialized,
1553                AgentData::object(
1554                    [
1555                        ("key1".to_string(), AgentValue::string("test")),
1556                        ("key2".to_string(), AgentValue::integer(3))
1557                    ]
1558                    .into()
1559                )
1560            );
1561        }
1562
1563        // Test custom object deserialization
1564        {
1565            let deserialized: AgentData =
1566                serde_json::from_str(r#"{"kind":"custom","value":{"name":"test","value":3}}"#)
1567                    .unwrap();
1568            assert_eq!(
1569                deserialized,
1570                AgentData::object_with_kind(
1571                    "custom",
1572                    [
1573                        ("name".to_string(), AgentValue::string("test")),
1574                        ("value".to_string(), AgentValue::integer(3))
1575                    ]
1576                    .into()
1577                )
1578            );
1579        }
1580
1581        // Test Array deserialization
1582        {
1583            let deserialized: AgentData =
1584                serde_json::from_str(r#"{"kind":"unit","value":[null,null]}"#).unwrap();
1585            assert_eq!(
1586                deserialized,
1587                AgentData::array("unit", vec![AgentValue::unit(), AgentValue::unit(),])
1588            );
1589
1590            let deserialized: AgentData =
1591                serde_json::from_str(r#"{"kind":"boolean","value":[true,false]}"#).unwrap();
1592            assert_eq!(
1593                deserialized,
1594                AgentData::array(
1595                    "boolean",
1596                    vec![AgentValue::boolean(true), AgentValue::boolean(false),]
1597                )
1598            );
1599
1600            let deserialized: AgentData =
1601                serde_json::from_str(r#"{"kind":"integer","value":[1,2,3]}"#).unwrap();
1602            assert_eq!(
1603                deserialized,
1604                AgentData::array(
1605                    "integer",
1606                    vec![
1607                        AgentValue::integer(1),
1608                        AgentValue::integer(2),
1609                        AgentValue::integer(3),
1610                    ]
1611                )
1612            );
1613
1614            let deserialized: AgentData =
1615                serde_json::from_str(r#"{"kind":"number","value":[1.0,2.1,3]}"#).unwrap();
1616            assert_eq!(
1617                deserialized,
1618                AgentData::array(
1619                    "number",
1620                    vec![
1621                        AgentValue::number(1.0),
1622                        AgentValue::number(2.1),
1623                        AgentValue::number(3.0),
1624                    ]
1625                )
1626            );
1627
1628            let deserialized: AgentData =
1629                serde_json::from_str(r#"{"kind":"string","value":["test","hello\nworld\n",""]}"#)
1630                    .unwrap();
1631            assert_eq!(
1632                deserialized,
1633                AgentData::array(
1634                    "string",
1635                    vec![
1636                        AgentValue::string("test"),
1637                        AgentValue::string("hello\nworld\n"),
1638                        AgentValue::string(""),
1639                    ]
1640                )
1641            );
1642
1643            let deserialized: AgentData =
1644                    serde_json::from_str(r#"{"kind":"object","value":[{"key1":"test","key2":1},{"key1":"test2","key2":"hi"},{}]}"#)
1645                        .unwrap();
1646            assert_eq!(
1647                deserialized,
1648                AgentData::array(
1649                    "object",
1650                    vec![
1651                        AgentValue::object(
1652                            [
1653                                ("key1".to_string(), AgentValue::string("test")),
1654                                ("key2".to_string(), AgentValue::integer(1)),
1655                            ]
1656                            .into()
1657                        ),
1658                        AgentValue::object(
1659                            [
1660                                ("key1".to_string(), AgentValue::string("test2")),
1661                                ("key2".to_string(), AgentValue::string("hi")),
1662                            ]
1663                            .into()
1664                        ),
1665                        AgentValue::object(AgentValueMap::default()),
1666                    ]
1667                )
1668            );
1669
1670            let deserialized: AgentData =
1671                    serde_json::from_str(r#"{"kind":"custom","value":[{"key1":"test","key2":1},{"key1":"test2","key2":"hi"},{}]}"#)
1672                        .unwrap();
1673            assert_eq!(
1674                deserialized,
1675                AgentData::array(
1676                    "custom",
1677                    vec![
1678                        AgentValue::object(
1679                            [
1680                                ("key1".to_string(), AgentValue::string("test")),
1681                                ("key2".to_string(), AgentValue::integer(1)),
1682                            ]
1683                            .into()
1684                        ),
1685                        AgentValue::object(
1686                            [
1687                                ("key1".to_string(), AgentValue::string("test2")),
1688                                ("key2".to_string(), AgentValue::string("hi")),
1689                            ]
1690                            .into()
1691                        ),
1692                        AgentValue::object(AgentValueMap::default()),
1693                    ]
1694                )
1695            );
1696        }
1697    }
1698
1699    #[test]
1700    fn test_agent_value_constructors() {
1701        // Test AgentValue constructors
1702        let unit = AgentValue::unit();
1703        assert_eq!(unit, AgentValue::Unit);
1704
1705        let boolean = AgentValue::boolean(true);
1706        assert_eq!(boolean, AgentValue::Boolean(true));
1707
1708        let integer = AgentValue::integer(42);
1709        assert_eq!(integer, AgentValue::Integer(42));
1710
1711        let number = AgentValue::number(3.14);
1712        assert!(matches!(number, AgentValue::Number(_)));
1713        if let AgentValue::Number(num) = number {
1714            assert!((num - 3.14).abs() < f64::EPSILON);
1715        }
1716
1717        let string = AgentValue::string("hello");
1718        assert!(matches!(string, AgentValue::String(_)));
1719        assert_eq!(string.as_str().unwrap(), "hello");
1720
1721        let text = AgentValue::string("multiline\ntext");
1722        assert!(matches!(text, AgentValue::String(_)));
1723        assert_eq!(text.as_str().unwrap(), "multiline\ntext");
1724
1725        let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
1726        assert!(matches!(array, AgentValue::Array(_)));
1727        if let AgentValue::Array(arr) = array {
1728            assert_eq!(arr.len(), 2);
1729            assert_eq!(arr[0].as_i64().unwrap(), 1);
1730            assert_eq!(arr[1].as_i64().unwrap(), 2);
1731        }
1732
1733        let obj = AgentValue::object(
1734            [
1735                ("key1".to_string(), AgentValue::string("string1")),
1736                ("key2".to_string(), AgentValue::integer(2)),
1737            ]
1738            .into(),
1739        );
1740        assert!(matches!(obj, AgentValue::Object(_)));
1741        if let AgentValue::Object(obj) = obj {
1742            assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
1743            assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
1744        } else {
1745            panic!("Object was not deserialized correctly");
1746        }
1747    }
1748
1749    #[test]
1750    fn test_agent_value_from_json_value() {
1751        // Test converting from JSON value to AgentValue
1752        let null = AgentValue::from_json(json!(null)).unwrap();
1753        assert_eq!(null, AgentValue::Unit);
1754
1755        let boolean = AgentValue::from_json(json!(true)).unwrap();
1756        assert_eq!(boolean, AgentValue::Boolean(true));
1757
1758        let integer = AgentValue::from_json(json!(42)).unwrap();
1759        assert_eq!(integer, AgentValue::Integer(42));
1760
1761        let number = AgentValue::from_json(json!(3.14)).unwrap();
1762        assert!(matches!(number, AgentValue::Number(_)));
1763        if let AgentValue::Number(num) = number {
1764            assert!((num - 3.14).abs() < f64::EPSILON);
1765        }
1766
1767        let string = AgentValue::from_json(json!("hello")).unwrap();
1768        assert!(matches!(string, AgentValue::String(_)));
1769        if let AgentValue::String(s) = string {
1770            assert_eq!(*s, "hello");
1771        } else {
1772            panic!("Expected string value");
1773        }
1774
1775        let array = AgentValue::from_json(json!([1, "test", true])).unwrap();
1776        assert!(matches!(array, AgentValue::Array(_)));
1777        if let AgentValue::Array(arr) = array {
1778            assert_eq!(arr.len(), 3);
1779            assert_eq!(arr[0], AgentValue::Integer(1));
1780            assert!(matches!(&arr[1], AgentValue::String(_)));
1781            if let AgentValue::String(s) = &arr[1] {
1782                assert_eq!(**s, "test");
1783            } else {
1784                panic!("Expected string value");
1785            }
1786            assert_eq!(arr[2], AgentValue::Boolean(true));
1787        }
1788
1789        let object = AgentValue::from_json(json!({"key1": "string1", "key2": 2})).unwrap();
1790        assert!(matches!(object, AgentValue::Object(_)));
1791        if let AgentValue::Object(obj) = object {
1792            assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
1793            assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
1794        } else {
1795            panic!("Object was not deserialized correctly");
1796        }
1797    }
1798
1799    #[test]
1800    fn test_agent_value_from_kind_value() {
1801        // Test AgentValue::from_kind_value with different kinds and values
1802        let unit = AgentValue::from_kind_json("unit", json!(null)).unwrap();
1803        assert_eq!(unit, AgentValue::Unit);
1804
1805        let boolean = AgentValue::from_kind_json("boolean", json!(true)).unwrap();
1806        assert_eq!(boolean, AgentValue::Boolean(true));
1807
1808        let integer = AgentValue::from_kind_json("integer", json!(42)).unwrap();
1809        assert_eq!(integer, AgentValue::Integer(42));
1810
1811        let integer = AgentValue::from_kind_json("integer", json!(42.0)).unwrap();
1812        assert_eq!(integer, AgentValue::Integer(42));
1813
1814        let number = AgentValue::from_kind_json("number", json!(3.14)).unwrap();
1815        assert!(matches!(number, AgentValue::Number(_)));
1816        if let AgentValue::Number(num) = number {
1817            assert!((num - 3.14).abs() < f64::EPSILON);
1818        }
1819
1820        let number = AgentValue::from_kind_json("number", json!(3)).unwrap();
1821        assert!(matches!(number, AgentValue::Number(_)));
1822        if let AgentValue::Number(num) = number {
1823            assert!((num - 3.0).abs() < f64::EPSILON);
1824        }
1825
1826        let string = AgentValue::from_kind_json("string", json!("hello")).unwrap();
1827        assert!(matches!(string, AgentValue::String(_)));
1828        if let AgentValue::String(s) = string {
1829            assert_eq!(*s, "hello");
1830        } else {
1831            panic!("Expected string value");
1832        }
1833
1834        let text = AgentValue::from_kind_json("string", json!("multiline\ntext")).unwrap();
1835        assert!(matches!(text, AgentValue::String(_)));
1836        if let AgentValue::String(t) = text {
1837            assert_eq!(*t, "multiline\ntext");
1838        } else {
1839            panic!("Expected text value");
1840        }
1841
1842        let array = AgentValue::from_kind_json("array", json!([1, "test", true])).unwrap();
1843        assert!(matches!(array, AgentValue::Array(_)));
1844        if let AgentValue::Array(arr) = array {
1845            assert_eq!(arr.len(), 3);
1846            assert_eq!(arr[0], AgentValue::Integer(1));
1847            assert!(matches!(&arr[1], AgentValue::String(_)));
1848            if let AgentValue::String(s) = &arr[1] {
1849                assert_eq!(**s, "test");
1850            } else {
1851                panic!("Expected string value");
1852            }
1853            assert_eq!(arr[2], AgentValue::Boolean(true));
1854        }
1855
1856        let obj = AgentValue::from_kind_json("object", json!({"key1": "test", "key2": 2})).unwrap();
1857        assert!(matches!(obj, AgentValue::Object(_)));
1858        if let AgentValue::Object(obj) = obj {
1859            assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("test"));
1860            assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
1861        } else {
1862            panic!("Object was not deserialized correctly");
1863        }
1864
1865        // Test arrays
1866        let unit_array = AgentValue::from_kind_json("unit", json!([null, null])).unwrap();
1867        assert!(matches!(unit_array, AgentValue::Array(_)));
1868        if let AgentValue::Array(arr) = unit_array {
1869            assert_eq!(arr.len(), 2);
1870            for val in arr.iter() {
1871                assert_eq!(*val, AgentValue::Unit);
1872            }
1873        }
1874
1875        let bool_array = AgentValue::from_kind_json("boolean", json!([true, false])).unwrap();
1876        assert!(matches!(bool_array, AgentValue::Array(_)));
1877        if let AgentValue::Array(arr) = bool_array {
1878            assert_eq!(arr.len(), 2);
1879            assert_eq!(arr[0], AgentValue::Boolean(true));
1880            assert_eq!(arr[1], AgentValue::Boolean(false));
1881        }
1882
1883        let int_array = AgentValue::from_kind_json("integer", json!([1, 2, 3])).unwrap();
1884        assert!(matches!(int_array, AgentValue::Array(_)));
1885        if let AgentValue::Array(arr) = int_array {
1886            assert_eq!(arr.len(), 3);
1887            assert_eq!(arr[0], AgentValue::Integer(1));
1888            assert_eq!(arr[1], AgentValue::Integer(2));
1889            assert_eq!(arr[2], AgentValue::Integer(3));
1890        }
1891
1892        let num_array = AgentValue::from_kind_json("number", json!([1.1, 2.2, 3.3])).unwrap();
1893        assert!(matches!(num_array, AgentValue::Array(_)));
1894        if let AgentValue::Array(arr) = num_array {
1895            assert_eq!(arr.len(), 3);
1896            assert_eq!(arr[0], AgentValue::Number(1.1));
1897            assert_eq!(arr[1], AgentValue::Number(2.2));
1898            assert_eq!(arr[2], AgentValue::Number(3.3));
1899        }
1900
1901        let string_array = AgentValue::from_kind_json("string", json!(["hello", "world"])).unwrap();
1902        assert!(matches!(string_array, AgentValue::Array(_)));
1903        if let AgentValue::Array(arr) = string_array {
1904            assert_eq!(arr.len(), 2);
1905            assert!(matches!(&arr[0], AgentValue::String(_)));
1906            if let AgentValue::String(s) = &arr[0] {
1907                assert_eq!(**s, "hello".to_string());
1908            }
1909            assert!(matches!(&arr[1], AgentValue::String(_)));
1910            if let AgentValue::String(s) = &arr[1] {
1911                assert_eq!(**s, "world".to_string());
1912            }
1913        }
1914
1915        let text_array =
1916            AgentValue::from_kind_json("string", json!(["hello", "world!\n"])).unwrap();
1917        assert!(matches!(text_array, AgentValue::Array(_)));
1918        if let AgentValue::Array(arr) = text_array {
1919            assert_eq!(arr.len(), 2);
1920            assert!(matches!(&arr[0], AgentValue::String(_)));
1921            if let AgentValue::String(s) = &arr[0] {
1922                assert_eq!(**s, "hello".to_string());
1923            }
1924            assert!(matches!(&arr[1], AgentValue::String(_)));
1925            if let AgentValue::String(s) = &arr[1] {
1926                assert_eq!(**s, "world!\n".to_string());
1927            }
1928        }
1929
1930        // array_array
1931
1932        // object_array
1933    }
1934
1935    #[test]
1936    fn test_agent_value_test_methods() {
1937        // Test test methods on AgentValue
1938        let unit = AgentValue::unit();
1939        assert_eq!(unit.is_unit(), true);
1940        assert_eq!(unit.is_boolean(), false);
1941        assert_eq!(unit.is_integer(), false);
1942        assert_eq!(unit.is_number(), false);
1943        assert_eq!(unit.is_string(), false);
1944        assert_eq!(unit.is_array(), false);
1945        assert_eq!(unit.is_object(), false);
1946
1947        let boolean = AgentValue::boolean(true);
1948        assert_eq!(boolean.is_unit(), false);
1949        assert_eq!(boolean.is_boolean(), true);
1950        assert_eq!(boolean.is_integer(), false);
1951        assert_eq!(boolean.is_number(), false);
1952        assert_eq!(boolean.is_string(), false);
1953        assert_eq!(boolean.is_array(), false);
1954        assert_eq!(boolean.is_object(), false);
1955
1956        let integer = AgentValue::integer(42);
1957        assert_eq!(integer.is_unit(), false);
1958        assert_eq!(integer.is_boolean(), false);
1959        assert_eq!(integer.is_integer(), true);
1960        assert_eq!(integer.is_number(), false);
1961        assert_eq!(integer.is_string(), false);
1962        assert_eq!(integer.is_array(), false);
1963        assert_eq!(integer.is_object(), false);
1964
1965        let number = AgentValue::number(3.14);
1966        assert_eq!(number.is_unit(), false);
1967        assert_eq!(number.is_boolean(), false);
1968        assert_eq!(number.is_integer(), false);
1969        assert_eq!(number.is_number(), true);
1970        assert_eq!(number.is_string(), false);
1971        assert_eq!(number.is_array(), false);
1972        assert_eq!(number.is_object(), false);
1973
1974        let string = AgentValue::string("hello");
1975        assert_eq!(string.is_unit(), false);
1976        assert_eq!(string.is_boolean(), false);
1977        assert_eq!(string.is_integer(), false);
1978        assert_eq!(string.is_number(), false);
1979        assert_eq!(string.is_string(), true);
1980        assert_eq!(string.is_array(), false);
1981        assert_eq!(string.is_object(), false);
1982
1983        let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
1984        assert_eq!(array.is_unit(), false);
1985        assert_eq!(array.is_boolean(), false);
1986        assert_eq!(array.is_integer(), false);
1987        assert_eq!(array.is_number(), false);
1988        assert_eq!(array.is_string(), false);
1989        assert_eq!(array.is_array(), true);
1990        assert_eq!(array.is_object(), false);
1991
1992        let obj = AgentValue::object(
1993            [
1994                ("key1".to_string(), AgentValue::string("string1")),
1995                ("key2".to_string(), AgentValue::integer(2)),
1996            ]
1997            .into(),
1998        );
1999        assert_eq!(obj.is_unit(), false);
2000        assert_eq!(obj.is_boolean(), false);
2001        assert_eq!(obj.is_integer(), false);
2002        assert_eq!(obj.is_number(), false);
2003        assert_eq!(obj.is_string(), false);
2004        assert_eq!(obj.is_array(), false);
2005        assert_eq!(obj.is_object(), true);
2006    }
2007
2008    #[test]
2009    fn test_agent_value_accessor_methods() {
2010        // Test accessor methods on AgentValue
2011        let boolean = AgentValue::boolean(true);
2012        assert_eq!(boolean.as_bool(), Some(true));
2013        assert_eq!(boolean.as_i64(), None);
2014        assert_eq!(boolean.as_f64(), None);
2015        assert_eq!(boolean.as_str(), None);
2016        assert!(boolean.as_array().is_none());
2017        assert_eq!(boolean.as_object(), None);
2018
2019        let integer = AgentValue::integer(42);
2020        assert_eq!(integer.as_bool(), None);
2021        assert_eq!(integer.as_i64(), Some(42));
2022        assert_eq!(integer.as_f64(), Some(42.0));
2023        assert_eq!(integer.as_str(), None);
2024        assert!(integer.as_array().is_none());
2025        assert_eq!(integer.as_object(), None);
2026
2027        let number = AgentValue::number(3.14);
2028        assert_eq!(number.as_bool(), None);
2029        assert_eq!(number.as_i64(), Some(3)); // truncated
2030        assert_eq!(number.as_f64().unwrap(), 3.14);
2031        assert_eq!(number.as_str(), None);
2032        assert!(number.as_array().is_none());
2033        assert_eq!(number.as_object(), None);
2034
2035        let string = AgentValue::string("hello");
2036        assert_eq!(string.as_bool(), None);
2037        assert_eq!(string.as_i64(), None);
2038        assert_eq!(string.as_f64(), None);
2039        assert_eq!(string.as_str(), Some("hello"));
2040        assert!(string.as_array().is_none());
2041        assert_eq!(string.as_object(), None);
2042
2043        let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
2044        assert_eq!(array.as_bool(), None);
2045        assert_eq!(array.as_i64(), None);
2046        assert_eq!(array.as_f64(), None);
2047        assert_eq!(array.as_str(), None);
2048        assert!(array.as_array().is_some());
2049        if let Some(arr) = array.as_array() {
2050            assert_eq!(arr.len(), 2);
2051            assert_eq!(arr[0].as_i64().unwrap(), 1);
2052            assert_eq!(arr[1].as_i64().unwrap(), 2);
2053        }
2054        assert_eq!(array.as_object(), None);
2055
2056        let obj = AgentValue::object(
2057            [
2058                ("key1".to_string(), AgentValue::string("string1")),
2059                ("key2".to_string(), AgentValue::integer(2)),
2060            ]
2061            .into(),
2062        );
2063        assert_eq!(obj.as_bool(), None);
2064        assert_eq!(obj.as_i64(), None);
2065        assert_eq!(obj.as_f64(), None);
2066        assert_eq!(obj.as_str(), None);
2067        assert!(obj.as_array().is_none());
2068        assert!(obj.as_object().is_some());
2069        if let Some(value) = obj.as_object() {
2070            assert_eq!(value.get("key1").and_then(|v| v.as_str()), Some("string1"));
2071            assert_eq!(value.get("key2").and_then(|v| v.as_i64()), Some(2));
2072        }
2073    }
2074
2075    #[test]
2076    fn test_agent_value_default() {
2077        assert_eq!(AgentValue::default(), AgentValue::Unit);
2078    }
2079
2080    #[test]
2081    fn test_agent_value_serialization() {
2082        // Test Null serialization
2083        {
2084            let null = AgentValue::Unit;
2085            assert_eq!(serde_json::to_string(&null).unwrap(), "null");
2086        }
2087
2088        // Test Boolean serialization
2089        {
2090            let boolean_t = AgentValue::boolean(true);
2091            assert_eq!(serde_json::to_string(&boolean_t).unwrap(), "true");
2092
2093            let boolean_f = AgentValue::boolean(false);
2094            assert_eq!(serde_json::to_string(&boolean_f).unwrap(), "false");
2095        }
2096
2097        // Test Integer serialization
2098        {
2099            let integer = AgentValue::integer(42);
2100            assert_eq!(serde_json::to_string(&integer).unwrap(), "42");
2101        }
2102
2103        // Test Number serialization
2104        {
2105            let num = AgentValue::number(3.14);
2106            assert_eq!(serde_json::to_string(&num).unwrap(), "3.14");
2107
2108            let num = AgentValue::number(3.0);
2109            assert_eq!(serde_json::to_string(&num).unwrap(), "3.0");
2110        }
2111
2112        // Test String serialization
2113        {
2114            let s = AgentValue::string("Hello, world!");
2115            assert_eq!(serde_json::to_string(&s).unwrap(), "\"Hello, world!\"");
2116
2117            let s = AgentValue::string("hello\nworld\n\n");
2118            assert_eq!(serde_json::to_string(&s).unwrap(), r#""hello\nworld\n\n""#);
2119        }
2120
2121        // Test Image serialization
2122        #[cfg(feature = "image")]
2123        {
2124            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
2125            assert_eq!(
2126                serde_json::to_string(&img).unwrap(),
2127                r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
2128            );
2129        }
2130
2131        // Test Array serialization
2132        {
2133            let array = AgentValue::array(vec![
2134                AgentValue::integer(1),
2135                AgentValue::string("test"),
2136                AgentValue::object(
2137                    [
2138                        ("key1".to_string(), AgentValue::string("test")),
2139                        ("key2".to_string(), AgentValue::integer(2)),
2140                    ]
2141                    .into(),
2142                ),
2143            ]);
2144            assert_eq!(
2145                serde_json::to_string(&array).unwrap(),
2146                r#"[1,"test",{"key1":"test","key2":2}]"#
2147            );
2148        }
2149
2150        // Test Object serialization
2151        {
2152            let obj = AgentValue::object(
2153                [
2154                    ("key1".to_string(), AgentValue::string("test")),
2155                    ("key2".to_string(), AgentValue::integer(3)),
2156                ]
2157                .into(),
2158            );
2159            assert_eq!(
2160                serde_json::to_string(&obj).unwrap(),
2161                r#"{"key1":"test","key2":3}"#
2162            );
2163        }
2164    }
2165
2166    #[test]
2167    fn test_agent_value_deserialization() {
2168        // Test Null deserialization
2169        {
2170            let deserialized: AgentValue = serde_json::from_str("null").unwrap();
2171            assert_eq!(deserialized, AgentValue::Unit);
2172        }
2173
2174        // Test Boolean deserialization
2175        {
2176            let deserialized: AgentValue = serde_json::from_str("false").unwrap();
2177            assert_eq!(deserialized, AgentValue::boolean(false));
2178
2179            let deserialized: AgentValue = serde_json::from_str("true").unwrap();
2180            assert_eq!(deserialized, AgentValue::boolean(true));
2181        }
2182
2183        // Test Integer deserialization
2184        {
2185            let deserialized: AgentValue = serde_json::from_str("123").unwrap();
2186            assert_eq!(deserialized, AgentValue::integer(123));
2187        }
2188
2189        // Test Number deserialization
2190        {
2191            let deserialized: AgentValue = serde_json::from_str("3.14").unwrap();
2192            assert_eq!(deserialized, AgentValue::number(3.14));
2193
2194            let deserialized: AgentValue = serde_json::from_str("3.0").unwrap();
2195            assert_eq!(deserialized, AgentValue::number(3.0));
2196        }
2197
2198        // Test String deserialization
2199        {
2200            let deserialized: AgentValue = serde_json::from_str("\"Hello, world!\"").unwrap();
2201            assert_eq!(deserialized, AgentValue::string("Hello, world!"));
2202
2203            let deserialized: AgentValue = serde_json::from_str(r#""hello\nworld\n\n""#).unwrap();
2204            assert_eq!(deserialized, AgentValue::string("hello\nworld\n\n"));
2205        }
2206
2207        // Test Image deserialization
2208        #[cfg(feature = "image")]
2209        {
2210            let deserialized: AgentValue = serde_json::from_str(
2211                r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#,
2212            )
2213            .unwrap();
2214            assert!(matches!(deserialized, AgentValue::Image(_)));
2215        }
2216
2217        // Test Array deserialization
2218        {
2219            let deserialized: AgentValue =
2220                serde_json::from_str(r#"[1,"test",{"key1":"test","key2":2}]"#).unwrap();
2221            assert!(matches!(deserialized, AgentValue::Array(_)));
2222            if let AgentValue::Array(arr) = deserialized {
2223                assert_eq!(arr.len(), 3, "Array length mismatch after serialization");
2224                assert_eq!(arr[0], AgentValue::integer(1));
2225                assert_eq!(arr[1], AgentValue::string("test"));
2226                assert_eq!(
2227                    arr[2],
2228                    AgentValue::object(
2229                        [
2230                            ("key1".to_string(), AgentValue::string("test")),
2231                            ("key2".to_string(), AgentValue::integer(2)),
2232                        ]
2233                        .into()
2234                    )
2235                );
2236            }
2237        }
2238
2239        // Test Object deserialization
2240        {
2241            let deserialized: AgentValue =
2242                serde_json::from_str(r#"{"key1":"test","key2":3}"#).unwrap();
2243            assert_eq!(
2244                deserialized,
2245                AgentValue::object(
2246                    [
2247                        ("key1".to_string(), AgentValue::string("test")),
2248                        ("key2".to_string(), AgentValue::integer(3)),
2249                    ]
2250                    .into()
2251                )
2252            );
2253        }
2254    }
2255
2256    #[test]
2257    fn test_serialize_deserialize_roundtrip() {
2258        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2259        struct TestStruct {
2260            name: String,
2261            age: i64,
2262            active: bool,
2263        }
2264
2265        let test_data = TestStruct {
2266            name: "Alice".to_string(),
2267            age: 30,
2268            active: true,
2269        };
2270
2271        // Test AgentData roundtrip
2272        let agent_data = AgentData::from_serialize(&test_data).unwrap();
2273        assert_eq!(agent_data.kind, "object");
2274        assert_eq!(agent_data.get_str("name"), Some("Alice"));
2275        assert_eq!(agent_data.get_i64("age"), Some(30));
2276        assert_eq!(agent_data.get_bool("active"), Some(true));
2277
2278        let restored: TestStruct = agent_data.to_deserialize().unwrap();
2279        assert_eq!(restored, test_data);
2280
2281        // Test AgentData with custom kind
2282        let agent_data_custom = AgentData::from_serialize_with_kind("person", &test_data).unwrap();
2283        assert_eq!(agent_data_custom.kind, "person");
2284        let restored_custom: TestStruct = agent_data_custom.to_deserialize().unwrap();
2285        assert_eq!(restored_custom, test_data);
2286
2287        // Test AgentValue roundtrip
2288        let agent_value = AgentValue::from_serialize(&test_data).unwrap();
2289        assert!(agent_value.is_object());
2290        assert_eq!(agent_value.get_str("name"), Some("Alice"));
2291
2292        let restored_value: TestStruct = agent_value.to_deserialize().unwrap();
2293        assert_eq!(restored_value, test_data);
2294    }
2295
2296    #[test]
2297    fn test_serialize_deserialize_nested() {
2298        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2299        struct Address {
2300            street: String,
2301            city: String,
2302            zip: String,
2303        }
2304
2305        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2306        struct Person {
2307            name: String,
2308            age: i64,
2309            address: Address,
2310            tags: Vec<String>,
2311        }
2312
2313        let person = Person {
2314            name: "Bob".to_string(),
2315            age: 25,
2316            address: Address {
2317                street: "123 Main St".to_string(),
2318                city: "Springfield".to_string(),
2319                zip: "12345".to_string(),
2320            },
2321            tags: vec!["developer".to_string(), "rust".to_string()],
2322        };
2323
2324        // Test AgentData roundtrip with nested structures
2325        let agent_data = AgentData::from_serialize(&person).unwrap();
2326        assert_eq!(agent_data.kind, "object");
2327        assert_eq!(agent_data.get_str("name"), Some("Bob"));
2328
2329        let address = agent_data.get_object("address").unwrap();
2330        assert_eq!(
2331            address.get("city").and_then(|v| v.as_str()),
2332            Some("Springfield")
2333        );
2334
2335        let tags = agent_data.get_array("tags").unwrap();
2336        assert_eq!(tags.len(), 2);
2337        assert_eq!(tags[0].as_str(), Some("developer"));
2338
2339        let restored: Person = agent_data.to_deserialize().unwrap();
2340        assert_eq!(restored, person);
2341    }
2342}