prompty 2.0.0-beta.3

Prompty is an asset class and format for LLM prompts
Documentation
// <auto-generated by typra-emitter>
// Code generated by Typra emitter; DO NOT EDIT.

#![allow(
    unused_imports,
    dead_code,
    non_camel_case_types,
    unused_variables,
    clippy::all
)]

use super::super::context::{LoadContext, SaveContext};

use super::checkpoint::Checkpoint;

use super::session_event::SessionEvent;

use super::session_file_ref::SessionFileRef;

use super::session_ref::SessionRef;

use super::session_summary::SessionSummary;

use super::trajectory_event::TrajectoryEvent;

use super::turn_trace::TurnTrace;

/// Portable replay container for an outer harness session.
#[derive(Debug, Clone, Default)]
pub struct SessionTrace {
    /// Trace schema version
    pub version: String,
    /// Runtime name that produced the trace
    pub runtime: Option<String>,
    /// Prompty library version that produced the trace
    pub prompty_version: Option<String>,
    /// Stable session identifier
    pub session_id: Option<String>,
    /// Recorded session events in emission order
    pub events: Vec<SessionEvent>,
    /// Recorded turn traces associated with the session
    pub turns: Vec<TurnTrace>,
    /// Checkpoints created during the session
    pub checkpoints: Vec<Checkpoint>,
    /// Compact trajectory records associated with the session
    pub trajectory: Vec<TrajectoryEvent>,
    /// Files observed or touched during the session
    pub files: Vec<SessionFileRef>,
    /// Non-file references observed during the session
    pub refs: Vec<SessionRef>,
    /// Optional summary computed from the event stream
    pub summary: Option<SessionSummary>,
}

impl SessionTrace {
    /// Create a new SessionTrace with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load SessionTrace from a JSON string.
    pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_str(json)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load SessionTrace from a YAML string.
    pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
        let value: serde_json::Value = serde_yaml::from_str(yaml)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load SessionTrace from a `serde_json::Value`.
    ///
    /// Calls `ctx.process_input` before field extraction.
    pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
        let value = ctx.process_input(value.clone());
        Self {
            version: value
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            runtime: value
                .get("runtime")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            prompty_version: value
                .get("promptyVersion")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            session_id: value
                .get("sessionId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            events: value
                .get("events")
                .map(|v| Self::load_events(v, ctx))
                .unwrap_or_default(),
            turns: value
                .get("turns")
                .map(|v| Self::load_turns(v, ctx))
                .unwrap_or_default(),
            checkpoints: value
                .get("checkpoints")
                .map(|v| Self::load_checkpoints(v, ctx))
                .unwrap_or_default(),
            trajectory: value
                .get("trajectory")
                .map(|v| Self::load_trajectory(v, ctx))
                .unwrap_or_default(),
            files: value
                .get("files")
                .map(|v| Self::load_files(v, ctx))
                .unwrap_or_default(),
            refs: value
                .get("refs")
                .map(|v| Self::load_refs(v, ctx))
                .unwrap_or_default(),
            summary: value
                .get("summary")
                .filter(|v| v.is_object() || v.is_array() || v.is_string())
                .map(|v| SessionSummary::load_from_value(v, ctx)),
        }
    }

    /// Serialize SessionTrace to a `serde_json::Value`.
    ///
    /// Calls `ctx.process_dict` after serialization.
    pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
        let mut result = serde_json::Map::new();
        // Write base fields
        if !self.version.is_empty() {
            result.insert(
                "version".to_string(),
                serde_json::Value::String(self.version.clone()),
            );
        }
        if let Some(ref val) = self.runtime {
            result.insert(
                "runtime".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if let Some(ref val) = self.prompty_version {
            result.insert(
                "promptyVersion".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if let Some(ref val) = self.session_id {
            result.insert(
                "sessionId".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if !self.events.is_empty() {
            result.insert("events".to_string(), Self::save_events(&self.events, ctx));
        }
        if !self.turns.is_empty() {
            result.insert("turns".to_string(), Self::save_turns(&self.turns, ctx));
        }
        if !self.checkpoints.is_empty() {
            result.insert(
                "checkpoints".to_string(),
                Self::save_checkpoints(&self.checkpoints, ctx),
            );
        }
        if !self.trajectory.is_empty() {
            result.insert(
                "trajectory".to_string(),
                Self::save_trajectory(&self.trajectory, ctx),
            );
        }
        if !self.files.is_empty() {
            result.insert("files".to_string(), Self::save_files(&self.files, ctx));
        }
        if !self.refs.is_empty() {
            result.insert("refs".to_string(), Self::save_refs(&self.refs, ctx));
        }
        if let Some(ref val) = self.summary {
            let nested = val.to_value(ctx);
            if !nested.is_null() {
                result.insert("summary".to_string(), nested);
            }
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize SessionTrace to a JSON string.
    pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_value(ctx))
    }

    /// Serialize SessionTrace to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }

    /// Load a collection of SessionEvent from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_events(data: &serde_json::Value, ctx: &LoadContext) -> Vec<SessionEvent> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| SessionEvent::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of SessionEvent to a JSON value.
    fn save_events(items: &[SessionEvent], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of TurnTrace from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_turns(data: &serde_json::Value, ctx: &LoadContext) -> Vec<TurnTrace> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| TurnTrace::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of TurnTrace to a JSON value.
    fn save_turns(items: &[TurnTrace], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of Checkpoint from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_checkpoints(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Checkpoint> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| Checkpoint::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of Checkpoint to a JSON value.
    fn save_checkpoints(items: &[Checkpoint], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of TrajectoryEvent from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_trajectory(data: &serde_json::Value, ctx: &LoadContext) -> Vec<TrajectoryEvent> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| TrajectoryEvent::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of TrajectoryEvent to a JSON value.
    fn save_trajectory(items: &[TrajectoryEvent], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of SessionFileRef from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_files(data: &serde_json::Value, ctx: &LoadContext) -> Vec<SessionFileRef> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| SessionFileRef::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of SessionFileRef to a JSON value.
    fn save_files(items: &[SessionFileRef], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of SessionRef from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_refs(data: &serde_json::Value, ctx: &LoadContext) -> Vec<SessionRef> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| SessionRef::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of SessionRef to a JSON value.
    fn save_refs(items: &[SessionRef], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }
}