agents-core 0.0.30

Core traits, data models, and prompt primitives for building deep agents.
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
//! Security utilities for PII protection and data sanitization

use regex::Regex;
use serde_json::Value;
use std::collections::HashSet;

/// Maximum length for message previews to prevent PII leakage
pub const MAX_PREVIEW_LENGTH: usize = 100;

/// Sensitive field names that should be redacted from tool payloads
const SENSITIVE_FIELDS: &[&str] = &[
    "password",
    "passwd",
    "pwd",
    "secret",
    "token",
    "api_key",
    "apikey",
    "access_token",
    "refresh_token",
    "auth_token",
    "authorization",
    "bearer",
    "credit_card",
    "card_number",
    "cvv",
    "ssn",
    "social_security",
    "private_key",
    "privatekey",
    "encryption_key",
];

lazy_static::lazy_static! {
    /// Regex patterns for detecting PII in text
    static ref EMAIL_PATTERN: Regex = Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b").unwrap();
    static ref PHONE_PATTERN: Regex = Regex::new(r"\b(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b").unwrap();
    static ref CREDIT_CARD_PATTERN: Regex = Regex::new(r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b").unwrap();
}

/// Truncate a string to a maximum length, adding ellipsis if truncated
///
/// # Examples
///
/// ```
/// use agents_core::security::truncate_string;
///
/// let short = "Hello";
/// assert_eq!(truncate_string(short, 100), "Hello");
///
/// let long = "a".repeat(150);
/// let truncated = truncate_string(&long, 100);
/// assert_eq!(truncated.len(), 103); // 100 chars + "..."
/// assert!(truncated.ends_with("..."));
/// ```
pub fn truncate_string(text: &str, max_length: usize) -> String {
    if text.chars().count() <= max_length {
        text.to_string()
    } else {
        format!("{:.len$}...", text, len = max_length)
    }
}

/// Sanitize a JSON value by redacting sensitive fields
///
/// This function recursively traverses a JSON structure and replaces
/// values of sensitive fields with "[REDACTED]".
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use agents_core::security::sanitize_json;
///
/// let input = json!({
///     "username": "john",
///     "password": "secret123",
///     "api_key": "sk-1234567890"
/// });
///
/// let sanitized = sanitize_json(&input);
/// assert_eq!(sanitized["username"], "john");
/// assert_eq!(sanitized["password"], "[REDACTED]");
/// assert_eq!(sanitized["api_key"], "[REDACTED]");
/// ```
pub fn sanitize_json(value: &Value) -> Value {
    let sensitive_set: HashSet<&str> = SENSITIVE_FIELDS.iter().copied().collect();
    sanitize_json_recursive(value, &sensitive_set)
}

fn sanitize_json_recursive(value: &Value, sensitive_fields: &HashSet<&str>) -> Value {
    match value {
        Value::Object(map) => {
            let mut sanitized = serde_json::Map::new();
            for (key, val) in map {
                let key_lower = key.to_lowercase();
                if sensitive_fields
                    .iter()
                    .any(|&field| key_lower.contains(field))
                {
                    sanitized.insert(key.clone(), Value::String("[REDACTED]".to_string()));
                } else {
                    sanitized.insert(key.clone(), sanitize_json_recursive(val, sensitive_fields));
                }
            }
            Value::Object(sanitized)
        }
        Value::Array(arr) => Value::Array(
            arr.iter()
                .map(|v| sanitize_json_recursive(v, sensitive_fields))
                .collect(),
        ),
        _ => value.clone(),
    }
}

/// Redact PII patterns from text (emails, phone numbers, credit cards)
///
/// # Examples
///
/// ```
/// use agents_core::security::redact_pii;
///
/// let text = "Contact me at john@example.com or call 555-123-4567";
/// let redacted = redact_pii(text);
/// assert!(redacted.contains("[EMAIL]"));
/// assert!(redacted.contains("[PHONE]"));
/// assert!(!redacted.contains("john@example.com"));
/// assert!(!redacted.contains("555-123-4567"));
/// ```
pub fn redact_pii(text: &str) -> String {
    let mut result = text.to_string();

    // Redact emails
    result = EMAIL_PATTERN.replace_all(&result, "[EMAIL]").to_string();

    // Redact phone numbers
    result = PHONE_PATTERN.replace_all(&result, "[PHONE]").to_string();

    // Redact credit card numbers
    result = CREDIT_CARD_PATTERN
        .replace_all(&result, "[CARD]")
        .to_string();

    result
}

/// Create a safe preview of text by truncating and redacting PII
///
/// This combines truncation and PII redaction for maximum safety.
///
/// # Examples
///
/// ```
/// use agents_core::security::safe_preview;
///
/// let text = "My email is john@example.com and here's a very long message that goes on and on...";
/// let preview = safe_preview(text, 50);
/// assert!(preview.len() <= 53); // 50 + "..."
/// assert!(preview.contains("[EMAIL]"));
/// ```
pub fn safe_preview(text: &str, max_length: usize) -> String {
    let redacted = redact_pii(text);
    truncate_string(&redacted, max_length)
}

/// Sanitize tool payload for safe logging/broadcasting
///
/// This function:
/// 1. Redacts sensitive fields from JSON
/// 2. Truncates the result to prevent excessive data
/// 3. Redacts any remaining PII patterns
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use agents_core::security::sanitize_tool_payload;
///
/// let payload = json!({
///     "password": "secret123",
///     "api_key": "sk-1234567890",
///     "user": "john@example.com"
/// });
///
/// let sanitized = sanitize_tool_payload(&payload, 100);
/// assert!(sanitized.contains("[REDACTED]"));
/// assert!(sanitized.contains("[EMAIL]"));
/// assert!(sanitized.len() <= 103); // 100 + "..."
/// ```
pub fn sanitize_tool_payload(payload: &Value, max_length: usize) -> String {
    let sanitized_json = sanitize_json(payload);
    let json_str = sanitized_json.to_string();
    safe_preview(&json_str, max_length)
}

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

    #[test]
    fn test_truncate_string_short() {
        let text = "Hello, world!";
        assert_eq!(truncate_string(text, 100), "Hello, world!");
    }

    #[test]
    fn test_truncate_string_long() {
        let text = "a".repeat(150);
        let truncated = truncate_string(&text, 100);
        assert_eq!(truncated.len(), 103); // 100 + "..."
        assert!(truncated.ends_with("..."));
        assert_eq!(&truncated[..100], &text[..100]);
    }

    #[test]
    fn test_truncate_string_exact() {
        let text = "a".repeat(100);
        let truncated = truncate_string(&text, 100);
        assert_eq!(truncated.len(), 100);
        assert!(!truncated.ends_with("..."));
    }

    // Unicode Tests: Edge Cases
    #[test]
    fn test_truncate_string_empty() {
        let text = "";
        assert_eq!(truncate_string(text, 10), "");
        assert_eq!(truncate_string(text, 0), "");
    }

    #[test]
    fn test_truncate_string_composite_emoji() {
        // Family emoji: 👨‍👩‍👧‍👦
        // chars().count() = 7: ['👨', '\u{200D}', '👩', '\u{200D}', '👧', '\u{200D}', '👦']
        let family = "👨‍👩‍👧‍👦";
        let result = truncate_string(family, 3);
        // Will truncate at the ZWJ, producing incomplete emoji sequence
        assert_eq!(result.chars().count(), 6); // 3 chars + "..."
        assert!(result.starts_with("👨‍👩"));
    }

    #[test]
    fn test_sanitize_json_simple() {
        let input = json!({
            "username": "john",
            "password": "secret123"
        });

        let sanitized = sanitize_json(&input);
        assert_eq!(sanitized["username"], "john");
        assert_eq!(sanitized["password"], "[REDACTED]");
    }

    #[test]
    fn test_sanitize_json_nested() {
        let input = json!({
            "user": {
                "name": "john",
                "credentials": {
                    "password": "secret123",
                    "api_key": "sk-1234567890"
                }
            }
        });

        let sanitized = sanitize_json(&input);
        assert_eq!(sanitized["user"]["name"], "john");
        assert_eq!(sanitized["user"]["credentials"]["password"], "[REDACTED]");
        assert_eq!(sanitized["user"]["credentials"]["api_key"], "[REDACTED]");
    }

    #[test]
    fn test_sanitize_json_array() {
        let input = json!({
            "users": [
                {"name": "john", "password": "secret1"},
                {"name": "jane", "token": "abc123"}
            ]
        });

        let sanitized = sanitize_json(&input);
        assert_eq!(sanitized["users"][0]["name"], "john");
        assert_eq!(sanitized["users"][0]["password"], "[REDACTED]");
        assert_eq!(sanitized["users"][1]["name"], "jane");
        assert_eq!(sanitized["users"][1]["token"], "[REDACTED]");
    }

    #[test]
    fn test_sanitize_json_case_insensitive() {
        let input = json!({
            "Password": "secret123",
            "API_KEY": "sk-1234567890",
            "AccessToken": "token123"
        });

        let sanitized = sanitize_json(&input);
        assert_eq!(sanitized["Password"], "[REDACTED]");
        assert_eq!(sanitized["API_KEY"], "[REDACTED]");
        assert_eq!(sanitized["AccessToken"], "[REDACTED]");
    }

    #[test]
    fn test_redact_pii_email() {
        let text = "Contact me at john.doe@example.com for more info";
        let redacted = redact_pii(text);
        assert!(redacted.contains("[EMAIL]"));
        assert!(!redacted.contains("john.doe@example.com"));
    }

    #[test]
    fn test_redact_pii_phone() {
        let text = "Call me at 555-123-4567 or (555) 987-6543";
        let redacted = redact_pii(text);
        assert!(redacted.contains("[PHONE]"));
        assert!(!redacted.contains("555-123-4567"));
        assert!(!redacted.contains("555) 987-6543"));
    }

    #[test]
    fn test_redact_pii_credit_card() {
        let text = "Card number: 4532-1234-5678-9010";
        let redacted = redact_pii(text);
        assert!(redacted.contains("[CARD]"));
        assert!(!redacted.contains("4532-1234-5678-9010"));
    }

    #[test]
    fn test_redact_pii_multiple() {
        let text = "Email: john@example.com, Phone: 555-123-1234, Card: 4532123456789010";
        let redacted = redact_pii(text);
        assert!(redacted.contains("[EMAIL]"));
        assert!(redacted.contains("[PHONE]"));
        assert!(redacted.contains("[CARD]"));
    }

    #[test]
    fn test_safe_preview() {
        let text = "My email is john@example.com and here's a very long message that goes on and on and on and on and on and on";
        let preview = safe_preview(text, 50);

        // Should be truncated
        assert!(preview.len() <= 53); // 50 + "..."

        // Should have PII redacted
        assert!(preview.contains("[EMAIL]"));
        assert!(!preview.contains("john@example.com"));
    }

    #[test]
    fn test_sanitize_tool_payload() {
        let payload = json!({
            "password": "secret123",
            "api_key": "sk-1234567890",
            "user": "john@example.com"
        });

        let sanitized = sanitize_tool_payload(&payload, 100);

        // Should be truncated
        assert!(
            sanitized.len() <= 103,
            "Length should be <= 103, got: {}",
            sanitized.len()
        );

        // Password and api_key fields should be redacted
        assert!(
            sanitized.contains("[REDACTED]"),
            "Expected [REDACTED] in output, got: {}",
            sanitized
        );

        // Email should be redacted
        assert!(
            sanitized.contains("[EMAIL]"),
            "Expected [EMAIL] in output, got: {}",
            sanitized
        );
    }

    #[test]
    fn test_sanitize_tool_payload_long_message() {
        let payload = json!({
            "password": "secret123",
            "message": "a".repeat(200)
        });

        let sanitized = sanitize_tool_payload(&payload, 100);

        // Should be truncated
        assert!(sanitized.len() <= 103);

        // Even though truncated, password should still be redacted in the JSON structure
        // The order of fields in JSON is not guaranteed, but [REDACTED] should appear
        // if the password field comes before the truncation point
        assert!(sanitized.contains("[REDACTED]") || sanitized.ends_with("..."));
    }

    #[test]
    fn test_sanitize_tool_payload_no_sensitive_data() {
        let payload = json!({
            "action": "get_weather",
            "location": "Dubai"
        });

        let sanitized = sanitize_tool_payload(&payload, 100);
        assert!(sanitized.contains("get_weather"));
        assert!(sanitized.contains("Dubai"));
        assert!(!sanitized.contains("[REDACTED]"));
    }
}