1use 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
45const MAX_ITEM_CHARS: usize = 5_000;
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52#[non_exhaustive]
53pub struct SocialItem {
54 pub id: String,
56 pub author: String,
58 pub text: String,
60 pub at: DateTime<Utc>,
62 pub visibility: String,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub url: Option<String>,
67}
68
69impl SocialItem {
70 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 pub fn is_direct(&self) -> bool {
89 self.visibility == "direct"
90 }
91}
92
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96#[non_exhaustive]
97pub struct SocialPage {
98 pub items: Vec<SocialItem>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub cursor: Option<String>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub struct SocialPosted {
110 pub id: String,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub url: Option<String>,
115 pub at: DateTime<Utc>,
117}
118
119#[async_trait]
123pub trait SocialDriver: Send + Sync {
124 fn name(&self) -> &str;
126
127 fn max_chars(&self) -> usize;
129
130 async fn mentions(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage>;
136
137 async fn messages(&self, cursor: Option<&str>, limit: usize) -> Result<SocialPage>;
143
144 async fn reply(&self, item: &SocialItem, text: &str) -> Result<SocialPosted>;
150
151 async fn post(&self, text: &str) -> Result<SocialPosted>;
157}
158
159#[derive(Debug, Default)]
162pub struct InMemorySocial {
163 received: Mutex<Vec<SocialItem>>,
164 published: Mutex<Vec<(Option<String>, SocialItem)>>,
165}
166
167impl InMemorySocial {
168 pub fn new() -> Self {
170 Self::default()
171 }
172
173 pub fn receive(&self, item: SocialItem) {
175 self.received.lock().unwrap_or_else(PoisonError::into_inner).push(item);
176 }
177
178 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
241pub 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
282pub struct SocialOutboxBuilder {
284 outbox: SocialOutbox,
285}
286
287impl SocialOutboxBuilder {
288 #[must_use]
290 pub fn suppressions(mut self, suppressions: Arc<dyn SuppressionList>) -> Self {
291 self.outbox.suppressions = suppressions;
292 self
293 }
294
295 #[must_use]
297 pub fn templates(mut self, templates: ReplyTemplates) -> Self {
298 self.outbox.templates = templates;
299 self
300 }
301
302 #[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 pub fn build(self) -> SocialOutbox {
314 self.outbox
315 }
316}
317
318impl SocialOutbox {
319 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 pub fn driver(&self) -> &Arc<dyn SocialDriver> {
337 &self.driver
338 }
339
340 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 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 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 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 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 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
435pub 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
488pub 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
532fn 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
554pub 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}