agentsec-core 0.1.0

AgentSec core library — scan / web / paste logic, pure Rust
Documentation
//! Two-layer sanitize pipeline for fetched URL content.
//!
//! Layer order is fixed:
//!
//! 1. [`regex_layer::strip`] — fast, local, Aho-Corasick over a static
//!    pattern list. Replaces matches with the literal `[STRIPPED]`.
//! 2. [`semantic_layer::review`] — optional LLM review via Anthropic
//!    Messages API. **Fails open** when `ANTHROPIC_API_KEY` is unset or
//!    the API returns non-2xx: regex-only output is passed through
//!    unchanged.
//! 3. [`wrap::envelope`] — wrap into `<untrusted_content>` so the caller
//!    LLM physically separates instruction from data.

pub mod regex_layer;
pub mod semantic_layer;
pub mod wrap;

use crate::LlmConfig;
use crate::error::Result;

/// Run the 2-layer sanitize pipeline and return `(envelope, removed)`.
///
/// `envelope` is the wrapped `<untrusted_content>...</untrusted_content>`
/// string ready to hand to the caller LLM; `removed` is the cumulative
/// list of pattern labels stripped by both layers.
///
/// # Errors
///
/// Returns [`crate::Error::Http`] only if the semantic layer's HTTP call
/// fails before the fail-open fallback engages (e.g. TLS handshake
/// failure). API non-2xx is **not** an error here — see
/// [`semantic_layer::review`].
pub async fn run(llm: &LlmConfig, url: &str, raw: &str) -> Result<(String, Vec<String>)> {
    // 1st layer: regex (cheap, local).
    let (stripped, mut removed) = regex_layer::strip(raw);

    // 2nd layer: semantic check via Anthropic API (Haiku / Sonnet).
    // Fails open if `llm.api_key` is `None` (see semantic_layer).
    let (cleaned, semantic_removed) = semantic_layer::review(llm, &stripped).await?;
    removed.extend(semantic_removed);

    // Wrap into <untrusted_content> envelope.
    let envelope = wrap::envelope(url, &cleaned, &removed);
    Ok((envelope, removed))
}