1use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, PoisonError, Weak};
7use std::time::Duration;
8
9use adk_core::approval::{ApprovalEventKind, ApprovalNotification, ApprovalNotifier};
10use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
11use adk_core::principal::SubjectRef;
12use adk_core::{
13 ApprovalAction, ApprovalDecision, ApprovalRequest, ApprovalRisk, ApprovalState, ErrorCategory,
14 NewRun, OnConflict, RunRecord, RunState,
15};
16use async_trait::async_trait;
17use futures::StreamExt;
18use serde_json::{Value, json};
19use tokio::sync::mpsc;
20use tokio::task::JoinHandle;
21
22use super::{
23 ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelHost, ChannelInbound, ChannelNotice,
24 ChannelPairingRequest, ChannelSink, DecisionCard, InboundBody, InboundOutcome, InboundRoute,
25 StopNotice, TAKE_OVER_TOOL, TurnOrigin, card_summary, chat_may_decide, thread_session,
26};
27use crate::audit;
28use crate::error::{KernelError, Result};
29use crate::pairing::secret;
30use crate::sched::QueueClass;
31
32const DEFAULT_TARGET: &str = "adk-rust";
35const DEFAULT_CODE_TTL: Duration = Duration::from_secs(60 * 60);
38const DEFAULT_MAX_WAITING: usize = 5;
40const VERSION_CONFLICT_CODE: &str = "approval.version_conflict";
42const ALREADY_DECIDED_CODE: &str = "approval.already_decided";
44const DEFAULT_RESWEEP: Duration = Duration::from_secs(60);
47const TURN_POLL: Duration = Duration::from_secs(2);
49const CLOCK_CHECK: Duration = Duration::from_secs(60);
52
53pub struct ChannelDoorbell {
75 sender: mpsc::UnboundedSender<ApprovalRequest>,
76 receiver: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<ApprovalRequest>>>,
78}
79
80impl fmt::Debug for ChannelDoorbell {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 f.debug_struct("ChannelDoorbell").finish_non_exhaustive()
83 }
84}
85
86impl ChannelDoorbell {
87 pub fn new() -> Self {
89 let (sender, receiver) = mpsc::unbounded_channel();
90 Self { sender, receiver: Arc::new(tokio::sync::Mutex::new(receiver)) }
91 }
92}
93
94impl Default for ChannelDoorbell {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100#[async_trait]
101impl ApprovalNotifier for ChannelDoorbell {
102 async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
104 if notification.kind == ApprovalEventKind::Submitted {
105 if self.sender.send(notification.request.clone()).is_err() {
107 tracing::warn!(approval.id = %notification.request.id, "the decision doorbell is gone; the decision waits in the inbox");
108 }
109 }
110 Ok(())
111 }
112}
113
114pub struct ChannelGatewayBuilder {
116 host: Arc<dyn ChannelHost>,
117 bindings: Arc<dyn ChannelBindingStore>,
118 sinks: BTreeMap<String, Arc<dyn ChannelSink>>,
119 target: String,
120 home: Option<String>,
121 code_ttl: Duration,
122 max_waiting: usize,
123 doorbell: Option<Arc<ChannelDoorbell>>,
124 money_tools: Vec<String>,
125 resweep: Duration,
126 route: Option<Arc<dyn InboundRoute>>,
127}
128
129impl fmt::Debug for ChannelGatewayBuilder {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("ChannelGatewayBuilder")
132 .field("sinks", &self.sinks.keys().collect::<Vec<_>>())
133 .field("target", &self.target)
134 .finish_non_exhaustive()
135 }
136}
137
138impl ChannelGatewayBuilder {
139 #[must_use]
141 pub fn sink(mut self, sink: Arc<dyn ChannelSink>) -> Self {
142 self.sinks.insert(sink.channel().to_string(), sink);
143 self
144 }
145
146 #[must_use]
148 pub fn target(mut self, target: impl Into<String>) -> Self {
149 self.target = target.into();
150 self
151 }
152
153 #[must_use]
155 pub fn home_url(mut self, url: impl Into<String>) -> Self {
156 self.home = Some(url.into().trim_end_matches('/').to_string());
157 self
158 }
159
160 #[must_use]
162 pub fn code_ttl(mut self, ttl: Duration) -> Self {
163 self.code_ttl = ttl;
164 self
165 }
166
167 #[must_use]
169 pub fn max_waiting(mut self, max: usize) -> Self {
170 self.max_waiting = max;
171 self
172 }
173
174 #[must_use]
176 pub fn doorbell(mut self, doorbell: Arc<ChannelDoorbell>) -> Self {
177 self.doorbell = Some(doorbell);
178 self
179 }
180
181 #[must_use]
184 pub fn resweep(mut self, every: Duration) -> Self {
185 self.resweep = every;
186 self
187 }
188
189 #[must_use]
204 pub fn money_tools(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
205 self.money_tools.extend(names.into_iter().map(Into::into));
206 self
207 }
208
209 #[must_use]
222 pub fn route(mut self, route: Arc<dyn InboundRoute>) -> Self {
223 self.route = Some(route);
224 self
225 }
226
227 pub fn build(self) -> ChannelGateway {
229 ChannelGateway {
230 inner: Arc::new(Inner {
231 host: self.host,
232 bindings: self.bindings,
233 sinks: self.sinks,
234 target: self.target,
235 home: self.home,
236 code_ttl: self.code_ttl,
237 max_waiting: self.max_waiting,
238 doorbell: self.doorbell,
239 money_tools: self.money_tools,
240 resweep: self.resweep,
241 route: self.route,
242 lifecycle: Mutex::new(Lifecycle::default()),
243 held: Mutex::new(Vec::new()),
244 carded: Mutex::new(Carded::default()),
245 started: Mutex::new(std::collections::BTreeSet::new()),
246 steered: Mutex::new(Carded::default()),
247 replied: Mutex::new(Carded::default()),
248 unpaired: tokio::sync::Mutex::new(()),
249 }),
250 }
251 }
252}
253
254#[derive(Clone)]
278pub struct ChannelGateway {
279 inner: Arc<Inner>,
280}
281
282struct Inner {
283 host: Arc<dyn ChannelHost>,
284 bindings: Arc<dyn ChannelBindingStore>,
285 sinks: BTreeMap<String, Arc<dyn ChannelSink>>,
286 target: String,
287 home: Option<String>,
288 code_ttl: Duration,
289 max_waiting: usize,
290 doorbell: Option<Arc<ChannelDoorbell>>,
291 money_tools: Vec<String>,
292 resweep: Duration,
293 route: Option<Arc<dyn InboundRoute>>,
294 lifecycle: Mutex<Lifecycle>,
296 held: Mutex<Vec<JoinHandle<()>>>,
298 carded: Mutex<Carded>,
300 started: Mutex<std::collections::BTreeSet<String>>,
302 steered: Mutex<Carded>,
305 replied: Mutex<Carded>,
308 unpaired: tokio::sync::Mutex<()>,
311}
312
313#[derive(Default)]
315struct Lifecycle {
316 running: bool,
317 generation: u64,
319 tasks: Vec<JoinHandle<()>>,
320}
321
322#[derive(Default)]
324struct Carded {
325 seen: std::collections::HashSet<(String, u64)>,
326 order: std::collections::VecDeque<(String, u64)>,
327}
328
329impl Carded {
330 const LIMIT: usize = 4096;
331
332 fn note(&mut self, id: &str, version: u64) -> bool {
334 let key = (id.to_string(), version);
335 if !self.seen.insert(key.clone()) {
336 return false;
337 }
338 self.order.push_back(key);
339 if self.order.len() > Self::LIMIT
340 && let Some(oldest) = self.order.pop_front()
341 {
342 self.seen.remove(&oldest);
343 }
344 true
345 }
346
347 fn forget(&mut self, id: &str, version: u64) {
349 let key = (id.to_string(), version);
350 if self.seen.remove(&key) {
351 self.order.retain(|noted| *noted != key);
352 }
353 }
354}
355
356impl Drop for Inner {
357 fn drop(&mut self) {
358 let lifecycle = self.lifecycle.get_mut().unwrap_or_else(PoisonError::into_inner);
359 let held = self.held.get_mut().unwrap_or_else(PoisonError::into_inner);
360 for task in lifecycle.tasks.drain(..).chain(held.drain(..)) {
361 task.abort();
362 }
363 }
364}
365
366impl fmt::Debug for ChannelGateway {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 f.debug_struct("ChannelGateway")
369 .field("sinks", &self.inner.sinks.keys().collect::<Vec<_>>())
370 .field("target", &self.inner.target)
371 .field("home", &self.inner.home)
372 .finish_non_exhaustive()
373 }
374}
375
376enum Control {
378 Stop,
379 Resume,
380}
381
382fn control_word(text: &str) -> Option<Control> {
384 let text = text.trim().trim_end_matches(['.', '!']).to_lowercase();
385 let text = match text.strip_prefix('/') {
387 Some(command) => format!("/{}", command.split('@').next().unwrap_or_default()),
388 None => text,
389 };
390 match text.as_str() {
391 "stop all" | "stop everything" | "/stop" | "/stopall" | "/stop_all" => Some(Control::Stop),
392 "resume" | "resume all" | "unfreeze" | "/resume" | "/resumeall" | "/resume_all"
393 | "/unfreeze" => Some(Control::Resume),
394 _ => None,
395 }
396}
397
398impl ChannelGateway {
399 pub fn builder(
401 host: Arc<dyn ChannelHost>,
402 bindings: Arc<dyn ChannelBindingStore>,
403 ) -> ChannelGatewayBuilder {
404 ChannelGatewayBuilder {
405 host,
406 bindings,
407 sinks: BTreeMap::new(),
408 target: DEFAULT_TARGET.to_string(),
409 home: None,
410 code_ttl: DEFAULT_CODE_TTL,
411 max_waiting: DEFAULT_MAX_WAITING,
412 doorbell: None,
413 money_tools: vec!["payments_*".to_string()],
414 resweep: DEFAULT_RESWEEP,
415 route: None,
416 }
417 }
418
419 pub fn bindings(&self) -> &Arc<dyn ChannelBindingStore> {
421 &self.inner.bindings
422 }
423
424 pub async fn start(&self) -> Result<()> {
433 let generation = {
434 let mut lifecycle = self.lifecycle();
435 if lifecycle.running {
436 return Ok(());
437 }
438 lifecycle.running = true;
439 lifecycle.generation += 1;
440 lifecycle.generation
441 };
442 let mut turns = match self.inner.host.finished_turns().await {
443 Ok(turns) => turns,
444 Err(error) => {
445 let mut lifecycle = self.lifecycle();
446 if lifecycle.generation == generation {
447 lifecycle.running = false;
448 }
449 return Err(error);
450 }
451 };
452 let mut lifecycle = self.lifecycle();
453 if !lifecycle.running || lifecycle.generation != generation {
454 return Ok(());
456 }
457 let weak = Arc::downgrade(&self.inner);
458 lifecycle.tasks.push(tokio::spawn(async move {
459 while let Some(run) = turns.next().await {
460 let Some(gateway) = upgrade(&weak) else { break };
461 gateway.finished(&run).await;
462 }
463 }));
464 let weak = Arc::downgrade(&self.inner);
466 lifecycle.tasks.push(tokio::spawn(async move {
467 loop {
468 tokio::time::sleep(TURN_POLL).await;
469 let Some(gateway) = upgrade(&weak) else { break };
470 gateway.follow_started().await;
471 }
472 }));
473 let weak = Arc::downgrade(&self.inner);
475 let every = self.inner.resweep;
476 lifecycle.tasks.push(tokio::spawn(async move {
477 loop {
478 tokio::time::sleep(every).await;
479 let Some(gateway) = upgrade(&weak) else { break };
480 if let Err(error) = gateway.ring_waiting().await {
481 tracing::warn!(error = %error, "the waiting decisions could not be rung");
482 }
483 }
484 }));
485 if let Some(doorbell) = &self.inner.doorbell {
486 let receiver = doorbell.receiver.clone();
487 let weak = Arc::downgrade(&self.inner);
488 lifecycle.tasks.push(tokio::spawn(async move {
489 let mut receiver = receiver.lock().await;
491 while let Some(request) = receiver.recv().await {
492 let Some(gateway) = upgrade(&weak) else { break };
493 if let Err(error) = gateway.ring(&request).await {
494 tracing::warn!(approval.id = %request.id, error = %error, "a decision card could not be sent");
495 }
496 }
497 }));
498 }
499 Ok(())
500 }
501
502 pub fn stop(&self) {
505 let tasks = {
506 let mut lifecycle = self.lifecycle();
507 lifecycle.running = false;
508 lifecycle.generation += 1;
509 std::mem::take(&mut lifecycle.tasks)
510 };
511 let held =
512 std::mem::take(&mut *self.inner.held.lock().unwrap_or_else(PoisonError::into_inner));
513 for task in tasks.into_iter().chain(held) {
514 task.abort();
515 }
516 *self.inner.carded.lock().unwrap_or_else(PoisonError::into_inner) = Carded::default();
518 }
519
520 fn lifecycle(&self) -> std::sync::MutexGuard<'_, Lifecycle> {
521 self.inner.lifecycle.lock().unwrap_or_else(PoisonError::into_inner)
522 }
523
524 fn hold(&self, task: JoinHandle<()>) {
525 let mut held = self.inner.held.lock().unwrap_or_else(PoisonError::into_inner);
526 held.retain(|task| !task.is_finished());
527 held.push(task);
528 }
529
530 pub async fn receive(&self, inbound: ChannelInbound) -> Result<InboundOutcome> {
542 let sink = self.sink(&inbound.channel)?;
543 let id = ChannelBinding::id_for(&inbound.channel, &inbound.account);
544 let binding = self.inner.bindings.get_binding(&id).await?.filter(ChannelBinding::is_active);
545 if let Some(route) = &self.inner.route
546 && route.take(&inbound, binding.as_ref()).await?
547 {
548 return Ok(InboundOutcome::Routed);
549 }
550 let Some(binding) = binding else {
551 return self.unpaired(sink.as_ref(), &inbound).await;
552 };
553 match &inbound.body {
554 InboundBody::Text { text } if text.trim().is_empty() => Ok(InboundOutcome::Empty),
556 InboundBody::Text { text } => match control_word(text) {
557 Some(Control::Stop) => self.stop_all(sink.as_ref(), &binding, &inbound).await,
558 Some(Control::Resume) => {
559 self.refuse_resume(sink.as_ref(), &binding, &inbound).await
560 }
561 None => self.turn(sink.as_ref(), &binding, &inbound, text).await,
562 },
563 InboundBody::StopAll => self.stop_all(sink.as_ref(), &binding, &inbound).await,
564 InboundBody::ResumeAll => self.refuse_resume(sink.as_ref(), &binding, &inbound).await,
565 InboundBody::Answer { decision, version, answer } => {
566 self.answer(sink.as_ref(), &binding, &inbound, decision, *version, *answer).await
567 }
568 }
569 }
570
571 pub async fn ring(&self, request: &ApprovalRequest) -> Result<usize> {
582 if request.state != ApprovalState::Pending {
583 return Ok(0);
584 }
585 let bindings = self.answering_bindings(request).await?;
586 if bindings.is_empty() {
587 return Ok(0);
588 }
589 if !self.carded().note(&request.id, request.version) {
590 return Ok(0);
591 }
592 let now = self.inner.host.now();
593 if let Some(until) = self.inner.host.quiet_ends(request, now).await {
594 let weak = Arc::downgrade(&self.inner);
595 let held = request.clone();
596 tracing::debug!(approval.id = %request.id, quiet.until = %until, "decision card held for quiet time");
597 let held = tokio::spawn(async move {
598 let id = held.id.clone();
599 if let Err(error) = ring_after_quiet(weak, held).await {
600 tracing::warn!(approval.id = %id, error = %error, "a held decision card could not be sent");
601 }
602 });
603 self.hold(held);
604 return Ok(0);
605 }
606 let reached = self.deliver_card(request, &bindings).await;
607 if reached == 0 {
608 self.carded().forget(&request.id, request.version);
609 }
610 Ok(reached)
611 }
612
613 fn carded(&self) -> std::sync::MutexGuard<'_, Carded> {
614 self.inner.carded.lock().unwrap_or_else(PoisonError::into_inner)
615 }
616
617 async fn finished(&self, run: &RunRecord) {
619 self.inner.started.lock().unwrap_or_else(PoisonError::into_inner).remove(&run.run_id);
620 let first =
621 self.inner.replied.lock().unwrap_or_else(PoisonError::into_inner).note(&run.run_id, 0);
622 if first && let Err(error) = self.reply(run).await {
623 tracing::warn!(run.id = %run.run_id, error = %error, "a chat reply could not be sent");
624 }
625 }
626
627 async fn follow_started(&self) {
629 let started: Vec<String> = self
630 .inner
631 .started
632 .lock()
633 .unwrap_or_else(PoisonError::into_inner)
634 .iter()
635 .cloned()
636 .collect();
637 for pid in started {
638 match self.inner.host.turn(&pid).await {
639 Ok(Some(run)) if run.state.is_terminal() => self.finished(&run).await,
640 Ok(Some(_)) => {}
641 Ok(None) => {
643 self.inner.started.lock().unwrap_or_else(PoisonError::into_inner).remove(&pid);
644 }
645 Err(error) => {
646 tracing::debug!(process.pid = %pid, error = %error, "a chat turn could not be read");
647 }
648 }
649 }
650 }
651
652 async fn answering_bindings(&self, request: &ApprovalRequest) -> Result<Vec<ChannelBinding>> {
655 let mut bindings = self.bindings_of(&request.scope.user_id).await?;
656 bindings.retain(|binding| may_answer(request, binding));
657 Ok(bindings)
658 }
659
660 fn chat_may_answer(&self, request: &ApprovalRequest) -> bool {
663 chat_may_decide(self.risk_of(request)) && !self.moves_money(request)
664 }
665
666 fn risk_of(&self, request: &ApprovalRequest) -> ApprovalRisk {
668 if self.inner.host.rates_high(request) {
669 request.risk.max(ApprovalRisk::High)
670 } else {
671 request.risk
672 }
673 }
674
675 fn moves_money(&self, request: &ApprovalRequest) -> bool {
678 self.inner.host.moves_money(request)
679 || self.inner.money_tools.iter().any(|name| match name.strip_suffix('*') {
680 Some(prefix) => request.tool_name.starts_with(prefix),
681 None => request.tool_name == *name,
682 })
683 }
684
685 fn card(&self, request: &ApprovalRequest) -> DecisionCard {
687 let mut card = DecisionCard::from_request(request, self.inner.home.as_deref());
688 card.risk = self.risk_of(request);
689 if !self.chat_may_answer(request) && !card.adds_agent {
691 card.answers.clear();
692 }
693 card
694 }
695
696 pub async fn ring_waiting(&self) -> Result<usize> {
706 let Some(approvals) = self.inner.host.approvals() else { return Ok(0) };
707 let mut people: BTreeMap<String, Vec<String>> = BTreeMap::new();
708 for binding in self.inner.bindings.list_bindings().await? {
709 if binding.is_active() && self.inner.sinks.contains_key(&binding.channel) {
710 people.entry(binding.user_id.clone()).or_default().extend(binding.groups);
711 }
712 }
713 let mut reached = 0;
714 for (user, groups) in people {
715 let mut cursor = None;
716 loop {
717 let query = adk_core::InboxQuery::for_approver(
718 SubjectRef::human(user.clone()),
719 groups.clone(),
720 )
721 .with_cursor(cursor)
722 .with_limit(200);
723 let page = approvals.inbox(query).await?;
724 for request in page.items.iter().filter(|request| request.scope.user_id == user) {
725 reached += self.ring(request).await?;
726 }
727 match page.next_cursor {
728 Some(next) => cursor = Some(next),
729 None => break,
730 }
731 }
732 }
733 Ok(reached)
734 }
735
736 async fn bindings_of(&self, user_id: &str) -> Result<Vec<ChannelBinding>> {
738 Ok(self
739 .inner
740 .bindings
741 .list_bindings()
742 .await?
743 .into_iter()
744 .filter(|binding| {
745 binding.is_active()
746 && binding.user_id == user_id
747 && self.inner.sinks.contains_key(&binding.channel)
748 })
749 .collect())
750 }
751
752 async fn deliver_card(&self, request: &ApprovalRequest, bindings: &[ChannelBinding]) -> usize {
753 let card = self.card(request);
754 let mut reached = 0;
755 for binding in bindings {
756 let Some(sink) = self.inner.sinks.get(&binding.channel) else { continue };
757 let extra =
758 [("risk", json!(self.risk_of(request))), ("version", json!(request.version))];
759 if let Err(error) = self
760 .record(binding, Some(&binding.user_id), "notify", Some(&request.id), &extra)
761 .await
762 {
763 tracing::warn!(error = %error, "a decision card was not sent: its record failed");
764 continue;
765 }
766 match sink.send_decision(&binding.thread, &card).await {
767 Ok(()) => reached += 1,
768 Err(error) => {
769 tracing::warn!(channel = %binding.channel, error = %error, "a decision card could not be sent")
770 }
771 }
772 }
773 reached
774 }
775
776 async fn reply(&self, run: &RunRecord) -> Result<bool> {
779 let Some(origin) = TurnOrigin::of(run) else { return Ok(false) };
780 let Some(sink) = self.inner.sinks.get(&origin.channel) else { return Ok(false) };
781 let id = ChannelBinding::id_for(&origin.channel, &origin.account);
783 if !self.inner.bindings.get_binding(&id).await?.is_some_and(|binding| binding.is_active()) {
784 return Ok(false);
785 }
786 match run.state {
787 RunState::Completed => {
788 let text = run
789 .result
790 .as_ref()
791 .and_then(|result| result.get("text"))
792 .and_then(Value::as_str)
793 .unwrap_or_default();
794 if text.trim().is_empty() {
795 return Ok(false);
796 }
797 sink.send_message(&origin.thread, text).await?;
798 Ok(true)
799 }
800 RunState::Failed => {
801 sink.send_notice(&origin.thread, &ChannelNotice::TurnFailed).await?;
802 Ok(true)
803 }
804 _ => Ok(false),
805 }
806 }
807
808 fn sink(&self, channel: &str) -> Result<Arc<dyn ChannelSink>> {
809 self.inner.sinks.get(channel).cloned().ok_or_else(|| KernelError::Config {
810 reason: format!(
811 "no adapter for channel `{channel}` on this gateway: add it with \
812 ChannelGatewayBuilder::sink"
813 ),
814 })
815 }
816
817 async fn unpaired(
818 &self,
819 sink: &dyn ChannelSink,
820 inbound: &ChannelInbound,
821 ) -> Result<InboundOutcome> {
822 let _serial = self.inner.unpaired.lock().await;
825 let store = &self.inner.bindings;
826 let now = self.inner.host.now();
827 store.prune_requests(now).await?;
828 if let Some(waiting) = store.get_request(&inbound.channel, &inbound.account).await?
829 && waiting.expires_at > now
830 {
831 if waiting.dismissed {
833 tracing::debug!(channel.name = %inbound.channel, "a dismissed chat account wrote");
834 return Ok(InboundOutcome::PairingDismissed);
835 }
836 if waiting.undelivered {
838 return self.send_code(sink, &inbound.thread, waiting).await;
839 }
840 let notice = ChannelNotice::PairingWaiting { expires_at: waiting.expires_at };
841 self.notify(sink, &inbound.thread, ¬ice).await;
842 return Ok(InboundOutcome::PairingWaiting);
843 }
844 let waiting = store
845 .list_requests()
846 .await?
847 .iter()
848 .filter(|request| {
849 request.channel == inbound.channel && !request.dismissed && request.expires_at > now
850 })
851 .count();
852 let account = Account::of(inbound);
853 if waiting >= self.inner.max_waiting {
854 self.record(&account, None, "pairing.busy", None, &[]).await?;
855 self.notify(sink, &inbound.thread, &ChannelNotice::PairingBusy).await;
856 return Ok(InboundOutcome::PairingBusy);
857 }
858 let expires_at = now + chrono::Duration::from_std(self.inner.code_ttl).unwrap_or_default();
859 let mut request = ChannelPairingRequest::new(
860 String::new(),
861 &inbound.channel,
862 &inbound.account,
863 &inbound.thread,
864 now,
865 expires_at,
866 );
867 request.display_name = inbound
868 .display_name
869 .as_deref()
870 .map(|name| secret::clean_name(name, super::MAX_NAME_CHARS))
871 .filter(|name| !name.is_empty());
872 self.record(
873 &account,
874 None,
875 "pairing.requested",
876 Some(&ChannelBinding::id_for(&inbound.channel, &inbound.account)),
877 &[],
878 )
879 .await?;
880 self.send_code(sink, &inbound.thread, request).await
881 }
882
883 async fn send_code(
889 &self,
890 sink: &dyn ChannelSink,
891 thread: &str,
892 mut request: ChannelPairingRequest,
893 ) -> Result<InboundOutcome> {
894 let store = &self.inner.bindings;
895 let code = secret::new_code()?;
896 request.code_hash = secret::code_hash(&code);
897 request.undelivered = false;
898 store.put_request(request.clone()).await?;
899 let notice = ChannelNotice::PairingCode { code, expires_at: request.expires_at };
900 if let Err(error) = sink.send_notice(thread, ¬ice).await {
901 request.undelivered = true;
902 store.put_request(request).await?;
903 return Err(error);
904 }
905 Ok(InboundOutcome::PairingRequested)
906 }
907
908 async fn turn(
909 &self,
910 sink: &dyn ChannelSink,
911 binding: &ChannelBinding,
912 inbound: &ChannelInbound,
913 text: &str,
914 ) -> Result<InboundOutcome> {
915 let session = thread_session(&inbound.channel, &inbound.thread);
916 let origin = TurnOrigin {
917 channel: inbound.channel.clone(),
918 account: inbound.account.clone(),
919 thread: inbound.thread.clone(),
920 };
921 let run = NewRun::new(
924 QueueClass::INTERACTIVE,
925 self.inner.host.app_name(),
926 binding.user_id.clone(),
927 self.inner.target.clone(),
928 json!({ "text": text, "channel": origin }),
929 )
930 .with_session_id(session.clone())
931 .with_idempotency_key(format!(
932 "channel:{}:{}:{}",
933 inbound.channel, inbound.thread, inbound.message_id
934 ))
935 .with_concurrency_key(session.clone(), OnConflict::Enqueue)
936 .with_authenticated_user();
937 self.record(binding, Some(&binding.user_id), "message", Some(&session), &[]).await?;
938 let key = run.idempotency_key.clone().unwrap_or_default();
941 if !self.steered().note(&key, 0) {
942 return Ok(InboundOutcome::Steered);
943 }
944 match self.inner.host.steer(&binding.user_id, &session, text).await {
945 Ok(Some(receipt)) => {
946 let gateway = self.clone();
948 let thread = inbound.thread.clone();
949 tokio::spawn(async move { gateway.settle(receipt, run, &thread).await });
950 return Ok(InboundOutcome::Steered);
951 }
952 Ok(None) => {}
953 Err(error) => {
955 tracing::debug!(session.id = %session, error = %error, "a chat message was not handed to the running turn");
956 }
957 }
958 self.steered().forget(&key, 0);
959 self.start_turn(sink, &inbound.thread, run).await
960 }
961
962 fn steered(&self) -> std::sync::MutexGuard<'_, Carded> {
963 self.inner.steered.lock().unwrap_or_else(PoisonError::into_inner)
964 }
965
966 async fn start_turn(
968 &self,
969 sink: &dyn ChannelSink,
970 thread: &str,
971 run: NewRun,
972 ) -> Result<InboundOutcome> {
973 match self.inner.host.start_turn(run).await {
974 Ok(pid) => {
975 self.inner
976 .started
977 .lock()
978 .unwrap_or_else(PoisonError::into_inner)
979 .insert(pid.clone());
980 Ok(InboundOutcome::TurnStarted { pid })
981 }
982 Err(KernelError::Frozen { .. }) => {
983 let notice = ChannelNotice::Stopped { home: self.inner.home.clone() };
984 self.notify(sink, thread, ¬ice).await;
985 Ok(InboundOutcome::TurnRefused)
986 }
987 Err(error) => Err(error),
988 }
989 }
990
991 async fn settle(&self, receipt: adk_core::SteerReceipt, run: NewRun, thread: &str) {
995 let steer_id = receipt.steer_id().to_string();
996 let key = run.idempotency_key.clone().unwrap_or_default();
997 let channel = run.input["channel"]["channel"].as_str().unwrap_or_default().to_string();
998 let Ok(sink) = self.sink(&channel) else { return };
999 match receipt.outcome().await {
1000 Ok(adk_core::SteerOutcome::Delivered { .. }) => return,
1001 Ok(adk_core::SteerOutcome::Returned(_)) => {}
1002 Err(error) => {
1005 tracing::warn!(steer.id = %steer_id, error = %error, "a chat message handed to a running turn has no outcome");
1006 self.notify(sink.as_ref(), thread, &ChannelNotice::TurnFailed).await;
1007 return;
1008 }
1009 }
1010 if let Err(error) = self.start_turn(sink.as_ref(), thread, run).await {
1011 tracing::warn!(steer.id = %steer_id, error = %error, "a chat message a turn handed back could not start a turn");
1012 self.steered().forget(&key, 0);
1014 self.notify(sink.as_ref(), thread, &ChannelNotice::TurnFailed).await;
1015 }
1016 }
1017
1018 async fn stop_all(
1019 &self,
1020 sink: &dyn ChannelSink,
1021 binding: &ChannelBinding,
1022 inbound: &ChannelInbound,
1023 ) -> Result<InboundOutcome> {
1024 if let Err(error) = self.record(binding, Some(&binding.user_id), "stop", None, &[]).await {
1026 tracing::warn!(error = %error, "the chat stop's record failed; stopping regardless");
1027 }
1028 let reason = format!("stopped from {} by {}", inbound.channel, binding.user_id);
1029 let by = AuditActor::subject(SubjectRef::human(binding.user_id.clone()));
1030 self.inner.host.stop_all(&reason, by).await?;
1031 let notice = StopNotice { at: self.inner.host.now(), home: self.inner.home.clone() };
1032 if let Err(error) = sink.send_stopped(&inbound.thread, ¬ice).await {
1033 tracing::warn!(error = %error, "the stop notice could not be sent");
1034 }
1035 Ok(InboundOutcome::Stopped)
1036 }
1037
1038 async fn refuse_resume(
1039 &self,
1040 sink: &dyn ChannelSink,
1041 binding: &ChannelBinding,
1042 inbound: &ChannelInbound,
1043 ) -> Result<InboundOutcome> {
1044 if let Err(error) =
1045 self.record(binding, Some(&binding.user_id), "resume.refused", None, &[]).await
1046 {
1047 tracing::warn!(error = %error, "the refused resume's record failed");
1048 }
1049 let notice = ChannelNotice::ResumeRefused { home: self.inner.home.clone() };
1050 self.notify(sink, &inbound.thread, ¬ice).await;
1051 Ok(InboundOutcome::ResumeRefused)
1052 }
1053
1054 async fn answer(
1055 &self,
1056 sink: &dyn ChannelSink,
1057 binding: &ChannelBinding,
1058 inbound: &ChannelInbound,
1059 decision: &str,
1060 version: u64,
1061 answer: ChannelAnswer,
1062 ) -> Result<InboundOutcome> {
1063 let thread = &inbound.thread;
1064 let refused =
1065 |decision: &str| InboundOutcome::DecisionRefused { decision: decision.to_string() };
1066 let gone = ChannelNotice::DecisionGone;
1067 let Some(approvals) = self.inner.host.approvals() else {
1068 self.notify(sink, thread, &gone).await;
1069 return Ok(refused(decision));
1070 };
1071 let request = approvals
1073 .get(decision)
1074 .await?
1075 .filter(|request| request.scope.user_id == binding.user_id);
1076 let Some(request) = request else {
1077 self.record(
1078 binding,
1079 Some(&binding.user_id),
1080 "decide.refused",
1081 Some(decision),
1082 &[("reason", json!("gone"))],
1083 )
1084 .await?;
1085 self.notify(sink, thread, &gone).await;
1086 return Ok(refused(decision));
1087 };
1088 let action = match answer {
1089 ChannelAnswer::AllowOnce => ApprovalAction::Approve,
1090 ChannelAnswer::Deny => ApprovalAction::Reject,
1091 };
1092 let take_over = request.tool_name == TAKE_OVER_TOOL && answer == ChannelAnswer::AllowOnce;
1093 let adds_agent = request.tool_name == crate::agents::AGENT_CREATE_TOOL_NAME;
1095 let not_here = if adds_agent {
1096 answer != ChannelAnswer::Deny
1097 } else {
1098 !self.chat_may_answer(&request) || take_over
1099 };
1100 if not_here || !request.allowed_actions.contains(&action) {
1101 let reason = match (adds_agent, self.moves_money(&request), take_over) {
1104 (true, _, _) => "adds_agent",
1105 (false, true, _) => "money",
1106 (false, false, true) => "take_over",
1107 (false, false, false) => "not_in_chat",
1108 };
1109 let extra = [("reason", json!(reason)), ("risk", json!(self.risk_of(&request)))];
1110 self.record(binding, Some(&binding.user_id), "decide.refused", Some(decision), &extra)
1111 .await?;
1112 self.notify(
1113 sink,
1114 thread,
1115 &ChannelNotice::DecideInHome { home: self.inner.home.clone() },
1116 )
1117 .await;
1118 return Ok(refused(decision));
1119 }
1120 if request.state.is_terminal() {
1121 self.notify(sink, thread, &already_decided(&request, &binding.user_id)).await;
1122 return Ok(InboundOutcome::AlreadyDecided { decision: decision.to_string() });
1123 }
1124 let extra = [
1125 ("answer", json!(answer)),
1126 ("version", json!(version)),
1127 ("risk", json!(self.risk_of(&request))),
1128 ];
1129 self.record(binding, Some(&binding.user_id), "decide", Some(decision), &extra).await?;
1130 let subject = SubjectRef::human(binding.user_id.clone());
1131 let mut choice = match answer {
1132 ChannelAnswer::AllowOnce => ApprovalDecision::approve(subject),
1133 ChannelAnswer::Deny => ApprovalDecision::reject(subject, String::new()),
1134 }
1135 .with_groups(binding.groups.iter().cloned());
1136 if answer == ChannelAnswer::Deny {
1137 choice.reason = None;
1138 }
1139 match approvals.decide(decision, version, choice).await {
1140 Ok(decided) if decided.state == ApprovalState::Pending => {
1142 let notice = ChannelNotice::WaitingForOthers { answered: true };
1143 self.notify(sink, thread, ¬ice).await;
1144 Ok(InboundOutcome::Decided { decision: decision.to_string() })
1145 }
1146 Ok(decided) => {
1147 let summary = card_summary(&decided.summary, &decided.args_redacted);
1148 self.notify(sink, thread, &ChannelNotice::Decided { answer, summary }).await;
1149 Ok(InboundOutcome::Decided { decision: decision.to_string() })
1150 }
1151 Err(error) if error.code == VERSION_CONFLICT_CODE => {
1154 match approvals.get(decision).await? {
1155 Some(current) if current.state == ApprovalState::Pending => {
1156 self.notify(sink, thread, &ChannelNotice::DecisionChanged).await;
1157 let card = self.card(¤t);
1158 if let Err(error) = sink.send_decision(thread, &card).await {
1159 tracing::warn!(error = %error, "a fresh decision card could not be sent");
1160 }
1161 Ok(InboundOutcome::DecisionChanged { decision: decision.to_string() })
1162 }
1163 Some(current) => {
1164 self.notify(sink, thread, &already_decided(¤t, &binding.user_id))
1165 .await;
1166 Ok(InboundOutcome::AlreadyDecided { decision: decision.to_string() })
1167 }
1168 None => {
1169 self.notify(sink, thread, &gone).await;
1170 Ok(refused(decision))
1171 }
1172 }
1173 }
1174 Err(error) if error.code == ALREADY_DECIDED_CODE => {
1176 let notice = ChannelNotice::WaitingForOthers { answered: true };
1177 self.notify(sink, thread, ¬ice).await;
1178 Ok(InboundOutcome::AlreadyDecided { decision: decision.to_string() })
1179 }
1180 Err(error) if error.category == ErrorCategory::Conflict => {
1182 match approvals.get(decision).await? {
1183 Some(current) if current.state.is_terminal() => {
1184 self.notify(sink, thread, &already_decided(¤t, &binding.user_id))
1185 .await;
1186 Ok(InboundOutcome::AlreadyDecided { decision: decision.to_string() })
1187 }
1188 _ => {
1189 self.notify(sink, thread, &gone).await;
1190 Ok(refused(decision))
1191 }
1192 }
1193 }
1194 Err(error) if error.category == ErrorCategory::Forbidden => {
1196 let notice = ChannelNotice::WaitingForOthers { answered: false };
1197 self.notify(sink, thread, ¬ice).await;
1198 Ok(refused(decision))
1199 }
1200 Err(error) => Err(error.into()),
1201 }
1202 }
1203
1204 async fn notify(&self, sink: &dyn ChannelSink, thread: &str, notice: &ChannelNotice) {
1206 if let Err(error) = sink.send_notice(thread, notice).await {
1207 tracing::warn!(channel = sink.channel(), error = %error, "a chat notice could not be sent");
1208 }
1209 }
1210
1211 async fn record(
1217 &self,
1218 account: &impl AccountRef,
1219 user: Option<&str>,
1220 action: &str,
1221 target: Option<&str>,
1222 extra: &[(&str, Value)],
1223 ) -> Result<()> {
1224 let (channel, account) = (account.channel(), account.account());
1225 tracing::info!(
1226 channel.name = channel,
1227 channel.action = action,
1228 channel.target = target.unwrap_or_default(),
1229 "kernel channel action"
1230 );
1231 let Some(trail) = self.inner.host.audit_trail() else { return Ok(()) };
1232 let actor = match user {
1233 Some(user) => AuditActor::subject(SubjectRef::human(user)),
1234 None => AuditActor::default(),
1235 };
1236 let draft = AuditRecordDraft::new(
1237 AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.into()),
1238 audit::CHANNEL,
1239 )
1240 .actor(actor)
1241 .ext("surface", json!("chat"))
1242 .ext("origin", json!({ "kind": "chat", "channel": channel }))
1244 .ext("channel", json!(channel))
1245 .ext("account", json!(account))
1246 .ext("action", json!(action))
1247 .ext("target", json!(target));
1248 let draft = extra.iter().fold(draft, |draft, (key, value)| draft.ext(*key, value.clone()));
1249 trail.record(draft).await.map_err(KernelError::from)
1250 }
1251}
1252
1253fn upgrade(weak: &Weak<Inner>) -> Option<ChannelGateway> {
1254 weak.upgrade().map(|inner| ChannelGateway { inner })
1255}
1256
1257async fn ring_after_quiet(weak: Weak<Inner>, held: ApprovalRequest) -> Result<usize> {
1262 loop {
1263 let Some(gateway) = upgrade(&weak) else { return Ok(0) };
1264 let now = gateway.inner.host.now();
1265 let Some(until) = gateway.inner.host.quiet_ends(&held, now).await else { break };
1266 drop(gateway);
1267 let wait = (until - now).to_std().unwrap_or_default().min(CLOCK_CHECK);
1268 tokio::time::sleep(wait).await;
1269 }
1270 let Some(gateway) = upgrade(&weak) else { return Ok(0) };
1271 let Some(approvals) = gateway.inner.host.approvals() else { return Ok(0) };
1272 let Some(request) = approvals.get(&held.id).await? else { return Ok(0) };
1273 if request.state != ApprovalState::Pending {
1274 return Ok(0);
1275 }
1276 let bindings = gateway.answering_bindings(&request).await?;
1277 let reached = gateway.deliver_card(&request, &bindings).await;
1278 if reached == 0 {
1279 gateway.carded().forget(&held.id, held.version);
1281 }
1282 Ok(reached)
1283}
1284
1285fn may_answer(request: &ApprovalRequest, binding: &ChannelBinding) -> bool {
1288 let person = SubjectRef::human(binding.user_id.clone());
1289 request.is_eligible(&person, &binding.groups)
1290 && !(request.policy.forbid_self_approval && request.is_self(&person))
1291}
1292
1293fn already_decided(request: &ApprovalRequest, user_id: &str) -> ChannelNotice {
1295 let Some(last) = request.decisions.last() else {
1296 return ChannelNotice::DecisionGone;
1297 };
1298 let said = match last.kind {
1299 ApprovalAction::Approve | ApprovalAction::Edit => "yes",
1300 ApprovalAction::Reject => "no",
1301 ApprovalAction::Respond => "something else",
1302 };
1303 let by = (last.approver.id != user_id).then(|| last.approver.id.clone());
1304 ChannelNotice::AlreadyDecided { by, said: said.to_string(), at: Some(last.decided_at) }
1305}
1306
1307trait AccountRef {
1309 fn channel(&self) -> &str;
1310 fn account(&self) -> &str;
1311}
1312
1313impl AccountRef for ChannelBinding {
1314 fn channel(&self) -> &str {
1315 &self.channel
1316 }
1317
1318 fn account(&self) -> &str {
1319 &self.account
1320 }
1321}
1322
1323struct Account<'a> {
1325 channel: &'a str,
1326 account: &'a str,
1327}
1328
1329impl<'a> Account<'a> {
1330 fn of(inbound: &'a ChannelInbound) -> Self {
1331 Self { channel: &inbound.channel, account: &inbound.account }
1332 }
1333}
1334
1335impl AccountRef for Account<'_> {
1336 fn channel(&self) -> &str {
1337 self.channel
1338 }
1339
1340 fn account(&self) -> &str {
1341 self.account
1342 }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::*;
1348
1349 #[test]
1350 fn control_words() {
1351 for text in ["stop all", "Stop all.", "/stop", "/stop@agent_bot", " STOP ALL! "] {
1352 assert!(matches!(control_word(text), Some(Control::Stop)), "{text}");
1353 }
1354 for text in ["resume", "Resume all", "/resume@agent_bot", "/unfreeze"] {
1355 assert!(matches!(control_word(text), Some(Control::Resume)), "{text}");
1356 }
1357 for text in ["stop", "please stop all the things", "stop allowing it", "resume the draft"] {
1358 assert!(control_word(text).is_none(), "{text}");
1359 }
1360 }
1361}