Skip to main content

adk_kernel/channels/
gateway.rs

1//! The channel gateway (spec 3.3 §10 K1): inbound messages become pairing codes, turns,
2//! answers and stops; decisions and replies go out to the right thread.
3
4use 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
32/// The target a paired account's turn runs by default: the harness, as `adk-rust up`
33/// registers it.
34const DEFAULT_TARGET: &str = "adk-rust";
35/// How long a chat account's pairing code works by default: an hour, time to reach the
36/// machine the kernel runs on.
37const DEFAULT_CODE_TTL: Duration = Duration::from_secs(60 * 60);
38/// How many accounts of one channel may wait to be paired at once by default.
39const DEFAULT_MAX_WAITING: usize = 5;
40/// The approval service's code for an answer at a version the decision has left.
41const VERSION_CONFLICT_CODE: &str = "approval.version_conflict";
42/// The approval service's code for an approver whose answer already counts toward a quorum.
43const ALREADY_DECIDED_CODE: &str = "approval.already_decided";
44/// How often the gateway rings the decisions still waiting by default: a card that could not
45/// be sent, or a decision held on another replica, reaches the thread within a minute.
46const DEFAULT_RESWEEP: Duration = Duration::from_secs(60);
47/// How often the gateway asks after the turns it started that have not finished.
48const TURN_POLL: Duration = Duration::from_secs(2);
49/// The longest one wait for the end of quiet time sleeps before it reads the clock again:
50/// a timer does not run while the machine sleeps, the wall clock does.
51const CLOCK_CHECK: Duration = Duration::from_secs(60);
52
53/// The decision doorbell (spec 3.3 §5.3, §10 K1): an `ApprovalNotifier` registered on
54/// `StoreApprovalService::with_notifier` that hands each submitted decision to the
55/// [`ChannelGateway`] given it, which sends the card to every paired thread of the
56/// decision's person.
57///
58/// The approval service is built before the kernel and the gateway, so the doorbell holds
59/// the decisions it is told about until the gateway starts, and again while a stopped
60/// gateway is started anew.
61///
62/// # Example
63///
64/// ```rust
65/// use std::sync::Arc;
66/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
67/// use adk_kernel::channels::ChannelDoorbell;
68///
69/// let doorbell = Arc::new(ChannelDoorbell::new());
70/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
71///     .with_notifier(doorbell.clone());
72/// # let _ = service;
73/// ```
74pub struct ChannelDoorbell {
75    sender: mpsc::UnboundedSender<ApprovalRequest>,
76    /// Held by the running gateway's bell task; a stopped task lets the next one take it.
77    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    /// A doorbell with no gateway yet.
88    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    /// Passes each submitted decision on; every other change rings nothing.
103    async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
104        if notification.kind == ApprovalEventKind::Submitted {
105            // The doorbell holds its receiver, so a send fails only while it is dropped.
106            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
114/// Builds a [`ChannelGateway`].
115pub 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    /// Adds a channel's adapter; a second adapter of the same channel replaces the first.
140    #[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    /// The target paired accounts' turns run; defaults to `adk-rust`, the harness.
147    #[must_use]
148    pub fn target(mut self, target: impl Into<String>) -> Self {
149        self.target = target.into();
150        self
151    }
152
153    /// The web home's address, which cards and notices link to for what chat cannot do.
154    #[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    /// How long a pairing code sent to an unpaired account works; defaults to an hour.
161    #[must_use]
162    pub fn code_ttl(mut self, ttl: Duration) -> Self {
163        self.code_ttl = ttl;
164        self
165    }
166
167    /// How many accounts of one channel may wait to be paired at once; defaults to five.
168    #[must_use]
169    pub fn max_waiting(mut self, max: usize) -> Self {
170        self.max_waiting = max;
171        self
172    }
173
174    /// Rings `doorbell`'s decisions once [`ChannelGateway::start`] runs.
175    #[must_use]
176    pub fn doorbell(mut self, doorbell: Arc<ChannelDoorbell>) -> Self {
177        self.doorbell = Some(doorbell);
178        self
179    }
180
181    /// How often a started gateway rings the decisions still waiting, as
182    /// [`ChannelGateway::ring_waiting`] does; defaults to a minute.
183    #[must_use]
184    pub fn resweep(mut self, every: Duration) -> Self {
185        self.resweep = every;
186        self
187    }
188
189    /// Adds tools whose calls move money, which chat never decides (spec 3.3 §7.4 rule 4):
190    /// their cards link to the home and carry no answers. A name ending in `*` names every
191    /// tool it starts. The list starts with `payments_*`, the tools `adk-payments`
192    /// publishes, beside the tools the host's drivers declare `financial`
193    /// ([`ChannelHost::moves_money`]).
194    ///
195    /// # Example
196    ///
197    /// ```rust,no_run
198    /// # fn example(builder: adk_kernel::channels::ChannelGatewayBuilder) {
199    /// let builder = builder.money_tools(["transfer", "bank_*"]);
200    /// # let _ = builder;
201    /// # }
202    /// ```
203    #[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    /// Lets `route` decide each inbound message before the gateway does (spec 3.5 §10 X12):
210    /// a message it takes gets no pairing code, starts no turn and answers nothing
211    /// ([`InboundOutcome::Routed`]). Without one, the gateway decides every message.
212    ///
213    /// # Example
214    ///
215    /// ```rust,no_run
216    /// # fn example(builder: adk_kernel::channels::ChannelGatewayBuilder, route: std::sync::Arc<dyn adk_kernel::channels::InboundRoute>) {
217    /// let builder = builder.route(route);
218    /// # let _ = builder;
219    /// # }
220    /// ```
221    #[must_use]
222    pub fn route(mut self, route: Arc<dyn InboundRoute>) -> Self {
223        self.route = Some(route);
224        self
225    }
226
227    /// The gateway.
228    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/// The kernel's side of every chat channel (spec 3.3 §5.3, §10 K1, S-I5, S-I6, S-I10): see
255/// the [module documentation](super) for the rules it applies.
256///
257/// An adapter hands each inbound message to [`receive`](Self::receive);
258/// [`start`](Self::start) follows the host's finished turns, so each reply goes back to the
259/// thread its turn came from, and rings the doorbell's decisions.
260///
261/// # Example
262///
263/// ```rust,no_run
264/// use std::sync::Arc;
265/// use adk_kernel::channels::{ChannelGateway, ChannelInbound, InMemoryChannel, InMemoryChannelBindingStore};
266///
267/// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
268/// let chat = Arc::new(InMemoryChannel::new("chat"));
269/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
270///     .sink(chat.clone())
271///     .build();
272/// gateway.start().await?;
273/// gateway.receive(ChannelInbound::text("chat", "ana", "t1", "m1", "hello")).await?;
274/// # Ok(())
275/// # }
276/// ```
277#[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    /// The tasks [`ChannelGateway::start`] runs, and whether it runs.
295    lifecycle: Mutex<Lifecycle>,
296    /// The cards held through quiet time.
297    held: Mutex<Vec<JoinHandle<()>>>,
298    /// The decisions carded, or held to be carded, at their version.
299    carded: Mutex<Carded>,
300    /// The turns this gateway started that have not finished.
301    started: Mutex<std::collections::BTreeSet<String>>,
302    /// The messages handed to a running turn, by idempotency key, so a redelivery of one is
303    /// handed to no turn again.
304    steered: Mutex<Carded>,
305    /// The turns replied to, so a turn finished here and seen in the run store is answered
306    /// once.
307    replied: Mutex<Carded>,
308    /// Taken while an unpaired account is given a code, so the waiting limit and one code
309    /// per account hold for messages that arrive together.
310    unpaired: tokio::sync::Mutex<()>,
311}
312
313/// Whether the gateway runs, and its tasks.
314#[derive(Default)]
315struct Lifecycle {
316    running: bool,
317    /// Counts starts and stops, so a start that a stop overtook spawns nothing.
318    generation: u64,
319    tasks: Vec<JoinHandle<()>>,
320}
321
322/// The decisions the gateway carded at a version, newest last, at most [`Carded::LIMIT`].
323#[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    /// Notes decision `id` at `version`; `false` when it was noted before.
333    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    /// Forgets decision `id` at `version`, so it can be carded again.
348    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
376/// A command a typed message gives.
377enum Control {
378    Stop,
379    Resume,
380}
381
382/// The command `text` gives, when it is one: "stop all" or `/stop`, "resume" or `/resume`.
383fn control_word(text: &str) -> Option<Control> {
384    let text = text.trim().trim_end_matches(['.', '!']).to_lowercase();
385    // A platform command may name the bot: `/stop@agent_bot`.
386    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    /// A gateway over `host` keeping pairings in `bindings`, with no channels yet.
400    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    /// The binding store.
420    pub fn bindings(&self) -> &Arc<dyn ChannelBindingStore> {
421        &self.inner.bindings
422    }
423
424    /// Follows the host's finished turns, sending each reply to the thread its turn came
425    /// from, and rings the doorbell's decisions. Stopped by [`stop`](Self::stop) or when the
426    /// last handle to the gateway is dropped; starting a running gateway changes nothing,
427    /// and a stopped one starts again with the decisions the doorbell held meanwhile.
428    ///
429    /// # Errors
430    ///
431    /// Returns the host's error when it cannot follow its turns.
432    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            // A stop came first.
455            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        // A turn another replica ran finishes on that replica's bus: ask after it.
465        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        // A card that could not be sent, or a decision another replica holds, is rung again.
474        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                // The previous bell task, once aborted, lets go of the receiver.
490                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    /// Stops following turns and ringing decisions, and drops the cards held through quiet
503    /// time; [`ring_waiting`](Self::ring_waiting) after the next start sends them.
504    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        // Held cards were dropped: they may be carded again.
517        *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    /// Handles one inbound message (spec 3.3 §10 K1): an unpaired account gets a pairing code
531    /// and starts nothing; a paired account's message starts a turn as its person, or is
532    /// handed to the thread's turn when one runs on this host (spec 3.3 §6 "steer"), "stop
533    /// all" stops everything, "resume" is refused, and an answer decides at low and medium
534    /// risk.
535    ///
536    /// # Errors
537    ///
538    /// Returns [`KernelError::Config`] for a channel with no sink, an audit failure under
539    /// `AuditFailureMode::Block` for an action that must be recorded first, or a store's,
540    /// the host's or the approval service's error.
541    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            // A photo alone, say, which a route did not take, starts no turn.
555            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    /// Sends the card of `request` to every paired thread of its person, when the policy
572    /// lets that person answer it, or, during quiet time, when quiet time ends if the
573    /// decision still waits (spec 3.3 §5.3, §7.3). The card carries answers only when chat
574    /// may decide it: low or medium risk, and no money (§7.2, §7.4). A decision is carded
575    /// once at each version, whether the doorbell or [`ring_waiting`](Self::ring_waiting)
576    /// rings it first. Returns how many threads it reached now.
577    ///
578    /// # Errors
579    ///
580    /// Returns the binding store's error.
581    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    /// Replies to the finished turn `run` once, however it was seen to finish.
618    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    /// Replies to the turns this gateway started that finished, wherever they ran.
628    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                // The host follows its turns only on its bus, or the run is gone.
642                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    /// The active bindings of `request`'s person whose channel has a sink, when the policy
653    /// lets that person answer it, as the inbox lists it for them.
654    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    /// Whether chat may answer `request` at all: low or medium risk, and no money (spec 3.3
661    /// §7.2, §7.4 rule 4).
662    fn chat_may_answer(&self, request: &ApprovalRequest) -> bool {
663        chat_may_decide(self.risk_of(request)) && !self.moves_money(request)
664    }
665
666    /// The risk of `request`: as the request rates it, or high when the host rates it so.
667    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    /// Whether `request`'s call moves money: the host says so, or the tool is one the
676    /// gateway was told moves money.
677    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    /// The card of `request`, with its answers only when chat may answer it.
686    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        // A suggested agent keeps "Don't add" at any risk (spec 3.3 §7.2).
690        if !self.chat_may_answer(request) && !card.adds_agent {
691            card.answers.clear();
692        }
693        card
694    }
695
696    /// Rings every decision still waiting for a paired person, as [`ring`](Self::ring) does
697    /// one (spec 3.3 §7.3): call it after a restart, so a decision whose card a restart held
698    /// through quiet time, or never sent, still reaches the thread. A card this gateway sent
699    /// since it started is not sent again, while one sent before a process restart, or
700    /// before [`stop`](Self::stop), is. Returns how many threads it reached now.
701    ///
702    /// # Errors
703    ///
704    /// Returns the binding store's or the approval service's error.
705    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    /// The active bindings of `user_id` whose channel has a sink.
737    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    /// Sends a finished turn's reply to its thread: the agent's answer when it completed, a
777    /// notice when it failed. Returns whether it sent anything.
778    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        // An account removed while its turn ran hears nothing more.
782        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        // One at a time: the waiting count and the account's earlier code are read and the
823        // new code stored with no other unpaired message in between.
824        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            // A dismissed account hears nothing until its dismissal ends.
832            if waiting.dismissed {
833                tracing::debug!(channel.name = %inbound.channel, "a dismissed chat account wrote");
834                return Ok(InboundOutcome::PairingDismissed);
835            }
836            // The account never received its code: a new one takes its place.
837            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, &notice).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    /// Stores `request` under a new code and sends the code to `thread`. A code that cannot
884    /// be sent keeps the request, marked undelivered: it holds the account's place and its
885    /// one record, so an account the agent cannot reply to — a stranger who blocked the bot —
886    /// starts no new request and no new record with each message, and its next message is
887    /// sent a new code (spec 3.3 §10 K1, §11 S-I6).
888    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, &notice).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        // The pairing is the authentication: the turn is the paired person's own, a `Human`
922        // subject, keyed by the platform's message id so a redelivery starts nothing (K-I3).
923        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        // The thread's running turn takes the message at its agent's next safe point (spec 3.3
939        // §6 "steer"). Noted first, so a redelivery that arrives meanwhile reaches no turn.
940        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                // The gateway outlives the wait: a message the turn hands back is never lost.
947                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            // What a running turn may not take starts a turn, which answers as any turn does.
954            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    /// Starts `run`, a paired account's turn, and follows it for its reply.
967    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, &notice).await;
985                Ok(InboundOutcome::TurnRefused)
986            }
987            Err(error) => Err(error),
988        }
989    }
990
991    /// Waits for what became of a message handed to a running turn: delivered, the turn's
992    /// reply answers it; handed back, it starts the thread's next turn as `run`, whose
993    /// idempotency key is the message's.
994    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            // The run was dropped before it said whether it took the message. Starting a turn
1003            // could send the message twice, so the thread is told instead.
1004            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            // A redelivery may start it.
1013            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        // Stopping takes effect even when its record cannot be written.
1025        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, &notice).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, &notice).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        // Another person's decision reads as no decision at all (S-I8).
1072        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        // Spec 3.3 §7.2, S-I11: chat refuses a suggested agent at any risk, never adds one.
1094        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            // §7.2, §7.4 rule 4: chat says yes once or no, at low and medium risk only, and
1102            // never to money; a take-over's secret is typed in the home (§8.2).
1103            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            // A quorum's first answer counts, and the decision still waits.
1141            Ok(decided) if decided.state == ApprovalState::Pending => {
1142                let notice = ChannelNotice::WaitingForOthers { answered: true };
1143                self.notify(sink, thread, &notice).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            // S-I2: a stale answer is shown, never retried; only a changed decision that
1152            // still waits gets a fresh card.
1153            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(&current);
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(&current, &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            // This person's answer already counts toward the quorum.
1175            Err(error) if error.code == ALREADY_DECIDED_CODE => {
1176                let notice = ChannelNotice::WaitingForOthers { answered: true };
1177                self.notify(sink, thread, &notice).await;
1178                Ok(InboundOutcome::AlreadyDecided { decision: decision.to_string() })
1179            }
1180            // Resolved or expired meanwhile.
1181            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(&current, &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            // The policy does not ask this person, or forbids them answering their own call.
1195            Err(error) if error.category == ErrorCategory::Forbidden => {
1196                let notice = ChannelNotice::WaitingForOthers { answered: false };
1197                self.notify(sink, thread, &notice).await;
1198                Ok(refused(decision))
1199            }
1200            Err(error) => Err(error.into()),
1201        }
1202    }
1203
1204    /// Sends `notice`, logging a failure: a notice is a courtesy, not the action.
1205    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    /// Writes a `kernel.channel` record of `action` by the account (spec 3.3 §11).
1212    ///
1213    /// # Errors
1214    ///
1215    /// The trail's error under `AuditFailureMode::Block`.
1216    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        // The origin as `adk-surface` records an answer's: how it was given (spec 3.3 §11).
1243        .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
1257/// Waits for quiet time to end, then sends `held`'s card if the decision still waits; the
1258/// card was noted at `held`'s version. The wait reads the wall clock at least every
1259/// [`CLOCK_CHECK`], so a machine that slept through the night sends the card when quiet
1260/// time ends, not hours later.
1261async 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        // The next sweep rings it again.
1280        gateway.carded().forget(&held.id, held.version);
1281    }
1282    Ok(reached)
1283}
1284
1285/// Whether the person `binding` acts for may answer `request`: an approver the policy
1286/// names, and not its requester when the policy forbids self-approval.
1287fn 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
1293/// The notice of a decision that was answered before.
1294fn 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
1307/// Something naming a channel and an account, for the records.
1308trait 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
1323/// An unpaired account.
1324struct 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}