agent_stream_kit/
data.rs

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