use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use adk_core::{Tool, ToolContext, ToolEffect};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::error::{DriverError, Result};
pub const IN_PROCESS_ORIGIN_PREFIX: &str = "adk-drivers:";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Disclosure {
owner: String,
line: String,
}
impl Disclosure {
pub fn new(owner: impl Into<String>) -> Result<Self> {
let owner = owner.into().trim().to_string();
if owner.is_empty() || owner.contains(['\r', '\n']) {
return Err(DriverError::invalid(
"the disclosure names the site's owner: give their name on one line",
));
}
let line = format!("This message was written by an AI agent for {owner}.");
Ok(Self { owner, line })
}
pub fn with_line(mut self, line: impl Into<String>) -> Result<Self> {
let line = line.into().trim().to_string();
let says_ai = line
.split(|c: char| !c.is_alphanumeric())
.any(|word| word == "AI" || word.eq_ignore_ascii_case("KI") || word == "IA");
if line.contains(['\r', '\n']) || !line.contains(&self.owner) || !says_ai {
return Err(DriverError::invalid(format!(
"a disclosure line names the owner ({}) and says an AI agent wrote the message, \
on one line (spec 3.5 A-I17)",
self.owner
)));
}
self.line = line;
Ok(self)
}
pub fn owner(&self) -> &str {
&self.owner
}
pub fn line(&self) -> &str {
&self.line
}
pub fn apply(&self, body: &str) -> String {
let body = body.trim_end();
if body.ends_with(&self.line) {
body.to_string()
} else if body.is_empty() {
self.line.clone()
} else {
format!("{body}\n\n{}", self.line)
}
}
pub fn is_present(&self, body: &str) -> bool {
body.trim_end().ends_with(&self.line)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum SuppressionScope {
Marketing,
All,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Suppression {
pub recipient: String,
pub scope: SuppressionScope,
pub at: DateTime<Utc>,
pub source: String,
}
impl Suppression {
pub fn new(recipient: &str, scope: SuppressionScope, source: impl Into<String>) -> Self {
Self { recipient: recipient_key(recipient), scope, at: Utc::now(), source: source.into() }
}
}
pub fn recipient_key(recipient: &str) -> String {
recipient.trim().to_lowercase()
}
#[async_trait]
pub trait SuppressionList: Send + Sync {
async fn suppress(&self, suppression: Suppression) -> Result<()>;
async fn lookup(&self, recipient: &str) -> Result<Option<Suppression>>;
async fn lift(&self, recipient: &str) -> Result<bool>;
}
#[derive(Debug, Default)]
pub struct InMemorySuppressions {
entries: Mutex<BTreeMap<String, Suppression>>,
}
impl InMemorySuppressions {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl SuppressionList for InMemorySuppressions {
async fn suppress(&self, suppression: Suppression) -> Result<()> {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
let key = recipient_key(&suppression.recipient);
let wider = entries.get(&key).is_none_or(|known| suppression.scope >= known.scope);
if wider {
entries.insert(key, suppression);
}
Ok(())
}
async fn lookup(&self, recipient: &str) -> Result<Option<Suppression>> {
let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
Ok(entries.get(&recipient_key(recipient)).cloned())
}
async fn lift(&self, recipient: &str) -> Result<bool> {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
Ok(entries.remove(&recipient_key(recipient)).is_some())
}
}
#[async_trait]
pub trait ConsentCheck: Send + Sync {
async fn is_live(&self, recipient: &str, scope: &str) -> Result<bool>;
}
#[derive(Debug, Default)]
pub struct InMemoryConsent {
granted: Mutex<BTreeSet<(String, String)>>,
}
impl InMemoryConsent {
pub fn new() -> Self {
Self::default()
}
pub fn grant(&self, recipient: &str, scope: &str) {
self.granted
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert((recipient_key(recipient), scope.to_string()));
}
pub fn revoke(&self, recipient: &str, scope: &str) {
self.granted
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&(recipient_key(recipient), scope.to_string()));
}
}
#[async_trait]
impl ConsentCheck for InMemoryConsent {
async fn is_live(&self, recipient: &str, scope: &str) -> Result<bool> {
Ok(self
.granted
.lock()
.unwrap_or_else(PoisonError::into_inner)
.contains(&(recipient_key(recipient), scope.to_string())))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RateLimit {
pub max: u32,
pub per: Duration,
}
impl RateLimit {
pub fn new(max: u32, per: Duration) -> Self {
Self { max, per }
}
}
#[derive(Debug)]
pub(crate) struct Limiter {
limit: RateLimit,
hits: Mutex<HashMap<String, VecDeque<Instant>>>,
}
impl Limiter {
pub(crate) fn new(limit: RateLimit) -> Self {
Self { limit, hits: Mutex::default() }
}
pub(crate) fn take(&self, key: &str, what: &str) -> Result<()> {
let now = Instant::now();
let mut hits = self.hits.lock().unwrap_or_else(PoisonError::into_inner);
let window = hits.entry(key.to_string()).or_default();
while window.front().is_some_and(|at| now.duration_since(*at) >= self.limit.per) {
window.pop_front();
}
if window.len() >= self.limit.max as usize {
let retry = window
.front()
.map(|at| self.limit.per.saturating_sub(now.duration_since(*at)))
.unwrap_or(self.limit.per);
return Err(DriverError::RateLimited {
reason: format!(
"{what}: at most {} per {} s",
self.limit.max,
self.limit.per.as_secs()
),
retry_after_secs: retry.as_secs().max(1),
});
}
window.push_back(now);
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplyTemplates {
templates: BTreeMap<String, String>,
max_field_chars: usize,
}
impl Default for ReplyTemplates {
fn default() -> Self {
Self { templates: BTreeMap::new(), max_field_chars: 1_500 }
}
}
impl ReplyTemplates {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn template(mut self, name: impl Into<String>, text: impl Into<String>) -> Self {
self.templates.insert(name.into(), text.into());
self
}
#[must_use]
pub fn max_field_chars(mut self, chars: usize) -> Self {
self.max_field_chars = chars;
self
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.templates.keys().map(String::as_str)
}
pub fn render(&self, name: &str, fields: &BTreeMap<String, String>) -> Result<String> {
let Some(template) = self.templates.get(name) else {
let names: Vec<&str> = self.names().collect();
return Err(DriverError::refused(format!(
"`{name}` is not one of the playbook's reply templates ({})",
names.join(", ")
)));
};
let placeholders = placeholders(template);
if let Some(extra) = fields.keys().find(|field| !placeholders.contains(field.as_str())) {
return Err(DriverError::invalid(format!("template `{name}` has no field `{extra}`")));
}
let mut out = template.clone();
for placeholder in &placeholders {
let Some(value) = fields.get(*placeholder) else {
return Err(DriverError::invalid(format!(
"template `{name}` needs field `{placeholder}`"
)));
};
if value.chars().count() > self.max_field_chars {
return Err(DriverError::invalid(format!(
"field `{placeholder}` is longer than {} characters",
self.max_field_chars
)));
}
out = out.replace(&format!("{{{placeholder}}}"), value);
}
Ok(out)
}
}
fn placeholders(template: &str) -> BTreeSet<&str> {
let mut out = BTreeSet::new();
let mut rest = template;
while let Some(start) = rest.find('{') {
let after = &rest[start + 1..];
let Some(end) = after.find('}') else { break };
let name = &after[..end];
if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
out.insert(name);
}
rest = &after[end + 1..];
}
out
}
#[async_trait]
pub trait ThreadReplier: Send + Sync {
fn prefix(&self) -> &str;
async fn reply_in_thread(
&self,
thread: &str,
template: &str,
fields: &BTreeMap<String, String>,
) -> Result<Value>;
}
pub struct ReplyInThread {
repliers: Vec<Arc<dyn ThreadReplier>>,
}
impl std::fmt::Debug for ReplyInThread {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let prefixes: Vec<&str> = self.repliers.iter().map(|replier| replier.prefix()).collect();
f.debug_struct("ReplyInThread").field("prefixes", &prefixes).finish()
}
}
impl ReplyInThread {
pub fn new(repliers: impl IntoIterator<Item = Arc<dyn ThreadReplier>>) -> Self {
Self { repliers: repliers.into_iter().collect() }
}
pub async fn reply(
&self,
thread_ref: &str,
template: &str,
fields: &BTreeMap<String, String>,
) -> Result<Value> {
let (prefix, thread) = thread_ref.split_once(':').ok_or_else(|| {
DriverError::invalid(format!(
"`{thread_ref}` is not a thread reference; use the `thread` the inbox gave"
))
})?;
let replier =
self.repliers.iter().find(|replier| replier.prefix() == prefix).ok_or_else(|| {
DriverError::invalid(format!("no driver answers `{prefix}` threads"))
})?;
replier.reply_in_thread(thread, template, fields).await
}
}
#[async_trait]
impl Tool for ReplyInThread {
fn name(&self) -> &str {
"reply_in_thread"
}
fn description(&self) -> &str {
"Answer the person who wrote, in the same thread, by filling one of the playbook's \
reply templates. Goes only to the thread's sender; no new recipients, no attachments."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {
"thread": {"type": "string", "description": "The thread reference the inbox gave, such as email:... or social:..."},
"template": {"type": "string", "description": "The playbook's reply template"},
"fields": {"type": "object", "additionalProperties": {"type": "string"}, "description": "The template's fields"}
},
"required": ["thread", "template", "fields"]
}))
}
fn effect(&self) -> ToolEffect {
ToolEffect::NonIdempotent
}
fn origin(&self) -> &str {
"adk-drivers:reply"
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
let thread = str_arg(&args, "thread")?;
let template = str_arg(&args, "template")?;
let fields = fields_arg(&args)?;
Ok(self.reply(&thread, &template, &fields).await?)
}
}
pub(crate) fn str_arg(args: &Value, name: &str) -> Result<String> {
args.get(name)
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| DriverError::invalid(format!("`{name}` is required, as a string")))
}
pub(crate) fn fields_arg(args: &Value) -> Result<BTreeMap<String, String>> {
let Some(fields) = args.get("fields") else {
return Ok(BTreeMap::new());
};
let object = fields
.as_object()
.ok_or_else(|| DriverError::invalid("`fields` is an object of strings"))?;
object
.iter()
.map(|(name, value)| match value {
Value::String(text) => Ok((name.clone(), text.clone())),
Value::Number(number) => Ok((name.clone(), number.to_string())),
_ => Err(DriverError::invalid(format!("field `{name}` is not a string"))),
})
.collect()
}
pub(crate) fn bounded(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let mut cut: String = text.chars().take(max.saturating_sub(1)).collect();
cut.push('…');
cut
}