agent_control_specification_core 0.3.1-beta.0

Stateless Rust core for Agent Control Specification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::dispatchers::{constants::*, http};
use crate::JsonValue;
use serde_json::json;
use std::{collections::BTreeMap, sync::Mutex};

#[cfg(feature = "aacs")]
mod aacs;
#[cfg(feature = "auto")]
mod auto;
#[cfg(feature = "lakera_guard")]
mod lakera_guard;
#[cfg(feature = "llama_guard")]
mod llama_guard;
#[cfg(feature = "openai_moderation")]
mod openai_moderation;
#[cfg(feature = "perspective")]
mod perspective;

#[cfg(feature = "aacs")]
pub use aacs::AacsProvider;
#[cfg(feature = "auto")]
pub use auto::AutoProvider;
#[cfg(feature = "lakera_guard")]
pub use lakera_guard::LakeraGuardProvider;
#[cfg(feature = "llama_guard")]
pub use llama_guard::LlamaGuardProvider;
#[cfg(feature = "openai_moderation")]
pub use openai_moderation::OpenAiModerationProvider;
#[cfg(feature = "perspective")]
pub use perspective::PerspectiveProvider;

pub trait BundledClassifierProvider {
    fn classify(
        &self,
        cfg: &ResolvedClassifierConfig,
        subject: &str,
        transport: &dyn HttpTransport,
    ) -> Result<ClassifierVerdict, String>;
}

#[derive(Debug, Clone, PartialEq)]
pub struct ClassifierVerdict {
    pub flagged: bool,
    pub score: f64,
    pub threshold: f64,
    pub label: Option<String>,
    pub reason: Option<String>,
    pub category_scores: BTreeMap<String, f64>,
}

impl ClassifierVerdict {
    pub fn is_failure(&self) -> bool {
        self.flagged
    }

    pub fn to_json(&self) -> JsonValue {
        json!({
            "verdict": if self.flagged { "block" } else { "allow" },
            "flagged": self.flagged,
            "score": self.score,
            "threshold": self.threshold,
            "label": self.label,
            "reason": self.reason,
            "category_scores": self.category_scores,
        })
    }
}

#[derive(Debug, Clone)]
pub struct ResolvedClassifierConfig {
    pub provider: String,
    pub endpoint: String,
    pub api_key: Option<String>,
    pub timeout_ms: u64,
    pub threshold: f64,
    pub category_thresholds: BTreeMap<String, f64>,
    pub extra_headers: BTreeMap<String, String>,
    pub provider_config: JsonValue,
}

impl ResolvedClassifierConfig {
    pub fn from_fields(fields: &BTreeMap<String, JsonValue>) -> Result<Self, String> {
        let provider = http::optional_string_field(fields, FIELD_PROVIDER)
            .ok_or_else(|| "missing required field 'provider'".to_string())?
            .to_ascii_lowercase();
        let endpoint = http::optional_string_field(fields, FIELD_ENDPOINT)
            .or_else(|| http::optional_string_field(fields, FIELD_BASE_URL))
            .or_else(|| http::optional_string_field(fields, FIELD_URL))
            .unwrap_or_default()
            .to_string();
        let api_key = match http::optional_string_field(fields, FIELD_API_KEY_ENV) {
            Some(env_name) => Some(
                std::env::var(env_name)
                    .map_err(|_| format!("API key environment variable '{env_name}' is not set"))?,
            ),
            None => None,
        };
        let threshold = optional_f64_field(fields, FIELD_THRESHOLD).unwrap_or(0.5);
        validate_threshold(FIELD_THRESHOLD, threshold)?;
        let category_thresholds = optional_f64_map(fields, FIELD_CATEGORY_THRESHOLDS)?;
        for (category, threshold) in &category_thresholds {
            validate_threshold(
                &format!("{FIELD_CATEGORY_THRESHOLDS}.{category}"),
                *threshold,
            )?;
        }
        Ok(Self {
            provider,
            endpoint,
            api_key,
            timeout_ms: optional_u64_field(fields, FIELD_TIMEOUT_MS).unwrap_or(10_000),
            threshold,
            category_thresholds,
            extra_headers: optional_string_map(fields, FIELD_HEADERS)?,
            provider_config: fields
                .get(FIELD_PROVIDER_CONFIG)
                .cloned()
                .unwrap_or(JsonValue::Null),
        })
    }
}

fn optional_u64_field(fields: &BTreeMap<String, JsonValue>, name: &str) -> Option<u64> {
    fields.get(name).and_then(JsonValue::as_u64)
}

