Skip to main content

agentmux_srv_core/backend/
cold_hold.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Holding a routine message for an agent whose session has gone cold
5//! (`SPEC_JEKT_HOLD_FOR_COLD_SESSIONS_2026_10_25.md`). A Claude session that
6//! has been quiet past the prompt cache's lifetime pays for its whole context
7//! again on its next turn, so a message that could wait should not be what
8//! starts that turn. This module is the rules; `server/jekt_cold.rs` applies
9//! them and `server/jekt_held.rs` replays what was held.
10
11use std::collections::HashMap;
12
13use super::reactive::types::{InjectionRequest, JektTier};
14use super::storage::store::Store;
15
16/// The setting: minutes of quiet after which a session counts as cold. 0
17/// turns the hold off.
18pub const SETTING_COLD_MINUTES: &str = "jekt:cold_hold_minutes";
19/// A little under the prompt cache's one hour, so a session is held before
20/// its cache has actually lapsed.
21pub const DEFAULT_COLD_MINUTES: i64 = 55;
22
23/// `held_reason` in the answer, and the held row's reason.
24pub const REASON_IDLE: &str = "idle";
25
26/// The reason of a routine message kept back by quota mode (`backend::quota_mode`): it goes when the
27/// agent next writes output, or when the mode is off.
28pub const REASON_QUOTA: &str = "quota";
29
30/// How far back a task the sender filed for the target keeps its messages
31/// urgent.
32pub const FILED_WINDOW_MS: i64 = 15 * 60 * 1000;
33
34/// At most this many `#N` in a message are looked up.
35const MAX_TASK_NUMBERS: usize = 8;
36
37/// How long a session must be quiet to be cold, or `None` when the hold is off.
38pub fn cold_after_ms(extra: &HashMap<String, serde_json::Value>) -> Option<i64> {
39    let minutes = extra.get(SETTING_COLD_MINUTES).and_then(|v| v.as_i64()).unwrap_or(DEFAULT_COLD_MINUTES);
40    (minutes > 0).then(|| minutes.saturating_mul(60_000))
41}
42
43/// A session is cold when it last wrote output more than `after_ms` ago. One
44/// that has written nothing since it started is not cold: it has no cache to
45/// lose, and a message may be what it is waiting for.
46pub fn is_cold(last_output_ms: Option<i64>, now_ms: i64, after_ms: i64) -> bool {
47    last_output_ms.is_some_and(|at| now_ms.saturating_sub(at) > after_ms)
48}
49
50/// The sender asked for it to be delivered now (`urgent: true`, or a priority
51/// of `urgent` or `high`).
52pub fn asks_to_wake(priority: Option<&str>) -> bool {
53    priority.is_some_and(|p| matches!(p.trim().to_ascii_lowercase().as_str(), "urgent" | "high"))
54}
55
56/// Why a message may not wait, or `None` when it may: a sender proven on this machine (or, with
57/// `proven_peer`, one proven by the LAN or WAN checks), an ordinary tier, no files, and nothing
58/// the receiver's rules would treat as sensitive. Anything else is delivered as before, and the
59/// reason is what the log says.
60pub fn why_not_routine(req: &InjectionRequest, proven_peer: bool) -> Option<&'static str> {
61    if req.sig_verified != Some(true) && !proven_peer {
62        Some("its sender is not proven")
63    } else if req.files.is_some() {
64        Some("it carries files")
65    } else if req.files_delivery.is_some() {
66        // Its files were dropped, with a note saying why (malformed, over the limits, a signature that did
67        // not match). A held row has nowhere to keep the note, so the message is delivered with it now.
68        Some("its files were dropped and a note says why")
69    } else if req.is_transcript_request {
70        Some("it asks for a transcript")
71    } else if matches!(req.jekt_tier, Some(JektTier::Sensitive)) {
72        Some("it is a sensitive-tier message")
73    } else if super::reactive::sanitize::is_sensitive_message(&req.message) {
74        Some("its text reads as sensitive")
75    } else {
76        None
77    }
78}
79
80/// A message that may wait, from a sender proven on this machine ([`why_not_routine`]).
81pub fn is_routine(req: &InjectionRequest) -> bool {
82    why_not_routine(req, false).is_none()
83}
84
85/// The task numbers a message names ("#812"), at most [`MAX_TASK_NUMBERS`].
86pub fn task_numbers(text: &str) -> Vec<i64> {
87    let bytes = text.as_bytes();
88    let mut found = Vec::new();
89    let mut i = 0;
90    while i < bytes.len() && found.len() < MAX_TASK_NUMBERS {
91        if bytes[i] == b'#' {
92            let start = i + 1;
93            let mut end = start;
94            while end < bytes.len() && bytes[end].is_ascii_digit() {
95                end += 1;
96            }
97            // "#12" but not "a#12" inside a word or a hex colour such as "#1a2b3c".
98            let word_before = i > 0 && bytes[i - 1].is_ascii_alphanumeric();
99            let word_after = end < bytes.len() && bytes[end].is_ascii_alphanumeric();
100            if end > start && end - start <= 9 && !word_before && !word_after {
101                if let Ok(n) = text[start..end].parse::<i64>() {
102                    if !found.contains(&n) {
103                        found.push(n);
104                    }
105                }
106            }
107            i = end.max(i + 1);
108        } else {
109            i += 1;
110        }
111    }
112    found
113}
114
115/// When the Claude session of `block_id` last wrote output, or `None` when it
116/// is not one to hold for: another provider (its cache works differently),
117/// no controller, or a turn in flight (it is working, whatever it last wrote).
118pub fn session_last_output(mstore: &Store, block_id: &str) -> Option<i64> {
119    let block = mstore.get::<super::obj::Block>(block_id).ok().flatten()?;
120    let raw = super::obj::meta_get_string(&block.meta, "agentProvider", "");
121    if super::providers::resolve_provider_alias(&raw) != "claude" {
122        return None;
123    }
124    let ctrl = super::blockcontroller::get_controller(block_id)?;
125    if ctrl.turn_tracker().and_then(|t| t.pass_started_ms()).is_some() {
126        return None;
127    }
128    ctrl.last_output_ms()
129}
130
131/// Whether a turn is in flight in the agent of `block_id` (a message joins it without a new context
132/// read), and when it last wrote output. `None` when nothing here can say: no controller, or one that
133/// tracks no turns (a shell or SSH pane), which is delivered to as before.
134pub fn session_activity(block_id: &str) -> Option<(bool, Option<i64>)> {
135    let ctrl = super::blockcontroller::get_controller(block_id)?;
136    let tracker = ctrl.turn_tracker()?;
137    let in_flight = tracker.pass_started_ms().is_some();
138    Some((in_flight, ctrl.last_output_ms()))
139}
140
141/// Whether the agent in `block_id` is a cold Claude session now, by the setting's limit.
142pub fn block_is_cold(mstore: &Store, extra: &HashMap<String, serde_json::Value>, block_id: &str) -> bool {
143    let Some(after_ms) = cold_after_ms(extra) else { return false };
144    is_cold(session_last_output(mstore, block_id), agentmux_common::time::now_ms(), after_ms)
145}
146
147/// srv's own `[AgentMux]` note `text` for the agent in `block_id` (`target`), for a note that
148/// asks nothing urgent of it: delivered now, which starts a turn, to a warm session; kept under
149/// `key` for the agent's next turn, never starting one, when the session has gone cold.
150pub fn note_or_wait_if_cold(
151    mstore: &Store,
152    extra: &HashMap<String, serde_json::Value>,
153    block_id: &str,
154    target: &str,
155    key: &str,
156    text: &str,
157) -> Result<(), String> {
158    if block_is_cold(mstore, extra, block_id) {
159        super::blockcontroller::system_note_into_turn_or_hold(block_id, key, text);
160        return Ok(());
161    }
162    super::reactive::get_global_handler().deliver_system_note(target, text)
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    fn routine() -> InjectionRequest {
170        InjectionRequest {
171            target_agent: "loap".into(),
172            message: "thanks, noted".into(),
173            sig_verified: Some(true),
174            ..Default::default()
175        }
176    }
177
178    #[test]
179    fn the_setting_defaults_to_55_minutes_and_zero_is_off() {
180        let mut extra = HashMap::new();
181        assert_eq!(cold_after_ms(&extra), Some(55 * 60_000));
182        extra.insert(SETTING_COLD_MINUTES.into(), serde_json::json!(30));
183        assert_eq!(cold_after_ms(&extra), Some(30 * 60_000));
184        extra.insert(SETTING_COLD_MINUTES.into(), serde_json::json!(0));
185        assert_eq!(cold_after_ms(&extra), None);
186        extra.insert(SETTING_COLD_MINUTES.into(), serde_json::json!(-5));
187        assert_eq!(cold_after_ms(&extra), None);
188        extra.insert(SETTING_COLD_MINUTES.into(), serde_json::json!("soon"));
189        assert_eq!(cold_after_ms(&extra), Some(55 * 60_000), "not a number: the default");
190    }
191
192    #[test]
193    fn cold_means_quiet_past_the_limit_and_never_for_a_session_with_no_output() {
194        let after = 55 * 60_000;
195        let now = 10_000_000;
196        assert!(is_cold(Some(now - after - 1), now, after));
197        assert!(!is_cold(Some(now - after), now, after), "exactly at the limit is still warm");
198        assert!(!is_cold(Some(now - 1000), now, after));
199        assert!(!is_cold(None, now, after));
200        assert!(!is_cold(Some(now + 5), now, after), "a clock step back is not cold");
201    }
202
203    #[test]
204    fn a_sender_can_ask_to_wake_it() {
205        for p in ["urgent", "high", "URGENT", " high "] {
206            assert!(asks_to_wake(Some(p)), "{p}");
207        }
208        for p in [None, Some("normal"), Some(""), Some("low")] {
209            assert!(!asks_to_wake(p), "{p:?}");
210        }
211    }
212
213    #[test]
214    fn only_a_routine_message_from_a_proven_sender_may_wait() {
215        assert!(is_routine(&routine()));
216        let mut unproven = routine();
217        unproven.sig_verified = None;
218        assert!(!is_routine(&unproven));
219        unproven.sig_verified = Some(false);
220        assert!(!is_routine(&unproven));
221        let mut sensitive = routine();
222        sensitive.jekt_tier = Some(JektTier::Sensitive);
223        assert!(!is_routine(&sensitive));
224        let mut keyword = routine();
225        keyword.message = "here is the password: hunter2".into();
226        assert!(!is_routine(&keyword), "{}", keyword.message);
227        let mut transcript = routine();
228        transcript.is_transcript_request = true;
229        assert!(!is_routine(&transcript));
230        assert_eq!(why_not_routine(&unproven, false), Some("its sender is not proven"));
231        assert_eq!(why_not_routine(&unproven, true), None, "a proven peer on another machine may wait too");
232        assert_eq!(why_not_routine(&transcript, false), Some("it asks for a transcript"));
233        let mut dropped = routine();
234        dropped.files_delivery = Some(Default::default());
235        assert_eq!(why_not_routine(&dropped, true), Some("its files were dropped and a note says why"));
236    }
237
238    #[test]
239    fn task_numbers_are_hash_then_digits_standing_alone() {
240        assert_eq!(task_numbers("#812 is yours"), [812]);
241        assert_eq!(task_numbers("see #12, #34 and #12 again"), [12, 34]);
242        assert_eq!(task_numbers("colour #1a2b3c and a#5 and #7th"), Vec::<i64>::new());
243        assert_eq!(task_numbers("(#99)"), [99]);
244        assert_eq!(task_numbers("##5"), [5]);
245        assert_eq!(task_numbers("no numbers # here"), Vec::<i64>::new());
246        let many: String = (1..=20).map(|n| format!("#{n} ")).collect();
247        assert_eq!(task_numbers(&many).len(), MAX_TASK_NUMBERS);
248        assert_eq!(task_numbers("#12345678901"), Vec::<i64>::new(), "too long to be a task number");
249    }
250
251    fn claude_block(m: &Store) -> String {
252        let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
253        block.meta.insert("agentProvider".into(), serde_json::json!("claude"));
254        m.insert(&mut block).unwrap();
255        block.oid
256    }
257
258    #[test]
259    fn a_note_for_a_cold_session_waits_for_its_next_turn_instead_of_starting_one() {
260        use crate::backend::agent_state::test_support::register_quiet;
261        let m = Store::open_in_memory().unwrap();
262        let block = claude_block(&m);
263        register_quiet(&block, 2 * 60 * 60 * 1000);
264        assert!(block_is_cold(&m, &HashMap::new(), &block));
265        note_or_wait_if_cold(&m, &HashMap::new(), &block, "nobody", "track:7", "[AgentMux] following task #7").unwrap();
266        let (with_notes, _attached) = crate::backend::reactive::held_notes::attach(&block, "hello");
267        assert!(with_notes.starts_with("hello") && with_notes.contains("following task #7"), "{with_notes}");
268        crate::backend::blockcontroller::delete_controller(&block);
269    }
270
271    #[test]
272    fn a_warm_session_or_a_switched_off_hold_gets_the_note_at_once() {
273        use crate::backend::agent_state::test_support::register_quiet;
274        let m = Store::open_in_memory().unwrap();
275        let block = claude_block(&m);
276        // Delivered means handed to the handler, which here has no such agent: an error, and
277        // nothing held.
278        register_quiet(&block, 1000);
279        assert!(!block_is_cold(&m, &HashMap::new(), &block));
280        assert!(note_or_wait_if_cold(&m, &HashMap::new(), &block, "nobody-here", "track:8", "[AgentMux] x").is_err());
281        register_quiet(&block, 2 * 60 * 60 * 1000);
282        let mut off = HashMap::new();
283        off.insert(SETTING_COLD_MINUTES.to_string(), serde_json::json!(0));
284        assert!(!block_is_cold(&m, &off, &block));
285        assert!(note_or_wait_if_cold(&m, &off, &block, "nobody-here", "track:8", "[AgentMux] x").is_err());
286        let (plain, _attached) = crate::backend::reactive::held_notes::attach(&block, "hello");
287        assert_eq!(plain, "hello", "nothing was held");
288        crate::backend::blockcontroller::delete_controller(&block);
289    }
290}