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::super::events::checkpoint::Checkpoint;

use super::super::events::host_tool_result::HostToolResult;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RunTurnStatus {
    Success,
    Error,
    Cancelled,
}

impl Default for RunTurnStatus {
    fn default() -> Self {
        Self::Success
    }
}

impl std::fmt::Display for RunTurnStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Success => write!(f, "success"),
            Self::Error => write!(f, "error"),
            Self::Cancelled => write!(f, "cancelled"),
        }
    }
}

impl RunTurnStatus {
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "success" => Some(Self::Success),
            "error" => Some(Self::Error),
            "cancelled" => Some(Self::Cancelled),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Success => "success",
            Self::Error => "error",
            Self::Cancelled => "cancelled",
        }
    }
}

/// Result returned by a reference turn runner implementation.
#[derive(Debug, Clone, Default)]
pub struct RunTurnResult {
    /// Stable harness session identifier
    pub session_id: String,
    /// Stable turn identifier within the session
    pub turn_id: String,
    /// Final semantic status for the deterministic turn
    pub status: RunTurnStatus,
    /// Provider-neutral final output returned by the injected model callback
    pub output: Option<serde_json::Value>,
    /// Number of model loop iterations executed
    pub iterations: i32,
    /// Host tool results produced during the turn
    pub tool_results: Vec<HostToolResult>,
    /// Checkpoints created during the turn
    pub checkpoints: Vec<Checkpoint>,
}

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

    /// Load RunTurnResult 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 RunTurnResult 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 RunTurnResult 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 {
            session_id: value
                .get("sessionId")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            turn_id: value
                .get("turnId")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            status: value
                .get("status")
                .and_then(|v| v.as_str())
                .and_then(|s| RunTurnStatus::from_str_opt(s))
                .unwrap_or(RunTurnStatus::Success),
            output: value.get("output").cloned(),
            iterations: value
                .get("iterations")
                .and_then(|v| v.as_i64())
                .unwrap_or(0) as i32,
            tool_results: value
                .get("toolResults")
                .map(|v| Self::load_tool_results(v, ctx))
                .unwrap_or_default(),
            checkpoints: value
                .get("checkpoints")
                .map(|v| Self::load_checkpoints(v, ctx))
                .unwrap_or_default(),
        }
    }

    /// Serialize RunTurnResult 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.session_id.is_empty() {
            result.insert(
                "sessionId".to_string(),
                serde_json::Value::String(self.session_id.clone()),
            );
        }
        if !self.turn_id.is_empty() {
            result.insert(
                "turnId".to_string(),
                serde_json::Value::String(self.turn_id.clone()),
            );
        }
        result.insert(
            "status".to_string(),
            serde_json::Value::String(self.status.to_string()),
        );
        if let Some(ref val) = self.output {
            result.insert("output".to_string(), val.clone());
        }
        if self.iterations != 0 {
            result.insert(
                "iterations".to_string(),
                serde_json::Value::Number(serde_json::Number::from(self.iterations)),
            );
        }
        if !self.tool_results.is_empty() {
            result.insert(
                "toolResults".to_string(),
                Self::save_tool_results(&self.tool_results, ctx),
            );
        }
        if !self.checkpoints.is_empty() {
            result.insert(
                "checkpoints".to_string(),
                Self::save_checkpoints(&self.checkpoints, ctx),
            );
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize RunTurnResult 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 RunTurnResult 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 HostToolResult from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_tool_results(data: &serde_json::Value, ctx: &LoadContext) -> Vec<HostToolResult> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| HostToolResult::load_from_value(v, ctx))
                .collect(),

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

    /// Save a collection of HostToolResult to a JSON value.
    fn save_tool_results(items: &[HostToolResult], 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<_>>(),
        )
    }
}