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 HookEndScope {
    Turn,
    Session,
}

impl Default for HookEndScope {
    fn default() -> Self {
        Self::Turn
    }
}

impl std::fmt::Display for HookEndScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Turn => write!(f, "turn"),
            Self::Session => write!(f, "session"),
        }
    }
}

impl HookEndScope {
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "turn" => Some(Self::Turn),
            "session" => Some(Self::Session),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Turn => "turn",
            Self::Session => "session",
        }
    }
}

/// Payload for "hook_end" events — a host lifecycle hook finished.
#[derive(Debug, Clone, Default)]
pub struct HookEndPayload {
    /// Stable hook invocation identifier
    pub hook_invocation_id: String,
    /// Host-defined hook type
    pub hook_type: String,
    /// Whether the hook is scoped to a turn or the outer session
    pub scope: Option<HookEndScope>,
    /// Whether the hook completed successfully
    pub success: bool,
    /// Hook output after host-side sanitization
    pub output: serde_json::Value,
    /// Hook execution duration in milliseconds
    pub duration_ms: Option<f64>,
    /// Human-readable error when success is false
    pub error: Option<String>,
    /// Redaction state for sensitive hook output fields
    pub redaction: Option<RedactionMetadata>,
}

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

    /// Load HookEndPayload 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 HookEndPayload 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 HookEndPayload 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 {
            hook_invocation_id: value
                .get("hookInvocationId")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            hook_type: value
                .get("hookType")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            scope: value
                .get("scope")
                .and_then(|v| v.as_str())
                .and_then(|s| HookEndScope::from_str_opt(s)),
            success: value
                .get("success")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            output: value
                .get("output")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
            duration_ms: value.get("durationMs").and_then(|v| v.as_f64()),
            error: value
                .get("error")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            redaction: value
                .get("redaction")
                .filter(|v| v.is_object() || v.is_array() || v.is_string())
                .map(|v| RedactionMetadata::load_from_value(v, ctx)),
        }
    }

    /// Serialize HookEndPayload 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.hook_invocation_id.is_empty() {
            result.insert(
                "hookInvocationId".to_string(),
                serde_json::Value::String(self.hook_invocation_id.clone()),
            );
        }
        if !self.hook_type.is_empty() {
            result.insert(
                "hookType".to_string(),
                serde_json::Value::String(self.hook_type.clone()),
            );
        }
        if let Some(ref val) = self.scope {
            result.insert(
                "scope".to_string(),
                serde_json::Value::String(val.to_string()),
            );
        }
        result.insert("success".to_string(), serde_json::Value::Bool(self.success));
        if !self.output.is_null() {
            result.insert("output".to_string(), self.output.clone());
        }
        if let Some(val) = self.duration_ms {
            result.insert(
                "durationMs".to_string(),
                serde_json::Number::from_f64(val as f64)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::Null),
            );
        }
        if let Some(ref val) = self.error {
            result.insert("error".to_string(), serde_json::Value::String(val.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 HookEndPayload 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 HookEndPayload 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_output_dict(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
        self.output.as_object()
    }
}