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.infer_type() {
216                        ValueType::Integer | ValueType::Float => ValueType::Number,
217                        other => other,
218                    };
219                    match kind {
220                        None => kind = Some(t),
221                        Some(k) if k == t => {}
222                        Some(_) => return ValueType::ArrayAny,
223                    }
224                }
225                match kind {
226                    Some(ValueType::String) => ValueType::ArrayString,
227                    Some(ValueType::Number) => ValueType::ArrayNumber,
228                    Some(ValueType::Boolean) => ValueType::ArrayBoolean,
229                    Some(ValueType::Object) => ValueType::ArrayObject,
230                    Some(ValueType::File) => ValueType::ArrayFile,
231                    _ => ValueType::ArrayAny,
232                }
233            }
234        }
235    }
236
237    pub fn is_null(&self) -> bool {
238        matches!(self, Value::Null)
239    }
240
241    pub fn as_str(&self) -> Option<&str> {
242        match self {
243            Value::String(s) => Some(s),
244            _ => None,
245        }
246    }
247
248    /// Raw string contents, including secrets. Use only where the plaintext is required
249    /// (e.g. an outgoing HTTP header), never for logging.
250    ///
251    /// Returns `None` for a redacted secret (see [`Value::redacted_secret`]).
252    pub fn expose_secret(&self) -> Option<&str> {
253        match self {
254            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => None,
255            Value::String(s) | Value::Secret(s) => Some(s),
256            _ => None,
257        }
258    }
259
260    /// Like [`Value::expose_secret`], but explains why the plaintext is unavailable.
261    /// Nodes that must transmit a secret should use this so a redacted secret fails
262    /// loudly instead of sending an empty or masked value.
263    pub fn require_secret(&self) -> Result<&str, SecretError> {
264        match self {
265            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => Err(SecretError::Redacted),
266            Value::String(s) | Value::Secret(s) => Ok(s),
267            other => Err(SecretError::NotText(other.type_name())),
268        }
269    }
270
271    /// A secret whose plaintext is not available (restored from a snapshot).
272    /// It renders masked, exposes nothing and fails [`Value::require_secret`].
273    pub fn redacted_secret() -> Value {
274        Value::Secret(Arc::from(REDACTED_SECRET))
275    }
276
277    /// Whether this is a [`Value::redacted_secret`].
278    pub fn is_redacted_secret(&self) -> bool {
279        matches!(self, Value::Secret(s) if s.as_ref() == REDACTED_SECRET)
280    }
281
282    /// Persistable form of this value: every secret (at any depth) becomes the
283    /// marker object `{"$secret": "redacted"}`, so neither plaintext nor a mask
284    /// string that could be mistaken for data is written to a snapshot.
285    pub fn to_snapshot_value(&self) -> Value {
286        match self {
287            Value::Secret(_) => Value::object([(SECRET_MARKER_KEY, Value::from("redacted"))]),
288            Value::Array(items) => Value::Array(Arc::new(items.iter().map(Value::to_snapshot_value).collect())),
289            Value::Object(map) => {
290                Value::Object(Arc::new(map.iter().map(|(k, v)| (k.clone(), v.to_snapshot_value())).collect()))
291            }
292            other => other.clone(),
293        }
294    }
295
296    /// Inverse of [`Value::to_snapshot_value`]: secret markers become redacted secrets.
297    pub fn from_snapshot_value(self) -> Value {
298        match self {
299            Value::Object(map) => {
300                if map.len() == 1 && map.contains_key(SECRET_MARKER_KEY) {
301                    return Value::redacted_secret();
302                }
303                let map = Arc::unwrap_or_clone(map);
304                Value::Object(Arc::new(map.into_iter().map(|(k, v)| (k, v.from_snapshot_value())).collect()))
305            }
306            Value::Array(items) => {
307                let items = Arc::unwrap_or_clone(items);
308                Value::Array(Arc::new(items.into_iter().map(Value::from_snapshot_value).collect()))
309            }
310            other => other,
311        }
312    }
313
314    pub fn as_bool(&self) -> Option<bool> {
315        match self {
316            Value::Bool(b) => Some(*b),
317            _ => None,
318        }
319    }
320
321    pub fn as_i64(&self) -> Option<i64> {
322        match self {
323            Value::Int(i) => Some(*i),
324            Value::Float(f) if f.fract() == 0.0 && f.is_finite() =>
325            {
326                #[allow(clippy::cast_possible_truncation)]
327                Some(*f as i64)
328            }
329            _ => None,
330        }
331    }
332
333    pub fn as_f64(&self) -> Option<f64> {
334        match self {
335            #[allow(clippy::cast_precision_loss)]
336            Value::Int(i) => Some(*i as f64),
337            Value::Float(f) => Some(*f),
338            _ => None,
339        }
340    }
341
342    pub fn as_array(&self) -> Option<&[Value]> {
343        match self {
344            Value::Array(a) => Some(a.as_slice()),
345            _ => None,
346        }
347    }
348
349    pub fn as_object(&self) -> Option<&Map> {
350        match self {
351            Value::Object(o) => Some(o),
352            _ => None,
353        }
354    }
355
356    pub fn as_file(&self) -> Option<&File> {
357        match self {
358            Value::File(f) => Some(f),
359            _ => None,
360        }
361    }
362
363    /// Whether the value is "empty" in the condition-operator sense.
364    pub fn is_empty(&self) -> bool {
365        match self {
366            Value::Null => true,
367            Value::String(s) | Value::Secret(s) => s.is_empty(),
368            Value::Array(a) => a.is_empty(),
369            Value::Object(o) => o.is_empty(),
370            _ => false,
371        }
372    }
373
374    /// Build an array value.
375    pub fn array(items: impl IntoIterator<Item = Value>) -> Value {
376        Value::Array(Arc::new(items.into_iter().collect()))
377    }
378
379    /// Build an object value.
380    pub fn object<K: Into<String>>(entries: impl IntoIterator<Item = (K, Value)>) -> Value {
381        Value::Object(Arc::new(entries.into_iter().map(|(k, v)| (k.into(), v)).collect()))
382    }
383
384    /// Descend into the value along a path. Objects are indexed by key, arrays by
385    /// decimal index (negative indexes count from the end), and files expose their
386    /// attributes. Returns `None` when any hop is missing.
387    pub fn get_path<S: AsRef<str>>(&self, path: &[S]) -> Option<Value> {
388        let mut current = self.clone();
389        for key in path {
390            let key = key.as_ref();
391            current = match &current {
392                Value::Object(map) => map.get(key)?.clone(),
393                Value::Array(items) => {
394                    if key == "length" || key == "len" {
395                        Value::Int(i64::try_from(items.len()).ok()?)
396                    } else {
397                        let idx: i64 = key.parse().ok()?;
398                        let len = i64::try_from(items.len()).ok()?;
399                        let idx = if idx < 0 { len + idx } else { idx };
400                        let idx = usize::try_from(idx).ok()?;
401                        items.get(idx)?.clone()
402                    }
403                }
404                Value::File(file) => file.attribute(key)?,
405                _ => return None,
406            };
407        }
408        Some(current)
409    }
410
411    /// Plain-text rendering used when a value is interpolated into a text template.
412    ///
413    /// Strings render raw, numbers and booleans in JSON form, objects/arrays as
414    /// compact JSON, files as their URL or name, null as empty text, and secrets
415    /// are masked.
416    pub fn to_text(&self) -> String {
417        match self {
418            Value::Null => String::new(),
419            Value::String(s) => s.to_string(),
420            Value::Secret(_) => SECRET_MASK.to_owned(),
421            Value::Bool(b) => b.to_string(),
422            Value::Int(i) => i.to_string(),
423            Value::Float(f) => format_float(*f),
424            Value::File(f) => f.url.clone().unwrap_or_else(|| f.name.clone()),
425            Value::Array(_) | Value::Object(_) => serde_json::to_string(self).unwrap_or_default(),
426        }
427    }
428
429    /// Like [`Value::to_text`], but reveals secrets. Only for nodes that must transmit
430    /// the plaintext (HTTP auth headers, code sandbox inputs).
431    /// A redacted secret renders as empty text.
432    pub fn to_text_exposed(&self) -> String {
433        match self {
434            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => String::new(),
435            Value::Secret(s) => s.to_string(),
436            other => other.to_text(),
437        }
438    }
439
440    /// Convert from an **untrusted** JSON value (HTTP bodies, tool results, model
441    /// output). Never creates [`Value::File`]: objects with a [`FILE_MARKER_KEY`]
442    /// stay plain objects, so remote data cannot forge file references.
443    pub fn from_json(json: serde_json::Value) -> Value {
444        json_to_value(json, false)
445    }
446
447    /// Convert from **trusted** JSON (snapshots, host-supplied inputs). Objects
448    /// carrying the [`FILE_MARKER_KEY`] that decode as a [`File`] become files.
449    /// The [`Deserialize`] impl of [`Value`] follows the same trusted rule.
450    pub fn from_json_trusted(json: serde_json::Value) -> Value {
451        json_to_value(json, true)
452    }
453}
454
455fn json_to_value(json: serde_json::Value, trusted: bool) -> Value {
456    {
457        match json {
458            serde_json::Value::Null => Value::Null,
459            serde_json::Value::Bool(b) => Value::Bool(b),
460            serde_json::Value::Number(n) => match n.as_i64() {
461                Some(i) => Value::Int(i),
462                None => Value::Float(n.as_f64().unwrap_or(f64::NAN)),
463            },
464            serde_json::Value::String(s) => Value::String(Arc::from(s)),
465            serde_json::Value::Array(items) => {
466                Value::Array(Arc::new(items.into_iter().map(|v| json_to_value(v, trusted)).collect()))
467            }
468            serde_json::Value::Object(map) => {
469                if trusted && map.contains_key(FILE_MARKER_KEY) {
470                    if let Ok(file) = serde_json::from_value::<File>(serde_json::Value::Object(map.clone())) {
471                        return Value::File(Arc::new(file));
472                    }
473                }
474                Value::Object(Arc::new(map.into_iter().map(|(k, v)| (k, json_to_value(v, trusted))).collect()))
475            }
476        }
477    }
478}
479
480impl Value {
481    /// Convert to a JSON value. Secrets are masked.
482    pub fn to_json(&self) -> serde_json::Value {
483        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
484    }
485
486    /// Convert to JSON revealing secrets. Only for trusted sinks such as a code sandbox.
487    /// A redacted secret becomes `null`.
488    pub fn to_json_exposed(&self) -> serde_json::Value {
489        match self {
490            Value::Secret(s) if s.as_ref() == REDACTED_SECRET => serde_json::Value::Null,
491            Value::Secret(s) => serde_json::Value::String(s.to_string()),
492            Value::Array(items) => serde_json::Value::Array(items.iter().map(Value::to_json_exposed).collect()),
493            Value::Object(map) => {
494                serde_json::Value::Object(map.iter().map(|(k, v)| (k.clone(), v.to_json_exposed())).collect())
495            }
496            other => other.to_json(),
497        }
498    }
499}
500
501fn format_float(f: f64) -> String {
502    if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e16 { format!("{f:.1}") } else { f.to_string() }
503}
504
505impl fmt::Debug for Value {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        match self {
508            Value::Null => f.write_str("Null"),
509            Value::Bool(b) => write!(f, "{b}"),
510            Value::Int(i) => write!(f, "{i}"),
511            Value::Float(x) => write!(f, "{x}"),
512            Value::String(s) => write!(f, "{s:?}"),
513            Value::Secret(_) => write!(f, "Secret({SECRET_MASK})"),
514            Value::Array(a) => f.debug_list().entries(a.iter()).finish(),
515            Value::Object(o) => f.debug_map().entries(o.iter()).finish(),
516            Value::File(file) => write!(f, "File({:?})", file.name),
517        }
518    }
519}
520
521impl From<&str> for Value {
522    fn from(s: &str) -> Self {
523        Value::String(Arc::from(s))
524    }
525}
526impl From<String> for Value {
527    fn from(s: String) -> Self {
528        Value::String(Arc::from(s))
529    }
530}
531impl From<bool> for Value {
532    fn from(b: bool) -> Self {
533        Value::Bool(b)
534    }
535}
536impl From<i64> for Value {
537    fn from(i: i64) -> Self {
538        Value::Int(i)
539    }
540}
541impl From<i32> for Value {
542    fn from(i: i32) -> Self {
543        Value::Int(i64::from(i))
544    }
545}
546impl From<f64> for Value {
547    fn from(f: f64) -> Self {
548        Value::Float(f)
549    }
550}
551impl From<Vec<Value>> for Value {
552    fn from(v: Vec<Value>) -> Self {
553        Value::Array(Arc::new(v))
554    }
555}
556impl From<Map> for Value {
557    fn from(m: Map) -> Self {
558        Value::Object(Arc::new(m))
559    }
560}
561impl From<File> for Value {
562    fn from(f: File) -> Self {
563        Value::File(Arc::new(f))
564    }
565}
566impl From<serde_json::Value> for Value {
567    fn from(v: serde_json::Value) -> Self {
568        Value::from_json(v)
569    }
570}
571
572impl Serialize for Value {
573    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
574        match self {
575            Value::Null => serializer.serialize_unit(),
576            Value::Bool(b) => serializer.serialize_bool(*b),
577            Value::Int(i) => serializer.serialize_i64(*i),
578            Value::Float(f) => serializer.serialize_f64(*f),
579            Value::String(s) => serializer.serialize_str(s),
580            Value::Secret(_) => serializer.serialize_str(SECRET_MASK),
581            Value::Array(items) => {
582                let mut seq = serializer.serialize_seq(Some(items.len()))?;
583                for item in items.iter() {
584                    seq.serialize_element(item)?;
585                }
586                seq.end()
587            }
588            Value::Object(map) => {
589                let mut m = serializer.serialize_map(Some(map.len()))?;
590                for (k, v) in map.iter() {
591                    m.serialize_entry(k, v)?;
592                }
593                m.end()
594            }
595            Value::File(file) => file.serialize(serializer),
596        }
597    }
598}
599
600impl<'de> Deserialize<'de> for Value {
601    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
602        deserializer.deserialize_any(ValueVisitor)
603    }
604}
605
606struct ValueVisitor;
607
608impl<'de> Visitor<'de> for ValueVisitor {
609    type Value = Value;
610
611    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612        f.write_str("any JSON-compatible value")
613    }
614    fn visit_unit<E: de::Error>(self) -> Result<Value, E> {
615        Ok(Value::Null)
616    }
617    fn visit_none<E: de::Error>(self) -> Result<Value, E> {
618        Ok(Value::Null)
619    }
620    fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
621        Value::deserialize(d)
622    }
623    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Value, E> {
624        Ok(Value::Bool(v))
625    }
626    fn visit_i64<E: de::Error>(self, v: i64) -> Result<Value, E> {
627        Ok(Value::Int(v))
628    }
629    fn visit_u64<E: de::Error>(self, v: u64) -> Result<Value, E> {
630        Ok(match i64::try_from(v) {
631            Ok(i) => Value::Int(i),
632            #[allow(clippy::cast_precision_loss)]
633            Err(_) => Value::Float(v as f64),
634        })
635    }
636    fn visit_f64<E: de::Error>(self, v: f64) -> Result<Value, E> {
637        Ok(Value::Float(v))
638    }
639    fn visit_str<E: de::Error>(self, v: &str) -> Result<Value, E> {
640        Ok(Value::from(v))
641    }
642    fn visit_string<E: de::Error>(self, v: String) -> Result<Value, E> {
643        Ok(Value::from(v))
644    }
645    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
646        let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
647        while let Some(v) = seq.next_element::<Value>()? {
648            out.push(v);
649        }
650        Ok(Value::Array(Arc::new(out)))
651    }
652    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
653        let mut map = Map::with_capacity(access.size_hint().unwrap_or(0));
654        while let Some((k, v)) = access.next_entry::<String, Value>()? {
655            map.insert(k, v);
656        }
657        if map.contains_key(FILE_MARKER_KEY) {
658            let json = Value::Object(Arc::new(map.clone())).to_json();
659            if let Ok(file) = serde_json::from_value::<File>(json) {
660                return Ok(Value::File(Arc::new(file)));
661            }
662        }
663        Ok(Value::Object(Arc::new(map)))
664    }
665}
666
667/// How a file's bytes are reachable. The runtime never reads file bytes itself;
668/// nodes that need content ask a host-provided resolver.
669#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
670#[serde(rename_all = "snake_case")]
671pub enum FileTransfer {
672    /// Publicly fetchable URL.
673    #[default]
674    RemoteUrl,
675    /// Host-managed storage, addressed by `reference`.
676    LocalFile,
677    /// Produced by a tool; addressed by `reference`.
678    ToolFile,
679    /// Inline data URL / base64 payload in `url`.
680    Inline,
681}
682
683/// Coarse file category used for routing (e.g. vision inputs).
684#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
685#[serde(rename_all = "snake_case")]
686pub enum FileKind {
687    Image,
688    Document,
689    Audio,
690    Video,
691    #[default]
692    Custom,
693}
694
695/// A reference to a file. Content is resolved by the host.
696#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
697pub struct File {
698    /// Always `true`; marks this object as a file when serialized to JSON.
699    #[serde(rename = "$file", default = "file_marker")]
700    pub marker: bool,
701    #[serde(default)]
702    pub id: Option<String>,
703    pub name: String,
704    #[serde(default)]
705    pub kind: FileKind,
706    #[serde(default)]
707    pub transfer: FileTransfer,
708    #[serde(default)]
709    pub url: Option<String>,
710    /// Opaque host storage key for `local_file` / `tool_file`.
711    #[serde(default)]
712    pub reference: Option<String>,
713    #[serde(default)]
714    pub mime_type: Option<String>,
715    #[serde(default)]
716    pub size: Option<u64>,
717    #[serde(default)]
718    pub extension: Option<String>,
719}
720
721fn file_marker() -> bool {
722    true
723}
724
725impl File {
726    /// Attribute lookup used by selectors and list/condition operators.
727    pub fn attribute(&self, key: &str) -> Option<Value> {
728        let opt = |s: &Option<String>| s.as_deref().map(Value::from).unwrap_or(Value::Null);
729        Some(match key {
730            "name" => Value::from(self.name.as_str()),
731            "type" | "kind" => Value::from(enum_name(&self.kind)),
732            "transfer_method" | "transfer" => Value::from(enum_name(&self.transfer)),
733            "url" => opt(&self.url),
734            "mime_type" => opt(&self.mime_type),
735            "extension" => opt(&self.extension),
736            "id" | "related_id" => opt(&self.id),
737            "reference" => opt(&self.reference),
738            "size" => self.size.and_then(|s| i64::try_from(s).ok()).map(Value::Int).unwrap_or(Value::Null),
739            _ => return None,
740        })
741    }
742}
743
744fn enum_name<T: Serialize>(v: &T) -> String {
745    match serde_json::to_value(v) {
746        Ok(serde_json::Value::String(s)) => s,
747        _ => String::new(),
748    }
749}
750
751#[cfg(test)]
752mod tests {
753    use super::*;
754
755    #[test]
756    fn integer_rejects_fractional_float() {
757        assert!(ValueType::Integer.coerce(Value::Float(1.5)).is_err());
758        assert_eq!(ValueType::Integer.coerce(Value::Float(3.0)), Ok(Value::Int(3)));
759    }
760
761    #[test]
762    fn number_rejects_bool() {
763        assert!(ValueType::Number.coerce(Value::Bool(true)).is_err());
764    }
765
766    #[test]
767    fn secret_is_masked_everywhere() {
768        let v = Value::Secret(Arc::from("sk-123"));
769        assert_eq!(v.to_text(), SECRET_MASK);
770        assert_eq!(serde_json::to_string(&v).ok().as_deref(), Some("\"******\""));
771        assert!(!format!("{v:?}").contains("sk-123"));
772        assert_eq!(v.expose_secret(), Some("sk-123"));
773    }
774
775    #[test]
776    fn path_supports_index_and_length() {
777        let v = Value::from_json(serde_json::json!({"a": [1, {"b": "x"}]}));
778        assert_eq!(v.get_path(&["a", "1", "b"]), Some(Value::from("x")));
779        assert_eq!(v.get_path(&["a", "-1", "b"]), Some(Value::from("x")));
780        assert_eq!(v.get_path(&["a", "length"]), Some(Value::Int(2)));
781        assert_eq!(v.get_path(&["a", "9"]), None);
782    }
783
784    #[test]
785    fn file_roundtrip_through_json() {
786        let f = File { marker: true, name: "a.png".into(), kind: FileKind::Image, ..File::default() };
787        let v = Value::from(f.clone());
788        let json = serde_json::to_value(&v).ok();
789        let back = json.clone().map(Value::from_json_trusted);
790        assert_eq!(back, Some(Value::File(Arc::new(f))));
791        // Untrusted JSON never forges files.
792        let untrusted = json.map(Value::from_json);
793        assert!(matches!(untrusted, Some(Value::Object(_))));
794    }
795
796    #[test]
797    fn secrets_survive_snapshot_form_as_redacted() {
798        let v = Value::object([("k", Value::Secret(Arc::from("sk-1"))), ("n", Value::Int(1))]);
799        let snap = v.to_snapshot_value();
800        let text = serde_json::to_string(&snap).unwrap();
801        assert!(!text.contains("sk-1"));
802        assert!(text.contains("\"$secret\""));
803        let back: Value = serde_json::from_str::<Value>(&text).unwrap().from_snapshot_value();
804        let k = back.get_path(&["k"]).unwrap();
805        assert!(k.is_redacted_secret());
806        assert_eq!(k.expose_secret(), None);
807        assert_eq!(k.require_secret(), Err(SecretError::Redacted));
808        assert_eq!(k.to_text(), SECRET_MASK);
809        assert_eq!(k.to_text_exposed(), "");
810        assert_eq!(back.get_path(&["n"]), Some(Value::Int(1)));
811    }
812
813    #[test]
814    fn infer_array_types() {
815        let v = Value::from_json(serde_json::json!([1, 2.5]));
816        assert_eq!(v.infer_type(), ValueType::ArrayNumber);
817        let v = Value::from_json(serde_json::json!([1, "a"]));
818        assert_eq!(v.infer_type(), ValueType::ArrayAny);
819    }
820
821    #[test]
822    fn text_rendering_is_json_like() {
823        assert_eq!(Value::Bool(true).to_text(), "true");
824        assert_eq!(Value::Float(1.0).to_text(), "1.0");
825        assert_eq!(Value::from_json(serde_json::json!(["a", 1])).to_text(), "[\"a\",1]");
826    }
827}