1use std::collections::HashMap;
18use std::sync::{LazyLock, Mutex};
19
20pub const SETTING_REFUSE_BARE_ACKS: &str = "message:refuse_bare_acks";
22
23pub const ACK_WINDOW_MS: i64 = 30 * 60 * 1000;
25const REMEMBER_MS: i64 = 60 * 60 * 1000;
27const MAX_KEPT: usize = 4096;
29const MAX_ACK_CHARS: usize = 24;
31
32const ACK_WORDS: &[&str] = &[
34 "ack", "acked", "ok", "okay", "k", "kk", "got it", "gotcha", "thanks", "thank you", "thx", "ty", "noted", "will do",
35 "on it", "done", "roger", "understood", "received", "copy", "copy that", "+1", "sounds good", "perfect", "great",
36];
37
38pub fn is_bare_ack(text: &str) -> bool {
40 let trimmed = text.trim();
41 if trimmed.is_empty() || trimmed.chars().count() > MAX_ACK_CHARS || trimmed.contains('?') {
43 return false;
44 }
45 let kept: String = trimmed
46 .to_lowercase()
47 .chars()
48 .filter(|c| c.is_alphanumeric() || c.is_whitespace() || *c == '+')
49 .collect();
50 let words = kept.split_whitespace().collect::<Vec<_>>().join(" ");
51 words.is_empty() || ACK_WORDS.contains(&words.as_str())
53}
54
55#[derive(Default)]
56pub struct AckPolicy {
57 no_reply: HashMap<String, (String, String, i64)>,
59 last_sent: HashMap<(String, String), i64>,
61}
62
63fn route(name: &str) -> String {
64 crate::backend::reactive::sanitize::route_name(name).unwrap_or_default().to_lowercase()
65}
66
67impl AckPolicy {
68 pub fn record(&mut self, from: &str, to: &str, msg_id: Option<&str>, no_reply: bool, now_ms: i64) {
70 let (from, to) = (route(from), route(to));
71 if from.is_empty() || to.is_empty() {
72 return;
73 }
74 self.last_sent.insert((from.clone(), to.clone()), now_ms);
75 if let (true, Some(id)) = (no_reply, msg_id.filter(|id| !id.is_empty())) {
76 self.no_reply.insert(id.to_string(), (from, to, now_ms));
77 }
78 if self.no_reply.len() > MAX_KEPT || self.last_sent.len() > MAX_KEPT {
79 self.no_reply.retain(|_, (_, _, at)| now_ms.saturating_sub(*at) <= REMEMBER_MS);
80 self.last_sent.retain(|_, at| now_ms.saturating_sub(*at) <= ACK_WINDOW_MS);
81 if self.no_reply.len() > MAX_KEPT {
83 let mut ages: Vec<i64> = self.no_reply.values().map(|(_, _, at)| *at).collect();
84 ages.sort_unstable();
85 let cut = ages[ages.len() / 2];
86 self.no_reply.retain(|_, (_, _, at)| *at > cut);
87 }
88 if self.last_sent.len() > MAX_KEPT {
89 let mut ages: Vec<i64> = self.last_sent.values().copied().collect();
90 ages.sort_unstable();
91 let cut = ages[ages.len() / 2];
92 self.last_sent.retain(|_, at| *at > cut);
93 }
94 }
95 }
96
97 pub fn asked_for_no_reply(&self, msg_id: &str, now_ms: i64) -> bool {
99 self.no_reply.get(msg_id).is_some_and(|(_, _, at)| now_ms.saturating_sub(*at) <= REMEMBER_MS)
100 }
101
102 pub fn check(
104 &self,
105 from: &str,
106 to: &str,
107 text: &str,
108 in_reply_to: Option<&str>,
109 refuse_bare_acks: bool,
110 now_ms: i64,
111 ) -> Result<(), String> {
112 let (from, to) = (route(from), route(to));
113 if from.is_empty() || to.is_empty() || from == to {
114 return Ok(());
115 }
116 if let Some((sender, target, at)) = in_reply_to.and_then(|id| self.no_reply.get(id)) {
117 if *sender == to && *target == from && now_ms.saturating_sub(*at) <= REMEMBER_MS {
118 return Err(format!(
119 "that message asked for no reply. If you have a new fact for {to}, send it as its own message"
120 ));
121 }
122 }
123 if refuse_bare_acks && is_bare_ack(text) {
124 let recent = self.last_sent.get(&(to.clone(), from)).is_some_and(|at| now_ms.saturating_sub(*at) <= ACK_WINDOW_MS);
125 if recent {
126 return Err(format!(
127 "a bare acknowledgement only makes {to} read its whole context again. Say something new, or say nothing"
128 ));
129 }
130 }
131 Ok(())
132 }
133}
134
135static POLICY: LazyLock<Mutex<AckPolicy>> = LazyLock::new(Default::default);
136
137pub fn record(from: &str, to: &str, msg_id: Option<&str>, no_reply: bool) {
139 let mut p = POLICY.lock().unwrap_or_else(|e| e.into_inner());
140 p.record(from, to, msg_id, no_reply, agentmux_common::time::now_ms());
141}
142
143pub fn canon(store: &crate::backend::storage::store::Store, name: &str) -> String {
146 crate::backend::agent_resolve::resolve_agent_id(store, name).unwrap_or_else(|_| name.to_string())
147}
148
149pub fn remember_arrival(store: &crate::backend::storage::store::Store, req: &crate::backend::reactive::types::InjectionRequest) {
152 let Some(source) = req.source_agent.as_deref().filter(|s| !s.is_empty() && *s != "cron") else { return };
153 record(
154 &canon(store, source),
155 &canon(store, &req.target_agent),
156 req.request_id.as_deref(),
157 req.reply.as_deref() == Some("none"),
158 );
159}
160
161pub fn asked_for_no_reply(msg_id: &str) -> bool {
163 let p = POLICY.lock().unwrap_or_else(|e| e.into_inner());
164 p.asked_for_no_reply(msg_id, agentmux_common::time::now_ms())
165}
166
167pub fn check(from: &str, to: &str, text: &str, in_reply_to: Option<&str>, refuse_bare_acks: bool) -> Result<(), String> {
169 let p = POLICY.lock().unwrap_or_else(|e| e.into_inner());
170 p.check(from, to, text, in_reply_to, refuse_bare_acks, agentmux_common::time::now_ms())
171}
172
173pub fn refuses_bare_acks(extra: &HashMap<String, serde_json::Value>) -> bool {
175 extra.get(SETTING_REFUSE_BARE_ACKS).and_then(|v| v.as_bool()).unwrap_or(true)
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn only_a_short_list_of_bare_words_is_an_acknowledgement() {
184 for yes in ["ok", "Got it!", " thanks. ", "๐", "on it", "+1", "Thank you!!", "copy that"] {
185 assert!(is_bare_ack(yes), "{yes}");
186 }
187 for no in [
188 "",
189 "ok, and the PR is #5850",
190 "got it, merging now",
191 "thanks for the review of the cache hold spec",
192 "done: #5850 merged",
193 "ok?",
194 ] {
195 assert!(!is_bare_ack(no), "{no}");
196 }
197 }
198
199 const NOW: i64 = 1_000_000_000;
200
201 #[test]
202 fn a_reply_to_a_no_reply_message_is_refused_and_a_new_message_is_not() {
203 let mut p = AckPolicy::default();
204 p.record("AgentX", "agent1", Some("m1"), true, NOW);
205 let refused = p.check("agent1", "agentx", "pausing now, nothing in flight", Some("m1"), true, NOW + 1000);
206 assert!(refused.unwrap_err().contains("asked for no reply"));
207 assert!(p.check("agent1", "agentx", "pausing now", None, true, NOW + 1000).is_ok(), "no in_reply_to, not an ack");
208 assert!(p.check("agent1", "agentx", "pausing now", Some("other"), true, NOW + 1000).is_ok());
209 assert!(p.check("camper", "agentx", "pausing now", Some("m1"), true, NOW + 1000).is_ok(), "it was not sent to camper");
210 let later = NOW + REMEMBER_MS + 1;
211 assert!(p.check("agent1", "agentx", "pausing now", Some("m1"), true, later).is_ok(), "forgotten after an hour");
212 }
213
214 #[test]
215 fn a_bare_acknowledgement_is_refused_only_soon_after_a_message_from_the_target() {
216 let mut p = AckPolicy::default();
217 assert!(p.check("agent1", "agentx", "got it", None, true, NOW).is_ok(), "agentx sent nothing");
218 p.record("agentx", "agent1", Some("m2"), false, NOW);
219 assert!(p.check("agent1", "agentx", "got it", None, true, NOW + 60_000).unwrap_err().contains("bare acknowledgement"));
220 assert!(p.check("agent1", "agentx", "got it", None, false, NOW + 60_000).is_ok(), "the setting is off");
221 assert!(p.check("agent1", "agentx", "got it", None, true, NOW + ACK_WINDOW_MS + 1).is_ok(), "too long ago");
222 assert!(p.check("agent1", "agentx", "got it, merged #5850", None, true, NOW + 60_000).is_ok(), "says something");
223 assert!(p.check("agent1", "agenty", "got it", None, true, NOW + 60_000).is_ok(), "agenty sent nothing");
224 }
225
226 #[test]
227 fn the_tables_stay_under_the_cap_even_when_every_entry_is_fresh() {
228 let mut p = AckPolicy::default();
229 for i in 0..(MAX_KEPT + 50) {
230 p.record("a", &format!("b{i}"), Some(&format!("m{i}")), true, NOW + i as i64);
231 }
232 assert!(p.no_reply.len() <= MAX_KEPT && p.last_sent.len() <= MAX_KEPT);
233 let newest = MAX_KEPT + 49;
234 assert!(p.asked_for_no_reply(&format!("m{newest}"), NOW + newest as i64), "the newest is kept");
235 assert!(!p.asked_for_no_reply("m0", NOW + newest as i64), "the oldest went");
236 }
237
238 #[test]
239 fn an_agent_may_say_anything_to_itself() {
240 let p = AckPolicy::default();
241 assert!(p.check("agent1", "Agent1", "ok", Some("m1"), true, NOW).is_ok());
242 }
243
244 #[test]
245 fn the_setting_defaults_to_refusing() {
246 let mut extra = HashMap::new();
247 assert!(refuses_bare_acks(&extra));
248 extra.insert(SETTING_REFUSE_BARE_ACKS.to_string(), serde_json::json!(false));
249 assert!(!refuses_bare_acks(&extra));
250 }
251}