Skip to main content

adk_kernel/channels/
mod.rs

1//! The chat channel contract (spec 3.3 §5.3, §10 K1, §11 S-I5, S-I6, S-I10; feature
2//! `channels`).
3//!
4//! A chat thread is the doorbell and the conversation: a paired account talks to its agents,
5//! gets decision cards, says yes once or no, and stops everything. The kernel owns the rules;
6//! a platform adapter (Telegram first, in `adk-surface`) only moves messages. An adapter
7//! implements [`ChannelSink`] for what goes out and hands what comes in to
8//! [`ChannelGateway::receive`] as a [`ChannelInbound`]; it passes the contract suite in
9//! `conformance::channel_contract` (feature `conformance`).
10//!
11//! | Rule | What the gateway does |
12//! |---|---|
13//! | Only paired accounts reach an agent (S-I6) | An unpaired account's message, or answer, gets a pairing code ([`ChannelNotice::PairingCode`]) and starts nothing; the person accepts the code where the kernel runs (`adk-rust pair accept`, `POST /api/kernel/channels/pair`) |
14//! | One code per account, at most so many waiting | The gateway serializes unpaired accounts' messages, so concurrent messages from one account get one code and the waiting limit holds; the operator dismisses a waiting account (`adk-rust pair revoke`, `POST /api/kernel/channels/waiting/{id}/dismiss`), which then gets no code for [`DISMISSED_FOR`] |
15//! | A paired account's message is a turn | It starts a turn as the paired person, a `Human` subject, in the thread's session, keyed by the platform's message id so a redelivery starts nothing; the turn's reply goes back to the same thread, from whichever replica ran it |
16//! | A message for a running turn reaches it (spec 3.3 §6 "steer") | While the thread's turn runs on this host, the gateway hands the message to that turn ([`ChannelHost::steer`], [`InboundOutcome::Steered`]): its agent takes it at its next safe point and its reply answers it. A turn that ends first hands the message back, and it starts the thread's next turn under the message's idempotency key, once. A turn another replica runs is handed nothing: the message starts a turn behind it. A redelivery of a message handed to a turn is recognised by the replica that took it |
17//! | A removed account reaches no agent | Removing it stops its turns that have not finished, those queued behind the thread's session included |
18//! | Cards carry no arguments (S-I5) | A [`DecisionCard`] holds the agent, a short summary with every argument value masked, and the risk; never the call's arguments |
19//! | Chat says yes once or no, never money (§7.2, §7.4) | Answers are [`ChannelAnswer::AllowOnce`] and [`ChannelAnswer::Deny`] at low and medium risk only, through `ApprovalService::decide` with the version the card showed (S-I2); a call that moves money ([`ChannelHost::moves_money`], [`ChannelGatewayBuilder::money_tools`]) and high risk link to the home — high as the request rates it, or as the host does ([`ChannelHost::rates_high`]) — and a take-over, whose secret is typed in the home (§8.2), can only be denied |
20//! | Only who may answer gets buttons | A card goes to the decision's person when the policy lets that person answer it, and its answers only when chat may decide it |
21//! | A second answer is shown, never retried (S-I2) | A version conflict answers [`ChannelNotice::AlreadyDecided`], or a fresh card when the decision still waits; an answer that counts toward a quorum, or one from someone the policy does not ask, answers [`ChannelNotice::WaitingForOthers`] |
22//! | Stop all from anywhere; resume only at home (S-I10) | "stop all" freezes the kernel and answers [`StopNotice`]; "resume" is refused with [`ChannelNotice::ResumeRefused`] |
23//! | Nothing notifies during quiet time | A card for a decision asked during quiet time is delivered when quiet time ends, if it still waits: the quiet time of the decision's area in force, a change made while the kernel runs included ([`ChannelHost::quiet_ends`]) |
24//! | Every waiting decision reaches the thread | Every minute the gateway rings the decisions still waiting, so a card that could not be sent is sent again, and one held on another replica is sent too |
25//! | A host may decide first (spec 3.5 §10 X12) | An [`InboundRoute`] set with [`ChannelGatewayBuilder::route`] sees each message, with the account's pairing, before the gateway: a message it takes gets no pairing code and starts no turn ([`InboundOutcome::Routed`]). A served site sends strangers to its Inbox this way |
26//! | Files ride with a message | [`ChannelInbound::attachments`], downloaded by the adapter; never in a turn's input. A paired account's message with no words starts no turn ([`InboundOutcome::Empty`]) |
27//!
28//! Every answer, pairing request, notification, stop and refusal writes a `kernel.channel`
29//! audit record with `surface: chat`, the channel and the account, before it acts.
30//!
31//! | Backend of [`ChannelBindingStore`] | Type | Feature |
32//! |---|---|---|
33//! | In-memory | [`InMemoryChannelBindingStore`] | — |
34//! | SQLite | `SqliteChannelBindingStore` | `sqlite` (default) |
35//! | PostgreSQL | `PostgresChannelBindingStore` | `postgres` |
36//! | Redis | `RedisChannelBindingStore` | `redis` |
37//!
38//! Text from an agent, a tool or a chat platform reaches a sink as it is; the adapter
39//! escapes it for its platform before display (S-I9).
40
41use std::fmt;
42use std::sync::Arc;
43
44use adk_core::audit_log::{AuditActor, AuditTrail};
45use adk_core::{ApprovalRequest, ApprovalRisk, ApprovalService, NewRun, RunRecord};
46use async_trait::async_trait;
47use chrono::{DateTime, Utc};
48use futures::stream::BoxStream;
49use serde::{Deserialize, Serialize};
50use serde_json::Value;
51
52use crate::control::api::{ChannelAccountState, ChannelAccountView, ChannelPairingView};
53use crate::error::{KernelError, Result};
54use crate::pairing::secret;
55
56mod gateway;
57mod host;
58mod memory;
59#[cfg(feature = "postgres")]
60mod postgres;
61#[cfg(feature = "redis")]
62mod redis;
63#[cfg(any(feature = "sqlite", feature = "postgres"))]
64mod sql;
65#[cfg(feature = "sqlite")]
66mod sqlite;
67mod testing;
68
69pub use gateway::{ChannelDoorbell, ChannelGateway, ChannelGatewayBuilder};
70pub(crate) use host::stop_account_turns;
71pub use memory::InMemoryChannelBindingStore;
72#[cfg(feature = "postgres")]
73pub use postgres::PostgresChannelBindingStore;
74#[cfg(feature = "redis")]
75pub use redis::RedisChannelBindingStore;
76#[cfg(feature = "sqlite")]
77pub use sqlite::SqliteChannelBindingStore;
78pub use testing::{Delivered, InMemoryChannel};
79
80/// The longest summary a card carries, in characters.
81const MAX_SUMMARY_CHARS: usize = 160;
82/// How long an account the operator dismissed gets no pairing code (spec 3.3 §10 K1): a day.
83pub const DISMISSED_FOR: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
84pub(crate) use crate::pairing::TAKE_OVER_TOOL;
85/// The longest display name kept for an account.
86const MAX_NAME_CHARS: usize = 64;
87
88/// What a person can answer from a chat thread (spec 3.3 §7.2, §8.2).
89///
90/// # Example
91///
92/// ```rust
93/// use adk_kernel::channels::ChannelAnswer;
94///
95/// assert_eq!(ChannelAnswer::AllowOnce.label(), "Allow once");
96/// assert_eq!(serde_json::to_value(ChannelAnswer::Deny).unwrap(), "deny");
97/// ```
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100#[non_exhaustive]
101pub enum ChannelAnswer {
102    /// Run this one call.
103    AllowOnce,
104    /// Refuse it.
105    Deny,
106}
107
108impl ChannelAnswer {
109    /// The button's words (spec 3.3 §8.2).
110    pub fn label(self) -> &'static str {
111        match self {
112            Self::AllowOnce => "Allow once",
113            Self::Deny => "Deny",
114        }
115    }
116}
117
118/// What arrived from a chat thread (spec 3.3 §10 K1): untrusted input (S-I6).
119///
120/// # Example
121///
122/// ```rust
123/// use adk_kernel::channels::{ChannelInbound, InboundBody};
124///
125/// let inbound = ChannelInbound::text("telegram", "4217", "4217", "msg-1", "what's on today?")
126///     .with_display_name("Ana");
127/// assert!(matches!(inbound.body, InboundBody::Text { .. }));
128/// ```
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131#[non_exhaustive]
132pub struct ChannelInbound {
133    /// The channel, such as `telegram`: the [`ChannelSink::channel`] of its adapter.
134    pub channel: String,
135    /// The sending account on that channel.
136    pub account: String,
137    /// The account's display name, as the platform gave it.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub display_name: Option<String>,
140    /// The conversation the message is in; replies go back to it.
141    pub thread: String,
142    /// The platform's id of the message, unique per thread, so a redelivery starts nothing.
143    pub message_id: String,
144    /// What the person sent.
145    pub body: InboundBody,
146    /// The files the message carried, such as photos, as the adapter downloaded them (spec
147    /// 3.5 §5 S18, §10 X12); a turn's input never carries them.
148    #[serde(default, skip_serializing_if = "Vec::is_empty")]
149    pub attachments: Vec<ChannelAttachment>,
150}
151
152impl ChannelInbound {
153    fn new(
154        channel: impl Into<String>,
155        account: impl Into<String>,
156        thread: impl Into<String>,
157        message_id: impl Into<String>,
158        body: InboundBody,
159    ) -> Self {
160        Self {
161            channel: channel.into(),
162            account: account.into(),
163            display_name: None,
164            thread: thread.into(),
165            message_id: message_id.into(),
166            body,
167            attachments: Vec::new(),
168        }
169    }
170
171    /// A typed message.
172    pub fn text(
173        channel: impl Into<String>,
174        account: impl Into<String>,
175        thread: impl Into<String>,
176        message_id: impl Into<String>,
177        text: impl Into<String>,
178    ) -> Self {
179        Self::new(channel, account, thread, message_id, InboundBody::Text { text: text.into() })
180    }
181
182    /// A pressed answer on the card for `decision` at `version`.
183    pub fn answer(
184        channel: impl Into<String>,
185        account: impl Into<String>,
186        thread: impl Into<String>,
187        message_id: impl Into<String>,
188        card: &DecisionCard,
189        answer: ChannelAnswer,
190    ) -> Self {
191        let body =
192            InboundBody::Answer { decision: card.decision.clone(), version: card.version, answer };
193        Self::new(channel, account, thread, message_id, body)
194    }
195
196    /// A pressed "Stop all".
197    pub fn stop_all(
198        channel: impl Into<String>,
199        account: impl Into<String>,
200        thread: impl Into<String>,
201        message_id: impl Into<String>,
202    ) -> Self {
203        Self::new(channel, account, thread, message_id, InboundBody::StopAll)
204    }
205
206    /// Sets the account's display name.
207    #[must_use]
208    pub fn with_display_name(mut self, name: impl Into<String>) -> Self {
209        self.display_name = Some(name.into());
210        self
211    }
212
213    /// Sets the files the message carried (spec 3.5 §10 X12).
214    ///
215    /// # Example
216    ///
217    /// ```rust
218    /// use adk_kernel::channels::{ChannelAttachment, ChannelInbound};
219    ///
220    /// let photo = ChannelAttachment::new("image/png", "rye-1.png", vec![0x89, b'P', b'N', b'G']);
221    /// let inbound = ChannelInbound::text("whatsapp", "254700000001", "254700000001", "wamid.1", "")
222    ///     .with_attachments([photo]);
223    /// assert_eq!(inbound.attachments[0].media_type, "image/png");
224    /// ```
225    #[must_use]
226    pub fn with_attachments(
227        mut self,
228        attachments: impl IntoIterator<Item = ChannelAttachment>,
229    ) -> Self {
230        self.attachments = attachments.into_iter().collect();
231        self
232    }
233}
234
235/// A file an inbound chat message carried, as its adapter downloaded it, bounded in size and
236/// type (spec 3.5 §5 S18, §10 X12): untrusted input, which only a paired account's message
237/// may bring into the site, through the media pipeline.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(rename_all = "camelCase")]
240#[non_exhaustive]
241pub struct ChannelAttachment {
242    /// The media type the platform gave, such as `image/jpeg`.
243    pub media_type: String,
244    /// A file name for it.
245    pub name: String,
246    /// What the person wrote under it, when the platform keeps a caption per file.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub caption: Option<String>,
249    /// Its bytes; never serialized.
250    #[serde(skip)]
251    pub bytes: Vec<u8>,
252}
253
254impl ChannelAttachment {
255    /// A file of `media_type` named `name`.
256    pub fn new(media_type: impl Into<String>, name: impl Into<String>, bytes: Vec<u8>) -> Self {
257        Self { media_type: media_type.into(), name: name.into(), caption: None, bytes }
258    }
259
260    /// Sets its caption.
261    #[must_use]
262    pub fn with_caption(mut self, caption: impl Into<String>) -> Self {
263        self.caption = Some(caption.into());
264        self
265    }
266}
267
268/// What a host decides about an inbound message before the gateway does (spec 3.5 §10 X12,
269/// §7.19, A-I24): a served site sends a stranger's message to its Inbox, where it never gets
270/// a pairing code or starts a turn, and takes a paired person's photos into its media
271/// pipeline. Set it with [`ChannelGatewayBuilder::route`].
272///
273/// # Example
274///
275/// ```rust
276/// use adk_kernel::channels::{ChannelBinding, ChannelInbound, InboundRoute};
277/// use async_trait::async_trait;
278///
279/// /// Strangers are read elsewhere; everyone else goes through the gateway.
280/// struct Strangers;
281///
282/// #[async_trait]
283/// impl InboundRoute for Strangers {
284///     async fn take(&self, inbound: &ChannelInbound, binding: Option<&ChannelBinding>) -> adk_kernel::Result<bool> {
285///         Ok(binding.is_none())
286///     }
287/// }
288/// ```
289#[async_trait]
290pub trait InboundRoute: Send + Sync {
291    /// Takes `inbound`, from the account whose active pairing is `binding`, or leaves it to
292    /// the gateway: `true` when it took it and the gateway does nothing more with it.
293    ///
294    /// # Errors
295    ///
296    /// The route's error, which the gateway returns.
297    async fn take(
298        &self,
299        inbound: &ChannelInbound,
300        binding: Option<&ChannelBinding>,
301    ) -> Result<bool>;
302}
303
304/// What a person sent from a chat thread (spec 3.3 §10 K1).
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
307#[non_exhaustive]
308pub enum InboundBody {
309    /// A typed message. "stop all" and "/stop" stop everything; "resume" and "/resume" are
310    /// refused.
311    Text {
312        /// The text, as typed.
313        text: String,
314    },
315    /// An answer pressed on a decision card.
316    Answer {
317        /// The card's [`DecisionCard::decision`].
318        decision: String,
319        /// The card's [`DecisionCard::version`].
320        version: u64,
321        /// What was pressed.
322        answer: ChannelAnswer,
323    },
324    /// A pressed "Stop all".
325    StopAll,
326    /// A pressed "Resume all", which a chat thread may not do (S-I10).
327    ResumeAll,
328}
329
330/// A decision as a chat thread shows it (spec 3.3 §5.3, §7.1, S-I5): who asks, a short
331/// summary, the risk, and the answers the thread may give. Never the call's arguments.
332///
333/// # Example
334///
335/// ```rust
336/// use adk_core::{ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApproverSelector, ToolConfirmationRequest};
337/// use adk_kernel::channels::{ChannelAnswer, DecisionCard};
338///
339/// let call = ToolConfirmationRequest::new("send_email", serde_json::json!({"to": "client@example.com"}));
340/// let request = ApprovalRequest::new("a1", ApprovalScope::new("adk-rust", "ana", "s1"), &call, ApprovalPolicy::new([ApproverSelector::group("operator")]))
341///     .with_summary("Send the invoice to client@example.com")
342///     .with_risk(ApprovalRisk::Medium);
343/// let card = DecisionCard::from_request(&request, None);
344/// assert_eq!(card.summary, "Send the invoice to […]");
345/// assert_eq!(card.answers, [ChannelAnswer::AllowOnce, ChannelAnswer::Deny]);
346/// ```
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase")]
349#[non_exhaustive]
350pub struct DecisionCard {
351    /// The decision's id, which an answer carries back; never shown (spec 3.3 §8).
352    pub decision: String,
353    /// The decision's version when the card was made, which an answer carries back so a
354    /// changed decision is not answered blind (S-I2); never shown.
355    pub version: u64,
356    /// The agent asking.
357    pub agent: String,
358    /// What will happen, in at most 160 characters, with every argument value masked as
359    /// `[…]`: one of three or more characters wherever it appears, ignoring case, and a
360    /// shorter one wherever it stands as a word or a number of its own, newlines and other
361    /// control characters read as spaces (S-I5).
362    pub summary: String,
363    /// The risk.
364    pub risk: ApprovalRisk,
365    /// The answers the thread may give: allow once and deny at low and medium risk, none at
366    /// high risk, and deny alone for a take-over, whose secret is typed in the home.
367    pub answers: Vec<ChannelAnswer>,
368    /// Where the decision is answered in full: the web home, when the gateway knows it.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub home: Option<String>,
371    /// When it was asked.
372    pub asked_at: DateTime<Utc>,
373    /// Whether it suggests an agent ([`AGENT_CREATE_TOOL_NAME`](crate::agents::AGENT_CREATE_TOOL_NAME)):
374    /// chat refuses it only, as "Don't add" (spec 3.3 §7.2, S-I11).
375    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
376    pub adds_agent: bool,
377}
378
379impl DecisionCard {
380    /// The card for `request`, linking to `home`.
381    pub fn from_request(request: &ApprovalRequest, home: Option<&str>) -> Self {
382        let mut answers = Vec::new();
383        let adds_agent = request.tool_name == crate::agents::AGENT_CREATE_TOOL_NAME;
384        if adds_agent {
385            // Only a person at a screen adds an agent; every surface may refuse one (S-I11).
386            if request.allowed_actions.contains(&adk_core::ApprovalAction::Reject) {
387                answers.push(ChannelAnswer::Deny);
388            }
389        } else if chat_may_decide(request.risk) {
390            // A take-over is done by typing the secret in the home; a yes delivers nothing.
391            if request.allowed_actions.contains(&adk_core::ApprovalAction::Approve)
392                && request.tool_name != TAKE_OVER_TOOL
393            {
394                answers.push(ChannelAnswer::AllowOnce);
395            }
396            if request.allowed_actions.contains(&adk_core::ApprovalAction::Reject) {
397                answers.push(ChannelAnswer::Deny);
398            }
399        }
400        Self {
401            decision: request.id.clone(),
402            version: request.version,
403            agent: agent_name(request),
404            summary: card_summary(&request.summary, &request.args_redacted),
405            risk: request.risk,
406            answers,
407            home: home.map(str::to_string),
408            asked_at: request.created_at,
409            adds_agent,
410        }
411    }
412
413    /// The words of `answer`'s button on this card (spec 3.3 §8.2): "Don't add" refuses a
414    /// suggested agent, otherwise [`ChannelAnswer::label`].
415    ///
416    /// # Example
417    ///
418    /// ```rust
419    /// use adk_core::{ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalScope, ApproverSelector, ToolConfirmationRequest};
420    /// use adk_kernel::agents::AGENT_CREATE_TOOL_NAME;
421    /// use adk_kernel::channels::{ChannelAnswer, DecisionCard};
422    ///
423    /// let call = ToolConfirmationRequest::new(AGENT_CREATE_TOOL_NAME, serde_json::json!({"displayName": "Finance"}));
424    /// let request = ApprovalRequest::new("a1", ApprovalScope::new("adk-rust", "ana", "s1"), &call, ApprovalPolicy::new([ApproverSelector::group("operator")]))
425    ///     .with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject]);
426    /// let card = DecisionCard::from_request(&request, None);
427    /// assert_eq!(card.answers, [ChannelAnswer::Deny]);
428    /// assert_eq!(card.label(ChannelAnswer::Deny), "Don't add");
429    /// ```
430    pub fn label(&self, answer: ChannelAnswer) -> &'static str {
431        match answer {
432            ChannelAnswer::Deny if self.adds_agent => "Don't add",
433            other => other.label(),
434        }
435    }
436
437    /// The card in plain words (spec 3.3 §8): who asks, what will happen, and the risk.
438    pub fn text(&self) -> String {
439        let mut text = format!(
440            "{} is waiting for you\n{}\n{}",
441            self.agent,
442            self.summary,
443            risk_words(self.risk)
444        );
445        if self.adds_agent {
446            match &self.home {
447                Some(home) => text.push_str(&format!("\nOpen in home: {home}")),
448                None => text.push_str("\nOpen in home"),
449            }
450        } else if !self.answers.contains(&ChannelAnswer::AllowOnce) {
451            match &self.home {
452                Some(home) => text.push_str(&format!("\nDecide in the home: {home}")),
453                None => text.push_str("\nDecide in the home"),
454            }
455        }
456        text
457    }
458}
459
460/// Whether a chat thread may answer a decision of `risk` (spec 3.3 §7.2: low and medium).
461pub(crate) fn chat_may_decide(risk: ApprovalRisk) -> bool {
462    matches!(risk, ApprovalRisk::Low | ApprovalRisk::Medium)
463}
464
465/// The risk in plain words.
466fn risk_words(risk: ApprovalRisk) -> &'static str {
467    match risk {
468        ApprovalRisk::Low => "Low risk",
469        ApprovalRisk::Medium => "Medium risk",
470        ApprovalRisk::High => "High risk",
471        ApprovalRisk::Critical => "Critical risk",
472    }
473}
474
475/// The asking agent's name: the last part of its id, or "Your agent".
476fn agent_name(request: &ApprovalRequest) -> String {
477    let id = request.acting.as_ref().map(|acting| acting.agent.id.as_str()).unwrap_or_default();
478    let name = id.rsplit(['/', ':']).next().unwrap_or_default();
479    match secret::clean_name(name, MAX_NAME_CHARS) {
480        name if name.is_empty() => "Your agent".to_string(),
481        name => name,
482    }
483}
484
485/// `summary` with every argument value of `args` masked as `[…]`, in at most
486/// [`MAX_SUMMARY_CHARS`] characters (S-I5).
487///
488/// The summary and the values are read alike: control characters and runs of whitespace
489/// become one space, so a value with a newline or a tab is found in a summary that quotes
490/// it. A value of three or more characters is masked wherever it appears, ignoring case; a
491/// shorter one, and `true` or `false`, wherever it stands as a word or a number of its own,
492/// so `50` is masked in "Transfer 50 EUR" and "EUR50" but `5` is not taken out of "500".
493/// Whole numbers of four or more digits are also found with thousands separators, as
494/// `1,250`. Where masked values overlap or touch, one `[…]` covers them.
495pub(crate) fn card_summary(summary: &str, args: &Value) -> String {
496    let mut values = Vec::new();
497    collect_values(args, &mut values);
498    let text: Vec<char> = plain(summary).chars().collect();
499    let folded: Vec<char> = text.iter().map(|c| fold(*c)).collect();
500    let mut masked = vec![false; text.len()];
501    for value in values {
502        let needle: Vec<char> = plain(&value.text).chars().map(fold).collect();
503        if needle.is_empty() || needle.len() > text.len() {
504            continue;
505        }
506        let whole = value.whole_word || needle.len() < 3;
507        for start in 0..=text.len() - needle.len() {
508            let end = start + needle.len();
509            if folded[start..end] == needle[..] && (!whole || stands_alone(&text, start, end)) {
510                masked[start..end].fill(true);
511            }
512        }
513    }
514    let mut out = String::with_capacity(text.len());
515    for (index, c) in text.iter().enumerate() {
516        match (masked[index], index.checked_sub(1).is_some_and(|before| masked[before])) {
517            (true, true) => {}
518            (true, false) => out.push_str("[…]"),
519            (false, _) => out.push(*c),
520        }
521    }
522    let text = out.trim();
523    if text.chars().count() <= MAX_SUMMARY_CHARS {
524        return text.to_string();
525    }
526    let mut cut: String = text.chars().take(MAX_SUMMARY_CHARS - 1).collect();
527    cut.push('…');
528    cut
529}
530
531/// `text` with control characters and runs of whitespace as one space, trimmed.
532fn plain(text: &str) -> String {
533    text.split(|c: char| c.is_whitespace() || c.is_control())
534        .filter(|word| !word.is_empty())
535        .collect::<Vec<_>>()
536        .join(" ")
537}
538
539/// `c` in lower case, one character for one, so positions line up.
540fn fold(c: char) -> char {
541    c.to_lowercase().next().unwrap_or(c)
542}
543
544/// What a character is, for telling where a short value stands on its own.
545#[derive(PartialEq, Eq)]
546enum CharClass {
547    Digit,
548    Letter,
549    Other,
550}
551
552fn class(c: char) -> CharClass {
553    if c.is_numeric() {
554        CharClass::Digit
555    } else if c.is_alphabetic() {
556        CharClass::Letter
557    } else {
558        CharClass::Other
559    }
560}
561
562/// Whether `text[start..end]` is not part of a longer word or number: the characters on
563/// either side are of another kind than its own first and last.
564fn stands_alone(text: &[char], start: usize, end: usize) -> bool {
565    let edge = |inside: char, outside: Option<&char>| {
566        class(inside) == CharClass::Other || outside.is_none_or(|c| class(*c) != class(inside))
567    };
568    edge(text[start], start.checked_sub(1).and_then(|before| text.get(before)))
569        && edge(text[end - 1], text.get(end))
570}
571
572/// An argument value as the masking reads it.
573struct ArgValue {
574    text: String,
575    /// Masked only where it stands on its own, whatever its length.
576    whole_word: bool,
577}
578
579/// Every string, number and boolean of `value`, as text; whole numbers of four or more
580/// digits also with thousands separators.
581fn collect_values(value: &Value, out: &mut Vec<ArgValue>) {
582    match value {
583        Value::String(text) => out.push(ArgValue { text: text.clone(), whole_word: false }),
584        Value::Number(number) => {
585            let text = number.to_string();
586            if let Some(whole) = number.as_i64().filter(|whole| whole.unsigned_abs() >= 1_000) {
587                out.push(ArgValue { text: grouped(whole), whole_word: false });
588            }
589            out.push(ArgValue { text, whole_word: false });
590        }
591        Value::Bool(flag) => out.push(ArgValue { text: flag.to_string(), whole_word: true }),
592        Value::Array(items) => items.iter().for_each(|item| collect_values(item, out)),
593        Value::Object(fields) => fields.values().for_each(|item| collect_values(item, out)),
594        Value::Null => {}
595    }
596}
597
598/// `number` with a comma between each group of three digits, as `-1,250,000`.
599fn grouped(number: i64) -> String {
600    let digits = number.unsigned_abs().to_string();
601    let mut out = String::new();
602    for (index, digit) in digits.chars().enumerate() {
603        if index > 0 && (digits.len() - index).is_multiple_of(3) {
604            out.push(',');
605        }
606        out.push(digit);
607    }
608    if number < 0 { format!("-{out}") } else { out }
609}
610
611/// Everything was stopped from a chat thread (spec 3.3 S-I10).
612#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
613#[serde(rename_all = "camelCase")]
614#[non_exhaustive]
615pub struct StopNotice {
616    /// When.
617    pub at: DateTime<Utc>,
618    /// Where everything is resumed, when the gateway knows the home.
619    #[serde(default, skip_serializing_if = "Option::is_none")]
620    pub home: Option<String>,
621}
622
623impl StopNotice {
624    /// The notice in plain words.
625    pub fn text(&self) -> String {
626        match &self.home {
627            Some(home) => format!("Stopped all agents. Resume all in the home: {home}"),
628            None => "Stopped all agents. Resume all in the home.".to_string(),
629        }
630    }
631}
632
633/// Something the gateway tells a chat thread (spec 3.3 §5.3, §8).
634///
635/// # Example
636///
637/// ```rust
638/// use adk_kernel::channels::ChannelNotice;
639///
640/// let notice = ChannelNotice::ResumeRefused { home: None };
641/// assert_eq!(notice.text(), "Resuming happens only in the home.");
642/// ```
643#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
644#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
645#[non_exhaustive]
646pub enum ChannelNotice {
647    /// The account is not paired: its code, to be accepted where the kernel runs.
648    PairingCode {
649        /// The code, as `ABCD-EFGH-2345`.
650        code: String,
651        /// When it stops working.
652        expires_at: DateTime<Utc>,
653    },
654    /// The account was sent a code that still works.
655    PairingWaiting {
656        /// When it stops working.
657        expires_at: DateTime<Utc>,
658    },
659    /// Too many accounts wait to be paired; nothing was sent.
660    PairingBusy,
661    /// The answer was recorded.
662    Decided {
663        /// What was answered.
664        answer: ChannelAnswer,
665        /// The decision's summary.
666        summary: String,
667    },
668    /// The decision was answered before this answer arrived (S-I2).
669    AlreadyDecided {
670        /// Who answered: `None` when the answer was the same person's.
671        #[serde(default, skip_serializing_if = "Option::is_none")]
672        by: Option<String>,
673        /// What they answered, in plain words, such as "yes".
674        said: String,
675        /// When.
676        #[serde(default, skip_serializing_if = "Option::is_none")]
677        at: Option<DateTime<Utc>>,
678    },
679    /// The decision changed since the card was sent; a fresh card follows.
680    DecisionChanged,
681    /// The decision is not one this thread may answer: high risk, or an answer it does not
682    /// allow (spec 3.3 §7.2).
683    DecideInHome {
684        /// The web home, when the gateway knows it.
685        #[serde(default, skip_serializing_if = "Option::is_none")]
686        home: Option<String>,
687    },
688    /// The decision is no longer waiting, or is not this person's.
689    DecisionGone,
690    /// The decision waits for someone else: another approver after this person's answer
691    /// counted, or an approver other than this person.
692    WaitingForOthers {
693        /// Whether this person's answer was counted.
694        answered: bool,
695    },
696    /// A chat thread cannot resume (S-I10).
697    ResumeRefused {
698        /// The web home, when the gateway knows it.
699        #[serde(default, skip_serializing_if = "Option::is_none")]
700        home: Option<String>,
701    },
702    /// Everything is stopped, so the message started nothing.
703    Stopped {
704        /// The web home, when the gateway knows it.
705        #[serde(default, skip_serializing_if = "Option::is_none")]
706        home: Option<String>,
707    },
708    /// The turn failed.
709    TurnFailed,
710}
711
712impl ChannelNotice {
713    /// The notice in plain words (spec 3.3 §8).
714    pub fn text(&self) -> String {
715        let home = |home: &Option<String>| match home {
716            Some(home) => format!(": {home}"),
717            None => ".".to_string(),
718        };
719        match self {
720            Self::PairingCode { code, expires_at } => format!(
721                "This account isn't paired yet. To pair it, run `adk-rust pair accept {code}` where \
722                 your agents run, before {}.",
723                local_time(*expires_at)
724            ),
725            Self::PairingWaiting { expires_at } => format!(
726                "This account is waiting to be paired. Use the code you were sent before {}.",
727                local_time(*expires_at)
728            ),
729            Self::PairingBusy => {
730                "Too many accounts are waiting to be paired. Try again later.".to_string()
731            }
732            Self::Decided { answer: ChannelAnswer::AllowOnce, summary } => {
733                format!("Allowed once: {summary}")
734            }
735            Self::Decided { answer: ChannelAnswer::Deny, summary } => format!("Denied: {summary}"),
736            Self::AlreadyDecided { by, said, at } => {
737                let who = by.as_deref().unwrap_or("You");
738                match at {
739                    Some(at) => {
740                        format!("Decided already: {who} said {said} at {}.", local_time(*at))
741                    }
742                    None => format!("Decided already: {who} said {said}."),
743                }
744            }
745            Self::DecisionChanged => "This decision changed. Here it is again.".to_string(),
746            Self::DecideInHome { home: link } => {
747                format!("Decide this one in the home{}", home(link))
748            }
749            Self::DecisionGone => "That decision is no longer waiting for you.".to_string(),
750            Self::WaitingForOthers { answered: true } => {
751                "Your answer counts. The decision also waits for someone else.".to_string()
752            }
753            Self::WaitingForOthers { answered: false } => {
754                "This decision waits for someone else to answer it.".to_string()
755            }
756            Self::ResumeRefused { home: link } => match link {
757                Some(link) => format!("Resuming happens only in the home: {link}"),
758                None => "Resuming happens only in the home.".to_string(),
759            },
760            Self::Stopped { home: link } => {
761                format!("All agents are stopped. Resume all in the home{}", home(link))
762            }
763            Self::TurnFailed => {
764                "Something went wrong. Open the home to see what happened.".to_string()
765            }
766        }
767    }
768}
769
770/// `at` as `HH:MM` on this host's clock.
771fn local_time(at: DateTime<Utc>) -> String {
772    at.with_timezone(&chrono::Local).format("%H:%M").to_string()
773}
774
775/// Where a channel's messages go out (spec 3.3 §10 K1): implemented by each platform
776/// adapter.
777///
778/// Every method sends to `thread`, a conversation of [`channel`](Self::channel). The kernel
779/// sends structured values; the adapter renders them for its platform, escaping text
780/// (S-I9), and offers a card's [`answers`](DecisionCard::answers) as buttons, no others.
781/// The `text` method of each value gives plain words an adapter may use as they are.
782///
783/// # Example
784///
785/// ```rust
786/// use adk_kernel::channels::{ChannelSink, DecisionCard, StopNotice};
787/// use async_trait::async_trait;
788///
789/// struct Log;
790///
791/// #[async_trait]
792/// impl ChannelSink for Log {
793///     fn channel(&self) -> &str {
794///         "log"
795///     }
796///
797///     async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
798///         tracing::info!(thread, text, "message");
799///         Ok(())
800///     }
801///
802///     async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
803///         self.send_message(thread, &card.text()).await
804///     }
805///
806///     async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
807///         self.send_message(thread, &notice.text()).await
808///     }
809/// }
810/// ```
811#[async_trait]
812pub trait ChannelSink: Send + Sync {
813    /// The channel's name, such as `telegram`, which its inbound messages carry.
814    fn channel(&self) -> &str;
815
816    /// Sends an agent's reply or other text.
817    ///
818    /// # Errors
819    ///
820    /// Returns the platform's error; the gateway logs it.
821    async fn send_message(&self, thread: &str, text: &str) -> Result<()>;
822
823    /// Sends a decision card: its summary, agent and risk, with its answers as buttons.
824    ///
825    /// # Errors
826    ///
827    /// Returns the platform's error.
828    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> Result<()>;
829
830    /// Says that everything was stopped.
831    ///
832    /// # Errors
833    ///
834    /// Returns the platform's error.
835    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> Result<()>;
836
837    /// Sends a notice; by default as [`send_message`](Self::send_message) of its plain
838    /// words.
839    ///
840    /// # Errors
841    ///
842    /// Returns the platform's error.
843    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> Result<()> {
844        self.send_message(thread, &notice.text()).await
845    }
846}
847
848/// A chat account paired to a person (spec 3.3 §10 K1): its messages are that person's turns
849/// and its answers are that person's decisions, within what chat may decide.
850#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
851#[serde(rename_all = "camelCase")]
852#[non_exhaustive]
853pub struct ChannelBinding {
854    /// The pairing's id, [`ChannelBinding::id_for`] the channel and account.
855    pub id: String,
856    /// The channel.
857    pub channel: String,
858    /// The account on it.
859    pub account: String,
860    /// The account's display name, as the platform gave it.
861    #[serde(default, skip_serializing_if = "Option::is_none")]
862    pub display_name: Option<String>,
863    /// The thread decision cards go to: the one it asked to pair from.
864    pub thread: String,
865    /// The person it acts for: who accepted its code.
866    pub user_id: String,
867    /// Their approval groups when they accepted it.
868    #[serde(default, skip_serializing_if = "Vec::is_empty")]
869    pub groups: Vec<String>,
870    /// When it was paired.
871    pub paired_at: DateTime<Utc>,
872    /// When it was removed.
873    #[serde(default, skip_serializing_if = "Option::is_none")]
874    pub revoked_at: Option<DateTime<Utc>>,
875}
876
877impl ChannelBinding {
878    /// A binding of `account` on `channel` to `user_id`, delivering cards to `thread`.
879    pub fn new(
880        channel: impl Into<String>,
881        account: impl Into<String>,
882        thread: impl Into<String>,
883        user_id: impl Into<String>,
884        paired_at: DateTime<Utc>,
885    ) -> Self {
886        let (channel, account) = (channel.into(), account.into());
887        Self {
888            id: Self::id_for(&channel, &account),
889            channel,
890            account,
891            display_name: None,
892            thread: thread.into(),
893            user_id: user_id.into(),
894            groups: Vec::new(),
895            paired_at,
896            revoked_at: None,
897        }
898    }
899
900    /// The id of the binding of `account` on `channel`: `ch-` and sixteen hex digits of a
901    /// SHA-256 of both, so one account has one binding.
902    ///
903    /// # Example
904    ///
905    /// ```rust
906    /// use adk_kernel::channels::ChannelBinding;
907    ///
908    /// let id = ChannelBinding::id_for("telegram", "4217");
909    /// assert!(id.starts_with("ch-"));
910    /// assert_ne!(id, ChannelBinding::id_for("matrix", "4217"));
911    /// ```
912    pub fn id_for(channel: &str, account: &str) -> String {
913        format!("ch-{}", &secret::digest(&format!("{channel}\0{account}"))[..16])
914    }
915
916    /// Sets the approval groups.
917    #[must_use]
918    pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
919        self.groups = groups.into_iter().map(Into::into).collect();
920        self
921    }
922
923    /// Whether the account reaches the agents.
924    pub fn is_active(&self) -> bool {
925        self.revoked_at.is_none()
926    }
927
928    /// The binding as the control plane lists it.
929    pub fn view(&self) -> ChannelAccountView {
930        ChannelAccountView {
931            id: self.id.clone(),
932            channel: self.channel.clone(),
933            account: self.account.clone(),
934            display_name: self.display_name.clone(),
935            user_id: self.user_id.clone(),
936            paired_at: self.paired_at,
937            revoked_at: self.revoked_at,
938            state: if self.is_active() {
939                ChannelAccountState::Active
940            } else {
941                ChannelAccountState::Revoked
942            },
943        }
944    }
945}
946
947/// An unpaired account's request to pair (spec 3.3 §10 K1): the hash of the code it was
948/// sent, never the code.
949#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
950#[serde(rename_all = "camelCase")]
951#[non_exhaustive]
952pub struct ChannelPairingRequest {
953    /// The SHA-256 of the normalized code, in hex.
954    pub code_hash: String,
955    /// The channel.
956    pub channel: String,
957    /// The account.
958    pub account: String,
959    /// The account's display name.
960    #[serde(default, skip_serializing_if = "Option::is_none")]
961    pub display_name: Option<String>,
962    /// The thread it asked from, where cards will go.
963    pub thread: String,
964    /// When it asked.
965    pub requested_at: DateTime<Utc>,
966    /// When its code stops working.
967    pub expires_at: DateTime<Utc>,
968    /// The operator dismissed the account: until [`expires_at`](Self::expires_at) it holds
969    /// no code and gets none, and it waits for nothing.
970    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
971    pub dismissed: bool,
972    /// Its code could not be sent: the account's next message is sent a new code in its
973    /// place, with no second request on record, while it keeps its place among those waiting.
974    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
975    pub undelivered: bool,
976}
977
978impl ChannelPairingRequest {
979    /// A request from `account` on `channel` in `thread`, its code hashed `code_hash`.
980    pub fn new(
981        code_hash: impl Into<String>,
982        channel: impl Into<String>,
983        account: impl Into<String>,
984        thread: impl Into<String>,
985        requested_at: DateTime<Utc>,
986        expires_at: DateTime<Utc>,
987    ) -> Self {
988        Self {
989            code_hash: code_hash.into(),
990            channel: channel.into(),
991            account: account.into(),
992            display_name: None,
993            thread: thread.into(),
994            requested_at,
995            expires_at,
996            dismissed: false,
997            undelivered: false,
998        }
999    }
1000
1001    /// The dismissal of `waiting`'s account at `now`: no code for it until [`DISMISSED_FOR`]
1002    /// has passed. Its code hash names the dismissal, so no code ever takes it.
1003    pub(crate) fn dismissal(waiting: &ChannelPairingRequest, now: DateTime<Utc>) -> Self {
1004        let until = now + chrono::Duration::from_std(DISMISSED_FOR).unwrap_or_default();
1005        let id = ChannelBinding::id_for(&waiting.channel, &waiting.account);
1006        let mut dismissal = Self::new(
1007            format!("dismissed:{id}"),
1008            waiting.channel.clone(),
1009            waiting.account.clone(),
1010            waiting.thread.clone(),
1011            now,
1012            until,
1013        );
1014        dismissal.display_name = waiting.display_name.clone();
1015        dismissal.dismissed = true;
1016        dismissal
1017    }
1018
1019    /// The request as the control plane lists it.
1020    pub fn view(&self) -> ChannelPairingView {
1021        ChannelPairingView {
1022            id: ChannelBinding::id_for(&self.channel, &self.account),
1023            channel: self.channel.clone(),
1024            account: self.account.clone(),
1025            display_name: self.display_name.clone(),
1026            requested_at: self.requested_at,
1027            expires_at: self.expires_at,
1028        }
1029    }
1030}
1031
1032/// Where paired chat accounts and their pairing requests are kept (spec 3.3 §10 K1), on the
1033/// backends the kernel's other stores use, with one conformance suite
1034/// (`channel_binding_store_conformance_tests!`, feature `conformance`).
1035#[async_trait]
1036pub trait ChannelBindingStore: Send + Sync {
1037    /// Keeps a binding, replacing the one with the same id.
1038    async fn put_binding(&self, binding: ChannelBinding) -> Result<()>;
1039
1040    /// The binding `id`, removed ones included.
1041    async fn get_binding(&self, id: &str) -> Result<Option<ChannelBinding>>;
1042
1043    /// Every binding, oldest pairing first, then by id.
1044    async fn list_bindings(&self) -> Result<Vec<ChannelBinding>>;
1045
1046    /// Keeps an account's request, replacing that account's earlier one.
1047    async fn put_request(&self, request: ChannelPairingRequest) -> Result<()>;
1048
1049    /// The request of `account` on `channel`, expired or not.
1050    async fn get_request(
1051        &self,
1052        channel: &str,
1053        account: &str,
1054    ) -> Result<Option<ChannelPairingRequest>>;
1055
1056    /// Removes and returns the request whose code is hashed `code_hash`, expired or not; two
1057    /// takes of one code take it once.
1058    async fn take_request(&self, code_hash: &str) -> Result<Option<ChannelPairingRequest>>;
1059
1060    /// Every request, oldest first, then by channel and account.
1061    async fn list_requests(&self) -> Result<Vec<ChannelPairingRequest>>;
1062
1063    /// Removes the requests that expired at or before `before`; returns how many.
1064    async fn prune_requests(&self, before: DateTime<Utc>) -> Result<usize>;
1065}
1066
1067/// Pairs the account whose request was sent `code` to `user_id` with `groups` (spec 3.3 §10
1068/// K1): the control plane's `POST /kernel/channels/pair`.
1069///
1070/// # Errors
1071///
1072/// Returns [`KernelError::Unauthorized`] for a wrong, used or expired code, and the store's
1073/// error.
1074pub async fn accept_pairing(
1075    store: &dyn ChannelBindingStore,
1076    code: &str,
1077    user_id: &str,
1078    groups: &[String],
1079    now: DateTime<Utc>,
1080) -> Result<ChannelBinding> {
1081    let request = take_pairing(store, code, now).await?;
1082    let binding = binding_for(&request, user_id, groups, now);
1083    if let Err(error) = store.put_binding(binding.clone()).await {
1084        restore_pairing(store, request).await;
1085        return Err(error);
1086    }
1087    Ok(binding)
1088}
1089
1090/// Takes the waiting request that was sent `code`.
1091///
1092/// # Errors
1093///
1094/// Returns [`KernelError::Unauthorized`] for a wrong, used or expired code, and the store's
1095/// error.
1096pub(crate) async fn take_pairing(
1097    store: &dyn ChannelBindingStore,
1098    code: &str,
1099    now: DateTime<Utc>,
1100) -> Result<ChannelPairingRequest> {
1101    store
1102        .take_request(&secret::code_hash(code))
1103        .await?
1104        .filter(|request| now < request.expires_at)
1105        .ok_or_else(|| KernelError::Unauthorized {
1106            reason: "the chat pairing code is wrong, used or expired: write to the agent from the \
1107                     chat account again for a new one"
1108                .into(),
1109        })
1110}
1111
1112/// The binding a taken request becomes once `user_id` accepts it.
1113pub(crate) fn binding_for(
1114    request: &ChannelPairingRequest,
1115    user_id: &str,
1116    groups: &[String],
1117    now: DateTime<Utc>,
1118) -> ChannelBinding {
1119    let mut binding = ChannelBinding::new(
1120        request.channel.clone(),
1121        request.account.clone(),
1122        request.thread.clone(),
1123        user_id,
1124        now,
1125    )
1126    .with_groups(groups.iter().cloned());
1127    binding.display_name = request.display_name.clone();
1128    binding
1129}
1130
1131/// Puts a taken request back, so its code works again; a failure is logged, since the
1132/// caller is already answering with the error that made it put it back.
1133pub(crate) async fn restore_pairing(
1134    store: &dyn ChannelBindingStore,
1135    request: ChannelPairingRequest,
1136) {
1137    if let Err(error) = store.put_request(request).await {
1138        tracing::error!(error = %error, "a chat pairing code could not be put back");
1139    }
1140}
1141
1142/// The unexpired-or-not request of the account whose binding id would be `id`.
1143///
1144/// # Errors
1145///
1146/// Returns the store's error.
1147pub(crate) async fn waiting_request(
1148    store: &dyn ChannelBindingStore,
1149    id: &str,
1150) -> Result<Option<ChannelPairingRequest>> {
1151    Ok(store.list_requests().await?.into_iter().find(|request| {
1152        !request.dismissed && ChannelBinding::id_for(&request.channel, &request.account) == id
1153    }))
1154}
1155
1156/// Dismisses the account of `waiting` at `now`: its code stops working, its place frees,
1157/// and it gets no new code for [`DISMISSED_FOR`] (spec 3.3 §10 K1, S-I6).
1158///
1159/// # Errors
1160///
1161/// Returns the store's error.
1162pub(crate) async fn dismiss_request(
1163    store: &dyn ChannelBindingStore,
1164    waiting: &ChannelPairingRequest,
1165    now: DateTime<Utc>,
1166) -> Result<()> {
1167    store.take_request(&waiting.code_hash).await?;
1168    store.put_request(ChannelPairingRequest::dismissal(waiting, now)).await
1169}
1170
1171/// Removes the chat account `id` (spec 3.3 §10 K1); removing a removed one changes nothing.
1172///
1173/// # Errors
1174///
1175/// Returns [`KernelError::Core`] coded `kernel.not_found` for an unknown account, and the
1176/// store's error.
1177pub async fn revoke_binding(
1178    store: &dyn ChannelBindingStore,
1179    id: &str,
1180    now: DateTime<Utc>,
1181) -> Result<ChannelBinding> {
1182    let Some(mut binding) = store.get_binding(id).await? else {
1183        return Err(KernelError::Core(adk_core::AdkError::new(
1184            adk_core::ErrorComponent::Server,
1185            adk_core::ErrorCategory::NotFound,
1186            crate::error::NOT_FOUND_CODE,
1187            format!("no paired chat account {id}: list them with `adk-rust pair list`"),
1188        )));
1189    };
1190    if binding.revoked_at.is_none() {
1191        binding.revoked_at = Some(now);
1192        store.put_binding(binding.clone()).await?;
1193    }
1194    Ok(binding)
1195}
1196
1197/// What the gateway runs on (spec 3.3 §10 K1): the [`Kernel`](crate::Kernel), or a test
1198/// double such as the contract suite's.
1199#[async_trait]
1200pub trait ChannelHost: Send + Sync + 'static {
1201    /// The application the turns run in.
1202    fn app_name(&self) -> &str;
1203
1204    /// The time now.
1205    fn now(&self) -> DateTime<Utc>;
1206
1207    /// When quiet time that holds `at` ends, or `None` when `at` is not in quiet time; no
1208    /// card is delivered before then.
1209    fn quiet_until(&self, at: DateTime<Utc>) -> Option<DateTime<Utc>> {
1210        let _ = at;
1211        None
1212    }
1213
1214    /// The approval service decisions go through; `None` when the host has none.
1215    fn approvals(&self) -> Option<Arc<dyn ApprovalService>>;
1216
1217    /// When quiet time that holds `at` ends for `request`, or `None` when `at` is not in
1218    /// quiet time; no card of it is delivered before then. The kernel answers with the
1219    /// quiet time of the decision's area in force now, a change made while it runs included
1220    /// (spec 3.3 §10 K3); the default answers [`quiet_until`](Self::quiet_until).
1221    async fn quiet_ends(
1222        &self,
1223        request: &ApprovalRequest,
1224        at: DateTime<Utc>,
1225    ) -> Option<DateTime<Utc>> {
1226        let _ = request;
1227        self.quiet_until(at)
1228    }
1229
1230    /// Whether the host rates `request`'s call high risk whatever the request says, so chat
1231    /// links it to the home (spec 3.3 §7.2, S-I6). The kernel rates so a tool a mounted
1232    /// driver declares `publish_public` or `financial`, the classes nothing may allow without
1233    /// a person (spec 3.2 K-I9). `false` by default.
1234    fn rates_high(&self, request: &ApprovalRequest) -> bool {
1235        let _ = request;
1236        false
1237    }
1238
1239    /// Whether `request`'s call moves money, which chat never decides (spec 3.3 §7.4 rule
1240    /// 4). The kernel answers for the tools its mounted drivers declare `financial`; the
1241    /// gateway adds the tools [`ChannelGatewayBuilder::money_tools`] names. `false` by
1242    /// default.
1243    fn moves_money(&self, request: &ApprovalRequest) -> bool {
1244        let _ = request;
1245        false
1246    }
1247
1248    /// The audit trail the `kernel.channel` records go to.
1249    fn audit_trail(&self) -> Option<AuditTrail>;
1250
1251    /// Starts `run`, a paired account's turn; a run whose idempotency key was used returns
1252    /// the process that key started. Returns the process id.
1253    ///
1254    /// # Errors
1255    ///
1256    /// Returns [`KernelError::Frozen`] while everything is stopped, or the host's error.
1257    async fn start_turn(&self, run: NewRun) -> Result<String>;
1258
1259    /// Sends `text` to the turn of `user`'s session `session` that runs on this host (spec
1260    /// 3.3 §6 "steer"): its agent takes the message at its next safe point, and the receipt
1261    /// says whether it did. `None`, the default, when no turn of the session takes messages
1262    /// here — none runs, or another replica runs it — so the gateway starts a turn with the
1263    /// message instead.
1264    ///
1265    /// # Errors
1266    ///
1267    /// Returns the host's error when it refuses the message; the gateway then starts a turn
1268    /// with it, which answers the thread as any turn does.
1269    async fn steer(
1270        &self,
1271        user: &str,
1272        session: &str,
1273        text: &str,
1274    ) -> Result<Option<adk_core::SteerReceipt>> {
1275        let _ = (user, session, text);
1276        Ok(None)
1277    }
1278
1279    /// The turns that finish from now on, as their final run records.
1280    ///
1281    /// # Errors
1282    ///
1283    /// Returns the host's error when it cannot follow its runs.
1284    async fn finished_turns(&self) -> Result<BoxStream<'static, RunRecord>>;
1285
1286    /// The run of turn `pid` as it stands, wherever it runs: the gateway asks after the
1287    /// turns it started, so a turn another replica ran still gets its reply. `None` by
1288    /// default, for a host whose turns all finish in [`finished_turns`](Self::finished_turns).
1289    ///
1290    /// # Errors
1291    ///
1292    /// Returns the host's error when it cannot read the run.
1293    async fn turn(&self, pid: &str) -> Result<Option<RunRecord>> {
1294        let _ = pid;
1295        Ok(None)
1296    }
1297
1298    /// Stops everything, as `by`.
1299    ///
1300    /// # Errors
1301    ///
1302    /// Returns the host's error.
1303    async fn stop_all(&self, reason: &str, by: AuditActor) -> Result<()>;
1304}
1305
1306/// What the gateway did with one [`ChannelInbound`] (spec 3.3 §10 K1).
1307#[derive(Debug, Clone, PartialEq, Eq)]
1308#[non_exhaustive]
1309pub enum InboundOutcome {
1310    /// An unpaired account was sent a pairing code; nothing started (S-I6).
1311    PairingRequested,
1312    /// An unpaired account that already holds a working code was reminded; nothing started.
1313    PairingWaiting,
1314    /// Too many accounts wait; the account was told to try later and nothing started.
1315    PairingBusy,
1316    /// The operator dismissed the account lately: it got no code and nothing started.
1317    PairingDismissed,
1318    /// A paired account's message started, or for a redelivery found, a turn.
1319    TurnStarted {
1320        /// The turn's process.
1321        pid: String,
1322    },
1323    /// A paired account's message was handed to its thread's running turn (spec 3.3 §6
1324    /// "steer"): the turn takes it at its agent's next safe point, or hands it back and the
1325    /// message starts the thread's next turn. A redelivery of the message finds it.
1326    Steered,
1327    /// Everything is stopped, so the message started nothing.
1328    TurnRefused,
1329    /// Everything was stopped (S-I10).
1330    Stopped,
1331    /// Resuming from a chat thread was refused (S-I10).
1332    ResumeRefused,
1333    /// The answer decided the decision.
1334    Decided {
1335        /// The decision.
1336        decision: String,
1337    },
1338    /// The decision was answered before; the thread was told by whom (S-I2).
1339    AlreadyDecided {
1340        /// The decision.
1341        decision: String,
1342    },
1343    /// The decision changed since its card; a fresh card was sent.
1344    DecisionChanged {
1345        /// The decision.
1346        decision: String,
1347    },
1348    /// The answer was refused: high risk, an answer the decision does not allow, or a
1349    /// decision that is not this person's or no longer waits (spec 3.3 §7.2).
1350    DecisionRefused {
1351        /// The decision.
1352        decision: String,
1353    },
1354    /// The gateway's [`InboundRoute`] took the message (spec 3.5 §10 X12).
1355    Routed,
1356    /// A paired account's message with no text, such as a photo alone, which starts no turn.
1357    Empty,
1358}
1359
1360/// The channel, account and thread a turn came from, in its run's input.
1361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1362#[serde(rename_all = "camelCase")]
1363pub(crate) struct TurnOrigin {
1364    pub(crate) channel: String,
1365    pub(crate) account: String,
1366    pub(crate) thread: String,
1367}
1368
1369impl TurnOrigin {
1370    /// The origin a run's input carries, when a channel started it.
1371    pub(crate) fn of(run: &RunRecord) -> Option<Self> {
1372        serde_json::from_value(run.input.get("channel")?.clone()).ok()
1373    }
1374}
1375
1376/// The session a thread's turns continue: `chat-<channel>-` and sixteen hex digits of the
1377/// thread's SHA-256.
1378pub(crate) fn thread_session(channel: &str, thread: &str) -> String {
1379    format!("chat-{channel}-{}", &secret::digest(&format!("{channel}\0{thread}"))[..16])
1380}
1381
1382impl fmt::Display for ChannelAnswer {
1383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1384        f.write_str(self.label())
1385    }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390    use serde_json::json;
1391
1392    use super::*;
1393
1394    #[test]
1395    fn summaries_mask_every_argument_value() {
1396        let args =
1397            json!({"to": "client@example.com", "amount": 500, "cc": ["ab", "boss@example.com"]});
1398        assert_eq!(
1399            card_summary("Send 500 USD to client@example.com, cc boss@example.com", &args),
1400            "Send […] USD to […], cc […]"
1401        );
1402        assert_eq!(card_summary("Line one\nline two", &json!({})), "Line one line two");
1403        assert_eq!(card_summary("Pay 1,250 now", &json!({"amount": 1250})), "Pay […] now");
1404        let long = "x".repeat(400);
1405        assert_eq!(card_summary(&long, &json!({})).chars().count(), MAX_SUMMARY_CHARS);
1406    }
1407
1408    /// A value with a newline, a carriage return or a tab is masked in a
1409    /// summary that quotes it, raw or with the control characters already turned to spaces.
1410    #[test]
1411    fn values_with_control_characters_are_masked() {
1412        let message = "Sign in to Acme\nAccount 4417-2201";
1413        let args = json!({"message": message, "url": "https://acme.example/login"});
1414        let summary = format!("MCP server acme asks you to open a URL: {message}");
1415        let card = card_summary(&summary, &args);
1416        assert_eq!(card, "MCP server acme asks you to open a URL: […]");
1417        let spaced = "Sign in to Acme Account 4417-2201";
1418        assert!(!card_summary(spaced, &args).contains("4417"), "{}", card_summary(spaced, &args));
1419        let tabbed = json!({"note": "a\tb\r\nc"});
1420        assert_eq!(card_summary("Note: a\tb\r\nc!", &tabbed), "Note: […]!");
1421    }
1422
1423    /// Short values, strings and numbers alike, are masked where they
1424    /// stand on their own, and not inside a longer word or number.
1425    #[test]
1426    fn short_values_are_masked_where_they_stand_alone() {
1427        let args = json!({"amount": "50", "currency": "EUR", "fee": 5, "confirm": true});
1428        assert_eq!(
1429            card_summary("Transfer 50 EUR to savings, fee 5, confirm true", &args),
1430            "Transfer […] […] to savings, fee […], confirm […]"
1431        );
1432        assert_eq!(
1433            card_summary("EUR50 and 500 and a5", &json!({"n": "50"})),
1434            "EUR[…] and 500 and a5"
1435        );
1436        assert_eq!(card_summary("Transfer 50 EUR", &json!({"amount": 50})), "Transfer […] EUR");
1437        assert_eq!(card_summary("a cat", &json!({"x": "a"})), "[…] cat");
1438        assert_eq!(card_summary("Pay acme CORP", &json!({"to": "Acme Corp"})), "Pay […]");
1439    }
1440
1441    #[test]
1442    fn thread_sessions_are_stable_and_distinct() {
1443        assert_eq!(thread_session("telegram", "42"), thread_session("telegram", "42"));
1444        assert_ne!(thread_session("telegram", "42"), thread_session("telegram", "43"));
1445        assert_ne!(thread_session("telegram", "42"), thread_session("matrix", "42"));
1446    }
1447}