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