1use serde_json::json;
10
11use crate::backend::cold_hold::{self, REASON_IDLE, REASON_QUOTA};
12use crate::backend::reactive::handler::LookupOutcome;
13use crate::backend::reactive::InjectionRequest;
14use crate::backend::storage::jekt_held::HoldOutcome;
15use crate::backend::storage::store::Store;
16
17use super::reactive::{replay, HoldReason};
18use super::AppState;
19
20#[derive(Debug)]
22pub(super) enum Decision {
23 Deliver,
25 Hold,
27}
28
29pub(super) fn hands_over_work(identity: &Store, req: &InjectionRequest, target_uid: &str, target_slug: &str, now_ms: i64) -> bool {
33 let named = cold_hold::task_numbers(&req.message);
34 if identity.work_numbers_waiting_on(&named, target_uid, target_slug).unwrap_or(false) {
35 return true;
36 }
37 let sender = req.source_agent.as_deref().unwrap_or("");
38 identity
39 .work_filed_for_since(&req.audit_source_uid, sender, target_uid, target_slug, now_ms - cold_hold::FILED_WINDOW_MS)
40 .unwrap_or(false)
41}
42
43#[allow(clippy::too_many_arguments)]
46pub(super) fn decide(
47 mstore: &Store,
48 identity: &Store,
49 req: &InjectionRequest,
50 target_uid: &str,
51 target_slug: &str,
52 last_output_ms: Option<i64>,
53 now_ms: i64,
54 after_ms: i64,
55) -> Decision {
56 decide_why(mstore, identity, req, target_uid, target_slug, last_output_ms, now_ms, after_ms).0
57}
58
59#[allow(clippy::too_many_arguments)]
61pub(super) fn decide_why(
62 mstore: &Store,
63 identity: &Store,
64 req: &InjectionRequest,
65 target_uid: &str,
66 target_slug: &str,
67 last_output_ms: Option<i64>,
68 now_ms: i64,
69 after_ms: i64,
70) -> (Decision, String) {
71 if cold_hold::asks_to_wake(req.priority.as_deref()) {
72 let source = req.source_agent.clone().unwrap_or_default();
75 let message = crate::backend::reactive::sanitize::sanitize_message(&req.message);
76 let _ = mstore.jekt_held_delete_idle_copies(target_uid, &source, &message);
77 return (Decision::Deliver, "the sender asked for it to be delivered now (urgent)".to_string());
78 }
79 let Some(last) = last_output_ms else {
80 return (Decision::Deliver, "the session has written no output, is not a Claude session, or has a turn in flight".to_string());
81 };
82 use crate::backend::agent_availability::{verdict, Availability};
83 let quiet_ms = now_ms.saturating_sub(last);
84 let idle = Availability::Idle { quiet_for_ms: Some(u64::try_from(quiet_ms).unwrap_or(0)) };
85 let rule = verdict(&idle, false, true, u64::try_from(after_ms).ok(), || hands_over_work(identity, req, target_uid, target_slug, now_ms));
86 if rule.waits() {
87 (Decision::Hold, "idle".to_string())
88 } else if after_ms == i64::MAX {
89 (Decision::Deliver, format!("the cold hold is off and quota mode did not hold it; quiet for {} min", quiet_ms / 60_000))
91 } else if quiet_ms > after_ms {
92 (Decision::Deliver, format!("it hands the agent work (a task it names or one its sender just filed); quiet for {} min", quiet_ms / 60_000))
93 } else {
94 (Decision::Deliver, format!("the session is warm: quiet for {} min of {}", quiet_ms / 60_000, after_ms / 60_000))
95 }
96}
97
98fn outside_the_hold(auth_via: super::ReactiveAuthVia, req: &InjectionRequest) -> Option<String> {
102 if req.request_id.as_deref().is_none_or(str::is_empty) {
103 return Some("it has no request id".to_string());
104 }
105 match req.source_agent.as_deref() {
106 None | Some("") => return Some("it has no named sender".to_string()),
107 Some("cron") => return Some("it is a cron fire".to_string()),
108 _ => {}
109 }
110 let host = auth_via == super::ReactiveAuthVia::FullAuthKey && req.delivery_tier.as_deref() == Some("host");
111 if host || super::jekt_hold::verified_peer(req) {
112 return None;
113 }
114 let tier = req.delivery_tier.as_deref().unwrap_or("none");
115 Some(match tier {
116 "lan" | "wan" => format!("it came over the {tier} and its sender is not proven"),
117 _ => format!("it is not from a full-key host-tier caller (tier {tier})"),
118 })
119}
120
121fn delivered_because(req: &InjectionRequest, why: &str) {
123 tracing::info!(
124 target = %req.target_agent,
125 source = req.source_agent.as_deref().unwrap_or(""),
126 tier = req.delivery_tier.as_deref().unwrap_or(""),
127 why,
128 "reactive inject: the cold hold did not hold this message"
129 );
130}
131
132pub(super) fn quota_holds(identity: &Store, req: &InjectionRequest, target_uid: &str, target_slug: &str, activity: Option<(bool, Option<i64>)>, now_ms: i64) -> bool {
136 !cold_hold::asks_to_wake(req.priority.as_deref())
137 && matches!(activity, Some((false, _)))
138 && !hands_over_work(identity, req, target_uid, target_slug, now_ms)
139}
140
141pub(super) async fn hold_if_cold(
145 state: &AppState,
146 auth_via: super::ReactiveAuthVia,
147 req: &InjectionRequest,
148 replay: &mut replay::Reservation,
149) -> Option<serde_json::Value> {
150 let held = hold_decision(state, auth_via, req).await?;
151 replay.delivered();
152 let reason = if held.hold_reason == REASON_QUOTA { HoldReason::Quota } else { HoldReason::Idle };
153 Some(held_answer(&req.target_agent, &held.request_id, reason))
154}
155
156static RELAY_STATE: std::sync::OnceLock<AppState> = std::sync::OnceLock::new();
158
159pub(crate) fn install(state: &AppState) {
161 let _ = RELAY_STATE.set(state.clone());
162}
163
164pub(crate) async fn hold_relayed(req: &InjectionRequest) -> bool {
169 match RELAY_STATE.get() {
170 Some(state) => hold_decision(state, super::ReactiveAuthVia::LanKey, req).await.is_some(),
171 None => false,
172 }
173}
174
175async fn hold_decision(
178 state: &AppState,
179 auth_via: super::ReactiveAuthVia,
180 req: &InjectionRequest,
181) -> Option<crate::backend::storage::jekt_held::HeldJekt> {
182 if let Some(why) = outside_the_hold(auth_via, req) {
188 delivered_because(req, &why);
189 return None;
190 }
191 let request_id = req.request_id.clone().filter(|id| !id.is_empty())?;
192 let Some(route) = crate::backend::reactive::sanitize::route_name(&req.target_agent) else {
193 delivered_because(req, "its target is not an agent name");
194 return None;
195 };
196 if req.source_agent.as_deref().map(crate::backend::reactive::sanitize::route_name).flatten().as_deref() == Some(route.as_str()) {
197 delivered_because(req, "the agent sent it to itself");
198 return None;
199 }
200 let extra = state.config_watcher.get_full_config().settings.extra.clone();
201 let quota_tight = crate::backend::quota_mode::is_tight(&extra);
202 let after_ms = match cold_hold::cold_after_ms(&extra) {
204 Some(ms) => ms,
205 None if quota_tight => i64::MAX,
206 None => {
207 delivered_because(req, "the cold hold is off (jekt:cold_hold_minutes is 0)");
208 return None;
209 }
210 };
211 let LookupOutcome::One(reg) = state.reactive_handler.lookup_delivery_target(&route) else {
212 delivered_because(req, "its target is not exactly one running agent here");
213 return None;
214 };
215 let Some(target_uid) = reg.uid.clone() else {
216 delivered_because(req, "its target agent has no uid");
217 return None;
218 };
219 let (mstore, identity, request) = (state.mstore.clone(), state.work_store.clone(), req.clone());
220 let now = agentmux_common::time::now_ms();
221 let proven_peer = super::jekt_hold::verified_peer(req);
222 let held = tokio::task::spawn_blocking(move || {
223 if let Some(why) = cold_hold::why_not_routine(&request, proven_peer) {
226 if !cold_hold::asks_to_wake(request.priority.as_deref()) {
227 return Err(format!("it is not a routine message: {why}"));
228 }
229 }
230 let last_output = cold_hold::session_last_output(&mstore, ®.block_id);
231 let (decision, why) = decide_why(&mstore, &identity, &request, &target_uid, ®.agent_id, last_output, now, after_ms);
232 let reason = match decision {
233 Decision::Hold => REASON_IDLE,
234 Decision::Deliver
235 if quota_tight && quota_holds(&identity, &request, &target_uid, ®.agent_id, cold_hold::session_activity(®.block_id), now) =>
236 {
237 REASON_QUOTA
238 }
239 Decision::Deliver => return Err(why),
240 };
241 let mut row = super::jekt_hold::held_row(&request, request_id, now);
242 row.target_uid = target_uid;
243 row.hold_reason = reason.to_string();
244 match mstore.jekt_held_insert(&row) {
245 Ok(HoldOutcome::Held) | Ok(HoldOutcome::AlreadyHeld) => Ok(row),
246 Ok(HoldOutcome::Full) | Err(_) => Err("the held-message store is full or failed, so it is delivered rather than lost".to_string()),
248 }
249 })
250 .await;
251 let held = match held {
252 Ok(Ok(row)) => row,
253 Ok(Err(why)) => {
254 delivered_because(req, &why);
255 return None;
256 }
257 Err(_) => return None,
258 };
259 crate::backend::agent_resolve::record_uid_fallback("jekt.held");
260 let reason = if held.hold_reason == REASON_QUOTA { HoldReason::Quota } else { HoldReason::Idle };
261 tracing::info!(
262 target = %req.target_agent,
263 tier = req.delivery_tier.as_deref().unwrap_or(""),
264 reason = reason.as_str(),
265 "reactive inject: holding a routine message until the agent is next active"
266 );
267 Some(held)
268}
269
270fn held_answer(target: &str, request_id: &str, reason: HoldReason) -> serde_json::Value {
273 let error = match reason {
274 HoldReason::Quota => format!(
275 "quota mode is tight — held until agent {target} is next active or the mode is off (for up to 24 h). \
276 To deliver it now, send it again with urgent: true"
277 ),
278 _ => format!(
279 "agent {target}'s session has been idle — held until it is next active (for up to 24 h). \
280 To wake it now, send it again with urgent: true"
281 ),
282 };
283 json!({
284 "success": false,
285 "held": true,
286 "held_reason": reason.as_str(),
287 "retry_when": reason.wait_reason().retry_when(),
288 "request_id": request_id,
289 "error": error,
290 })
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::backend::storage::work_queue::WorkItem;
297
298 const AFTER: i64 = 55 * 60_000;
299 const NOW: i64 = 100_000_000;
300 const COLD: Option<i64> = Some(NOW - AFTER - 1);
301 const WARM: Option<i64> = Some(NOW - 60_000);
302
303 fn req(message: &str) -> InjectionRequest {
304 InjectionRequest {
305 target_agent: "loap".into(),
306 message: message.into(),
307 source_agent: Some("agentx".into()),
308 audit_source_uid: "uid-x".into(),
309 sig_verified: Some(true),
310 ..Default::default()
311 }
312 }
313
314 fn stores() -> (Store, Store, tempfile::TempDir) {
317 let dir = tempfile::tempdir().unwrap();
318 let identity = Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
319 (Store::open_in_memory().unwrap(), identity, dir)
320 }
321
322 fn task(id: &str, filer_uid: &str, target_uid: &str, created_at: i64) -> WorkItem {
323 WorkItem {
324 id: id.into(),
325 title: format!("task {id}"),
326 payload: "do it".into(),
327 kind: String::new(),
328 target_agent: "loap".into(),
329 target_group: String::new(),
330 priority: 0,
331 state: String::new(),
332 claimed_by: String::new(),
333 target_agent_uid: target_uid.into(),
334 claimed_by_uid: String::new(),
335 claim_expires: None,
336 attempts: 0,
337 max_attempts: 3,
338 created_by: "agentx".into(),
339 created_by_uid: filer_uid.into(),
340 created_at,
341 updated_at: created_at,
342 not_before: None,
343 result: String::new(),
344 }
345 }
346
347 fn decision(m: &Store, i: &Store, r: &InjectionRequest, last: Option<i64>) -> &'static str {
348 match decide(m, i, r, "uid-l", "loap", last, NOW, AFTER) {
349 Decision::Deliver => "deliver",
350 Decision::Hold => "hold",
351 }
352 }
353
354 #[test]
355 fn a_routine_message_to_a_cold_session_is_held_and_to_a_warm_one_is_not() {
356 let (m, i, _d) = stores();
357 assert_eq!(decision(&m, &i, &req("thanks, noted"), COLD), "hold");
358 assert_eq!(decision(&m, &i, &req("thanks, noted"), WARM), "deliver");
359 assert_eq!(decision(&m, &i, &req("thanks, noted"), None), "deliver", "no output yet: nothing to lose");
360 }
361
362 #[test]
363 fn urgent_wakes_a_cold_session_and_drops_the_copy_it_replaces() {
364 let (m, i, _d) = stores();
365 let first = req("deploy is done");
366 let mut row = super::super::jekt_hold::held_row(&first, "r1".into(), NOW - 1000);
367 row.target_uid = "uid-l".into();
368 row.source_agent = "agentx".into();
369 row.hold_reason = REASON_IDLE.into();
370 assert_eq!(m.jekt_held_insert(&row).unwrap(), HoldOutcome::Held);
371
372 let mut other = row.clone();
374 other.request_id = "r2".into();
375 other.source_agent = "agenty".into();
376 m.jekt_held_insert(&other).unwrap();
377
378 let mut again = req("deploy is done");
379 again.priority = Some("urgent".into());
380 assert_eq!(decision(&m, &i, &again, COLD), "deliver");
381 let left = m.jekt_held_for_target("uid-l", 10).unwrap();
382 assert_eq!(left.len(), 1, "{left:?}");
383 assert_eq!(left[0].source_agent, "agenty");
384 }
385
386 #[test]
387 fn naming_a_task_waiting_on_the_target_is_work_and_wakes_it() {
388 let (m, i, _d) = stores();
389 i.work_queue_enqueue(&task("t1", "uid-z", "uid-l", 1)).unwrap();
390 let num = i.work_card_create("t1", &Default::default(), 1).unwrap();
391 assert_eq!(decision(&m, &i, &req(&format!("#{num} is yours")), COLD), "deliver");
392 assert_eq!(decision(&m, &i, &req("#9999 is yours"), COLD), "hold", "no such task");
393 i.work_queue_enqueue(&task("t2", "uid-z", "uid-o", 1)).unwrap();
395 let other = i.work_card_create("t2", &Default::default(), 1).unwrap();
396 assert_eq!(decision(&m, &i, &req(&format!("#{other} is yours")), COLD), "hold");
397 }
398
399 #[test]
400 fn a_task_the_sender_just_filed_for_the_target_makes_the_next_message_urgent() {
401 let (m, i, _d) = stores();
402 i.work_queue_enqueue(&task("t1", "uid-x", "uid-l", NOW - 5 * 60_000)).unwrap();
403 i.work_card_create("t1", &Default::default(), 1).unwrap();
404 assert_eq!(decision(&m, &i, &req("take a look when you can"), COLD), "deliver");
405 let (m2, i2, _d2) = stores();
407 i2.work_queue_enqueue(&task("t1", "uid-x", "uid-l", NOW - 60 * 60_000)).unwrap();
408 i2.work_card_create("t1", &Default::default(), 1).unwrap();
409 assert_eq!(decision(&m2, &i2, &req("take a look when you can"), COLD), "hold");
410 let (m3, i3, _d3) = stores();
411 i3.work_queue_enqueue(&task("t1", "uid-z", "uid-l", NOW - 5 * 60_000)).unwrap();
412 i3.work_card_create("t1", &Default::default(), 1).unwrap();
413 assert_eq!(decision(&m3, &i3, &req("take a look when you can"), COLD), "hold");
414 }
415
416 fn with_id(mut r: InjectionRequest, tier: &str) -> InjectionRequest {
417 r.request_id = Some("r1".into());
418 r.delivery_tier = Some(tier.into());
419 r
420 }
421
422 #[test]
423 fn a_verified_peer_on_the_lan_is_inside_the_hold_and_an_unproven_one_says_why_not() {
424 let host = super::super::ReactiveAuthVia::FullAuthKey;
425 assert_eq!(outside_the_hold(host, &with_id(req("hi"), "host")), None);
426 let mut lan = with_id(req("hi"), "lan");
427 lan.sig_verified = None;
428 let why = outside_the_hold(super::super::ReactiveAuthVia::FullAuthKey, &lan).unwrap();
429 assert!(why.contains("lan") && why.contains("not proven"), "{why}");
430 lan.lan_verified = Some(true);
431 assert_eq!(outside_the_hold(host, &lan), None, "a LAN message whose signature checked out may wait like a local one");
432 }
433
434 #[test]
435 fn a_message_outside_the_hold_names_the_reason() {
436 let host = super::super::ReactiveAuthVia::FullAuthKey;
437 let mut no_id = req("hi");
438 no_id.delivery_tier = Some("host".into());
439 assert!(outside_the_hold(host, &no_id).unwrap().contains("no request id"));
440 let mut cron = with_id(req("hi"), "host");
441 cron.source_agent = Some("cron".into());
442 assert!(outside_the_hold(host, &cron).unwrap().contains("cron"));
443 let mut nobody = with_id(req("hi"), "host");
444 nobody.source_agent = None;
445 assert!(outside_the_hold(host, &nobody).unwrap().contains("no named sender"));
446 assert!(outside_the_hold(host, &with_id(req("hi"), "cross-channel")).unwrap().contains("cross-channel"));
447 }
448
449 #[test]
450 fn a_delivered_message_says_why_it_was_not_held() {
451 let (m, i, _d) = stores();
452 let why = |r: &InjectionRequest, last| decide_why(&m, &i, r, "uid-l", "loap", last, NOW, AFTER).1;
453 assert!(why(&req("thanks"), WARM).contains("warm"));
454 assert!(why(&req("thanks"), None).contains("no output"));
455 let off = decide_why(&m, &i, &req("thanks"), "uid-l", "loap", COLD, NOW, i64::MAX).1;
456 assert!(off.contains("cold hold is off") && !off.contains("warm"), "{off}");
457 let mut urgent = req("thanks");
458 urgent.priority = Some("urgent".into());
459 assert!(why(&urgent, COLD).contains("urgent"));
460 i.work_queue_enqueue(&task("t1", "uid-x", "uid-l", NOW - 5 * 60_000)).unwrap();
461 i.work_card_create("t1", &Default::default(), 1).unwrap();
462 assert!(why(&req("take a look"), COLD).contains("hands the agent work"));
463 let (m2, i2, _d2) = stores();
464 assert_eq!(decide_why(&m2, &i2, &req("thanks"), "uid-l", "loap", COLD, NOW, AFTER).1, "idle");
465 }
466
467 #[test]
468 fn the_idle_held_answer_says_when_to_retry() {
469 let a = held_answer("loap", "req-1", HoldReason::Idle);
470 assert_eq!(a["held_reason"], "idle");
471 assert_eq!(a["retry_when"], "session_active");
472 assert_eq!(a["request_id"], "req-1");
473 }
474
475 #[test]
476 fn the_quota_held_answer_names_the_mode_and_says_when_to_retry() {
477 let a = held_answer("loap", "req-2", HoldReason::Quota);
478 assert_eq!(a["held_reason"], "quota");
479 assert_eq!(a["retry_when"], "mode_off_or_session_active");
480 assert!(a["error"].as_str().unwrap().contains("urgent: true"), "{a}");
481 }
482
483 const IDLE_NOW: Option<(bool, Option<i64>)> = Some((false, WARM));
485
486 #[test]
487 fn quota_mode_holds_a_routine_message_only_to_an_agent_with_no_turn_in_flight() {
488 let (_m, i, _d) = stores();
489 let holds = |r: &InjectionRequest, activity| quota_holds(&i, r, "uid-l", "loap", activity, NOW);
490 assert!(holds(&req("thanks, noted"), IDLE_NOW));
491 assert!(holds(&req("thanks, noted"), Some((false, None))), "no output yet is still no turn");
492 assert!(!holds(&req("thanks, noted"), Some((true, WARM))), "a turn in flight: the message joins it");
493 assert!(!holds(&req("thanks, noted"), None), "nothing running: not this rule's to hold");
494 }
495
496 #[test]
497 fn quota_mode_never_holds_an_urgent_message_or_one_that_hands_over_work() {
498 let (_m, i, _d) = stores();
499 let mut urgent = req("thanks, noted");
500 urgent.priority = Some("urgent".into());
501 assert!(!quota_holds(&i, &urgent, "uid-l", "loap", IDLE_NOW, NOW));
502 let mut high = req("thanks, noted");
503 high.priority = Some("high".into());
504 assert!(!quota_holds(&i, &high, "uid-l", "loap", IDLE_NOW, NOW));
505
506 i.work_queue_enqueue(&task("t1", "uid-z", "uid-l", 1)).unwrap();
507 let num = i.work_card_create("t1", &Default::default(), 1).unwrap();
508 assert!(!quota_holds(&i, &req(&format!("#{num} is yours")), "uid-l", "loap", IDLE_NOW, NOW), "naming its task is work");
509 assert!(quota_holds(&i, &req("#9999 is yours"), "uid-l", "loap", IDLE_NOW, NOW), "no such task");
510 }
511
512 #[test]
513 fn a_block_with_no_claude_session_is_never_cold() {
514 let m = Store::open_in_memory().unwrap();
515 assert_eq!(cold_hold::session_last_output(&m, "no-such-block"), None);
516 assert_eq!(cold_hold::session_activity("no-such-block"), None, "nothing running: the quota hold leaves it alone");
517 }
518}