fn optional_f64_field(fields: &BTreeMap<String, JsonValue>, name: &str) -> Option<f64> {
    fields.get(name).and_then(JsonValue::as_f64)
}

fn validate_threshold(name: &str, threshold: f64) -> Result<(), String> {
    if (0.0..=1.0).contains(&threshold) {
        Ok(())
    } else {
        Err(format!("field '{name}' must be between 0 and 1"))
    }
}

fn optional_f64_map(
    fields: &BTreeMap<String, JsonValue>,
    name: &str,
) -> Result<BTreeMap<String, f64>, String> {
    let Some(value) = fields.get(name) else {
        return Ok(BTreeMap::new());
    };
    let object = value
        .as_object()
        .ok_or_else(|| format!("field '{name}' must be an object"))?;
    object
        .iter()
        .map(|(key, value)| {
            value
                .as_f64()
                .map(|number| (key.clone(), number))
                .ok_or_else(|| format!("field '{name}.{key}' must be a number"))
        })
        .collect()
}

fn optional_string_map(
    fields: &BTreeMap<String, JsonValue>,
    name: &str,
) -> Result<BTreeMap<String, String>, String> {
    let Some(value) = fields.get(name) else {
        return Ok(BTreeMap::new());
    };
    let object = value
        .as_object()
        .ok_or_else(|| format!("field '{name}' must be an object"))?;
    object
        .iter()
        .map(|(key, value)| {
            value
                .as_str()
                .map(|text| (key.clone(), text.to_string()))
                .ok_or_else(|| format!("field '{name}.{key}' must be a string"))
        })
        .collect()
}

