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::redaction_metadata::RedactionMetadata;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SessionEventType {
    Session_start,
    Session_end,
    Session_warning,
    Session_hook_start,
    Session_hook_end,
    Checkpoint_created,
    Trajectory_event,
}

impl Default for SessionEventType {
    fn default() -> Self {
        Self::Session_start
    }
}

impl std::fmt::Display for SessionEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Session_start => write!(f, "session_start"),
            Self::Session_end => write!(f, "session_end"),
            Self::Session_warning => write!(f, "session_warning"),
            Self::Session_hook_start => write!(f, "session_hook_start"),
            Self::Session_hook_end => write!(f, "session_hook_end"),
            Self::Checkpoint_created => write!(f, "checkpoint_created"),
            Self::Trajectory_event => write!(f, "trajectory_event"),
        }
    }
}

impl SessionEventType {
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "session_start" => Some(Self::Session_start),
            "session_end" => Some(Self::Session_end),
            "session_warning" => Some(Self::Session_warning),
            "session_hook_start" => Some(Self::Session_hook_start),
            "session_hook_end" => Some(Self::Session_hook_end),
            "checkpoint_created" => Some(Self::Checkpoint_created),
            "trajectory_event" => Some(Self::Trajectory_event),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Session_start => "session_start",
            Self::Session_end => "session_end",
            Self::Session_warning => "session_warning",
            Self::Session_hook_start => "session_hook_start",
            Self::Session_hook_end => "session_hook_end",
            Self::Checkpoint_created => "checkpoint_created",
            Self::Trajectory_event => "trajectory_event",
        }
    }
}

/// A canonical event envelope emitted by an outer harness session.
#[derive(Debug, Clone, Default)]
pub struct SessionEvent {
    /// Unique identifier for this event
    pub id: String,
    /// Event type discriminator
    pub r#type: SessionEventType,
    /// ISO 8601 UTC timestamp when the event was emitted
    pub timestamp: String,
    /// Stable identifier for the outer session
    pub session_id: Option<String>,
    /// Associated turn identifier, when this session event is linked to a turn
    pub turn_id: Option<String>,
    /// Parent event or span identifier for reconstructing event hierarchy
    pub parent_id: Option<String>,
    /// Trace span identifier associated with this event
    pub span_id: Option<String>,
    /// Event-specific payload. Use the typed payload model matching 'type'.
    pub payload: serde_json::Value,
    /// Redaction state for sensitive payload fields
    pub redaction: Option<RedactionMetadata>,
}

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

    /// Load SessionEvent 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 SessionEvent 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 SessionEvent 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 {
            id: value
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            r#type: value
                .get("type")
                .and_then(|v| v.as_str())
                .and_then(|s| SessionEventType::from_str_opt(s))
                .unwrap_or(SessionEventType::Session_start),
            timestamp: value
                .get("timestamp")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            session_id: value
                .get("sessionId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            turn_id: value
                .get("turnId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            parent_id: value
                .get("parentId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            span_id: value
                .get("spanId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            payload: value
                .get("payload")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
            redaction: value
                .get("redaction")
                .filter(|v| v.is_object() || v.is_array() || v.is_string())
                .map(|v| RedactionMetadata::load_from_value(v, ctx)),
        }
    }

    /// Serialize SessionEvent 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.id.is_empty() {
            result.insert("id".to_string(), serde_json::Value::String(self.id.clone()));
        }
        result.insert(
            "type".to_string(),
            serde_json::Value::String(self.r#type.to_string()),
        );
        if !self.timestamp.is_empty() {
            result.insert(
                "timestamp".to_string(),
                serde_json::Value::String(self.timestamp.clone()),
            );
        }
        if let Some(ref val) = self.session_id {
            result.insert(
                "sessionId".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if let Some(ref val) = self.turn_id {
            result.insert("turnId".to_string(), serde_json::Value::String(val.clone()));
        }
        if let Some(ref val) = self.parent_id {
            result.insert(
                "parentId".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if let Some(ref val) = self.span_id {
            result.insert("spanId".to_string(), serde_json::Value::String(val.clone()));
        }
        if !self.payload.is_null() {
            result.insert("payload".to_string(), self.payload.clone());
        }
        if let Some(ref val) = self.redaction {
            let nested = val.to_value(ctx);
            if !nested.is_null() {
                result.insert("redaction".to_string(), nested);
            }
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize SessionEvent 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 SessionEvent to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }
    /// Returns typed reference to the map if the field is an object.
    /// Returns `None` if the field is null or not an object.
    pub fn as_payload_dict(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
        self.payload.as_object()
    }
}