Skip to main content

adk_website/
inbox.rs

1//! The Inbox: the site's messages from people who are not paired to it (spec 3.5 §7.19,
2//! §7.10, §10 X12, A-I2, A-I3, A-I24).
3//!
4//! | What wakes it | What reaches the Inbox |
5//! |---|---|
6//! | The site's email | Each message the email driver's inbox reads, as channel `email`; a served site reads the inbox while it serves ([`SiteInbox::read_email`]) |
7//! | A chat channel the kernel has | A [`ChannelInbound`] that a [`ChannelSink`] adapter received from an account no person paired ([`SiteInbox::receive_inbound`]); a paired account's message is the owner's, for the kernel's channel gateway |
8//!
9//! The Inbox runs in the public partition over the edge's public tools — the declared
10//! capabilities, `search_site`, `reply_in_thread` and `emit_signal` — under the partition's
11//! manifest policy, as the Concierge does. A turn's `reply_in_thread` answers the message's
12//! own thread, `<channel>:<thread>`, through the inbox drivers' repliers: the email outbox
13//! for `email`, and [`ChannelReplier`] over a chat channel's sink. When the screen flags a
14//! message or the policy refuses one of the Inbox's calls, and the Inbox filed no signal,
15//! the site files an `inbound_message` signal for it, so the back office hears of every such
16//! message and reads none of its text (A-I3).
17
18use std::collections::BTreeMap;
19use std::path::PathBuf;
20use std::sync::Arc;
21
22use adk_awp::v2::capability::META_TIER;
23use adk_core::audit_log::AuditTrail;
24use adk_core::{
25    AdkError, Agent, Content, Llm, Part, PolicyCall, PolicyDecision, Result, RunConfig, SessionId,
26    ToolPolicy, ToolPolicyRequest, UserId,
27};
28use adk_drivers::ThreadReplier;
29use adk_harness::website::SitePartitions;
30use adk_kernel::Partitions;
31use adk_kernel::channels::{ChannelBindingStore, ChannelInbound, ChannelSink, InboundBody};
32use adk_runner::Runner;
33use adk_server::awp::{
34    ConversationScreen, InjectionScreen, META_BINDING, META_LIMIT_KEY, META_THREAD,
35    PublicPartitionPolicy, PublicTools, SignalEmitter,
36};
37use adk_session::{CreateRequest, GetRequest, InMemorySessionService, SessionService};
38use async_trait::async_trait;
39use awp_types::MessageCategory;
40use futures::StreamExt as _;
41use serde::{Deserialize, Serialize};
42use serde_json::{Value, json};
43use tokio::sync::Mutex;
44
45use crate::team::{AgentRole, SiteTeam};
46
47/// The longest message text the Inbox reads, in characters.
48const MAX_TEXT_CHARS: usize = 8_000;
49
50/// One message for the Inbox (spec 3.5 §7.19): untrusted input from a person who is not
51/// paired to the site.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub struct InboxMessage {
55    /// The channel, such as `email`, `telegram` or `social`: the prefix of its thread
56    /// reference.
57    pub channel: String,
58    /// The sending account on the channel.
59    pub account: String,
60    /// The thread the message is in, which a reply answers.
61    pub thread: String,
62    /// What the person wrote.
63    pub text: String,
64}
65
66impl InboxMessage {
67    /// The thread reference `reply_in_thread` answers: `<channel>:<thread>`.
68    ///
69    /// # Example
70    ///
71    /// ```rust
72    /// use adk_website::inbox::InboxMessage;
73    ///
74    /// let message = InboxMessage {
75    ///     channel: "email".into(),
76    ///     account: "wanjiru@mail.example".into(),
77    ///     thread: "m-1@mail.example".into(),
78    ///     text: "When do you open?".into(),
79    /// };
80    /// assert_eq!(message.thread_ref(), "email:m-1@mail.example");
81    /// ```
82    pub fn thread_ref(&self) -> String {
83        format!("{}:{}", self.channel, self.thread)
84    }
85}
86
87/// What one message did.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase", tag = "outcome", rename_all_fields = "camelCase")]
90pub enum InboxOutcome {
91    /// The Inbox read it.
92    Read {
93        /// The Inbox's last words in the turn.
94        reply: String,
95        /// The tools the policy refused in the turn.
96        refused: Vec<String>,
97        /// Whether the site filed the turn's `inbound_message` signal because the Inbox
98        /// filed none for a flagged or refused message.
99        site_signal: bool,
100    },
101    /// A paired account's message: the owner's, for the kernel's channel gateway (A-I24).
102    Owner,
103    /// Not a message: a pressed answer or a stop, which only the gateway takes.
104    Ignored,
105}
106
107/// The public partition's policy, noting the calls it refuses in the current turn.
108#[derive(Debug)]
109struct WatchedPolicy {
110    inner: PublicPartitionPolicy,
111    refused: Arc<std::sync::Mutex<Vec<String>>>,
112}
113
114#[async_trait]
115impl ToolPolicy for WatchedPolicy {
116    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
117        self.evaluate_call(request, &PolicyCall::new()).await
118    }
119
120    async fn evaluate_call(
121        &self,
122        request: &ToolPolicyRequest,
123        call: &PolicyCall<'_>,
124    ) -> PolicyDecision {
125        let decision = self.inner.evaluate_call(request, call).await;
126        if matches!(decision, PolicyDecision::Deny { .. }) {
127            self.refused
128                .lock()
129                .unwrap_or_else(std::sync::PoisonError::into_inner)
130                .push(request.tool_name.clone());
131        }
132        decision
133    }
134
135    fn policy_ref(&self) -> Option<String> {
136        self.inner.policy_ref()
137    }
138}
139
140/// What [`SiteInbox::new`] builds the Inbox from.
141pub struct InboxParts {
142    /// The site's team; the Inbox's instruction carries the kind's public instruction.
143    pub team: SiteTeam,
144    /// The site's partitions.
145    pub partitions: SitePartitions,
146    /// The kernel's partition table.
147    pub table: Partitions,
148    /// The model the Inbox reads with.
149    pub model: Arc<dyn Llm>,
150    /// The edge's public tools.
151    pub tools: PublicTools,
152    /// The Inbox's workspace, which holds its playbooks.
153    pub workspace: PathBuf,
154    /// Where the site's own `inbound_message` signals go: the edge's signals into the back
155    /// office.
156    pub signals: Arc<dyn SignalEmitter>,
157    /// Where refusals are audited.
158    pub audit: Option<AuditTrail>,
159}
160
161/// The site's Inbox agent (spec 3.5 §7.19).
162pub struct SiteInbox {
163    runner: Runner,
164    sessions: Arc<dyn SessionService>,
165    app: String,
166    principal: String,
167    signals: Arc<dyn SignalEmitter>,
168    screen: Arc<dyn ConversationScreen>,
169    refused: Arc<std::sync::Mutex<Vec<String>>>,
170    bindings: Option<Arc<dyn ChannelBindingStore>>,
171    turn: Mutex<()>,
172}
173
174impl std::fmt::Debug for SiteInbox {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.debug_struct("SiteInbox").field("app", &self.app).finish_non_exhaustive()
177    }
178}
179
180fn digest(text: &str) -> String {
181    adk_site::release::file_digest(text.as_bytes()).hex()[..24].to_string()
182}
183
184impl SiteInbox {
185    /// The Inbox of `parts.team`'s site over the edge's public tools (spec 3.5 §7.19,
186    /// §7.10): the website preset in the public partition with the Inbox's instruction, and
187    /// exactly the tools the edge's public policy admits.
188    ///
189    /// # Errors
190    ///
191    /// Returns the harness's or the runner's error when the agent does not build.
192    pub fn new(parts: InboxParts) -> Result<Self> {
193        let InboxParts { team, partitions, table, model, tools, workspace, signals, audit } = parts;
194        let instruction = match team.public_instruction() {
195            "" => AgentRole::Inbox.prompt().to_string(),
196            kind => format!("{}\n\n{kind}", AgentRole::Inbox.prompt()),
197        };
198        let served = adk_harness::website::ServedPublicTools {
199            partitions,
200            table,
201            search_site: tools.search_site.clone(),
202            reply_in_thread: Some(tools.reply_in_thread.clone()),
203            emit_signal: tools.emit_signal.clone(),
204            capabilities: tools.capabilities.iter().map(|tool| (tool.clone(), false)).collect(),
205        };
206        let agent: Arc<dyn Agent> = Arc::new(
207            adk_harness::HarnessAgent::builder(AgentRole::Inbox.as_str())
208                .model(model)
209                .workspace(adk_devtools::Workspace::new(&workspace))
210                .website_public_served(served)
211                .instruction(instruction)
212                .build()?,
213        );
214        let refused = Arc::new(std::sync::Mutex::new(Vec::new()));
215        let sessions: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
216        let app = format!("{}-inbox", team.site().name);
217        let mut builder = Runner::builder()
218            .app_name(app.clone())
219            .agent(agent)
220            .session_service(sessions.clone())
221            .tool_policy(Arc::new(WatchedPolicy {
222                inner: tools.policy(),
223                refused: refused.clone(),
224            }));
225        if let Some(audit) = &audit {
226            builder = builder.audit_log(audit.recorder().clone());
227        }
228        Ok(Self {
229            runner: builder.build()?,
230            sessions,
231            app,
232            principal: AgentRole::Inbox.principal(team.site()),
233            signals,
234            screen: Arc::new(InjectionScreen),
235            refused,
236            bindings: None,
237            turn: Mutex::new(()),
238        })
239    }
240
241    /// Routes chat messages with the kernel's channel `bindings`: a paired account's message
242    /// is the owner's and the Inbox does not read it (A-I24). Without them every message
243    /// handed to the Inbox is a stranger's.
244    #[must_use]
245    pub fn with_bindings(mut self, bindings: Arc<dyn ChannelBindingStore>) -> Self {
246        self.bindings = Some(bindings);
247        self
248    }
249
250    /// Reads `inbound` from a chat channel the kernel has (spec 3.5 §7.19, A-I24): a typed
251    /// message from an account no person paired is the Inbox's; a paired account's is
252    /// [`InboxOutcome::Owner`]; a pressed answer or a stop is [`InboxOutcome::Ignored`].
253    ///
254    /// # Errors
255    ///
256    /// The channel bindings' error, or [`receive`](Self::receive)'s.
257    pub async fn receive_inbound(&self, inbound: &ChannelInbound) -> Result<InboxOutcome> {
258        let InboundBody::Text { text } = &inbound.body else { return Ok(InboxOutcome::Ignored) };
259        if let Some(bindings) = &self.bindings {
260            let router = adk_harness::website::AuthoringRouter::new(bindings.clone());
261            if matches!(
262                router.route(inbound).await?,
263                adk_harness::website::AuthoringRoute::Owner { .. }
264            ) {
265                return Ok(InboxOutcome::Owner);
266            }
267        }
268        self.receive(InboxMessage {
269            channel: inbound.channel.clone(),
270            account: inbound.account.clone(),
271            thread: inbound.thread.clone(),
272            text: text.clone(),
273        })
274        .await
275    }
276
277    /// Runs one turn of the Inbox on `message` (spec 3.5 §7.19): its replies go to the
278    /// message's own thread, and a flagged or refused message the Inbox filed no signal for
279    /// gets the site's `inbound_message` signal.
280    ///
281    /// # Errors
282    ///
283    /// The session service's or the runner's error.
284    pub async fn receive(&self, message: InboxMessage) -> Result<InboxOutcome> {
285        let _turn = self.turn.lock().await;
286        let text: String = message.text.chars().take(MAX_TEXT_CHARS).collect();
287        let thread_ref = message.thread_ref();
288        let user = format!("inbox-{}", digest(&format!("{}:{}", message.channel, message.account)));
289        let session = format!("thread-{}", digest(&thread_ref));
290        self.ensure_session(&user, &session).await?;
291        self.refused.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
292        let metadata = std::collections::HashMap::from([
293            (META_TIER.to_string(), "public".to_string()),
294            (META_THREAD.to_string(), thread_ref.clone()),
295            (META_BINDING.to_string(), message.channel.clone()),
296            (META_LIMIT_KEY.to_string(), format!("{}:{}", message.channel, message.account)),
297        ]);
298        // A channel account is a stranger's claim, not an authenticated identity.
299        let config = RunConfig { request_metadata: metadata, ..RunConfig::default() };
300        let mut events = self
301            .runner
302            .run_with_config(
303                UserId::try_from(user)?,
304                SessionId::try_from(session)?,
305                Content::new("user").with_text(text.clone()),
306                Some(config),
307            )
308            .await?;
309        let (mut reply, mut signalled) = (String::new(), false);
310        while let Some(event) = events.next().await {
311            let event = event?;
312            if event.author == "user" || event.llm_response.partial {
313                continue;
314            }
315            let Some(content) = &event.llm_response.content else { continue };
316            for part in &content.parts {
317                match part {
318                    Part::FunctionResponse { function_response, .. }
319                        if function_response.name == "emit_signal"
320                            && function_response.response.get("error").is_none() =>
321                    {
322                        signalled = true;
323                    }
324                    _ => {}
325                }
326            }
327            let said: String = content
328                .parts
329                .iter()
330                .filter_map(|part| match part {
331                    Part::Text { text } => Some(text.as_str()),
332                    _ => None,
333                })
334                .collect();
335            if !said.is_empty() {
336                reply = said;
337            }
338        }
339        let refused = std::mem::take(
340            &mut *self.refused.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
341        );
342        let flagged = self.screen.flags(&text);
343        let site_signal = (flagged || !refused.is_empty()) && !signalled;
344        if site_signal {
345            self.file_signal(&message.channel, &thread_ref).await;
346        }
347        tracing::info!(
348            inbox.channel = %message.channel,
349            inbox.flagged = flagged,
350            inbox.refused = refused.len(),
351            inbox.site_signal = site_signal,
352            "the Inbox read a message"
353        );
354        Ok(InboxOutcome::Read { reply, refused, site_signal })
355    }
356
357    /// Reads up to `limit` new messages from the site's email after `cursor` and hands each
358    /// one a person wrote to the Inbox (spec 3.5 §7.19 "Email and social webhooks"); returns
359    /// the cursor after them. Bounces, complaints and unsubscribes are the outbox's to act
360    /// on, and a message software sent on its own gets no turn.
361    ///
362    /// # Errors
363    ///
364    /// The email driver's error; a message whose turn fails is logged and skipped.
365    pub async fn read_email(
366        &self,
367        outbox: &adk_drivers::email::EmailOutbox,
368        cursor: Option<&str>,
369        limit: usize,
370    ) -> Result<Option<String>> {
371        let page = outbox
372            .read_inbox(cursor, limit)
373            .await
374            .map_err(|e| AdkError::config(format!("the site's email inbox: {e}")))?;
375        for email in &page.messages {
376            if email.kind != adk_drivers::email::InboundKind::Message || email.auto_submitted {
377                continue;
378            }
379            let message = InboxMessage {
380                channel: "email".into(),
381                account: email.from.address.clone(),
382                thread: email.thread.clone(),
383                text: format!("Subject: {}\n\n{}", email.subject, email.text),
384            };
385            if let Err(error) = self.receive(message).await {
386                tracing::warn!(error = %error, "the Inbox could not read an email");
387            }
388        }
389        Ok(page.cursor.or_else(|| cursor.map(str::to_string)))
390    }
391
392    async fn ensure_session(&self, user: &str, session: &str) -> Result<()> {
393        let existing = self
394            .sessions
395            .get(GetRequest {
396                app_name: self.app.clone(),
397                user_id: user.to_string(),
398                session_id: session.to_string(),
399                num_recent_events: None,
400                after: None,
401            })
402            .await;
403        match existing {
404            Ok(_) => Ok(()),
405            Err(error) if error.is_not_found() => {
406                let created = self
407                    .sessions
408                    .create(CreateRequest {
409                        app_name: self.app.clone(),
410                        user_id: user.to_string(),
411                        session_id: Some(session.to_string()),
412                        state: std::collections::HashMap::new(),
413                    })
414                    .await;
415                match created {
416                    Err(error) if !error.is_conflict() => Err(error),
417                    _ => Ok(()),
418                }
419            }
420            Err(error) => Err(error),
421        }
422    }
423
424    /// Files the site's `inbound_message` signal for a thread: typed fields only (A-I3).
425    async fn file_signal(&self, channel: &str, thread_ref: &str) {
426        let signal = adk_harness::website::inbound_signal(
427            channel,
428            thread_ref,
429            MessageCategory::Other,
430            &self.principal,
431            chrono::Utc::now(),
432        );
433        if let Err(error) = self.signals.emit(signal).await {
434            tracing::warn!(error = %error, "the Inbox's signal could not be filed");
435        }
436    }
437}
438
439/// `reply_in_thread` over a chat channel the kernel has (spec 3.5 §7.10, §10 X12): a reply
440/// to `<channel>:<thread>` goes to that thread through the channel's [`ChannelSink`], and
441/// only as the playbook's reply template, whose `body` field is the text.
442///
443/// # Example
444///
445/// ```rust
446/// use std::collections::BTreeMap;
447/// use std::sync::Arc;
448/// use adk_drivers::ThreadReplier;
449/// use adk_kernel::channels::InMemoryChannel;
450/// use adk_website::inbox::ChannelReplier;
451///
452/// # #[tokio::main(flavor = "current_thread")]
453/// # async fn main() {
454/// let chat = Arc::new(InMemoryChannel::new("telegram"));
455/// let replier = ChannelReplier::new(chat.clone(), "reply");
456/// let body = BTreeMap::from([("body".to_string(), "We open at seven.".to_string())]);
457/// replier.reply_in_thread("5550", "reply", &body).await.unwrap();
458/// assert_eq!(chat.messages("5550"), ["We open at seven."]);
459/// assert!(replier.reply_in_thread("5550", "refund", &body).await.is_err());
460/// # }
461/// ```
462pub struct ChannelReplier {
463    sink: Arc<dyn ChannelSink>,
464    template: String,
465}
466
467impl ChannelReplier {
468    /// Replies on `sink`'s channel with the template named `template`.
469    pub fn new(sink: Arc<dyn ChannelSink>, template: impl Into<String>) -> Self {
470        Self { sink, template: template.into() }
471    }
472}
473
474#[async_trait]
475impl ThreadReplier for ChannelReplier {
476    fn prefix(&self) -> &str {
477        self.sink.channel()
478    }
479
480    async fn reply_in_thread(
481        &self,
482        thread: &str,
483        template: &str,
484        fields: &BTreeMap<String, String>,
485    ) -> adk_drivers::Result<Value> {
486        if template != self.template {
487            return Err(adk_drivers::DriverError::refused(format!(
488                "`{template}` is not one of the playbook's reply templates ({})",
489                self.template
490            )));
491        }
492        let body = fields.get("body").ok_or_else(|| {
493            adk_drivers::DriverError::invalid(format!("template `{template}` needs field `body`"))
494        })?;
495        self.sink
496            .send_message(thread, body)
497            .await
498            .map_err(|e| adk_drivers::DriverError::unavailable(self.sink.channel(), e))?;
499        Ok(json!({ "status": "sent", "channel": self.sink.channel() }))
500    }
501}