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};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TurnEventType {
    Turn_start,
    Turn_end,
    Llm_start,
    Llm_complete,
    Retry,
    Permission_requested,
    Permission_completed,
    Token,
    Thinking,
    Tool_call_start,
    Tool_call_complete,
    Tool_execution_start,
    Tool_execution_complete,
    Tool_result,
    Hook_start,
    Hook_end,
    Status,
    Messages_updated,
    Done,
    Error,
    Cancelled,
    Compaction_start,
    Compaction_complete,
    Compaction_failed,
}

impl Default for TurnEventType {
    fn default() -> Self {
        Self::Turn_start
    }
}

impl std::fmt::Display for TurnEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Turn_start => write!(f, "turn_start"),
            Self::Turn_end => write!(f, "turn_end"),
            Self::Llm_start => write!(f, "llm_start"),
            Self::Llm_complete => write!(f, "llm_complete"),
            Self::Retry => write!(f, "retry"),
            Self::Permission_requested => write!(f, "permission_requested"),
            Self::Permission_completed => write!(f, "permission_completed"),
            Self::Token => write!(f, "token"),
            Self::Thinking => write!(f, "thinking"),
            Self::Tool_call_start => write!(f, "tool_call_start"),
            Self::Tool_call_complete => write!(f, "tool_call_complete"),
            Self::Tool_execution_start => write!(f, "tool_execution_start"),
            Self::Tool_execution_complete => write!(f, "tool_execution_complete"),
            Self::Tool_result => write!(f, "tool_result"),
            Self::Hook_start => write!(f, "hook_start"),
            Self::Hook_end => write!(f, "hook_end"),
            Self::Status => write!(f, "status"),
            Self::Messages_updated => write!(f, "messages_updated"),
            Self::Done => write!(f, "done"),
            Self::Error => write!(f, "error"),
            Self::Cancelled => write!(f, "cancelled"),
            Self::Compaction_start => write!(f, "compaction_start"),
            Self::Compaction_complete => write!(f, "compaction_complete"),
            Self::Compaction_failed => write!(f, "compaction_failed"),
        }
    }
}

impl TurnEventType {
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "turn_start" => Some(Self::Turn_start),
            "turn_end" => Some(Self::Turn_end),
            "llm_start" => Some(Self::Llm_start),
            "llm_complete" => Some(Self::Llm_complete),
            "retry" => Some(Self::Retry),
            "permission_requested" => Some(Self::Permission_requested),
            "permission_completed" => Some(Self::Permission_completed),
            "token" => Some(Self::Token),
            "thinking" => Some(Self::Thinking),
            "tool_call_start" => Some(Self::Tool_call_start),
            "tool_call_complete" => Some(Self::Tool_call_complete),
            "tool_execution_start" => Some(Self::Tool_execution_start),
            "tool_execution_complete" => Some(Self::Tool_execution_complete),
            "tool_result" => Some(Self::Tool_result),
            "hook_start" => Some(Self::Hook_start),
            "hook_end" => Some(Self::Hook_end),
            "status" => Some(Self::Status),
            "messages_updated" => Some(Self::Messages_updated),
            "done" => Some(Self::Done),
            "error" => Some(Self::Error),
            "cancelled" => Some(Self::Cancelled),
            "compaction_start" => Some(Self::Compaction_start),
            "compaction_complete" => Some(Self::Compaction_complete),
            "compaction_failed" => Some(Self::Compaction_failed),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Turn_start => "turn_start",
            Self::Turn_end => "turn_end",
            Self::Llm_start => "llm_start",
            Self::Llm_complete => "llm_complete",
            Self::Retry => "retry",
            Self::Permission_requested => "permission_requested",
            Self::Permission_completed => "permission_completed",
            Self::Token => "token",
            Self::Thinking => "thinking",
            Self::Tool_call_start => "tool_call_start",
            Self::Tool_call_complete => "tool_call_complete",
            Self::Tool_execution_start => "tool_execution_start",
            Self::Tool_execution_complete => "tool_execution_complete",
            Self::Tool_result => "tool_result",
            Self::Hook_start => "hook_start",
            Self::Hook_end => "hook_end",
            Self::Status => "status",
            Self::Messages_updated => "messages_updated",
            Self::Done => "done",
            Self::Error => "error",
            Self::Cancelled => "cancelled",
            Self::Compaction_start => "compaction_start",
            Self::Compaction_complete => "compaction_complete",
            Self::Compaction_failed => "compaction_failed",
        }
    }
}

/// A canonical event envelope emitted by the turn harness. The payload is kept JSON-shaped so runtimes can load all events even when newer payload types are added; event-specific typed payload models below define the canonical shapes.
#[derive(Debug, Clone, Default)]
pub struct TurnEvent {
    /// Unique identifier for this event
    pub id: String,
    /// Event type discriminator
    pub r#type: TurnEventType,
    /// ISO 8601 UTC timestamp when the event was emitted
    pub timestamp: String,
    /// Stable identifier for the outer turn
    pub turn_id: Option<String>,
    /// Zero-based agent-loop iteration associated with the event
    pub iteration: Option<i32>,
    /// 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,
}

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

    /// Load TurnEvent 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 TurnEvent 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 TurnEvent 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| TurnEventType::from_str_opt(s))
                .unwrap_or(TurnEventType::Turn_start),
            timestamp: value
                .get("timestamp")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            turn_id: value
                .get("turnId")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            iteration: value
                .get("iteration")
                .and_then(|v| v.as_i64())
                .map(|v| v as i32),
            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),
        }
    }

    /// Serialize TurnEvent 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.turn_id {
            result.insert("turnId".to_string(), serde_json::Value::String(val.clone()));
        }
        if let Some(val) = self.iteration {
            result.insert(
                "iteration".to_string(),
                serde_json::Value::Number(serde_json::Number::from(val)),
            );
        }
        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());
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize TurnEvent 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 TurnEvent 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()
    }
}