Skip to main content

adk_drivers/
outbound.rs

1//! The rules every outbound message keeps, whichever driver sends it (spec 3.5 §7.10,
2//! §7.13, A-I8, A-I17).
3
4use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
5use std::sync::{Arc, Mutex, PoisonError};
6use std::time::{Duration, Instant};
7
8use adk_core::{Tool, ToolContext, ToolEffect};
9use async_trait::async_trait;
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use serde_json::{Value, json};
13
14use crate::error::{DriverError, Result};
15
16/// The origin every in-process driver tool reports: `adk-drivers:<class>`.
17pub const IN_PROCESS_ORIGIN_PREFIX: &str = "adk-drivers:";
18
19/// The line every outbound message carries (spec 3.5 A-I17, §13 Q6): it names the site's
20/// owner and says an AI agent wrote the message.
21///
22/// One default line, overridable per jurisdiction, never removable: an override must
23/// still name the owner and say "AI", and every driver's outbox appends the line to every
24/// message it sends. [`apply`](Self::apply) is idempotent, so a draft that already ends
25/// with the line keeps one copy.
26///
27/// # Example
28///
29/// ```rust
30/// use adk_drivers::Disclosure;
31///
32/// let disclosure = Disclosure::new("Wanjiru's Bakery").unwrap();
33/// let body = disclosure.apply("Your order is ready.");
34/// assert_eq!(body, "Your order is ready.\n\nThis message was written by an AI agent for Wanjiru's Bakery.");
35/// assert_eq!(disclosure.apply(&body), body);
36/// assert!(Disclosure::new("Wanjiru's Bakery").unwrap().with_line("Sent by a bot").is_err());
37/// ```
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub struct Disclosure {
41    owner: String,
42    line: String,
43}
44
45impl Disclosure {
46    /// The default line for `owner`: "This message was written by an AI agent for {owner}."
47    ///
48    /// # Errors
49    ///
50    /// Returns [`DriverError::Invalid`] for an empty owner or one with a line break.
51    pub fn new(owner: impl Into<String>) -> Result<Self> {
52        let owner = owner.into().trim().to_string();
53        if owner.is_empty() || owner.contains(['\r', '\n']) {
54            return Err(DriverError::invalid(
55                "the disclosure names the site's owner: give their name on one line",
56            ));
57        }
58        let line = format!("This message was written by an AI agent for {owner}.");
59        Ok(Self { owner, line })
60    }
61
62    /// Replaces the line, as a jurisdiction's wording requires.
63    ///
64    /// # Errors
65    ///
66    /// Returns [`DriverError::Invalid`] when the line does not name the owner, does not say
67    /// "AI", or spans more than one line: the disclosure can be reworded, never removed.
68    pub fn with_line(mut self, line: impl Into<String>) -> Result<Self> {
69        let line = line.into().trim().to_string();
70        let says_ai = line
71            .split(|c: char| !c.is_alphanumeric())
72            .any(|word| word == "AI" || word.eq_ignore_ascii_case("KI") || word == "IA");
73        if line.contains(['\r', '\n']) || !line.contains(&self.owner) || !says_ai {
74            return Err(DriverError::invalid(format!(
75                "a disclosure line names the owner ({}) and says an AI agent wrote the message, \
76                 on one line (spec 3.5 A-I17)",
77                self.owner
78            )));
79        }
80        self.line = line;
81        Ok(self)
82    }
83
84    /// The owner the line names.
85    pub fn owner(&self) -> &str {
86        &self.owner
87    }
88
89    /// The line.
90    pub fn line(&self) -> &str {
91        &self.line
92    }
93
94    /// `body` ending with the line, after a blank line; unchanged when it already ends
95    /// with it.
96    pub fn apply(&self, body: &str) -> String {
97        let body = body.trim_end();
98        if body.ends_with(&self.line) {
99            body.to_string()
100        } else if body.is_empty() {
101            self.line.clone()
102        } else {
103            format!("{body}\n\n{}", self.line)
104        }
105    }
106
107    /// Whether `body` ends with the line.
108    pub fn is_present(&self, body: &str) -> bool {
109        body.trim_end().ends_with(&self.line)
110    }
111}
112
113/// What an unsubscribe or a revocation stops (spec 3.5 A-I17).
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub enum SuppressionScope {
118    /// Sequences, newsletters and posts addressed to them: an unsubscribe.
119    Marketing,
120    /// Every message, replies included: a revocation, or "stop contacting me".
121    All,
122}
123
124/// A recipient who unsubscribed or revoked (spec 3.5 A-I17).
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct Suppression {
129    /// The recipient, as [`recipient_key`] writes it.
130    pub recipient: String,
131    /// What it stops.
132    pub scope: SuppressionScope,
133    /// When.
134    pub at: DateTime<Utc>,
135    /// Where it came from: `link`, `mailto`, `complaint`, `owner`.
136    pub source: String,
137}
138
139impl Suppression {
140    /// `recipient` suppressed for `scope` now, from `source`.
141    pub fn new(recipient: &str, scope: SuppressionScope, source: impl Into<String>) -> Self {
142        Self { recipient: recipient_key(recipient), scope, at: Utc::now(), source: source.into() }
143    }
144}
145
146/// A recipient as suppressions and consent key it: trimmed and in lower case.
147pub fn recipient_key(recipient: &str) -> String {
148    recipient.trim().to_lowercase()
149}
150
151/// Where unsubscribes and revocations are kept (spec 3.5 A-I17): every driver's outbox
152/// reads it before each send, so one takes effect before the next send.
153#[async_trait]
154pub trait SuppressionList: Send + Sync {
155    /// Keeps `suppression`; a wider scope replaces a narrower one, never the reverse.
156    async fn suppress(&self, suppression: Suppression) -> Result<()>;
157
158    /// The suppression of `recipient`, if any.
159    async fn lookup(&self, recipient: &str) -> Result<Option<Suppression>>;
160
161    /// Lifts the suppression of `recipient`, when they subscribe again with a fresh
162    /// consent; returns whether there was one.
163    async fn lift(&self, recipient: &str) -> Result<bool>;
164}
165
166/// Suppressions in process memory, for tests and single-process hosts.
167#[derive(Debug, Default)]
168pub struct InMemorySuppressions {
169    entries: Mutex<BTreeMap<String, Suppression>>,
170}
171
172impl InMemorySuppressions {
173    /// None suppressed.
174    pub fn new() -> Self {
175        Self::default()
176    }
177}
178
179#[async_trait]
180impl SuppressionList for InMemorySuppressions {
181    async fn suppress(&self, suppression: Suppression) -> Result<()> {
182        let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
183        let key = recipient_key(&suppression.recipient);
184        let wider = entries.get(&key).is_none_or(|known| suppression.scope >= known.scope);
185        if wider {
186            entries.insert(key, suppression);
187        }
188        Ok(())
189    }
190
191    async fn lookup(&self, recipient: &str) -> Result<Option<Suppression>> {
192        let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
193        Ok(entries.get(&recipient_key(recipient)).cloned())
194    }
195
196    async fn lift(&self, recipient: &str) -> Result<bool> {
197        let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
198        Ok(entries.remove(&recipient_key(recipient)).is_some())
199    }
200}
201
202/// Whether a recipient holds a live consent receipt for a scope (spec 3.5 A-I8): the edge's
203/// consent store answers it; sequences and newsletters ask it at send time.
204#[async_trait]
205pub trait ConsentCheck: Send + Sync {
206    /// Whether `recipient` holds a live receipt for `scope`.
207    async fn is_live(&self, recipient: &str, scope: &str) -> Result<bool>;
208}
209
210/// Consent receipts in process memory, for tests.
211///
212/// # Example
213///
214/// ```rust
215/// use adk_drivers::{ConsentCheck, InMemoryConsent};
216///
217/// # futures::executor::block_on(async {
218/// let consent = InMemoryConsent::new();
219/// consent.grant("ana@example.com", "newsletter");
220/// assert!(consent.is_live("Ana@Example.com", "newsletter").await.unwrap());
221/// consent.revoke("ana@example.com", "newsletter");
222/// assert!(!consent.is_live("ana@example.com", "newsletter").await.unwrap());
223/// # });
224/// ```
225#[derive(Debug, Default)]
226pub struct InMemoryConsent {
227    granted: Mutex<BTreeSet<(String, String)>>,
228}
229
230impl InMemoryConsent {
231    /// No consent given.
232    pub fn new() -> Self {
233        Self::default()
234    }
235
236    /// Records `recipient`'s consent for `scope`.
237    pub fn grant(&self, recipient: &str, scope: &str) {
238        self.granted
239            .lock()
240            .unwrap_or_else(PoisonError::into_inner)
241            .insert((recipient_key(recipient), scope.to_string()));
242    }
243
244    /// Revokes it.
245    pub fn revoke(&self, recipient: &str, scope: &str) {
246        self.granted
247            .lock()
248            .unwrap_or_else(PoisonError::into_inner)
249            .remove(&(recipient_key(recipient), scope.to_string()));
250    }
251}
252
253#[async_trait]
254impl ConsentCheck for InMemoryConsent {
255    async fn is_live(&self, recipient: &str, scope: &str) -> Result<bool> {
256        Ok(self
257            .granted
258            .lock()
259            .unwrap_or_else(PoisonError::into_inner)
260            .contains(&(recipient_key(recipient), scope.to_string())))
261    }
262}
263
264/// At most `max` calls per `per` (spec 3.5 §7.10: `reply_in_thread` is rate limited).
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "camelCase")]
267#[non_exhaustive]
268pub struct RateLimit {
269    /// Calls allowed in a window.
270    pub max: u32,
271    /// The window.
272    pub per: Duration,
273}
274
275impl RateLimit {
276    /// `max` calls per `per`.
277    pub fn new(max: u32, per: Duration) -> Self {
278        Self { max, per }
279    }
280}
281
282/// A sliding-window limiter keyed by string.
283#[derive(Debug)]
284pub(crate) struct Limiter {
285    limit: RateLimit,
286    hits: Mutex<HashMap<String, VecDeque<Instant>>>,
287}
288
289impl Limiter {
290    pub(crate) fn new(limit: RateLimit) -> Self {
291        Self { limit, hits: Mutex::default() }
292    }
293
294    /// Takes one call for `key`, or says how long until one is free.
295    pub(crate) fn take(&self, key: &str, what: &str) -> Result<()> {
296        let now = Instant::now();
297        let mut hits = self.hits.lock().unwrap_or_else(PoisonError::into_inner);
298        let window = hits.entry(key.to_string()).or_default();
299        while window.front().is_some_and(|at| now.duration_since(*at) >= self.limit.per) {
300            window.pop_front();
301        }
302        if window.len() >= self.limit.max as usize {
303            let retry = window
304                .front()
305                .map(|at| self.limit.per.saturating_sub(now.duration_since(*at)))
306                .unwrap_or(self.limit.per);
307            return Err(DriverError::RateLimited {
308                reason: format!(
309                    "{what}: at most {} per {} s",
310                    self.limit.max,
311                    self.limit.per.as_secs()
312                ),
313                retry_after_secs: retry.as_secs().max(1),
314            });
315        }
316        window.push_back(now);
317        Ok(())
318    }
319}
320
321/// The playbook's reply templates (spec 3.5 §7.10: `reply_in_thread` answers "within a
322/// playbook template"): a public agent fills a template's `{fields}`, never writes a
323/// message from nothing.
324///
325/// # Example
326///
327/// ```rust
328/// use std::collections::BTreeMap;
329/// use adk_drivers::ReplyTemplates;
330///
331/// let templates = ReplyTemplates::new().template("hours", "Hi {name}, we open at {time}.");
332/// let fields = BTreeMap::from([("name".to_string(), "Ana".to_string()), ("time".to_string(), "8am".to_string())]);
333/// assert_eq!(templates.render("hours", &fields).unwrap(), "Hi Ana, we open at 8am.");
334/// assert!(templates.render("refund", &fields).is_err());
335/// ```
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(rename_all = "camelCase")]
338pub struct ReplyTemplates {
339    templates: BTreeMap<String, String>,
340    max_field_chars: usize,
341}
342
343impl Default for ReplyTemplates {
344    fn default() -> Self {
345        Self { templates: BTreeMap::new(), max_field_chars: 1_500 }
346    }
347}
348
349impl ReplyTemplates {
350    /// No templates; fields of at most 1,500 characters.
351    pub fn new() -> Self {
352        Self::default()
353    }
354
355    /// Adds template `name`, whose `{field}` placeholders the agent fills.
356    #[must_use]
357    pub fn template(mut self, name: impl Into<String>, text: impl Into<String>) -> Self {
358        self.templates.insert(name.into(), text.into());
359        self
360    }
361
362    /// Sets the longest field value.
363    #[must_use]
364    pub fn max_field_chars(mut self, chars: usize) -> Self {
365        self.max_field_chars = chars;
366        self
367    }
368
369    /// The template names.
370    pub fn names(&self) -> impl Iterator<Item = &str> {
371        self.templates.keys().map(String::as_str)
372    }
373
374    /// Template `name` with `fields` filled in.
375    ///
376    /// # Errors
377    ///
378    /// Returns [`DriverError::Refused`] for a template the playbook does not have, and
379    /// [`DriverError::Invalid`] for a missing, unknown or too long field.
380    pub fn render(&self, name: &str, fields: &BTreeMap<String, String>) -> Result<String> {
381        let Some(template) = self.templates.get(name) else {
382            let names: Vec<&str> = self.names().collect();
383            return Err(DriverError::refused(format!(
384                "`{name}` is not one of the playbook's reply templates ({})",
385                names.join(", ")
386            )));
387        };
388        let placeholders = placeholders(template);
389        if let Some(extra) = fields.keys().find(|field| !placeholders.contains(field.as_str())) {
390            return Err(DriverError::invalid(format!("template `{name}` has no field `{extra}`")));
391        }
392        let mut out = template.clone();
393        for placeholder in &placeholders {
394            let Some(value) = fields.get(*placeholder) else {
395                return Err(DriverError::invalid(format!(
396                    "template `{name}` needs field `{placeholder}`"
397                )));
398            };
399            if value.chars().count() > self.max_field_chars {
400                return Err(DriverError::invalid(format!(
401                    "field `{placeholder}` is longer than {} characters",
402                    self.max_field_chars
403                )));
404            }
405            out = out.replace(&format!("{{{placeholder}}}"), value);
406        }
407        Ok(out)
408    }
409}
410
411/// The `{name}` placeholders of `template`.
412fn placeholders(template: &str) -> BTreeSet<&str> {
413    let mut out = BTreeSet::new();
414    let mut rest = template;
415    while let Some(start) = rest.find('{') {
416        let after = &rest[start + 1..];
417        let Some(end) = after.find('}') else { break };
418        let name = &after[..end];
419        if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
420            out.insert(name);
421        }
422        rest = &after[end + 1..];
423    }
424    out
425}
426
427/// A driver that answers the person who wrote, in the same thread (spec 3.5 §7.10): the
428/// email and social outboxes.
429#[async_trait]
430pub trait ThreadReplier: Send + Sync {
431    /// The prefix of the thread references it answers: `email` or `social`.
432    fn prefix(&self) -> &str;
433
434    /// Answers thread `thread` (without the prefix) with template `template` filled with
435    /// `fields`, under the rules of `reply_in_thread`.
436    async fn reply_in_thread(
437        &self,
438        thread: &str,
439        template: &str,
440        fields: &BTreeMap<String, String>,
441    ) -> Result<Value>;
442}
443
444/// `reply_in_thread`, the public partition's only `SendExternal` tool (spec 3.5 §7.10,
445/// A-I2): answers the person who wrote, in their thread, within a playbook template, at a
446/// rate limit, with no new recipients and no attachments.
447///
448/// A thread reference is `<prefix>:<thread>`, as the inbox gave it: `email:...` or
449/// `social:...`; each prefix goes to its [`ThreadReplier`].
450pub struct ReplyInThread {
451    repliers: Vec<Arc<dyn ThreadReplier>>,
452}
453
454impl std::fmt::Debug for ReplyInThread {
455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456        let prefixes: Vec<&str> = self.repliers.iter().map(|replier| replier.prefix()).collect();
457        f.debug_struct("ReplyInThread").field("prefixes", &prefixes).finish()
458    }
459}
460
461impl ReplyInThread {
462    /// The tool over `repliers`.
463    pub fn new(repliers: impl IntoIterator<Item = Arc<dyn ThreadReplier>>) -> Self {
464        Self { repliers: repliers.into_iter().collect() }
465    }
466
467    /// Answers `thread_ref` (`<prefix>:<thread>`).
468    ///
469    /// # Errors
470    ///
471    /// Returns [`DriverError::Invalid`] for a reference no replier serves, and the
472    /// replier's error.
473    pub async fn reply(
474        &self,
475        thread_ref: &str,
476        template: &str,
477        fields: &BTreeMap<String, String>,
478    ) -> Result<Value> {
479        let (prefix, thread) = thread_ref.split_once(':').ok_or_else(|| {
480            DriverError::invalid(format!(
481                "`{thread_ref}` is not a thread reference; use the `thread` the inbox gave"
482            ))
483        })?;
484        let replier =
485            self.repliers.iter().find(|replier| replier.prefix() == prefix).ok_or_else(|| {
486                DriverError::invalid(format!("no driver answers `{prefix}` threads"))
487            })?;
488        replier.reply_in_thread(thread, template, fields).await
489    }
490}
491
492#[async_trait]
493impl Tool for ReplyInThread {
494    fn name(&self) -> &str {
495        "reply_in_thread"
496    }
497
498    fn description(&self) -> &str {
499        "Answer the person who wrote, in the same thread, by filling one of the playbook's \
500         reply templates. Goes only to the thread's sender; no new recipients, no attachments."
501    }
502
503    fn parameters_schema(&self) -> Option<Value> {
504        Some(json!({
505            "type": "object",
506            "properties": {
507                "thread": {"type": "string", "description": "The thread reference the inbox gave, such as email:... or social:..."},
508                "template": {"type": "string", "description": "The playbook's reply template"},
509                "fields": {"type": "object", "additionalProperties": {"type": "string"}, "description": "The template's fields"}
510            },
511            "required": ["thread", "template", "fields"]
512        }))
513    }
514
515    fn effect(&self) -> ToolEffect {
516        ToolEffect::NonIdempotent
517    }
518
519    fn origin(&self) -> &str {
520        "adk-drivers:reply"
521    }
522
523    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
524        let thread = str_arg(&args, "thread")?;
525        let template = str_arg(&args, "template")?;
526        let fields = fields_arg(&args)?;
527        Ok(self.reply(&thread, &template, &fields).await?)
528    }
529}
530
531/// The string argument `name`.
532pub(crate) fn str_arg(args: &Value, name: &str) -> Result<String> {
533    args.get(name)
534        .and_then(Value::as_str)
535        .map(str::to_string)
536        .ok_or_else(|| DriverError::invalid(format!("`{name}` is required, as a string")))
537}
538
539/// The `fields` object of a template call.
540pub(crate) fn fields_arg(args: &Value) -> Result<BTreeMap<String, String>> {
541    let Some(fields) = args.get("fields") else {
542        return Ok(BTreeMap::new());
543    };
544    let object = fields
545        .as_object()
546        .ok_or_else(|| DriverError::invalid("`fields` is an object of strings"))?;
547    object
548        .iter()
549        .map(|(name, value)| match value {
550            Value::String(text) => Ok((name.clone(), text.clone())),
551            Value::Number(number) => Ok((name.clone(), number.to_string())),
552            _ => Err(DriverError::invalid(format!("field `{name}` is not a string"))),
553        })
554        .collect()
555}
556
557/// `text` cut to at most `max` characters, with `…` where it was cut.
558pub(crate) fn bounded(text: &str, max: usize) -> String {
559    if text.chars().count() <= max {
560        return text.to_string();
561    }
562    let mut cut: String = text.chars().take(max.saturating_sub(1)).collect();
563    cut.push('…');
564    cut
565}