Skip to main content

graphrt_core/
value.rs

1//! Runtime values.
2//!
3//! [`Value`] is the single dynamic value type flowing through a workflow. Large
4//! payloads (strings, arrays, objects, files) are reference-counted, so cloning a
5//! value — and therefore cloning a [`crate::pool::VariablePool`] — is O(1) per
6//! entry instead of a deep copy.
7//!
8//! Secrets are a distinct variant. They render in plaintext only where a node
9//! explicitly asks for the raw value ([`Value::expose_secret`]); every
10//! serialization path (events, logs, snapshots) masks them.
11
12use std::fmt;
13use std::sync::Arc;
14
15use indexmap::IndexMap;
16use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
17use serde::ser::{SerializeMap, SerializeSeq, Serializer};
18use serde::{Deserialize, Serialize};
19
20/// Ordered string-keyed map used for object values.
21pub type Map = IndexMap<String, Value>;
22
23/// Marker key used to serialize [`File`] values as plain JSON objects.
24pub const FILE_MARKER_KEY: &str = "$file";
25
26/// Text shown instead of a secret's contents.
27pub const SECRET_MASK: &str = "******";
28
29/// Marker key used for secrets inside snapshots: `{"$secret": "redacted"}`.
30pub const SECRET_MARKER_KEY: &str = "$secret";
31
32/// Internal contents of a redacted secret (a secret whose plaintext was not
33/// persisted). Contains NUL bytes so it can never collide with a real value.
34const REDACTED_SECRET: &str = "\u{0}graphrt:redacted-secret\u{0}";
35
36/// Error returned when a secret's plaintext is required but unavailable.
37#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
38#[non_exhaustive]
39pub enum SecretError {
40    /// The secret was restored from a snapshot without its plaintext.
41    #[error("secret is not available after resume; re-supply it in the resume input")]
42    Redacted,
43    /// The value is not a string or secret.
44    #[error("expected a secret or string, got {0}")]
45    NotText(&'static str),
46}
47
48/// A dynamic runtime value.
49#[derive(Clone, Default, PartialEq)]
50pub enum Value {
51    /// Absent / null.
52    #[default]
53    Null,
54    Bool(bool),
55    Int(i64),
56    Float(f64),
57    String(Arc<str>),
58    /// A sensitive string. Never serialized in plaintext.
59    Secret(Arc<str>),
60    Array(Arc<Vec<Value>>),
61    Object(Arc<Map>),
62    File(Arc<File>),
63}
64
65/// Declared type of a variable. Wire names are stable and used in workflow documents.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
67pub enum ValueType {
68    #[serde(rename = "any")]
69    Any,
70    #[serde(rename = "none")]
71    Null,
72    #[serde(rename = "string", alias = "text-input", alias = "paragraph", alias = "select")]
73    String,
74    #[serde(rename = "secret")]
75    Secret,
76    #[serde(rename = "number")]
77    Number,
78    #[serde(rename = "integer")]
79    Integer,
80    #[serde(rename = "float")]
81    Float,
82    #[serde(rename = "boolean", alias = "checkbox")]
83    Boolean,
84    #[serde(rename = "object", alias = "json")]
85    Object,
86    #[serde(rename = "file")]
87    File,
88    #[serde(rename = "array[any]", alias = "array")]
89    ArrayAny,
90    #[serde(rename = "array[string]")]
91    ArrayString,
92    #[serde(rename = "array[number]")]
93    ArrayNumber,
94    #[serde(rename = "array[boolean]")]
95    ArrayBoolean,
96    #[serde(rename = "array[object]")]
97    ArrayObject,
98    #[serde(rename = "array[file]", alias = "file-list")]
99    ArrayFile,
100}
101
102/// Error returned when a value does not match a declared [`ValueType`].
103#[derive(Debug, Clone, PartialEq, thiserror::Error)]
104#[error("expected {expected:?}, got {actual}")]
105pub struct TypeMismatch {
106    pub expected: ValueType,
107    pub actual: &'static str,
108}
109
110impl ValueType {
111    /// Element type for array types, `None` for scalars.
112    pub fn element(self) -> Option<ValueType> {
113        match self {
114            ValueType::ArrayAny => Some(ValueType::Any),
115            ValueType::ArrayString => Some(ValueType::String),
116            ValueType::ArrayNumber => Some(ValueType::Number),
117            ValueType::ArrayBoolean => Some(ValueType::Boolean),
118            ValueType::ArrayObject => Some(ValueType::Object),
119            ValueType::ArrayFile => Some(ValueType::File),
120            _ => None,
121        }
122    }
123
124    /// Whether this is one of the `array[...]` types.
125    pub fn is_array(self) -> bool {
126        self.element().is_some()
127    }
128
129    /// Zero value used when a typed variable has no explicit value.
130    pub fn zero(self) -> Value {
131        match self {
132            ValueType::String => Value::from(""),
133            ValueType::Secret => Value::Secret(Arc::from("")),
134            ValueType::Number | ValueType::Integer => Value::Int(0),
135            ValueType::Float => Value::Float(0.0),
136            ValueType::Boolean => Value::Bool(false),
137            ValueType::Object => Value::Object(Arc::default()),
138            t if t.is_array() => Value::Array(Arc::default()),
139            _ => Value::Null,
140        }
141    }
142
143    /// Check `value` against this type and apply the only lossless coercions
144    /// allowed: integer -> float for `float`, string -> secret for `secret`.
145    /// Integers never silently absorb fractional floats.
146    pub fn coerce(self, value: Value) -> Result<Value, TypeMismatch> {
147        let mismatch = |v: &Value| TypeMismatch { expected: self, actual: v.type_name() };
148        match (self, value) {
149            (ValueType::Any, v) => Ok(v),
150            (_, Value::Null) => Ok(Value::Null),
151            (ValueType::String, v @ Value::String(_)) => Ok(v),
152            (ValueType::Secret, Value::String(s) | Value::Secret(s)) => Ok(Value::Secret(s)),
153            (ValueType::Number, v @ (Value::Int(_) | Value::Float(_))) => Ok(v),
154            (ValueType::Integer, v @ Value::Int(_)) => Ok(v),
155            (ValueType::Integer, Value::Float(f)) if f.fract() == 0.0 && f.is_finite() => {
156                // Exact whole floats (e.g. `3.0` from JSON) are accepted; fractional ones are not.
157                #[allow(clippy::cast_possible_truncation)]
158                Ok(Value::Int(f as i64))
159            }
160            #[allow(clippy::cast_precision_loss)]
161            (ValueType::Float, Value::Int(i)) => Ok(Value::Float(i as f64)),
162            (ValueType::Float, v @ Value::Float(_)) => Ok(v),
163            (ValueType::Boolean, v @ Value::Bool(_)) => Ok(v),
164            (ValueType::Object, v @ Value::Object(_)) => Ok(v),
165            (ValueType::File, v @ Value::File(_)) => Ok(v),
166            (t, Value::Array(items)) if t.is_array() => {
167                let elem = t.element().unwrap_or(ValueType::Any);
168                if elem == ValueType::Any {
169                    return Ok(Value::Array(items));
170                }
171                let mut out = Vec::with_capacity(items.len());
172                for item in items.iter() {
173                    match elem.coerce(item.clone()) {
174                        Ok(v) => out.push(v),
175                        Err(_) => return Err(TypeMismatch { expected: self, actual: "array with mismatched element" }),
176                    }
177                }
178                Ok(Value::Array(Arc::new(out)))
179            }
180            (_, v) => Err(mismatch(&v)),
181        }
182    }
183}
184
185impl Value {
186    /// Short type name used in error messages.
187    pub fn type_name(&self) -> &'static str {
188        match self {
189            Value::Null => "null",
190            Value::Bool(_) => "boolean",
191            Value::Int(_) => "integer",
192            Value::Float(_) => "float",
193            Value::String(_) => "string",
194            Value::Secret(_) => "secret",
195            Value::Array(_) => "array",
196            Value::Object(_) => "object",
197            Value::File(_) => "file",
198        }
199    }
200
201    /// Infer the most specific declared type for this value.
202    pub fn infer_type(&self) -> ValueType {
203        match self {
204            Value::Null => ValueType::Null,
205            Value::Bool(_) => ValueType::Boolean,
206            Value::Int(_) => ValueType::Integer,
207            Value::Float(_) => ValueType::Float,
208            Value::String(_) => ValueType::String,
209            Value::Secret(_) => ValueType::Secret,
210            Value::Object(_) => ValueType::Object,
211            Value::File(_) => ValueType::File,
212            Value::Array(items) => {
213                let mut kind: Option<ValueType> = None;
214                for item in items.iter() {
215                    let t = match item {
216                        // Any nested array makes this an `ArrayAny`, so its own
217                        // elements need not be visited. Recursing here was
218                        // exponential on arrays that share themselves through
219                        // `Arc` (a loop appending a variable to itself).
220                        Value::Array(_) => return ValueType::ArrayAny,
221                        Value::Int(_) | Value::Float(_) => ValueType::Number,
222                        scalar => scalar.infer_type(),
223                    };
224                    match kind {
225                        None => kind = Some(t),
226                        Some(k) if k == t => {}
227                        Some(_) => return ValueType::ArrayAny,
228                    }
229                }
230                match kind {
231                    Some(ValueType::String) => ValueType::ArrayString,
232                    Some(ValueType::Number) => ValueType::ArrayNumber,
233                    Some(ValueType::Boolean) => ValueType::ArrayBoolean,
234                    Some(ValueType::Object) => ValueType::ArrayObject,
235                    Some(ValueType::File) => ValueType::ArrayFile,
236                    _ => ValueType::ArrayAny,
237                }
238            }
239        }
240    }
241
242    /// Whether this value holds at most `max_nodes` values in total (itself
243    /// included) and nests at most `max_depth` levels below itself (`[1]` is one
244    /// level, `[[1]]` two; empty containers do not add a level).
245    ///
246    /// Arrays and objects are reference-counted, so a value can share one child
247    /// many times: a loop that appends a variable to itself doubles its logical
248    /// size every round while its memory barely grows, and serializing it is
249    /// then exponential. The walk stops as soon as a limit is crossed, so it
250    /// costs at most `max_nodes` steps, and it uses no recursion.
251    pub fn fits_shape(&self, max_nodes: usize, max_depth: usize) -> bool {
252        let mut pending: Vec<(&Value, usize)> = vec![(self, 0)];
253        // Values seen so far, counted when queued so the queue stays bounded too.
254        let mut seen = 1usize;
255        while let Some((value, depth)) = pending.pop() {
256            let children = match value {
257                Value::Array(items) => items.len(),
258                Value::Object(map) => map.len(),
259                _ => continue,
260            };
261            if children == 0 {
262                continue;
263            }
264            seen = seen.saturating_add(children);
265            if seen > max_nodes || depth >= max_depth {
266                return false;
267            }
268            match value {
269                Value::Array(items) => pending.extend(items.iter().map(|item| (item, depth + 1))),
270                Value::Object(map) => pending.extend(map.values().map(|item| (item, depth + 1))),
271                _ => {}
272            }
273        }
274        seen <= max_nodes
275    }
276
277    pub fn is_null(&self) -> bool {
278        matches!(self, Value::Null)
279    }
280
281    pub fn as_str(&self) -> Option<&str> {
282        match self {
283            Value::String(s) => Some(s),
284            _ => None,
285        }
286    }
287
288    /// Raw string contents, including secrets. Use only where the plaintext is required
289    /// (e.g. an outgoing HTTP header), never for logging.
290    ///
291    /// Returns `None` for a redacted secret (see [`Value::redacted_secret`]).
292    pub fn expose_secret(&self) -> Option<&str> {
293        match self {
294            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => None,
295            Value::String(s) | Value::Secret(s) => Some(s),
296            _ => None,
297        }
298    }
299
300    /// Like [`Value::expose_secret`], but explains why the plaintext is unavailable.
301    /// Nodes that must transmit a secret should use this so a redacted secret fails
302    /// loudly instead of sending an empty or masked value.
303    pub fn require_secret(&self) -> Result<&str, SecretError> {
304        match self {
305            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => Err(SecretError::Redacted),
306            Value::String(s) | Value::Secret(s) => Ok(s),
307            other => Err(SecretError::NotText(other.type_name())),
308        }
309    }
310
311    /// A secret whose plaintext is not available (restored from a snapshot).
312    /// It renders masked, exposes nothing and fails [`Value::require_secret`].
313    pub fn redacted_secret() -> Value {
314        Value::Secret(Arc::from(REDACTED_SECRET))
315    }
316
317    /// Whether this is a [`Value::redacted_secret`].
318    pub fn is_redacted_secret(&self) -> bool {
319        matches!(self, Value::Secret(s) if s.as_ref() == REDACTED_SECRET)
320    }
321
322    /// Persistable form of this value: every secret (at any depth) becomes the
323    /// marker object `{"$secret": "redacted"}`, so neither plaintext nor a mask
324    /// string that could be mistaken for data is written to a snapshot.
325    pub fn to_snapshot_value(&self) -> Value {
326        match self {
327            Value::Secret(_) => Value::object([(SECRET_MARKER_KEY, Value::from("redacted"))]),
328            Value::Array(items) => Value::Array(Arc::new(items.iter().map(Value::to_snapshot_value).collect())),
329            Value::Object(map) => {
330                Value::Object(Arc::new(map.iter().map(|(k, v)| (k.clone(), v.to_snapshot_value())).collect()))
331            }
332            other => other.clone(),
333        }
334    }
335
336    /// Inverse of [`Value::to_snapshot_value`]: secret markers become redacted secrets.
337    pub fn from_snapshot_value(self) -> Value {
338        match self {
339            Value::Object(map) => {
340                if map.len() == 1 && map.contains_key(SECRET_MARKER_KEY) {
341                    return Value::redacted_secret();
342                }
343                let map = Arc::unwrap_or_clone(map);
344                Value::Object(Arc::new(map.into_iter().map(|(k, v)| (k, v.from_snapshot_value())).collect()))
345            }
346            Value::Array(items) => {
347                let items = Arc::unwrap_or_clone(items);
348                Value::Array(Arc::new(items.into_iter().map(Value::from_snapshot_value).collect()))
349            }
350            other => other,
351        }
352    }
353
354    pub fn as_bool(&self) -> Option<bool> {
355        match self {
356            Value::Bool(b) => Some(*b),
357            _ => None,
358        }
359    }
360
361    pub fn as_i64(&self) -> Option<i64> {
362        match self {
363            Value::Int(i) => Some(*i),
364            Value::Float(f) if f.fract() == 0.0 && f.is_finite() =>
365            {
366                #[allow(clippy::cast_possible_truncation)]
367                Some(*f as i64)
368            }
369            _ => None,
370        }
371    }
372
373    pub fn as_f64(&self) -> Option<f64> {
374        match self {
375            #[allow(clippy::cast_precision_loss)]
376            Value::Int(i) => Some(*i as f64),
377            Value::Float(f) => Some(*f),
378            _ => None,
379        }
380    }
381
382    pub fn as_array(&self) -> Option<&[Value]> {
383        match self {
384            Value::Array(a) => Some(a.as_slice()),
385            _ => None,
386        }
387    }
388
389    pub fn as_object(&self) -> Option<&Map> {
390        match self {
391            Value::Object(o) => Some(o),
392            _ => None,
393        }
394    }
395
396    pub fn as_file(&self) -> Option<&File> {
397        match self {
398            Value::File(f) => Some(f),
399            _ => None,
400        }
401    }
402
403    /// Whether the value is "empty" in the condition-operator sense.
404    pub fn is_empty(&self) -> bool {
405        match self {
406            Value::Null => true,
407            Value::String(s) | Value::Secret(s) => s.is_empty(),
408            Value::Array(a) => a.is_empty(),
409            Value::Object(o) => o.is_empty(),
410            _ => false,
411        }
412    }
413
414    /// Build an array value.
415    pub fn array(items: impl IntoIterator<Item = Value>) -> Value {
416        Value::Array(Arc::new(items.into_iter().collect()))
417    }
418
419    /// Build an object value.
420    pub fn object<K: Into<String>>(entries: impl IntoIterator<Item = (K, Value)>) -> Value {
421        Value::Object(Arc::new(entries.into_iter().map(|(k, v)| (k.into(), v)).collect()))
422    }
423
424    /// Descend into the value along a path. Objects are indexed by key, arrays by
425    /// decimal index (negative indexes count from the end), and files expose their
426    /// attributes. Returns `None` when any hop is missing.
427    pub fn get_path<S: AsRef<str>>(&self, path: &[S]) -> Option<Value> {
428        let mut current = self.clone();
429        for key in path {
430            let key = key.as_ref();
431            current = match &current {
432                Value::Object(map) => map.get(key)?.clone(),
433                Value::Array(items) => {
434                    if key == "length" || key == "len" {
435                        Value::Int(i64::try_from(items.len()).ok()?)
436                    } else {
437                        let idx: i64 = key.parse().ok()?;
438                        let len = i64::try_from(items.len()).ok()?;
439                        let idx = if idx < 0 { len + idx } else { idx };
440                        let idx = usize::try_from(idx).ok()?;
441                        items.get(idx)?.clone()
442                    }
443                }
444                Value::File(file) => file.attribute(key)?,
445                _ => return None,
446            };
447        }
448        Some(current)
449    }
450
451    /// Plain-text rendering used when a value is interpolated into a text template.
452    ///
453    /// Strings render raw, numbers and booleans in JSON form, objects/arrays as
454    /// compact JSON, files as their URL or name, null as empty text, and secrets
455    /// are masked.
456    pub fn to_text(&self) -> String {
457        match self {
458            Value::Null => String::new(),
459            Value::String(s) => s.to_string(),
460            Value::Secret(_) => SECRET_MASK.to_owned(),
461            Value::Bool(b) => b.to_string(),
462            Value::Int(i) => i.to_string(),
463            Value::Float(f) => format_float(*f),
464            Value::File(f) => f.url.clone().unwrap_or_else(|| f.name.clone()),
465            Value::Array(_) | Value::Object(_) => serde_json::to_string(self).unwrap_or_default(),
466        }
467    }
468
469    /// Like [`Value::to_text`], but reveals secrets. Only for nodes that must transmit
470    /// the plaintext (HTTP auth headers, code sandbox inputs).
471    /// A redacted secret renders as empty text.
472    pub fn to_text_exposed(&self) -> String {
473        match self {
474            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => String::new(),
475            Value::Secret(s) => s.to_string(),
476            other => other.to_text(),
477        }
478    }
479
480    /// Convert from an **untrusted** JSON value (HTTP bodies, tool results, model
481    /// output). Never creates [`Value::File`]: objects with a [`FILE_MARKER_KEY`]
482    /// stay plain objects, so remote data cannot forge file references.
483    pub fn from_json(json: serde_json::Value) -> Value {
484        json_to_value(json, false)
485    }
486
487    /// Convert from **trusted** JSON (snapshots, host-supplied inputs). Objects
488    /// carrying the [`FILE_MARKER_KEY`] that decode as a [`File`] become files.
489    /// The [`Deserialize`] impl of [`Value`] follows the same trusted rule.
490    pub fn from_json_trusted(json: serde_json::Value) -> Value {
491        json_to_value(json, true)
492    }
493}
494
495fn json_to_value(json: serde_json::Value, trusted: bool) -> Value {
496    {
497        match json {
498            serde_json::Value::Null => Value::Null,
499            serde_json::Value::Bool(b) => Value::Bool(b),
500            serde_json::Value::Number(n) => match n.as_i64() {
501                Some(i) => Value::Int(i),
502                None => Value::Float(n.as_f64().unwrap_or(f64::NAN)),
503            },
504            serde_json::Value::String(s) => Value::String(Arc::from(s)),
505            serde_json::Value::Array(items) => {
506                Value::Array(Arc::new(items.into_iter().map(|v| json_to_value(v, trusted)).collect()))
507            }
508            serde_json::Value::Object(map) => {
509                if trusted
510                    && map.contains_key(FILE_MARKER_KEY)
511                    && let Ok(file) = serde_json::from_value::<File>(serde_json::Value::Object(map.clone()))
512                {
513                    return Value::File(Arc::new(file));
514                }
515                Value::Object(Arc::new(map.into_iter().map(|(k, v)| (k, json_to_value(v, trusted))).collect()))
516            }
517        }
518    }
519}
520
521impl Value {
522    /// Convert to a JSON value. Secrets are masked.
523    pub fn to_json(&self) -> serde_json::Value {
524        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
525    }
526
527    /// Convert to JSON revealing secrets. Only for trusted sinks such as a code sandbox.
528    /// A redacted secret becomes `null`.
529    pub fn to_json_exposed(&self) -> serde_json::Value {
530        match self {
531            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => serde_json::Value::Null,
532            Value::Secret(s) => serde_json::Value::String(s.to_string()),
533            Value::Array(items) => serde_json::Value::Array(items.iter().map(Value::to_json_exposed).collect()),
534            Value::Object(map) => {
535                serde_json::Value::Object(map.iter().map(|(k, v)| (k.clone(), v.to_json_exposed())).collect())
536            }
537            other => other.to_json(),
538        }
539    }
540}
541
542fn format_float(f: f64) -> String {
543    if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e16 { format!("{f:.1}") } else { f.to_string() }
544}
545
546impl fmt::Debug for Value {
547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548        match self {
549            Value::Null => f.write_str("Null"),
550            Value::Bool(b) => write!(f, "{b}"),
551            Value::Int(i) => write!(f, "{i}"),
552            Value::Float(x) => write!(f, "{x}"),
553            Value::String(s) => write!(f, "{s:?}"),
554            Value::Secret(_) => write!(f, "Secret({SECRET_MASK})"),
555            Value::Array(a) => f.debug_list().entries(a.iter()).finish(),
556            Value::Object(o) => f.debug_map().entries(o.iter()).finish(),
557            Value::File(file) => write!(f, "File({:?})", file.name),
558        }
559    }
560}
561
562impl From<&str> for Value {
563    fn from(s: &str) -> Self {
564        Value::String(Arc::from(s))
565    }
566}
567impl From<String> for Value {
568    fn from(s: String) -> Self {
569        Value::String(Arc::from(s))
570    }
571}
572impl From<bool> for Value {
573    fn from(b: bool) -> Self {
574        Value::Bool(b)
575    }
576}
577impl From<i64> for Value {
578    fn from(i: i64) -> Self {
579        Value::Int(i)
580    }
581}
582impl From<i32> for Value {
583    fn from(i: i32) -> Self {
584        Value::Int(i64::from(i))
585    }
586}
587impl From<f64> for Value {
588    fn from(f: f64) -> Self {
589        Value::Float(f)
590    }
591}
592impl From<Vec<Value>> for Value {
593    fn from(v: Vec<Value>) -> Self {
594        Value::Array(Arc::new(v))
595    }
596}
597impl From<Map> for Value {
598    fn from(m: Map) -> Self {
599        Value::Object(Arc::new(m))
600    }
601}
602impl From<File> for Value {
603    fn from(f: File) -> Self {
604        Value::File(Arc::new(f))
605    }
606}
607impl From<serde_json::Value> for Value {
608    fn from(v: serde_json::Value) -> Self {
609        Value::from_json(v)
610    }
611}
612
613impl Serialize for Value {
614    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
615        match self {
616            Value::Null => serializer.serialize_unit(),
617            Value::Bool(b) => serializer.serialize_bool(*b),
618            Value::Int(i) => serializer.serialize_i64(*i),
619            Value::Float(f) => serializer.serialize_f64(*f),
620            Value::String(s) => serializer.serialize_str(s),
621            Value::Secret(_) => serializer.serialize_str(SECRET_MASK),
622            Value::Array(items) => {
623                let mut seq = serializer.serialize_seq(Some(items.len()))?;
624                for item in items.iter() {
625                    seq.serialize_element(item)?;
626                }
627                seq.end()
628            }
629            Value::Object(map) => {
630                let mut m = serializer.serialize_map(Some(map.len()))?;
631                for (k, v) in map.iter() {
632                    m.serialize_entry(k, v)?;
633                }
634                m.end()
635            }
636            Value::File(file) => file.serialize(serializer),
637        }
638    }
639}
640
641impl<'de> Deserialize<'de> for Value {
642    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
643        deserializer.deserialize_any(ValueVisitor)
644    }
645}
646
647struct ValueVisitor;
648
649impl<'de> Visitor<'de> for ValueVisitor {
650    type Value = Value;
651
652    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653        f.write_str("any JSON-compatible value")
654    }
655    fn visit_unit<E: de::Error>(self) -> Result<Value, E> {
656        Ok(Value::Null)
657    }
658    fn visit_none<E: de::Error>(self) -> Result<Value, E> {
659        Ok(Value::Null)
660    }
661    fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
662        Value::deserialize(d)
663    }
664    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Value, E> {
665        Ok(Value::Bool(v))
666    }
667    fn visit_i64<E: de::Error>(self, v: i64) -> Result<Value, E> {
668        Ok(Value::Int(v))
669    }
670    fn visit_u64<E: de::Error>(self, v: u64) -> Result<Value, E> {
671        Ok(match i64::try_from(v) {
672            Ok(i) => Value::Int(i),
673            #[allow(clippy::cast_precision_loss)]
674            Err(_) => Value::Float(v as f64),
675        })
676    }
677    fn visit_f64<E: de::Error>(self, v: f64) -> Result<Value, E> {
678        Ok(Value::Float(v))
679    }
680    fn visit_str<E: de::Error>(self, v: &str) -> Result<Value, E> {
681        Ok(Value::from(v))
682    }
683    fn visit_string<E: de::Error>(self, v: String) -> Result<Value, E> {
684        Ok(Value::from(v))
685    }
686    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
687        let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
688        while let Some(v) = seq.next_element::<Value>()? {
689            out.push(v);
690        }
691        Ok(Value::Array(Arc::new(out)))
692    }
693    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
694        let mut map = Map::with_capacity(access.size_hint().unwrap_or(0));
695        while let Some((k, v)) = access.next_entry::<String, Value>()? {
696            map.insert(k, v);
697        }
698        if map.contains_key(FILE_MARKER_KEY) {
699            let json = Value::Object(Arc::new(map.clone())).to_json();
700            if let Ok(file) = serde_json::from_value::<File>(json) {
701                return Ok(Value::File(Arc::new(file)));
702            }
703        }
704        Ok(Value::Object(Arc::new(map)))
705    }
706}
707
708/// How a file's bytes are reachable. The runtime never reads file bytes itself;
709/// nodes that need content ask a host-provided resolver.
710#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
711#[serde(rename_all = "snake_case")]
712pub enum FileTransfer {
713    /// Publicly fetchable URL.
714    #[default]
715    RemoteUrl,
716    /// Host-managed storage, addressed by `reference`.
717    LocalFile,
718    /// Produced by a tool; addressed by `reference`.
719    ToolFile,
720    /// Inline data URL / base64 payload in `url`.
721    Inline,
722}
723
724/// Coarse file category used for routing (e.g. vision inputs).
725#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
726#[serde(rename_all = "snake_case")]
727pub enum FileKind {
728    Image,
729    Document,
730    Audio,
731    Video,
732    #[default]
733    Custom,
734}
735
736/// A reference to a file. Content is resolved by the host.
737#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
738pub struct File {
739    /// Always `true`; marks this object as a file when serialized to JSON.
740    #[serde(rename = "$file", default = "file_marker")]
741    pub marker: bool,
742    #[serde(default)]
743    pub id: Option<String>,
744    pub name: String,
745    #[serde(default)]
746    pub kind: FileKind,
747    #[serde(default)]
748    pub transfer: FileTransfer,
749    #[serde(default)]
750    pub url: Option<String>,
751    /// Opaque host storage key for `local_file` / `tool_file`.
752    #[serde(default)]
753    pub reference: Option<String>,
754    #[serde(default)]
755    pub mime_type: Option<String>,
756    #[serde(default)]
757    pub size: Option<u64>,
758    #[serde(default)]
759    pub extension: Option<String>,
760}
761
762fn file_marker() -> bool {
763    true
764}
765
766impl File {
767    /// Attribute lookup used by selectors and list/condition operators.
768    pub fn attribute(&self, key: &str) -> Option<Value> {
769        let opt = |s: &Option<String>| s.as_deref().map(Value::from).unwrap_or(Value::Null);
770        Some(match key {
771            "name" => Value::from(self.name.as_str()),
772            "type" | "kind" => Value::from(enum_name(&self.kind)),
773            "transfer_method" | "transfer" => Value::from(enum_name(&self.transfer)),
774            "url" => opt(&self.url),
775            "mime_type" => opt(&self.mime_type),
776            "extension" => opt(&self.extension),
777            "id" | "related_id" => opt(&self.id),
778            "reference" => opt(&self.reference),
779            "size" => self.size.and_then(|s| i64::try_from(s).ok()).map(Value::Int).unwrap_or(Value::Null),
780            _ => return None,
781        })
782    }
783}
784
785fn enum_name<T: Serialize>(v: &T) -> String {
786    match serde_json::to_value(v) {
787        Ok(serde_json::Value::String(s)) => s,
788        _ => String::new(),
789    }
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795
796    /// An array that contains itself `rounds` times over: logically 2^rounds
797    /// values, in O(rounds) memory.
798    fn self_sharing_array(rounds: usize) -> Value {
799        let mut value = Value::array(Vec::new());
800        for _ in 0..rounds {
801            let mut items = value.as_array().map(<[Value]>::to_vec).unwrap_or_default();
802            items.push(value.clone());
803            value = Value::array(items);
804        }
805        value
806    }
807
808    #[test]
809    fn infer_type_does_not_walk_nested_arrays() {
810        // 2^200 logical values: finishes only if nested arrays are not visited.
811        let shared = self_sharing_array(200);
812        assert_eq!(shared.infer_type(), ValueType::ArrayAny);
813        assert_eq!(Value::from_json(serde_json::json!([[1], [2]])).infer_type(), ValueType::ArrayAny);
814        assert_eq!(Value::from_json(serde_json::json!([1, 2.5])).infer_type(), ValueType::ArrayNumber);
815        assert_eq!(Value::from_json(serde_json::json!([{"a": 1}])).infer_type(), ValueType::ArrayObject);
816    }
817
818    #[test]
819    fn fits_shape_counts_values_and_depth() {
820        let value = Value::from_json(serde_json::json!({"a": [1, 2], "b": {"c": []}}));
821        // root, a, 1, 2, b, c
822        assert!(value.fits_shape(6, 2));
823        assert!(!value.fits_shape(5, 2));
824        assert!(!value.fits_shape(6, 1));
825        assert!(Value::Int(1).fits_shape(1, 0));
826        assert!(Value::array(Vec::new()).fits_shape(1, 0));
827    }
828
829    #[test]
830    fn fits_shape_stops_early_on_shared_values() {
831        assert!(!self_sharing_array(200).fits_shape(1_000_000, 1_000));
832        let mut deep = Value::Int(0);
833        for _ in 0..100_000 {
834            deep = Value::array(vec![deep]);
835        }
836        assert!(!deep.fits_shape(usize::MAX, 128));
837        assert!(deep.fits_shape(usize::MAX, 100_000));
838        // Dropping 100k nested `Arc`s recursively would overflow the stack; take
839        // it apart iteratively.
840        while let Value::Array(items) = deep {
841            deep = Arc::try_unwrap(items).ok().and_then(|mut v| v.pop()).unwrap_or(Value::Null);
842        }
843    }
844
845    #[test]
846    fn integer_rejects_fractional_float() {
847        assert!(ValueType::Integer.coerce(Value::Float(1.5)).is_err());
848        assert_eq!(ValueType::Integer.coerce(Value::Float(3.0)), Ok(Value::Int(3)));
849    }
850
851    #[test]
852    fn number_rejects_bool() {
853        assert!(ValueType::Number.coerce(Value::Bool(true)).is_err());
854    }
855
856    #[test]
857    fn secret_is_masked_everywhere() {
858        let v = Value::Secret(Arc::from("sk-123"));
859        assert_eq!(v.to_text(), SECRET_MASK);
860        assert_eq!(serde_json::to_string(&v).ok().as_deref(), Some("\"******\""));
861        assert!(!format!("{v:?}").contains("sk-123"));
862        assert_eq!(v.expose_secret(), Some("sk-123"));
863    }
864
865    #[test]
866    fn path_supports_index_and_length() {
867        let v = Value::from_json(serde_json::json!({"a": [1, {"b": "x"}]}));
868        assert_eq!(v.get_path(&["a", "1", "b"]), Some(Value::from("x")));
869        assert_eq!(v.get_path(&["a", "-1", "b"]), Some(Value::from("x")));
870        assert_eq!(v.get_path(&["a", "length"]), Some(Value::Int(2)));
871        assert_eq!(v.get_path(&["a", "9"]), None);
872    }
873
874    #[test]
875    fn file_roundtrip_through_json() {
876        let f = File { marker: true, name: "a.png".into(), kind: FileKind::Image, ..File::default() };
877        let v = Value::from(f.clone());
878        let json = serde_json::to_value(&v).ok();
879        let back = json.clone().map(Value::from_json_trusted);
880        assert_eq!(back, Some(Value::File(Arc::new(f))));
881        // Untrusted JSON never forges files.
882        let untrusted = json.map(Value::from_json);
883        assert!(matches!(untrusted, Some(Value::Object(_))));
884    }
885
886    #[test]
887    fn secrets_survive_snapshot_form_as_redacted() {
888        let v = Value::object([("k", Value::Secret(Arc::from("sk-1"))), ("n", Value::Int(1))]);
889        let snap = v.to_snapshot_value();
890        let text = serde_json::to_string(&snap).unwrap();
891        assert!(!text.contains("sk-1"));
892        assert!(text.contains("\"$secret\""));
893        let back: Value = serde_json::from_str::<Value>(&text).unwrap().from_snapshot_value();
894        let k = back.get_path(&["k"]).unwrap();
895        assert!(k.is_redacted_secret());
896        assert_eq!(k.expose_secret(), None);
897        assert_eq!(k.require_secret(), Err(SecretError::Redacted));
898        assert_eq!(k.to_text(), SECRET_MASK);
899        assert_eq!(k.to_text_exposed(), "");
900        assert_eq!(back.get_path(&["n"]), Some(Value::Int(1)));
901    }
902
903    #[test]
904    fn infer_array_types() {
905        let v = Value::from_json(serde_json::json!([1, 2.5]));
906        assert_eq!(v.infer_type(), ValueType::ArrayNumber);
907        let v = Value::from_json(serde_json::json!([1, "a"]));
908        assert_eq!(v.infer_type(), ValueType::ArrayAny);
909    }
910
911    #[test]
912    fn text_rendering_is_json_like() {
913        assert_eq!(Value::Bool(true).to_text(), "true");
914        assert_eq!(Value::Float(1.0).to_text(), "1.0");
915        assert_eq!(Value::from_json(serde_json::json!(["a", 1])).to_text(), "[\"a\",1]");
916    }
917}