Skip to main content

adk_drivers/social/
mod.rs

1//! Social drivers (spec 3.5 §7.13): mentions and messages read in the public partition,
2//! replies in their thread, posts from the back office; Propose by default.
3//!
4//! | Tool | Effect class | Side | Default cap |
5//! |---|---|---|---|
6//! | `social_list_mentions` | `read` | public | Read |
7//! | `social_list_messages` | `read` | public | Read |
8//! | `social_reply_in_thread` | `send_external` | public | Propose |
9//! | `social_post` | `publish_public` | back office | Propose |
10//!
11//! [`SocialOutbox`] keeps the outbound rules over any [`SocialDriver`]: the disclosure line
12//! on every reply and post (A-I17), the suppression list before every reply, replies only
13//! to the author of an item the inbox read, from a playbook template, at a rate limit.
14//!
15//! | Adapter | Feature |
16//! |---|---|
17//! | [`InMemorySocial`] | — |
18//! | `MastodonSocial`: the Mastodon client API of an ActivityPub server (Mastodon, GoToSocial, Pleroma, Akkoma) | `mastodon` |
19
20use std::collections::BTreeMap;
21use std::sync::{Arc, Mutex, PoisonError};
22use std::time::Duration;
23
24use adk_core::Tool;
25use adk_kernel::drivers::EffectClass;
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::{Value, json};
30
31use crate::class::{AutonomyCap, Side, ToolSpec};
32use crate::error::{DriverError, Result};
33use crate::outbound::{
34    Disclosure, InMemorySuppressions, Limiter, RateLimit, ReplyTemplates, SuppressionList,
35    SuppressionScope, ThreadReplier, fields_arg, str_arg,
36};
37use crate::tools::DriverTool;
38
39#[cfg(feature = "mastodon")]
40mod mastodon;
41
42#[cfg(feature = "mastodon")]
43pub use mastodon::MastodonSocial;
44
45/// The longest text kept from a social item, in characters.
46const MAX_ITEM_CHARS: usize = 5_000;
47
48/// A mention or a direct message (spec 3.5 §7.13): untrusted input, read in the public
49/// partition only (A-I3).
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52#[non_exhaustive]
53pub struct SocialItem {
54    /// The item's id on the service; a reply answers it.
55    pub id: String,
56    /// The author's handle, such as `ana@social.example`.
57    pub author: String,
58    /// The text, without markup, at most 5,000 characters.
59    pub text: String,
60    /// When it was posted.
61    pub at: DateTime<Utc>,
62    /// Who sees it: `public`, `unlisted`, `private` or `direct`; a reply keeps it.
63    pub visibility: String,
64    /// Its address, when it has one.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub url: Option<String>,
67}
68
69impl SocialItem {
70    /// An item `id` by `author` saying `text`, for tests and the in-memory driver.
71    pub fn new(
72        id: impl Into<String>,
73        author: impl Into<String>,
74        text: impl Into<String>,
75        visibility: &str,
76    ) -> Self {
77        Self {
78            id: id.into(),
79            author: author.into(),
80            text: text.into(),
81            at: Utc::now(),
82            visibility: visibility.to_string(),
83            url: None,
84        }
85    }
86
87    /// Whether it is a direct message.
88    pub fn is_direct(&self) -> bool {
89        self.visibility == "direct"
90    }
91}
92
93/// A page of items after a cursor.
94#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96#[non_exhaustive]
97pub struct SocialPage {
98    /// The items, oldest first.
99    pub items: Vec<SocialItem>,
100    /// The cursor after the last item; unchanged when there are none.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub cursor: Option<String>,
103}
104
105/// What a reply or post created.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub struct SocialPosted {
110    /// Its id.
111    pub id: String,
112    /// Its address.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub url: Option<String>,
115    /// When.
116    pub at: DateTime<Utc>,
117}
118
119/// A social account (spec 3.5 §7.13): reads mentions and messages, replies, posts.
120///
121/// It only moves posts; [`SocialOutbox`] keeps the rules.
122#[async_trait]
123pub trait SocialDriver: Send + Sync {
124    /// The adapter's name.
125    fn name(&self) -> &str;
126
127    /// The longest post the service takes, in characters.
128    fn max_chars(&self) -> usize;
129
130    /// Public mentions of the account after `cursor`, oldest first, at most `limit`.
131    ///
132    /// # Errors
133    ///
134    /// Returns the service's errors.
135    async fn mentions(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage>;
136
137    /// Direct messages to the account after `cursor`, oldest first, at most `limit`.
138    ///
139    /// # Errors
140    ///
141    /// Returns the service's errors.
142    async fn messages(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage>;
143
144    /// Replies `text` to `item`, addressed to its author only, with its visibility.
145    ///
146    /// # Errors
147    ///
148    /// Returns the service's errors.
149    async fn reply(&self, item: &SocialItem, text: &str) -> Result<SocialPosted>;
150
151    /// Posts `text` publicly.
152    ///
153    /// # Errors
154    ///
155    /// Returns the service's errors.
156    async fn post(&self, text: &str) -> Result<SocialPosted>;
157}
158
159/// A social account in process memory (spec 3.5 §7.13), for tests and as the hermetic
160/// reference of the [`SocialDriver`] conformance suite.
161#[derive(Debug, Default)]
162pub struct InMemorySocial {
163    received: Mutex<Vec<SocialItem>>,
164    published: Mutex<Vec<(Option<String>, SocialItem)>>,
165}
166
167impl InMemorySocial {
168    /// An account with nothing received.
169    pub fn new() -> Self {
170        Self::default()
171    }
172
173    /// `item` arrives: a mention, or a direct message when its visibility is `direct`.
174    pub fn receive(&self, item: SocialItem) {
175        self.received.lock().unwrap_or_else(PoisonError::into_inner).push(item);
176    }
177
178    /// Everything posted, with the item each reply answers.
179    pub fn published(&self) -> Vec<(Option<String>, SocialItem)> {
180        self.published.lock().unwrap_or_else(PoisonError::into_inner).clone()
181    }
182
183    fn page(&self, direct: bool, cursor: Option<&str>, limit: usize) -> Result<SocialPage> {
184        let after = match cursor {
185            Some(cursor) => cursor.parse::<usize>().map_err(|_| {
186                DriverError::invalid(format!("`{cursor}` is not a cursor this driver gave"))
187            })?,
188            None => 0,
189        };
190        let received = self.received.lock().unwrap_or_else(PoisonError::into_inner);
191        let mut items = Vec::new();
192        let mut last = after;
193        for (index, item) in received.iter().enumerate().skip(after) {
194            if items.len() == limit {
195                break;
196            }
197            last = index + 1;
198            if item.is_direct() == direct {
199                items.push(item.clone());
200            }
201        }
202        Ok(SocialPage { items, cursor: Some(last.to_string()) })
203    }
204
205    fn publish(&self, answers: Option<&SocialItem>, text: &str, visibility: &str) -> SocialPosted {
206        let mut published = self.published.lock().unwrap_or_else(PoisonError::into_inner);
207        let id = format!("out-{}", published.len() + 1);
208        let item = SocialItem::new(id.clone(), "site", text, visibility);
209        published.push((answers.map(|item| item.id.clone()), item));
210        SocialPosted { id, url: None, at: Utc::now() }
211    }
212}
213
214#[async_trait]
215impl SocialDriver for InMemorySocial {
216    fn name(&self) -> &str {
217        "in-memory"
218    }
219
220    fn max_chars(&self) -> usize {
221        500
222    }
223
224    async fn mentions(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage> {
225        self.page(false, cursor, limit)
226    }
227
228    async fn messages(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage> {
229        self.page(true, cursor, limit)
230    }
231
232    async fn reply(&self, item: &SocialItem, text: &str) -> Result<SocialPosted> {
233        Ok(self.publish(Some(item), &format!("@{} {text}", item.author), &item.visibility))
234    }
235
236    async fn post(&self, text: &str) -> Result<SocialPosted> {
237        Ok(self.publish(None, text, "public"))
238    }
239}
240
241/// The outbound rules over a [`SocialDriver`] (spec 3.5 §7.10, §7.13, A-I17).
242///
243/// # Example
244///
245/// ```rust
246/// use std::collections::BTreeMap;
247/// use std::sync::Arc;
248/// use adk_drivers::social::{InMemorySocial, SocialItem, SocialOutbox};
249/// use adk_drivers::{Disclosure, ReplyTemplates};
250///
251/// # futures::executor::block_on(async {
252/// let social = Arc::new(InMemorySocial::new());
253/// social.receive(SocialItem::new("1", "ana@social.example", "Open on Sunday?", "public"));
254/// let outbox = SocialOutbox::builder(social.clone(), Disclosure::new("Wanjiru's Bakery").unwrap())
255///     .templates(ReplyTemplates::new().template("hours", "Yes, {hours} on Sundays."))
256///     .build();
257/// let page = outbox.read_mentions(None, 10).await.unwrap();
258/// let fields = BTreeMap::from([("hours".to_string(), "8–12".to_string())]);
259/// outbox.reply(&page.items[0].id, "hours", &fields).await.unwrap();
260/// let (answers, reply) = &social.published()[0];
261/// assert_eq!(answers.as_deref(), Some("1"));
262/// assert!(reply.text.starts_with("@ana@social.example Yes, 8–12 on Sundays."));
263/// # });
264/// ```
265pub struct SocialOutbox {
266    driver: Arc<dyn SocialDriver>,
267    disclosure: Disclosure,
268    suppressions: Arc<dyn SuppressionList>,
269    templates: ReplyTemplates,
270    per_thread: Limiter,
271    replies: Limiter,
272    posts: Limiter,
273    known: Mutex<BTreeMap<String, SocialItem>>,
274}
275
276impl std::fmt::Debug for SocialOutbox {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("SocialOutbox").field("driver", &self.driver.name()).finish_non_exhaustive()
279    }
280}
281
282/// Builds a [`SocialOutbox`].
283pub struct SocialOutboxBuilder {
284    outbox: SocialOutbox,
285}
286
287impl SocialOutboxBuilder {
288    /// Where unsubscribes and revocations are kept; share the email outbox's.
289    #[must_use]
290    pub fn suppressions(mut self, suppressions: Arc<dyn SuppressionList>) -> Self {
291        self.outbox.suppressions = suppressions;
292        self
293    }
294
295    /// The playbook's reply templates.
296    #[must_use]
297    pub fn templates(mut self, templates: ReplyTemplates) -> Self {
298        self.outbox.templates = templates;
299        self
300    }
301
302    /// The rate limits: replies per thread (2 an hour by default), replies overall (30 an
303    /// hour) and posts (6 a day).
304    #[must_use]
305    pub fn limits(mut self, per_thread: RateLimit, replies: RateLimit, posts: RateLimit) -> Self {
306        self.outbox.per_thread = Limiter::new(per_thread);
307        self.outbox.replies = Limiter::new(replies);
308        self.outbox.posts = Limiter::new(posts);
309        self
310    }
311
312    /// The outbox.
313    pub fn build(self) -> SocialOutbox {
314        self.outbox
315    }
316}
317
318impl SocialOutbox {
319    /// An outbox over `driver`, every reply and post ending with `disclosure`.
320    pub fn builder(driver: Arc<dyn SocialDriver>, disclosure: Disclosure) -> SocialOutboxBuilder {
321        SocialOutboxBuilder {
322            outbox: Self {
323                driver,
324                disclosure,
325                suppressions: Arc::new(InMemorySuppressions::new()),
326                templates: ReplyTemplates::new(),
327                per_thread: Limiter::new(RateLimit::new(2, Duration::from_secs(3_600))),
328                replies: Limiter::new(RateLimit::new(30, Duration::from_secs(3_600))),
329                posts: Limiter::new(RateLimit::new(6, Duration::from_secs(86_400))),
330                known: Mutex::default(),
331            },
332        }
333    }
334
335    /// The driver.
336    pub fn driver(&self) -> &Arc<dyn SocialDriver> {
337        &self.driver
338    }
339
340    /// The suppression list.
341    pub fn suppressions(&self) -> &Arc<dyn SuppressionList> {
342        &self.suppressions
343    }
344
345    fn remember(&self, page: &SocialPage) {
346        let mut known = self.known.lock().unwrap_or_else(PoisonError::into_inner);
347        for item in &page.items {
348            known.insert(item.id.clone(), item.clone());
349        }
350    }
351
352    /// Reads mentions after `cursor`, remembering each for a reply.
353    ///
354    /// # Errors
355    ///
356    /// Returns the driver's errors.
357    pub async fn read_mentions(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage> {
358        let page = self.driver.mentions(cursor, limit).await?;
359        self.remember(&page);
360        Ok(page)
361    }
362
363    /// Reads direct messages after `cursor`, remembering each for a reply.
364    ///
365    /// # Errors
366    ///
367    /// Returns the driver's errors.
368    pub async fn read_messages(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage> {
369        let page = self.driver.messages(cursor, limit).await?;
370        self.remember(&page);
371        Ok(page)
372    }
373
374    /// The text that will go out: `text` with the disclosure, within the service's length.
375    fn outgoing(&self, text: &str, prefix: usize) -> Result<String> {
376        let text = self.disclosure.apply(text);
377        if text.chars().count() + prefix > self.driver.max_chars() {
378            return Err(DriverError::invalid(format!(
379                "the text with its disclosure is longer than the {} characters {} takes",
380                self.driver.max_chars(),
381                self.driver.name()
382            )));
383        }
384        Ok(text)
385    }
386
387    /// Replies to item `item` with template `template` (spec 3.5 §7.10): to its author
388    /// only, ending with the disclosure.
389    ///
390    /// # Errors
391    ///
392    /// Returns [`DriverError::Refused`] for an item the inbox did not read, a revoked author
393    /// or an unknown template; [`DriverError::RateLimited`] over a limit; and the driver's
394    /// errors.
395    pub async fn reply(
396        &self,
397        item: &str,
398        template: &str,
399        fields: &BTreeMap<String, String>,
400    ) -> Result<SocialPosted> {
401        let item = self
402            .known
403            .lock()
404            .unwrap_or_else(PoisonError::into_inner)
405            .get(item)
406            .cloned()
407            .ok_or_else(|| {
408                DriverError::refused("a social reply answers only an item the inbox read")
409            })?;
410        let rendered = self.templates.render(template, fields)?;
411        if let Some(suppression) = self.suppressions.lookup(&social_key(&item.author)).await?
412            && suppression.scope == SuppressionScope::All
413        {
414            return Err(DriverError::refused(format!("{} asked not to be contacted", item.author)));
415        }
416        let text = self.outgoing(&rendered, item.author.chars().count() + 2)?;
417        self.per_thread.take(&item.id, "replies to one item")?;
418        self.replies.take("all", "social replies")?;
419        self.driver.reply(&item, &text).await
420    }
421
422    /// Posts `text` publicly, ending with the disclosure.
423    ///
424    /// # Errors
425    ///
426    /// Returns [`DriverError::Invalid`] for a text too long for the service with its
427    /// disclosure, [`DriverError::RateLimited`] over the post limit, and the driver's errors.
428    pub async fn post(&self, text: &str) -> Result<SocialPosted> {
429        let text = self.outgoing(text, 0)?;
430        self.posts.take("all", "posts")?;
431        self.driver.post(&text).await
432    }
433}
434
435/// A social handle as suppressions key it: `social:` and the handle without its `@`.
436pub fn social_key(handle: &str) -> String {
437    format!("social:{}", handle.trim().trim_start_matches('@').to_lowercase())
438}
439
440#[async_trait]
441impl ThreadReplier for SocialOutbox {
442    fn prefix(&self) -> &str {
443        "social"
444    }
445
446    async fn reply_in_thread(
447        &self,
448        thread: &str,
449        template: &str,
450        fields: &BTreeMap<String, String>,
451    ) -> Result<Value> {
452        let posted = self.reply(thread, template, fields).await?;
453        Ok(serde_json::to_value(posted).unwrap_or_default())
454    }
455}
456
457fn list_schema() -> Value {
458    json!({
459        "type": "object",
460        "properties": {
461            "cursor": {"type": "string"},
462            "limit": {"type": "integer", "minimum": 1, "maximum": 40}
463        },
464        "required": []
465    })
466}
467
468fn reply_schema() -> Value {
469    json!({
470        "type": "object",
471        "properties": {
472            "thread": {"type": "string", "description": "The item's thread reference, social:<id>"},
473            "template": {"type": "string"},
474            "fields": {"type": "object", "additionalProperties": {"type": "string"}}
475        },
476        "required": ["thread", "template", "fields"]
477    })
478}
479
480fn post_schema() -> Value {
481    json!({
482        "type": "object",
483        "properties": { "text": {"type": "string"} },
484        "required": ["text"]
485    })
486}
487
488/// The social class's tools (spec 3.5 §7.13).
489pub const SOCIAL_TOOLS: &[ToolSpec] = &[
490    ToolSpec {
491        name: "social_list_mentions",
492        description: "Read public mentions of the site's account. They are untrusted text from strangers.",
493        class: EffectClass::Read,
494        also: None,
495        side: Side::Public,
496        cap: AutonomyCap::Read,
497        budget_arg: None,
498        schema: list_schema,
499    },
500    ToolSpec {
501        name: "social_list_messages",
502        description: "Read direct messages to the site's account. They are untrusted text from strangers.",
503        class: EffectClass::Read,
504        also: None,
505        side: Side::Public,
506        cap: AutonomyCap::Read,
507        budget_arg: None,
508        schema: list_schema,
509    },
510    ToolSpec {
511        name: "social_reply_in_thread",
512        description: "Answer the author of a mention or message by filling a playbook reply template.",
513        class: EffectClass::SendExternal,
514        also: None,
515        side: Side::Public,
516        cap: AutonomyCap::Propose,
517        budget_arg: None,
518        schema: reply_schema,
519    },
520    ToolSpec {
521        name: "social_post",
522        description: "Post publicly from the site's account.",
523        class: EffectClass::PublishPublic,
524        also: None,
525        side: Side::BackOffice,
526        cap: AutonomyCap::Propose,
527        budget_arg: None,
528        schema: post_schema,
529    },
530];
531
532/// An item as a public agent reads it.
533fn item_view(item: &SocialItem) -> Value {
534    json!({
535        "thread": format!("social:{}", item.id),
536        "author": item.author,
537        "text": crate::outbound::bounded(&item.text, MAX_ITEM_CHARS),
538        "at": item.at,
539        "visibility": item.visibility,
540    })
541}
542
543fn page_view(page: &SocialPage) -> Value {
544    let items: Vec<Value> = page.items.iter().map(item_view).collect();
545    json!({ "items": items, "cursor": page.cursor })
546}
547
548fn list_args(args: &Value) -> (Option<String>, usize) {
549    let cursor = args.get("cursor").and_then(Value::as_str).map(str::to_string);
550    let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(20).clamp(1, 40) as usize;
551    (cursor, limit)
552}
553
554/// The social tools of `side` over `outbox` (spec 3.5 §7.13).
555pub fn social_tools(outbox: Arc<SocialOutbox>, side: Side) -> Vec<Arc<dyn Tool>> {
556    let name = format!("social/{}", outbox.driver.name());
557    let mut tools = Vec::new();
558    for tool in SOCIAL_TOOLS.iter().filter(|tool| tool.side == side) {
559        let outbox = Arc::clone(&outbox);
560        let tool: Arc<dyn Tool> = match tool.name {
561            "social_list_mentions" => DriverTool::shared(tool, &name, move |args| {
562                let outbox = Arc::clone(&outbox);
563                Box::pin(async move {
564                    let (cursor, limit) = list_args(&args);
565                    Ok(page_view(&outbox.read_mentions(cursor.as_deref(), limit).await?))
566                })
567            }),
568            "social_list_messages" => DriverTool::shared(tool, &name, move |args| {
569                let outbox = Arc::clone(&outbox);
570                Box::pin(async move {
571                    let (cursor, limit) = list_args(&args);
572                    Ok(page_view(&outbox.read_messages(cursor.as_deref(), limit).await?))
573                })
574            }),
575            "social_reply_in_thread" => DriverTool::shared(tool, &name, move |args| {
576                let outbox = Arc::clone(&outbox);
577                Box::pin(async move {
578                    let thread = str_arg(&args, "thread")?;
579                    let item = thread.strip_prefix("social:").unwrap_or(&thread).to_string();
580                    let posted = outbox
581                        .reply(&item, &str_arg(&args, "template")?, &fields_arg(&args)?)
582                        .await?;
583                    Ok(serde_json::to_value(posted).unwrap_or_default())
584                })
585            }),
586            _ => DriverTool::shared(tool, &name, move |args| {
587                let outbox = Arc::clone(&outbox);
588                Box::pin(async move {
589                    let posted = outbox.post(&str_arg(&args, "text")?).await?;
590                    Ok(serde_json::to_value(posted).unwrap_or_default())
591                })
592            }),
593        };
594        tools.push(tool);
595    }
596    tools
597}