pub fn fold_score_verdict(
    cfg: &ResolvedClassifierConfig,
    category_scores: &BTreeMap<String, f64>,
) -> ClassifierVerdict {
    let mut flagged = false;
    let mut top_label = None;
    let mut top_score = 0.0;
    let mut threshold = cfg.threshold;
    let mut reasons = Vec::new();

    if cfg.category_thresholds.is_empty() {
        for (category, score) in category_scores {
            if *score > top_score {
                top_score = *score;
                top_label = Some(category.clone());
            }
        }
        flagged = top_score >= cfg.threshold;
    } else {
        for (category, category_threshold) in &cfg.category_thresholds {
            let Some(score) = category_scores.get(category) else {
                continue;
            };
            if *score >= *category_threshold {
                flagged = true;
                reasons.push(format!("{category} {score:.3} >= {category_threshold:.3}"));
            }
            if *score > top_score {
                top_score = *score;
                top_label = Some(category.clone());
                threshold = *category_threshold;
            }
        }
    }

    ClassifierVerdict {
        flagged,
        score: top_score,
        threshold,
        label: top_label,
        reason: (!reasons.is_empty()).then(|| reasons.join("; ")),
        category_scores: category_scores.clone(),
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct TransportRequest {
    pub method: &'static str,
    pub url: String,
    pub headers: BTreeMap<String, String>,
    pub body: JsonValue,
    pub timeout_ms: u64,
}

impl TransportRequest {
    pub fn post(url: impl Into<String>) -> Self {
        Self {
            method: "POST",
            url: url.into(),
            headers: BTreeMap::new(),
            body: JsonValue::Null,
            timeout_ms: 10_000,
        }
    }

    pub fn header(mut self, name: &str, value: impl Into<String>) -> Self {
        self.headers.insert(name.to_string(), value.into());
        self
    }

    pub fn json(mut self, body: JsonValue) -> Self {
        self.body = body;
        self
    }

    pub fn timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransportResponse {
    pub status: u16,
    pub body: String,
}

pub trait HttpTransport: Send + Sync {
    fn send(&self, request: TransportRequest) -> Result<TransportResponse, String>;
}

#[derive(Debug, Default, Clone, Copy)]
pub struct UreqHttpTransport;

impl HttpTransport for UreqHttpTransport {
    fn send(&self, request: TransportRequest) -> Result<TransportResponse, String> {
        http::send_transport_request(request)
    }
}

#[derive(Debug, Default)]
pub struct StubHttpTransport {
    inner: Mutex<StubInner>,
}

#[derive(Debug, Default)]
struct StubInner {
    responses: Vec<Result<TransportResponse, String>>,
    requests: Vec<TransportRequest>,
}

impl StubHttpTransport {
    pub fn with_response(status: u16, body: impl Into<String>) -> Self {
        Self::with_responses([Ok(TransportResponse {
            status,
            body: body.into(),
        })])
    }

    pub fn with_responses<I>(responses: I) -> Self
    where
        I: IntoIterator<Item = Result<TransportResponse, String>>,
    {
        Self {
            inner: Mutex::new(StubInner {
                responses: responses.into_iter().collect(),
                requests: Vec::new(),
            }),
        }
    }

    pub fn last_request(&self) -> Option<TransportRequest> {
        self.inner.lock().ok()?.requests.last().cloned()
    }

    pub fn requests(&self) -> Vec<TransportRequest> {
        self.inner
            .lock()
            .map(|inner| inner.requests.clone())
            .unwrap_or_default()
    }
}

impl HttpTransport for StubHttpTransport {
    fn send(&self, request: TransportRequest) -> Result<TransportResponse, String> {
        let mut inner = self
            .inner
            .lock()
            .map_err(|_| "stub transport lock poisoned".to_string())?;
        inner.requests.push(request);
        if inner.responses.is_empty() {
            return Err("stub transport response queue exhausted".to_string());
        }
        inner.responses.remove(0)
    }
}

pub fn classify(
    cfg: &ResolvedClassifierConfig,
    _subject: &str,
    _transport: &dyn HttpTransport,
) -> Result<ClassifierVerdict, String> {
    match cfg.provider.as_str() {
        #[cfg(feature = "aacs")]
        "aacs" => AacsProvider.classify(cfg, _subject, _transport),
        #[cfg(feature = "openai_moderation")]
        "openai_moderation" => OpenAiModerationProvider.classify(cfg, _subject, _transport),
        #[cfg(feature = "perspective")]
        "perspective" => PerspectiveProvider.classify(cfg, _subject, _transport),
        #[cfg(feature = "llama_guard")]
        "llama_guard" => LlamaGuardProvider.classify(cfg, _subject, _transport),
        #[cfg(feature = "lakera_guard")]
        "lakera_guard" => LakeraGuardProvider.classify(cfg, _subject, _transport),
        #[cfg(feature = "auto")]
        "auto" => AutoProvider.classify(cfg, _subject, _transport),
        provider => Err(format!("unsupported classifier provider '{provider}'")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg(thresholds: &[(&str, f64)], global: f64) -> ResolvedClassifierConfig {
        ResolvedClassifierConfig {
            provider: "test".to_string(),
            endpoint: "https://example.test".to_string(),
            api_key: None,
            timeout_ms: 1000,
            threshold: global,
            category_thresholds: thresholds
                .iter()
                .map(|(key, value)| ((*key).to_string(), *value))
                .collect(),
            extra_headers: BTreeMap::new(),
            provider_config: JsonValue::Null,
        }
    }

    #[test]
    fn global_threshold_blocks_on_max_score() {
        let mut scores = BTreeMap::new();
        scores.insert("Hate".to_string(), 0.7);
        let verdict = fold_score_verdict(&cfg(&[], 0.5), &scores);
        assert!(verdict.is_failure());
    }

    #[test]
    fn category_thresholds_ignore_unlisted_scores() {
        let mut scores = BTreeMap::new();
        scores.insert("Hate".to_string(), 1.0);
        scores.insert("Sexual".to_string(), 0.1);
        let verdict = fold_score_verdict(&cfg(&[("Sexual", 0.5)], 0.5), &scores);
        assert!(!verdict.is_failure());
    }

    #[test]
    fn all_zero_scores_carry_no_label() {
        let mut scores = BTreeMap::new();
        scores.insert("Hate".to_string(), 0.0);
        scores.insert("Sexual".to_string(), 0.0);
        scores.insert("Violence".to_string(), 0.0);
        let verdict = fold_score_verdict(&cfg(&[], 0.5), &scores);
        assert!(!verdict.is_failure());
        assert_eq!(verdict.label, None);
        assert_eq!(verdict.score, 0.0);
    }

    #[test]
    fn top_label_is_the_highest_scoring_category() {
        let mut scores = BTreeMap::new();
        scores.insert("Hate".to_string(), 0.2);
        scores.insert("Sexual".to_string(), 0.0);
        scores.insert("Violence".to_string(), 0.9);
        let verdict = fold_score_verdict(&cfg(&[], 0.5), &scores);
        assert!(verdict.is_failure());
        assert_eq!(verdict.label.as_deref(), Some("Violence"));
        assert_eq!(verdict.score, 0.9);
    }
}