1use 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
16pub const IN_PROCESS_ORIGIN_PREFIX: &str = "adk-drivers:";
18
19#[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 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 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 pub fn owner(&self) -> &str {
86 &self.owner
87 }
88
89 pub fn line(&self) -> &str {
91 &self.line
92 }
93
94 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 pub fn is_present(&self, body: &str) -> bool {
109 body.trim_end().ends_with(&self.line)
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub enum SuppressionScope {
118 Marketing,
120 All,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct Suppression {
129 pub recipient: String,
131 pub scope: SuppressionScope,
133 pub at: DateTime<Utc>,
135 pub source: String,
137}
138
139impl Suppression {
140 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
146pub fn recipient_key(recipient: &str) -> String {
148 recipient.trim().to_lowercase()
149}
150
151#[async_trait]
154pub trait SuppressionList: Send + Sync {
155 async fn suppress(&self, suppression: Suppression) -> Result<()>;
157
158 async fn lookup(&self, recipient: &str) -> Result<Option<Suppression>>;
160
161 async fn lift(&self, recipient: &str) -> Result<bool>;
164}
165
166#[derive(Debug, Default)]
168pub struct InMemorySuppressions {
169 entries: Mutex<BTreeMap<String, Suppression>>,
170}
171
172impl InMemorySuppressions {
173 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#[async_trait]
205pub trait ConsentCheck: Send + Sync {
206 async fn is_live(&self, recipient: &str, scope: &str) -> Result<bool>;
208}
209
210#[derive(Debug, Default)]
226pub struct InMemoryConsent {
227 granted: Mutex<BTreeSet<(String, String)>>,
228}
229
230impl InMemoryConsent {
231 pub fn new() -> Self {
233 Self::default()
234 }
235
236 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "camelCase")]
267#[non_exhaustive]
268pub struct RateLimit {
269 pub max: u32,
271 pub per: Duration,
273}
274
275impl RateLimit {
276 pub fn new(max: u32, per: Duration) -> Self {
278 Self { max, per }
279 }
280}
281
282#[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 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#[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 pub fn new() -> Self {
352 Self::default()
353 }
354
355 #[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 #[must_use]
364 pub fn max_field_chars(mut self, chars: usize) -> Self {
365 self.max_field_chars = chars;
366 self
367 }
368
369 pub fn names(&self) -> impl Iterator<Item = &str> {
371 self.templates.keys().map(String::as_str)
372 }
373
374 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
411fn 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#[async_trait]
430pub trait ThreadReplier: Send + Sync {
431 fn prefix(&self) -> &str;
433
434 async fn reply_in_thread(
437 &self,
438 thread: &str,
439 template: &str,
440 fields: &BTreeMap<String, String>,
441 ) -> Result<Value>;
442}
443
444pub 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 pub fn new(repliers: impl IntoIterator<Item = Arc<dyn ThreadReplier>>) -> Self {
464 Self { repliers: repliers.into_iter().collect() }
465 }
466
467 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
531pub(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
539pub(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
557pub(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}