Skip to main content

agentmux_srv_core/backend/
urgent_asks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The urgent-message watch's record (docs/specs/SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md ยง2, third row):
5//! an urgent message that names a task (`#N`), from a sender that was proven for that message, is an ask the recipient
6//! owes an answer to. `quiet_watch` reads the asks that are still open and tells the sender when the recipient has gone
7//! quiet without answering.
8//!
9//! What is kept, and nothing else: the sender's name, the recipient's pane, the task numbers the message named and the
10//! time. Never the text. Only a delivered, urgent message whose sender was proven for it (`host-verified`,
11//! `channel-verified`, `lan-verified` or `wan-verified`) is kept, so a sender that was not proven (`self-declared`,
12//! `network-claimed`, `unverified`, a failed signature) can neither make an agent owe it work nor draw notes to itself.
13//! The record is made after the delivery is decided and cannot change it: it takes one lock for a moment, does not
14//! fail, and a panic in it is caught.
15
16use std::sync::LazyLock;
17
18use super::message_origin::OriginTrust;
19use super::reactive::{InjectionRequest, InjectionResponse};
20
21/// The most asks kept; the oldest go first.
22const MAX_ASKS: usize = 256;
23/// How long an ask is kept (unix ms): a day, then it is forgotten whether or not it was answered.
24pub const MAX_AGE_MS: u64 = 24 * 60 * 60_000;
25
26/// An urgent message to an agent that named tasks.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Ask {
29    /// Who sent it, lowercased (the name it gave; the trust of the message says it was proven).
30    pub sender: String,
31    /// The recipient's pane.
32    pub block_id: String,
33    /// The task numbers it named.
34    pub tasks: Vec<i64>,
35    /// When it was delivered (unix ms).
36    pub at_ms: u64,
37}
38
39static ASKS: LazyLock<parking_lot::Mutex<Vec<Ask>>> = LazyLock::new(Default::default);
40
41/// Whether the sender of a message was proven for it.
42fn proven(trust: OriginTrust) -> bool {
43    matches!(trust, OriginTrust::HostVerified | OriginTrust::ChannelVerified | OriginTrust::LanVerified | OriginTrust::WanVerified)
44}
45
46/// The ask a message makes, if it makes one. Pure: every condition is here.
47pub fn ask_from(priority: Option<&str>, trust: OriginTrust, sender: Option<&str>, message: &str, delivered_to: Option<&str>, now_ms: u64) -> Option<Ask> {
48    if priority != Some("urgent") || !proven(trust) {
49        return None;
50    }
51    let sender = sender.map(str::trim).filter(|s| !s.is_empty())?.to_lowercase();
52    let block_id = delivered_to.filter(|b| !b.is_empty())?.to_string();
53    let tasks = super::cold_hold::task_numbers(message);
54    if tasks.is_empty() {
55        return None;
56    }
57    Some(Ask { sender, block_id, tasks, at_ms: now_ms })
58}
59
60/// Keep the ask `req` makes, if it makes one, after `response` says it was delivered. Called by the handler once the
61/// delivery is decided; it changes nothing about it.
62pub fn note_delivery(req: &InjectionRequest, response: &InjectionResponse) {
63    if !response.success {
64        return;
65    }
66    guarded(|| {
67        let tier = req.delivery_tier.as_deref().unwrap_or("host");
68        let wan = super::reactive::sanitize::wan_verdict(req, tier);
69        let trust = super::reactive::sanitize::jekt_trust(tier, req.sig_verified, req.lan_verified, req.channel_verified, wan);
70        let now = agentmux_common::time::now_ms_u64();
71        if let Some(ask) = ask_from(req.priority.as_deref(), trust, req.source_agent.as_deref(), &req.message, response.block_id.as_deref(), now) {
72            push(ask);
73        }
74    });
75}
76
77/// Run `record`, and let nothing it does reach the caller: a panic in it is caught.
78fn guarded(record: impl FnOnce()) {
79    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
80}
81
82/// Keep `ask`. It never waits: if the list is in use at that moment (the watch is reading it) the ask is dropped,
83/// because a delivery is never held up for a note.
84fn push(ask: Ask) {
85    let Some(mut asks) = ASKS.try_lock() else { return };
86    asks.push(ask);
87    if asks.len() > MAX_ASKS {
88        let extra = asks.len() - MAX_ASKS;
89        asks.drain(..extra);
90    }
91}
92
93/// The asks not yet forgotten at `now_ms`, oldest first.
94pub fn open_asks(now_ms: u64) -> Vec<Ask> {
95    let mut asks = ASKS.lock();
96    asks.retain(|a| now_ms.saturating_sub(a.at_ms) < MAX_AGE_MS);
97    asks.clone()
98}
99
100/// Forget the asks for which `answered` says yes (they are done being watched).
101pub fn settle(mut answered: impl FnMut(&Ask) -> bool) {
102    ASKS.lock().retain(|a| !answered(a));
103}
104
105/// The record is one list for the process, so the tests that read or fill it (here and in `quiet_watch`) take turns.
106#[cfg(test)]
107pub(crate) static TEST_TURN: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
108
109#[cfg(test)]
110#[path = "urgent_asks_tests.rs"]
111mod tests;