1use std::collections::HashSet;
13use std::fmt;
14use std::sync::Arc;
15use std::time::Duration;
16
17use adk_core::audit_log::{
18 AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
19};
20use adk_core::principal::SubjectRef;
21use adk_core::{ApprovalRequest, ApprovalService, ErrorCategory};
22use adk_kernel::KernelError;
23use adk_kernel::channels::{
24 ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelGateway, ChannelInbound,
25 ChannelNotice, DecisionCard, StopNotice,
26};
27use async_trait::async_trait;
28use chrono::{DateTime, FixedOffset, Utc};
29use serde_json::{Value, json};
30use tokio::sync::mpsc;
31use tokio::task::JoinHandle;
32use tokio::time::Instant;
33
34#[cfg(any(feature = "whatsapp", feature = "slack", feature = "discord", feature = "teams"))]
35pub(crate) use super::telegram::wire::parse_callback;
36pub(crate) use super::telegram::wire::{
37 ANSWER_NOT_TAKEN, Heading, MESSAGE_NOT_TAKEN, callback_data, chat_images, heading, hh_mm,
38 is_hidden, is_invisible, split,
39};
40use crate::answers::{AnswerLog, AnswerRecord, SURFACE_AUDIT_DECIDE};
41use crate::origin::{Origin, SurfaceKind, Via};
42use crate::project::humanize;
43use crate::rules::{Answer, Risk};
44use crate::words;
45
46const MAX_INBOUND_CHARS: usize = 4096;
48const MIN_BACKOFF: Duration = Duration::from_secs(1);
50const UPDATE_ATTEMPTS: u32 = 5;
53#[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
55pub(crate) const MAX_RATE_LIMIT_WAIT: Duration = Duration::from_secs(30);
56pub(crate) const RATE_LIMIT_ATTEMPTS: u32 = 3;
58pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
60
61pub(crate) fn clean_inbound(text: &str) -> Option<String> {
68 let text: String = text.chars().filter(|c| !is_invisible(*c)).take(MAX_INBOUND_CHARS).collect();
69 let text = text.trim();
70 (!text.is_empty()).then(|| text.to_string())
71}
72
73pub(crate) fn clean_outbound(text: &str) -> String {
75 text.chars().filter(|c| !is_hidden(*c)).collect::<String>().trim().to_string()
76}
77
78pub(crate) fn chunks(text: &str, max: usize) -> Vec<String> {
81 split(&clean_outbound(text), max).into_iter().filter(|chunk| !chunk.trim().is_empty()).collect()
83}
84
85pub(crate) fn web_home(home: Option<&str>) -> Option<&str> {
87 home.filter(|home| home.starts_with("https://") || home.starts_with("http://"))
88}
89
90pub(crate) fn truncate(text: &str, max: usize) -> String {
92 if text.chars().count() <= max {
93 return text.to_string();
94 }
95 let mut cut: String = text.chars().take(max.saturating_sub(1)).collect();
96 cut.push('…');
97 cut
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
106pub(crate) enum Piece {
107 Plain(String),
109 Bold(String),
111 Code(String),
114 Link {
116 url: String,
118 label: String,
120 },
121}
122
123#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub(crate) struct Words {
126 pub(crate) lines: Vec<Vec<Piece>>,
127}
128
129impl Words {
130 fn line(mut self, pieces: Vec<Piece>) -> Self {
131 self.lines.push(pieces);
132 self
133 }
134
135 fn plain(text: impl Into<String>) -> Self {
136 Self::default().line(vec![Piece::Plain(text.into())])
137 }
138
139 fn with_home(sentence: &str, home: Option<&str>) -> Self {
141 let words = Self::plain(sentence);
142 match web_home(home) {
143 Some(url) => words.line(vec![Piece::Link {
144 url: url.to_string(),
145 label: words::OPEN_IN_HOME.to_string(),
146 }]),
147 None => words,
148 }
149 }
150
151 pub(crate) fn link(&self) -> Option<(&str, &str)> {
153 self.lines.iter().flatten().find_map(|piece| match piece {
154 Piece::Link { url, label } => Some((url.as_str(), label.as_str())),
155 _ => None,
156 })
157 }
158
159 #[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
161 pub(crate) fn without_link(&self) -> Self {
162 let lines = self
163 .lines
164 .iter()
165 .filter(|line| !line.iter().all(|piece| matches!(piece, Piece::Link { .. })))
166 .cloned()
167 .collect();
168 Self { lines }
169 }
170
171 #[cfg(any(feature = "slack", feature = "matrix", feature = "teams", test))]
173 pub(crate) fn text(&self) -> String {
174 self.render(|piece| match piece {
175 Piece::Plain(text) | Piece::Bold(text) | Piece::Code(text) => text.clone(),
176 Piece::Link { url, label } => format!("{label}: {url}"),
177 })
178 }
179
180 pub(crate) fn render(&self, mut render: impl FnMut(&Piece) -> String) -> String {
182 self.lines
183 .iter()
184 .map(|line| line.iter().map(&mut render).collect::<String>())
185 .collect::<Vec<_>>()
186 .join("\n")
187 }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
193pub(crate) struct Button {
194 pub(crate) answer: ChannelAnswer,
195 pub(crate) label: &'static str,
196 pub(crate) data: String,
197}
198
199pub(crate) fn buttons(card: &DecisionCard) -> Vec<Button> {
202 let buttons: Option<Vec<Button>> = card
203 .answers
204 .iter()
205 .map(|answer| {
206 callback_data(*answer, &card.decision, card.version).map(|data| Button {
207 answer: *answer,
208 label: card.label(*answer),
210 data,
211 })
212 })
213 .collect();
214 buttons.unwrap_or_default()
215}
216
217pub(crate) fn card_words(
222 card: &DecisionCard,
223 heading: &Heading,
224 offset: Option<FixedOffset>,
225) -> Words {
226 let mut words = Words::plain(format!(
227 "{} · {}",
228 words::WAITING_FOR_YOU,
229 words::since(&hh_mm(card.asked_at, offset))
230 ));
231 if !heading.title.trim().is_empty() {
232 words = words.line(vec![Piece::Bold(clean_outbound(&heading.title))]);
233 }
234 if let Some(detail) = &heading.detail {
235 words = words.line(vec![Piece::Plain(clean_outbound(detail))]);
236 }
237 words = words.line(vec![Piece::Plain(format!(
238 "{} · {}",
239 clean_outbound(&humanize(&card.agent)),
240 Risk::from(card.risk).words()
241 ))]);
242 if card.answers.is_empty() {
243 words = words.line(vec![Piece::Plain(words::NEEDS_A_SCREEN.to_string())]);
244 } else if buttons(card).is_empty() {
245 words = words.line(vec![Piece::Plain(ChannelNotice::DecideInHome { home: None }.text())]);
247 }
248 if let Some(url) = web_home(card.home.as_deref()) {
249 words = words.line(vec![Piece::Link {
250 url: url.to_string(),
251 label: words::OPEN_IN_HOME.to_string(),
252 }]);
253 }
254 words
255}
256
257pub(crate) fn stopped_words(notice: &StopNotice) -> Words {
259 Words::with_home(words::ALL_AGENTS_STOPPED_RESUME_IN_HOME, notice.home.as_deref())
260}
261
262pub(crate) fn notice_words(
266 notice: &ChannelNotice,
267 offset: Option<FixedOffset>,
268 now: DateTime<Utc>,
269 replying: bool,
270) -> Words {
271 match notice {
272 ChannelNotice::PairingCode { code, expires_at } => Words::default().line(vec![
273 Piece::Plain("This account isn't paired yet. To pair it, run ".into()),
274 Piece::Code(format!("adk-rust pair accept {}", clean_outbound(code))),
275 Piece::Plain(format!(" where your agents run, before {}.", hh_mm(*expires_at, offset))),
276 ]),
277 ChannelNotice::PairingWaiting { expires_at } => Words::plain(format!(
278 "This account is waiting to be paired. Use the code you were sent before {}.",
279 hh_mm(*expires_at, offset)
280 )),
281 ChannelNotice::AlreadyDecided { by, said, at } => {
282 let who = by.as_deref().unwrap_or("You");
283 let line = match at {
284 Some(at) => {
285 format!("Decided already: {who} said {said} at {}.", hh_mm(*at, offset))
286 }
287 None => format!("Decided already: {who} said {said}."),
288 };
289 Words::plain(clean_outbound(&line))
290 }
291 ChannelNotice::Decided { answer, summary } => {
292 let line = match answer {
293 ChannelAnswer::AllowOnce => format!("You allowed it once · {}", hh_mm(now, offset)),
294 ChannelAnswer::Deny => format!("You denied it · {}", hh_mm(now, offset)),
295 _ => return Words::plain(clean_outbound(¬ice.text())),
296 };
297 if replying {
298 Words::plain(line)
299 } else {
300 Words::plain(line).line(vec![Piece::Plain(clean_outbound(summary))])
301 }
302 }
303 ChannelNotice::Stopped { home } => {
304 Words::with_home(words::ALL_AGENTS_STOPPED_RESUME_IN_HOME, home.as_deref())
305 }
306 ChannelNotice::DecideInHome { home } => {
307 Words::with_home(&ChannelNotice::DecideInHome { home: None }.text(), home.as_deref())
308 }
309 ChannelNotice::ResumeRefused { home } => {
310 Words::with_home(&ChannelNotice::ResumeRefused { home: None }.text(), home.as_deref())
311 }
312 other => Words::plain(clean_outbound(&other.text())),
313 }
314}
315
316tokio::task_local! {
321 pub(crate) static HANDLING: Arc<Handling>;
323}
324
325pub(crate) struct Handling {
327 pub(crate) channel: &'static str,
329 pub(crate) thread: String,
331 pub(crate) account: String,
333 pub(crate) paired: bool,
335 pub(crate) bindings: Arc<dyn ChannelBindingStore>,
337 pub(crate) press: Option<PressedCard>,
339}
340
341pub(crate) struct PressedCard {
343 pub(crate) card: Option<String>,
345 pub(crate) decision: String,
347}
348
349impl Handling {
350 pub(crate) fn of(
352 channel: &'static str,
353 gateway: &ChannelGateway,
354 inbound: &ChannelInbound,
355 paired: bool,
356 press: Option<PressedCard>,
357 ) -> Arc<Self> {
358 Arc::new(Self {
359 channel,
360 thread: inbound.thread.clone(),
361 account: inbound.account.clone(),
362 paired,
363 bindings: Arc::clone(gateway.bindings()),
364 press,
365 })
366 }
367}
368
369pub(crate) fn handling(channel: &str, thread: &str) -> Option<Arc<Handling>> {
371 HANDLING
372 .try_with(Arc::clone)
373 .ok()
374 .filter(|handling| handling.channel == channel && handling.thread == thread)
375}
376
377pub(crate) fn patient(channel: &str, thread: &str) -> bool {
380 handling(channel, thread).is_none_or(|handling| handling.paired)
381}
382
383fn may_clear(error: &KernelError) -> bool {
386 if matches!(error, KernelError::Frozen { .. }) {
387 return false;
388 }
389 match error.category() {
390 ErrorCategory::Unavailable | ErrorCategory::Timeout | ErrorCategory::RateLimited => true,
391 ErrorCategory::InvalidInput
392 | ErrorCategory::Unauthorized
393 | ErrorCategory::Forbidden
394 | ErrorCategory::NotFound
395 | ErrorCategory::Cancelled
396 | ErrorCategory::Internal
397 | ErrorCategory::Unsupported
398 | ErrorCategory::ResourceExhausted
399 | ErrorCategory::Conflict => false,
400 }
401}
402
403pub(crate) async fn is_paired(gateway: &ChannelGateway, channel: &str, account: &str) -> bool {
406 paired_binding(gateway, channel, account).await.map_or(true, |binding| binding.is_some())
407}
408
409pub(crate) async fn paired_binding(
411 gateway: &ChannelGateway,
412 channel: &str,
413 account: &str,
414) -> std::result::Result<Option<ChannelBinding>, ()> {
415 let id = ChannelBinding::id_for(channel, account);
416 match gateway.bindings().get_binding(&id).await {
417 Ok(binding) => Ok(binding.filter(ChannelBinding::is_active)),
418 Err(error) => {
419 tracing::debug!(channel.name = channel, error = %error, "a chat account's pairing could not be read");
420 Err(())
421 }
422 }
423}
424
425pub(crate) struct Update<P> {
432 pub(crate) inbound: Option<ChannelInbound>,
433 pub(crate) press: Option<P>,
434}
435
436#[async_trait]
438pub(crate) trait Taker: Send + Sync + 'static {
439 type Press: Send + Sync + 'static;
441
442 fn channel_name(&self) -> &'static str;
444
445 async fn take(
447 &self,
448 gateway: &ChannelGateway,
449 update: &Update<Self::Press>,
450 paired: bool,
451 ) -> adk_kernel::Result<()>;
452
453 async fn not_taken(&self, update: &Update<Self::Press>);
455}
456
457struct Queued<P> {
458 update: Update<P>,
459 attempts: u32,
460 ready_at: Instant,
461}
462
463impl<P> Queued<P> {
464 fn new(update: Update<P>) -> Self {
465 Self { update, attempts: 0, ready_at: Instant::now() }
466 }
467}
468
469pub(crate) fn dispatch<T: Taker>(
477 taker: Arc<T>,
478 gateway: ChannelGateway,
479) -> (mpsc::UnboundedSender<Update<T::Press>>, JoinHandle<()>) {
480 let (sender, mut receiver) = mpsc::unbounded_channel::<Update<T::Press>>();
481 let task = tokio::spawn(async move {
482 let mut queue: Vec<Queued<T::Press>> = Vec::new();
483 let mut open = true;
484 loop {
485 if queue.is_empty() {
486 if !open {
487 return;
488 }
489 match receiver.recv().await {
490 Some(update) => queue.push(Queued::new(update)),
491 None => return,
492 }
493 }
494 while let Ok(update) = receiver.try_recv() {
495 queue.push(Queued::new(update));
496 }
497 queue = take_batch(taker.as_ref(), &gateway, queue).await;
498 let Some(next) = queue.iter().map(|queued| queued.ready_at).min() else { continue };
499 if open {
500 tokio::select! {
502 () = tokio::time::sleep_until(next) => {}
503 received = receiver.recv() => match received {
504 Some(update) => queue.push(Queued::new(update)),
505 None => open = false,
506 },
507 }
508 } else {
509 tokio::time::sleep_until(next).await;
510 }
511 }
512 });
513 (sender, task)
514}
515
516async fn take_batch<T: Taker>(
518 taker: &T,
519 gateway: &ChannelGateway,
520 queue: Vec<Queued<T::Press>>,
521) -> Vec<Queued<T::Press>> {
522 let now = Instant::now();
523 let mut batch = Vec::with_capacity(queue.len());
524 for queued in queue {
525 let paired = match &queued.update.inbound {
526 Some(inbound) => is_paired(gateway, taker.channel_name(), &inbound.account).await,
527 None => false,
528 };
529 batch.push((queued, paired));
530 }
531 batch.sort_by_key(|(_, paired)| !*paired);
533 let mut held: HashSet<String> = HashSet::new();
534 let mut kept = Vec::new();
535 for (mut queued, paired) in batch {
536 let account = queued.update.inbound.as_ref().map(|inbound| inbound.account.clone());
537 if account.as_ref().is_some_and(|account| held.contains(account)) {
538 kept.push(queued);
539 continue;
540 }
541 if queued.ready_at > now {
542 held.extend(account);
543 kept.push(queued);
544 continue;
545 }
546 let Err(error) = taker.take(gateway, &queued.update, paired).await else { continue };
547 queued.attempts += 1;
548 let attempt = queued.attempts;
549 if paired && may_clear(&error) && attempt < UPDATE_ATTEMPTS {
550 tracing::warn!(channel.name = taker.channel_name(), error = %error, attempt, "the gateway could not take a chat update; taking it again");
551 queued.ready_at = Instant::now() + MIN_BACKOFF * 2u32.pow(attempt - 1);
552 held.extend(account);
553 kept.push(queued);
554 continue;
555 }
556 tracing::warn!(channel.name = taker.channel_name(), error = %error, attempt, "the gateway could not take a chat update; dropping it");
557 if paired {
558 taker.not_taken(&queued.update).await;
559 }
560 }
561 kept
562}
563
564pub(crate) struct AbortOnDrop(pub(crate) JoinHandle<()>);
566
567impl Drop for AbortOnDrop {
568 fn drop(&mut self) {
569 self.0.abort();
570 }
571}
572
573pub struct ChannelConnection<E> {
587 task: Option<JoinHandle<std::result::Result<(), E>>>,
588}
589
590impl<E> fmt::Debug for ChannelConnection<E> {
591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 f.debug_struct("ChannelConnection").field("running", &!self.is_finished()).finish()
593 }
594}
595
596impl<E: Send + 'static> ChannelConnection<E> {
597 pub(crate) fn spawn(
598 future: impl Future<Output = std::result::Result<(), E>> + Send + 'static,
599 ) -> Self {
600 Self { task: Some(tokio::spawn(future)) }
601 }
602}
603
604impl<E> ChannelConnection<E> {
605 pub fn stop(&self) {
608 if let Some(task) = &self.task {
609 task.abort();
610 }
611 }
612
613 pub fn is_finished(&self) -> bool {
615 self.task.as_ref().is_none_or(JoinHandle::is_finished)
616 }
617
618 pub async fn join(mut self) -> std::result::Result<(), E> {
625 let Some(task) = self.task.take() else { return Ok(()) };
626 match task.await {
627 Ok(result) => result,
628 Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
629 Err(_) => Ok(()),
630 }
631 }
632}
633
634impl<E> Drop for ChannelConnection<E> {
635 fn drop(&mut self) {
636 if let Some(task) = &self.task {
637 task.abort();
638 }
639 }
640}
641
642#[derive(Clone, Default)]
649pub(crate) struct Kit {
650 pub(crate) offset: Option<FixedOffset>,
651 pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
652 pub(crate) answers: Option<Arc<dyn AnswerLog>>,
653 pub(crate) audit: Option<AuditTrail>,
654 pub(crate) card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
655}
656
657impl Kit {
658 pub(crate) async fn prepare(&self, card: &DecisionCard) -> (Heading, DecisionCard) {
662 let request = match &self.approvals {
663 Some(approvals) => approvals.get(&card.decision).await.unwrap_or_else(|error| {
664 tracing::warn!(error = %error, "a card's decision could not be read; headed by its summary");
665 None
666 }),
667 None => None,
668 };
669 let mut heading = heading(card, request.as_ref());
670 let mut card = card.clone();
671 if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
674 chat_images(request, None, &mut card, &mut heading).await;
675 }
676 if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
677 let mut headed = false;
678 for hints in &self.card_hints {
679 let Some(hint) = hints.hint(request).await else { continue };
680 if let Some(chat) = hint.chat_heading.filter(|_| !headed) {
681 heading.title = chat;
682 headed = true;
683 }
684 if hint.money == Some(true) && !card.adds_agent {
685 card.answers.clear();
686 }
687 }
688 }
689 (heading, card)
690 }
691
692 pub(crate) async fn before_notice(
697 &self,
698 channel: &'static str,
699 label: &'static str,
700 thread: &str,
701 notice: &ChannelNotice,
702 ) -> Option<String> {
703 let handling = handling(channel, thread)?;
704 let press = handling.press.as_ref()?;
705 if let ChannelNotice::Decided { answer, .. } = notice {
706 self.record_answer(channel, label, &handling, &press.decision, *answer).await;
707 }
708 press.card.clone()
709 }
710
711 async fn record_answer(
713 &self,
714 channel: &str,
715 label: &str,
716 handling: &Handling,
717 decision: &str,
718 answer: ChannelAnswer,
719 ) {
720 let answer = match answer {
721 ChannelAnswer::AllowOnce => Answer::AllowOnce,
722 ChannelAnswer::Deny => Answer::Deny,
723 _ => return,
724 };
725 let id = ChannelBinding::id_for(channel, &handling.account);
726 let binding = match handling.bindings.get_binding(&id).await {
727 Ok(Some(binding)) => binding,
728 Ok(None) => return,
729 Err(error) => {
730 tracing::warn!(channel.name = channel, error = %error, "a chat answer could not be recorded");
731 return;
732 }
733 };
734 let record = AnswerRecord {
735 approval_id: decision.to_string(),
736 by: SubjectRef::human(binding.user_id),
737 via: Via { surface: SurfaceKind::Chat, origin: Origin::Chat { channel: label.into() } },
738 answer,
739 at: Utc::now(),
740 };
741 if let Some(log) = &self.answers
742 && let Err(error) = log.record(&record).await
743 {
744 tracing::warn!(channel.name = channel, error = %error, "a chat answer could not be kept in the answer log");
745 }
746 let request = match (&self.audit, &self.approvals) {
747 (Some(_), Some(approvals)) => approvals.get(decision).await.ok().flatten(),
748 _ => None,
749 };
750 let title = match &request {
751 Some(request) => crate::hints::named(&self.card_hints, request).await,
752 None => None,
753 };
754 if let Some(trail) = &self.audit
755 && let Err(error) = trail.record(answer_record(&record, request.as_ref(), title)).await
756 {
757 tracing::warn!(channel.name = channel, error = %error, "a chat answer's audit record could not be written");
758 }
759 }
760}
761
762fn answer_record(
765 record: &AnswerRecord,
766 request: Option<&ApprovalRequest>,
767 title: Option<String>,
768) -> AuditRecordDraft {
769 let decision = match record.answer {
770 Answer::Deny => AuditDecision::Rejected,
771 Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => AuditDecision::Approved,
772 };
773 let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
774 .actor(AuditActor::subject(record.by.clone()))
775 .ext("surface", serde_json::to_value(record.via.surface).unwrap_or(Value::Null))
776 .ext("origin", serde_json::to_value(&record.via.origin).unwrap_or(Value::Null))
777 .ext("approvalId", json!(record.approval_id))
778 .ext("answer", serde_json::to_value(record.answer).unwrap_or(Value::Null))
779 .ext("outcome", json!("decided"))
780 .decision(decision);
781 if let Some(request) = request {
782 draft = draft.ext("tool", json!(request.tool_name));
783 if let Some(acting) = &request.acting {
784 draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
785 }
786 if let Some(title) = title {
788 draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
789 }
790 }
791 draft
792}
793
794macro_rules! kit_builder {
796 ($adapter:literal) => {
797 #[must_use]
800 pub fn utc_offset(mut self, offset: chrono::FixedOffset) -> Self {
801 self.kit.offset = Some(offset);
802 self
803 }
804
805 #[must_use]
810 pub fn approvals(mut self, approvals: std::sync::Arc<dyn adk_core::ApprovalService>) -> Self {
811 self.kit.approvals = Some(approvals);
812 self
813 }
814
815 #[doc = concat!("Records each answer given in ", $adapter, " in `log`, the engine's [`AnswerLog`](crate::AnswerLog), so every")]
816 #[doc = concat!("other surface shows \"You said yes in ", $adapter, " at 07:31\" (spec 3.3 §8.1). Give the log")]
817 #[must_use]
819 pub fn answer_log(mut self, log: std::sync::Arc<dyn crate::answers::AnswerLog>) -> Self {
820 self.kit.answers = Some(log);
821 self
822 }
823
824 #[doc = concat!("Writes a `surface.decide` record of each answer given in ", $adapter, " to `trail`, the")]
825 #[must_use]
828 pub fn audit(mut self, trail: adk_core::audit_log::AuditTrail) -> Self {
829 self.kit.audit = Some(trail);
830 self
831 }
832
833 #[must_use]
837 pub fn card_hints(mut self, hints: std::sync::Arc<dyn crate::hints::CardHints>) -> Self {
838 self.kit.card_hints.push(hints);
839 self
840 }
841 };
842}
843pub(crate) use kit_builder;
844
845pub(crate) fn checked_base(base: &str, what: &str, websocket: bool) -> Result<String, String> {
853 let base = base.trim_end_matches('/');
854 let url = reqwest::Url::parse(base)
855 .map_err(|error| format!("{what} `{base}` is not a URL: {error}"))?;
856 let secure = if websocket { "wss" } else { "https" };
857 let plain = if websocket { "ws" } else { "http" };
858 match url.scheme() {
859 scheme if scheme == secure => Ok(base.to_string()),
860 scheme if scheme == plain && is_loopback(&url) => Ok(base.to_string()),
861 scheme if scheme == plain => Err(format!(
862 "{what} `{base}` must use {secure}: the token travels with every call (plain \
863 {plain} is accepted on loopback only)"
864 )),
865 other => Err(format!("{what} `{base}` uses `{other}`: use {secure}")),
866 }
867}
868
869fn is_loopback(url: &reqwest::Url) -> bool {
871 let host = url.host_str().unwrap_or_default();
872 let host = host.trim_start_matches('[').trim_end_matches(']');
873 host == "localhost"
874 || host.ends_with(".localhost")
875 || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
876}
877
878pub(crate) fn checked_token(token: &str, what: &str) -> Result<(), String> {
881 if token.is_empty() || !token.bytes().all(|b| b.is_ascii_graphic()) {
882 return Err(format!("{what} is empty or malformed: copy it again from the platform"));
883 }
884 Ok(())
885}
886
887#[cfg(test)]
888mod tests {
889 use adk_core::{
890 ActingContext, AgentPrincipal, ApprovalPolicy, ApprovalRisk, ApprovalScope,
891 ApproverSelector, ToolConfirmationRequest,
892 };
893
894 use super::*;
895
896 fn utc() -> Option<FixedOffset> {
897 FixedOffset::east_opt(0)
898 }
899
900 fn card(risk: ApprovalRisk) -> DecisionCard {
901 let call =
902 ToolConfirmationRequest::new("send_email", json!({ "to": "client@example.com" }));
903 let request = ApprovalRequest::new(
904 "apr_1",
905 ApprovalScope::new("adk-rust", "ana", "s1"),
906 &call,
907 ApprovalPolicy::new([ApproverSelector::group("operator")]),
908 )
909 .with_summary("Send the invoice to client@example.com")
910 .with_risk(risk)
911 .with_acting(ActingContext::new(AgentPrincipal::derived("adk-rust", "finance")));
912 DecisionCard::from_request(&request, Some("https://home.example/ui/"))
913 }
914
915 #[test]
916 fn a_card_reads_as_the_chat_screen_and_carries_no_argument() {
917 let card = card(ApprovalRisk::Medium);
918 let words = card_words(&card, &heading(&card, None), utc());
919 let asked = hh_mm(card.asked_at, utc());
920 assert_eq!(
921 words.text(),
922 format!(
923 "Waiting for you · since {asked}\nSend the invoice to […]\nFinance · Medium \
924 risk\nOpen in home: https://home.example/ui/"
925 )
926 );
927 assert!(!words.text().contains("client@example.com"));
928 assert_eq!(
929 buttons(&card),
930 [
931 Button {
932 answer: ChannelAnswer::AllowOnce,
933 label: "Allow once",
934 data: format!("y:{}:apr_1", card.version)
935 },
936 Button {
937 answer: ChannelAnswer::Deny,
938 label: "Deny",
939 data: format!("n:{}:apr_1", card.version)
940 },
941 ]
942 );
943 assert_eq!(words.link(), Some(("https://home.example/ui/", "Open in home")));
944 #[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
945 assert!(words.without_link().link().is_none());
946 let high = self::card(ApprovalRisk::High);
947 let words = card_words(&high, &heading(&high, None), utc());
948 assert!(buttons(&high).is_empty());
949 assert!(words.text().contains(words::NEEDS_A_SCREEN), "{}", words.text());
950 }
951
952 #[test]
955 fn a_chat_answer_names_the_item_a_hint_names() {
956 let call = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "news-digest" }));
957 let request = ApprovalRequest::new(
958 "apr_1",
959 ApprovalScope::new("adk-rust", "ana", "s1"),
960 &call,
961 ApprovalPolicy::new([ApproverSelector::group("operator")]),
962 )
963 .with_summary("Move News digest to 19:00");
964 let given = AnswerRecord {
965 approval_id: "apr_1".into(),
966 by: SubjectRef::human("ana"),
967 via: Via {
968 surface: SurfaceKind::Chat,
969 origin: Origin::Chat { channel: "Slack".into() },
970 },
971 answer: Answer::Deny,
972 at: Utc::now(),
973 };
974 let named = answer_record(&given, Some(&request), Some("News digest".into()));
975 assert_eq!(
976 (named.ext.get("title"), named.ext.get("summary")),
977 (Some(&json!("News digest")), Some(&json!("Move News digest to 19:00")))
978 );
979 let unnamed = answer_record(&given, Some(&request), None);
980 assert_eq!((unnamed.ext.get("title"), unnamed.ext.get("summary")), (None, None));
981 }
982
983 #[test]
984 fn invisible_characters_never_reach_the_agent() {
985 assert_eq!(
986 clean_inbound("pay\u{200B}ment\u{202E} now\u{E0041} "),
987 Some("payment now".into())
988 );
989 assert_eq!(clean_inbound("\u{200F}\u{FEFF} "), None);
990 assert_eq!(clean_inbound(&"x".repeat(5000)).unwrap().chars().count(), MAX_INBOUND_CHARS);
991 assert_eq!(chunks(" Done.\u{202E}\n ", 10), ["Done."]);
992 assert!(chunks(" \u{200E} ", 10).is_empty());
993 }
994
995 #[test]
996 fn addresses_and_tokens_are_checked() {
997 assert!(checked_base("https://slack.com/api/", "x", false).is_ok());
998 assert!(checked_base("http://127.0.0.1:9", "x", false).is_ok());
999 assert!(checked_base("http://example.com", "x", false).is_err());
1000 assert!(checked_base("ws://[::1]:9/socket", "x", true).is_ok());
1001 assert!(checked_base("ws://example.com/socket", "x", true).is_err());
1002 assert!(checked_base("wss://example.com/socket", "x", true).is_ok());
1003 assert!(checked_token("xoxb-1-abc", "x").is_ok());
1004 for bad in ["", "a b", "a\nb", "é"] {
1005 assert!(checked_token(bad, "x").is_err(), "{bad:?}");
1006 }
1007 assert_eq!(truncate("abcdef", 4), "abc…");
1008 assert_eq!(truncate("abc", 4), "abc");
1009 }
1010}