artifactize-provider 0.27.1

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Joined views of the same response at the output, display, and tool boundaries.
use std::borrow::Cow;

use rig_core::message::{AssistantContent, DocumentSourceKind, Image, ReasoningContent};

use crate::secret::{Inventory, append_scalar_values};

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Protection {
    ScrubSeparately,
    WithholdReasoning,
    WithholdDisplay,
    RejectCall,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Channel {
    Text,
    Summary,
    Reasoning,
    Arguments,
    ToolMetadata,
    Other,
}

use Channel::{Arguments, Other, Reasoning, Summary, Text, ToolMetadata};

#[derive(Default)]
struct Parts<'a>(Vec<(Channel, Cow<'a, str>)>);

impl<'a> Parts<'a> {
    fn push(&mut self, channel: Channel, text: impl Into<Cow<'a, str>>) {
        let text = text.into();
        if !text.is_empty() {
            self.0.push((channel, text));
        }
    }

    fn joined(&self, channels: &[Channel]) -> String {
        self.0
            .iter()
            .filter(|(channel, _)| channels.contains(channel))
            .map(|(_, text)| text.as_ref())
            .collect()
    }

    fn ordered(&self) -> String {
        self.0.iter().map(|(_, text)| text.as_ref()).collect()
    }
}

pub(super) fn image_text(image: &Image) -> &str {
    match &image.data {
        DocumentSourceKind::Url(text)
        | DocumentSourceKind::FileId(text)
        | DocumentSourceKind::Base64(text)
        | DocumentSourceKind::String(text) => text,
        // Match text spellings, not decoded media or arbitrary bytes.
        DocumentSourceKind::Raw(_) | DocumentSourceKind::Unknown => "",
    }
}

fn response_parts(choice: &[AssistantContent]) -> Parts<'_> {
    let mut parts = Parts::default();
    for item in choice {
        let params = match item {
            AssistantContent::Text(text) => {
                parts.push(Text, text.text.as_str());
                text.additional_params.as_ref()
            }
            AssistantContent::Reasoning(sealed) => {
                if let Some(reasoning) = sealed.open(sealed.issuer()) {
                    for content in &reasoning.content {
                        match content {
                            ReasoningContent::Summary(text) => parts.push(Summary, text.as_str()),
                            ReasoningContent::Text { text, signature } => {
                                parts.push(Reasoning, text.as_str());
                                if let Some(signature) = signature {
                                    parts.push(Other, signature.as_str());
                                }
                            }
                            ReasoningContent::Encrypted(data)
                            | ReasoningContent::Redacted { data } => {
                                parts.push(Reasoning, data.as_str());
                            }
                        }
                    }
                }
                None
            }
            AssistantContent::ToolCall(call) => {
                let mut arguments = String::new();
                append_scalar_values(&call.function.arguments, &mut arguments);
                parts.push(Arguments, arguments);
                if let Some(signature) = &call.signature {
                    parts.push(ToolMetadata, signature.as_str());
                }
                if let Some(params) = &call.additional_params {
                    let mut metadata = String::new();
                    append_scalar_values(params, &mut metadata);
                    parts.push(ToolMetadata, metadata);
                }
                None
            }
            AssistantContent::Image(image) => {
                parts.push(Other, image_text(image));
                image.additional_params.as_ref()
            }
        };
        if let Some(params) = params {
            let mut metadata = String::new();
            for value in params.as_map().values() {
                append_scalar_values(value, &mut metadata);
            }
            parts.push(Other, metadata);
        }
    }
    parts
}

