1use 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
47const MAX_TEXT_CHARS: usize = 8_000;
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub struct InboxMessage {
55 pub channel: String,
58 pub account: String,
60 pub thread: String,
62 pub text: String,
64}
65
66impl InboxMessage {
67 pub fn thread_ref(&self) -> String {
83 format!("{}:{}", self.channel, self.thread)
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase", tag = "outcome", rename_all_fields = "camelCase")]
90pub enum InboxOutcome {
91 Read {
93 reply: String,
95 refused: Vec<String>,
97 site_signal: bool,
100 },
101 Owner,
103 Ignored,
105}
106
107#[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
140pub struct InboxParts {
142 pub team: SiteTeam,
144 pub partitions: SitePartitions,
146 pub table: Partitions,
148 pub model: Arc<dyn Llm>,
150 pub tools: PublicTools,
152 pub workspace: PathBuf,
154 pub signals: Arc<dyn SignalEmitter>,
157 pub audit: Option<AuditTrail>,
159}
160
161pub 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 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 #[must_use]
245 pub fn with_bindings(mut self, bindings: Arc<dyn ChannelBindingStore>) -> Self {
246 self.bindings = Some(bindings);
247 self
248 }
249
250 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 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 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 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 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
439pub struct ChannelReplier {
463 sink: Arc<dyn ChannelSink>,
464 template: String,
465}
466
467impl ChannelReplier {
468 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}