/// Inspect original item order first. A consumer can also omit non-displayable items,
/// collect an individual channel, or append grouped channels rather than render each item.
pub(super) fn protection(choice: &[AssistantContent], inventory: &Inventory) -> Protection {
    if choice.iter().any(|item| match item {
        AssistantContent::ToolCall(call) => {
            inventory.contains_short_tool_credential(&call.function.arguments)
        }
        _ => false,
    }) {
        return Protection::RejectCall;
    }
    if inventory.is_empty() {
        return Protection::ScrubSeparately;
    }
    let parts = response_parts(choice);
    let has = |channel| parts.0.iter().any(|(kind, _)| *kind == channel);
    let tool = has(Arguments) || has(ToolMetadata);
    let text = has(Text);
    let reasoning = has(Reasoning) || has(Summary);
    let other = has(Other);
    let contains = |channels: &[Channel]| inventory.contains(&parts.joined(channels));
    if (tool
        || [text, reasoning, other]
            .into_iter()
            .filter(|on| *on)
            .count()
            > 1)
        && inventory.contains(&parts.ordered())
    {
        return if tool {
            Protection::RejectCall
        } else {
            Protection::WithholdDisplay
        };
    }
    if has(ToolMetadata) && contains(&[Arguments, ToolMetadata]) {
        return Protection::RejectCall;
    }

    let text = parts.joined(&[Text]);
    let reasoning = parts.joined(&[Summary, Reasoning]);
    let arguments = parts.joined(&[Arguments]);
    let mixed = |a: &str, b: &str, channels: &[Channel]| {
        !a.is_empty()
            && !b.is_empty()
            && (contains(channels)
                || inventory.contains(&format!("{a}{b}"))
                || inventory.contains(&format!("{b}{a}")))
    };
    if !arguments.is_empty()
        && (inventory.contains(&arguments)
            || mixed(&arguments, &text, &[Arguments, Text])
            || mixed(&arguments, &reasoning, &[Arguments, Summary, Reasoning])
            || (has(Summary) && contains(&[Text, Summary, Arguments]))
            || ((other || has(ToolMetadata)) && contains(&[Text, Summary, Reasoning, Arguments]))
            || (!text.is_empty()
                && !reasoning.is_empty()
                && [
                    [&text, &reasoning, &arguments],
                    [&text, &arguments, &reasoning],
                    [&reasoning, &text, &arguments],
                    [&reasoning, &arguments, &text],
                    [&arguments, &text, &reasoning],
                    [&arguments, &reasoning, &text],
                ]
                .into_iter()
                .any(|[first, second, third]| {
                    inventory.contains(&format!("{first}{second}{third}"))
                })))
    {
        return Protection::RejectCall;
    }
    if mixed(&text, &reasoning, &[Text, Summary, Reasoning])
        || (!text.is_empty() && has(Summary) && contains(&[Text, Summary]))
        || (other && (contains(&[Other]) || contains(&[Text, Other])))
    {
        Protection::WithholdDisplay
    } else if inventory.contains(&reasoning) || contains(&[Summary]) || contains(&[Reasoning]) {
        Protection::WithholdReasoning
    } else {
        Protection::ScrubSeparately
    }
}

/// Recheck decoded arguments immediately before invoking a tool: a preceding tool
/// can change the inventory after the provider's response was first inspected.
pub(super) fn protected_arguments(arguments: &serde_json::Value, inventory: &Inventory) -> bool {
    if inventory.contains_short_tool_credential(arguments) {
        return true;
    }
    if inventory.is_empty() {
        return false;
    }
    let mut joined = String::new();
    append_scalar_values(arguments, &mut joined);
    inventory.contains(&joined)
}

/// A transcript may also append a finalized response to already published display text.
pub(super) fn follows_published(
    choice: &[AssistantContent],
    inventory: &Inventory,
    ordered: &str,
    text: &str,
    summary: &str,
) -> bool {
    if inventory.is_empty() || (ordered.is_empty() && text.is_empty() && summary.is_empty()) {
        return false;
    }
    let parts = response_parts(choice);
    let crosses = |prefix: &str, following: String| {
        !prefix.is_empty()
            && !following.is_empty()
            && inventory.contains(&format!("{prefix}{following}"))
    };
    crosses(ordered, parts.ordered())
        || crosses(ordered, parts.joined(&[Text, Summary]))
        || crosses(text, parts.joined(&[Text]))
        || crosses(summary, parts.joined(&[Summary]))
}