Skip to main content

agentmux_srv/server/
jekt_hold.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Holding a jekt this instance can't deliver now: its agent is defined here
5//! but not running (`SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md`), not signed in,
6//! or out of quota (`SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §5). The replay is
7//! `jekt_held`. Moved out of `reactive.rs`, whose `deliver` calls these.
8
9use serde_json::json;
10
11use crate::backend::reactive::InjectionRequest;
12
13use super::reactive::{defined_here, echo_local_delivery, replay, HoldReason};
14use super::AppState;
15
16/// Hold a jekt no tier could take, when every condition of
17/// `SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md` §2.1 holds: a full-key,
18/// host-tier request (a LAN caller never fills the hold); not a periodic
19/// `cron` fire; and a target that is a known agent of this channel —
20/// resolved to its row's UID, so a typo or a name registered later by
21/// another block never receives the backlog. `None` keeps today's error.
22///
23/// The same rules hold a jekt the target's spawn gate refused
24/// ([`HoldReason::NeedsLogin`]); the replay then waits for sign-in
25/// (`jekt_held::still_needs_login`). Delivered by UID or held, a message
26/// keeps its one-delivery `replay` reservation.
27pub(in crate::server) async fn hold_for_absent_target(
28    state: &AppState,
29    auth_via: super::ReactiveAuthVia,
30    req: &InjectionRequest,
31    resp: &crate::backend::reactive::types::InjectionResponse,
32    reason: HoldReason,
33    replay: &mut replay::Reservation,
34) -> Option<serde_json::Value> {
35    hold_with_reason(state, auth_via, req, resp, reason, None, replay).await
36}
37
38/// A message an agent of this instance could not take for a reason that passes on its own: its spawn
39/// gate refused (not signed in: recoverable, so it is held for sign-in instead of failed,
40/// SPEC_JEKT_DELIVERY_STATES_AND_MAILBOX_2026_10_01.md Phase 0 item 4), or its pane is open and its
41/// controller is not there yet (AgentMux is starting: held until the controller registers). No other
42/// tier can run it either: the agent lives on this instance. `None` for any other error, and for a
43/// starting agent's message the hold doesn't apply to, which keeps its error.
44pub(in crate::server) async fn hold_for_refusal_here(
45    state: &AppState,
46    auth_via: super::ReactiveAuthVia,
47    req: &InjectionRequest,
48    resp: &crate::backend::reactive::types::InjectionResponse,
49    replay: &mut replay::Reservation,
50) -> Option<serde_json::Value> {
51    let error = resp.error.as_deref().unwrap_or_default();
52    if super::jekt_held::is_spawn_gate_refusal(error) {
53        let held = hold_for_absent_target(state, auth_via, req, resp, HoldReason::NeedsLogin, replay).await;
54        return Some(held.unwrap_or_else(|| needs_login_refusal(serde_json::to_value(resp).unwrap_or_default())));
55    }
56    if crate::backend::reactive::controller_wait::is_no_controller(error) {
57        return hold_for_absent_target(state, auth_via, req, resp, HoldReason::Starting, replay).await;
58    }
59    None
60}
61
62/// Why messages to the agent on `block_id` wait now: it is signed out, or
63/// out of quota until a known reset. A confirmed sign-in clears auth failures.
64/// Limits without a reset still allow turns to discover recovery. While a probe turn
65/// runs (`limit_probe`) the pane counts as working, but its limit still holds
66/// until that turn clears it. BLOCKING.
67pub(in crate::server) fn holding_unavailable(
68    mstore: &crate::backend::storage::store::Store,
69    block_id: &str,
70) -> Option<crate::backend::agent_state::Unavailable> {
71    let now_ms = agentmux_common::time::now_ms_u64();
72    use crate::backend::agent_availability::{of_unavailable, verdict, Verdict, WaitReason};
73    crate::backend::agent_state::unavailable_of_block(mstore, None, block_id, now_ms)
74        .filter(|unavailable| {
75            let rule = verdict(&of_unavailable(unavailable), false, true, None, || false);
76            matches!(rule, Verdict::Wait { reason: WaitReason::UsageLimit | WaitReason::NeedsLogin, .. })
77        })
78        .or_else(|| super::limit_probe::unavailable_while_probing(mstore, block_id, now_ms))
79}
80
81/// Whether a peer's answer to a forwarded jekt is a refusal by an instance
82/// that has the agent (its files refused, the agent out of quota, or the message held), to be
83/// returned as is: not a stale route to evict and route around.
84pub(super) fn peer_refused(body: &serde_json::Value) -> bool {
85    body.get("files_refused").and_then(|v| v.as_bool()) == Some(true)
86        // Kept by the instance that has the agent: not a stale route, and not to be sent again by another.
87        || body.get("held").and_then(|v| v.as_bool()) == Some(true)
88        || body.get("refused_reason").and_then(|v| v.as_str()).is_some()
89        || body.get("error").and_then(|v| v.as_str()).is_some_and(crate::backend::reactive::is_unavailable_refusal)
90}
91
92/// [`holding_unavailable`] for the agent of this instance that `target`
93/// names. `None` for an agent that can work, and for a target that isn't
94/// registered here (an absent or remote one: the tiers below decide, and the
95/// receiving instance checks again).
96pub(super) async fn local_target_unavailable(state: &AppState, target: &str) -> Option<crate::backend::agent_state::Unavailable> {
97    use crate::backend::reactive::handler::LookupOutcome;
98    let target = crate::backend::reactive::sanitize::route_name(target)?;
99    let LookupOutcome::One(reg) = state.reactive_handler.lookup_delivery_target(&target) else {
100        return None;
101    };
102    let mstore = state.mstore.clone();
103    tokio::task::spawn_blocking(move || holding_unavailable(&mstore, &reg.block_id)).await.ok().flatten()
104}
105
106/// What delivery checks before a message reaches a running agent: unavailable (held, or
107/// refused where it can't be held), or a session gone cold (`jekt_cold`). `None` delivers.
108pub(super) async fn hold_before_delivery(
109    state: &AppState,
110    auth_via: super::ReactiveAuthVia,
111    req: &InjectionRequest,
112    replay: &mut replay::Reservation,
113) -> Option<serde_json::Value> {
114    if let Some(unavailable) = local_target_unavailable(state, &req.target_agent).await {
115        return Some(hold_for_unavailable(state, auth_via, req, &unavailable, replay).await);
116    }
117    if let Some(held) = hold_if_api_offline(state, auth_via, req, replay).await {
118        return Some(held);
119    }
120    super::jekt_cold::hold_if_cold(state, auth_via, req, replay).await
121}
122
123/// Whether a message to the agent on `block_id` would start a turn its offline model API fails
124/// (`agent_status::decide`, spec D2 of `SPEC_AGENT_AVAILABILITY_EVERY_PATH_ONE_DECISION_2026_10_31.md`).
125/// BLOCKING.
126pub(super) fn api_is_offline_for(mstore: &crate::backend::storage::store::Store, block_id: &str, net: &crate::connectivity::ConnectivityStatus, now_ms: u64) -> bool {
127    use crate::backend::agent_status::{decide, Decision, Intent};
128    let block = mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten();
129    let status = super::availability_view::status_of(mstore, Some(block_id), block.as_ref(), net, now_ms);
130    let message = Intent::Message { urgent: false, routine: true, cold_after_ms: None };
131    matches!(decide(&status, message, || false), Decision::Wait { reason: crate::backend::agent_availability::WaitReason::ApiOffline, .. })
132}
133
134/// Hold a message to a running agent that is between turns while its model API is offline, until the
135/// API answers. It is not injected into a turn that would fail, and it is held under the rules of any
136/// hold (a host-tier, full-key sender; never a cron fire or the agent's own message): a message the hold
137/// does not apply to is delivered as before. `None` delivers.
138async fn hold_if_api_offline(
139    state: &AppState,
140    auth_via: super::ReactiveAuthVia,
141    req: &InjectionRequest,
142    replay: &mut replay::Reservation,
143) -> Option<serde_json::Value> {
144    use crate::backend::reactive::handler::LookupOutcome;
145    use crate::backend::reactive::sanitize::route_name;
146    let route = route_name(&req.target_agent)?;
147    if req.source_agent.as_deref().and_then(route_name).as_deref() == Some(route.as_str()) {
148        return None;
149    }
150    let LookupOutcome::One(reg) = state.reactive_handler.lookup_delivery_target(&route) else {
151        return None;
152    };
153    let mstore = state.mstore.clone();
154    let offline = tokio::task::spawn_blocking(move || {
155        api_is_offline_for(&mstore, &reg.block_id, &crate::connectivity::status(), agentmux_common::time::now_ms_u64())
156    })
157    .await
158    .unwrap_or(false);
159    if !offline {
160        return None;
161    }
162    let target = &req.target_agent;
163    let resp = crate::backend::reactive::types::InjectionResponse {
164        deferred: None,
165        success: false,
166        request_id: req.request_id.clone().filter(|id| !id.is_empty()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
167        block_id: None,
168        error: Some(format!("agent {target}'s model API is offline")),
169        timestamp: agentmux_common::time::now_ms_u64(),
170        effective_tier: None,
171        requires_stop: None,
172        channel_verified: None,
173    };
174    tracing::info!(target = %target, "reactive inject: the target's model API is offline, holding the message");
175    hold_with_reason(state, auth_via, req, &resp, HoldReason::ApiOffline, None, replay).await
176}
177
178/// Hold a message for an agent that can't work now (`unavailable`), or,
179/// where the hold doesn't apply (a LAN or cross-channel hop, a cron fire),
180/// refuse it with the reason: either way it is not injected into a turn
181/// that would fail and lose it. The refusal begins with
182/// [`crate::backend::reactive::UNAVAILABLE_PREFIX`].
183pub(super) async fn hold_for_unavailable(
184    state: &AppState,
185    auth_via: super::ReactiveAuthVia,
186    req: &InjectionRequest,
187    unavailable: &crate::backend::agent_state::Unavailable,
188    replay: &mut replay::Reservation,
189) -> serde_json::Value {
190    use crate::backend::agent_state::AgentState;
191    let reason = HoldReason::for_state(unavailable.state).unwrap_or(HoldReason::Limited);
192    let target = &req.target_agent;
193    let why = match (unavailable.state, unavailable.resets_at_ms.and_then(local_time_label)) {
194        (AgentState::SignedOut, _) => format!("{target} needs to sign in again"),
195        (_, Some(until)) => format!("{target}'s account is out of quota until {until}"),
196        (_, None) => format!("{target}'s account is out of quota"),
197    };
198    let resp = crate::backend::reactive::types::InjectionResponse {
199        deferred: None,
200        success: false,
201        request_id: req.request_id.clone().filter(|id| !id.is_empty()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
202        block_id: None,
203        error: Some(format!("{}{why}", crate::backend::reactive::UNAVAILABLE_PREFIX)),
204        timestamp: agentmux_common::time::now_ms_u64(),
205        effective_tier: None,
206        requires_stop: None,
207        channel_verified: None,
208    };
209    tracing::info!(target = %target, state = ?unavailable.state, "reactive inject: target can't work now, holding or refusing");
210    if let Some(held) = hold_with_reason(state, auth_via, req, &resp, reason, unavailable.resets_at_ms, replay).await {
211        if held.get("held").and_then(|h| h.as_bool()) == Some(true) {
212            super::limit_probe::maybe_probe(state, req, unavailable).await;
213        }
214        return held;
215    }
216    with_refusal(serde_json::to_value(&resp).unwrap_or_default(), reason.wait_reason(), unavailable.resets_at_ms)
217}
218
219/// `body`, the answer to a message refused (not kept) because the agent can't take it now, with
220/// the reason as data: `refused_reason` (the `held_reason` strings), `retry_when` and, when
221/// known, `until_ms`. A sender reads these instead of the wording of `error`.
222pub(super) fn with_refusal(
223    mut body: serde_json::Value,
224    reason: crate::backend::agent_availability::WaitReason,
225    until_ms: Option<u64>,
226) -> serde_json::Value {
227    body["refused_reason"] = json!(reason.as_str());
228    body["retry_when"] = json!(reason.retry_when());
229    if let Some(until) = until_ms {
230        body["until_ms"] = json!(until);
231    }
232    body
233}
234
235/// [`with_refusal`] for a spawn gate that refused: the agent is not signed in.
236pub(super) fn needs_login_refusal(body: serde_json::Value) -> serde_json::Value {
237    with_refusal(body, crate::backend::agent_availability::WaitReason::NeedsLogin, None)
238}
239
240/// "Sun 7:00 PM": a reset time in this machine's zone, as the Kanban and
241/// Swarm show it (`agent_state::Unavailable::reason`).
242pub(super) fn local_time_label(ms: u64) -> Option<String> {
243    let t = chrono::DateTime::from_timestamp_millis(i64::try_from(ms).ok()?)?;
244    Some(t.with_timezone(&chrono::Local).format("%a %-I:%M %p").to_string())
245}
246
247/// [`hold_for_absent_target`], with the reset time of a usage limit for the
248/// answer (`held_until_ms`).
249async fn hold_with_reason(
250    state: &AppState,
251    auth_via: super::ReactiveAuthVia,
252    req: &InjectionRequest,
253    resp: &crate::backend::reactive::types::InjectionResponse,
254    reason: HoldReason,
255    until_ms: Option<u64>,
256    replay: &mut replay::Reservation,
257) -> Option<serde_json::Value> {
258    use crate::backend::storage::jekt_held::HoldOutcome;
259    // A verified message from another machine waits for an agent that can't work, as a local one does;
260    // an absent agent is still left to the routing tiers (`route_for_absent`).
261    let peer_waits = matches!(reason, HoldReason::NeedsLogin | HoldReason::Limited | HoldReason::Starting) && hold_applies_to_peer(req, resp);
262    if !hold_applies(auth_via, req, resp) && !peer_waits {
263        return None;
264    }
265    let mut held = held_row(req, resp.request_id.clone(), agentmux_common::time::now_ms());
266    let mstore = state.mstore.clone();
267    let outcome = tokio::task::spawn_blocking(move || {
268        let (uid, _slug) = defined_here(&mstore, &held.target_agent)?;
269        held.target_uid = uid;
270        Some(held)
271    })
272    .await
273    .ok()
274    .flatten()?;
275    // Registered under another of its names (the handler binds only the
276    // display and stable ones): it is running, so deliver by UID now rather
277    // than tell the sender it is not. Not for a spawn-gate refusal: that
278    // target is registered, and a retry now would only be refused again.
279    if reason == HoldReason::NotRunning && state.reactive_handler.has_uid_registration(&outcome.target_uid) {
280        let by_uid = req.addressed_by_uid(&outcome.target_uid);
281        let resp = state.reactive_handler.inject_message(by_uid);
282        if resp.success {
283            replay.delivered();
284            // As addressed, so the sender's echo names whom it wrote to
285            // (ReAgent P1 on #3632: this path skipped the echo).
286            echo_local_delivery(state, req, &resp);
287        }
288        // A refusal is the target's answer; but if it unregistered between
289        // the check and the delivery, fall through and hold it (Codex P2).
290        let raced_away = resp.error.as_deref().is_some_and(|e| e.starts_with("agent not found"));
291        if !raced_away {
292            return Some(serde_json::to_value(&resp).unwrap_or_default());
293        }
294    }
295    let target_uid = outcome.target_uid.clone();
296    let mstore = state.mstore.clone();
297    let outcome = tokio::task::spawn_blocking(move || mstore.jekt_held_insert(&outcome))
298        .await
299        .ok()?;
300    let target = &req.target_agent;
301    match outcome {
302        Ok(HoldOutcome::Held) | Ok(HoldOutcome::AlreadyHeld) => {
303            replay.delivered();
304            crate::backend::agent_resolve::record_uid_fallback("jekt.held");
305            let start = match reason { HoldReason::NotRunning => super::jekt_start::start_for_held(state, req, &target_uid), HoldReason::Starting => super::jekt_start::HeldStart::Starting, _ => super::jekt_start::HeldStart::No };
306            let error = match reason {
307                HoldReason::NotRunning | HoldReason::Starting => start.not_running_text(target),
308                HoldReason::NeedsLogin => {
309                    if resp.error.as_deref().is_some_and(super::jekt_held::is_spawn_gate_refusal) {
310                        super::jekt_held::mark_needs_login(&target_uid);
311                    }
312                    format!(
313                        "agent {target} is not signed in — held for delivery on this AgentMux instance for up to 24 h, delivered when it signs in"
314                    )
315                }
316                HoldReason::Limited => format!(
317                    "agent {target}'s account is out of quota — held for delivery on this AgentMux instance for up to 24 h, delivered when it can work again (an account move or the reset)"
318                ),
319                HoldReason::ApiOffline => format!("agent {target}'s model API is offline — held for up to 24 h, delivered when it answers again"),
320                HoldReason::Idle | HoldReason::Quota | HoldReason::PeerOffline => format!("agent {target}'s session is idle — held until it is next active"), // `jekt_cold` and `reactive::peer_hold` have their own answers; never through here
321            };
322            let mut answer = json!({
323                "success": false,
324                "held": true,
325                "held_reason": reason.as_str(),
326                "retry_when": reason.wait_reason().retry_when(),
327                "request_id": resp.request_id,
328                "error": error,
329            });
330            start.annotate(&mut answer);
331            if let Some(until) = until_ms.filter(|_| reason == HoldReason::Limited) {
332                answer["held_until_ms"] = json!(until);
333                if let Some(label) = local_time_label(until) {
334                    answer["held_until"] = json!(label);
335                }
336            }
337            Some(answer)
338        }
339        Ok(HoldOutcome::Full) => Some(json!({
340            "success": false,
341            "request_id": resp.request_id,
342            "error": format!(
343                "{} (hold full: too many messages already held for {target})",
344                resp.error.clone().unwrap_or_default()
345            ),
346        })),
347        Err(e) => {
348            tracing::warn!(error = %e, target = %target, "durable jekt: hold failed");
349            None
350        }
351    }
352}
353
354/// The row to keep for `req`: what the recipient would be given, with the
355/// verdicts it was accepted with. `target_uid` is filled in by the caller.
356pub(super) fn held_row(req: &InjectionRequest, request_id: String, now: i64) -> crate::backend::storage::jekt_held::HeldJekt {
357    use crate::backend::storage::jekt_held::{HeldJekt, HELD_TTL_MS};
358    HeldJekt {
359        request_id,
360        target_uid: String::new(),
361        target_agent: req.target_agent.clone(),
362        source_agent: req.source_agent.clone().unwrap_or_default(),
363        audit_source_uid: req.audit_source_uid.clone(),
364        // What the recipient would receive — sanitized and truncated to the
365        // delivery limit — never the unbounded body (Codex P2 on #3632).
366        message: crate::backend::reactive::sanitize::sanitize_message(&req.message),
367        priority: req.priority.clone().unwrap_or_default(),
368        jekt_tier: req
369            .jekt_tier
370            .as_ref()
371            .and_then(|t| serde_json::to_value(t).ok())
372            .and_then(|v| v.as_str().map(str::to_string))
373            .unwrap_or_default(),
374        delivery_tier: if verified_peer(req) { req.delivery_tier.clone().unwrap_or_default() } else { "host".to_string() },
375        sig_verified: req.sig_verified,
376        reagent_verified: req.reagent_verified,
377        lan_verified: req.lan_verified,
378        channel_verified: req.channel_verified,
379        is_transcript_request: req.is_transcript_request,
380        transcript_request_escalate_forced: req.transcript_request_escalate_forced,
381        files_json: req
382            .files
383            .as_ref()
384            .and_then(|f| serde_json::to_string(f).ok())
385            .unwrap_or_default(),
386        sent_at_ms: now,
387        expires_at_ms: now + HELD_TTL_MS,
388        // The sender's own deadline rides the row (issue #3894): the replay
389        // drops it instead of delivering it stale once it has passed, and the
390        // expiry sweep drops it whatever the hold reason. None keeps today's
391        // 24 h behaviour exactly.
392        sender_expires_at_ms: req.expires_at_ms,
393        attempts: 0,
394        last_error: String::new(),
395        hold_reason: String::new(),
396        wan_json: wan_json_of(req),
397    }
398}
399
400/// The WAN verdict a held message from an approved install keeps, as JSON ('' for any other).
401fn wan_json_of(req: &InjectionRequest) -> String {
402    if req.delivery_tier.as_deref() != Some("wan") || !verified_peer(req) {
403        return String::new();
404    }
405    serde_json::to_string(&json!({ "verified": true, "instance": req.wan_instance })).unwrap_or_default()
406}
407
408/// A message from another machine that proved who sent it (the cross-machine operations spec, §4.5):
409/// a LAN message whose signature checked out, or a WAN one from an approved install of this
410/// account. The LAN key alone proves nothing, and a `new` install is not enough.
411pub(super) fn verified_peer(req: &InjectionRequest) -> bool {
412    use crate::backend::reactive::types::WanInstanceStatus;
413    match req.delivery_tier.as_deref() {
414        Some("lan") => req.lan_verified == Some(true),
415        Some("wan") => {
416            req.wan_verified == Some(true)
417                && req.wan_instance.as_ref().is_some_and(|i| i.status == WanInstanceStatus::Approved)
418        }
419        _ => false,
420    }
421}
422
423/// The conditions under which this instance may hold a jekt at all (durable
424/// jekt spec §2.1): a full-key, host-tier request; not a periodic `cron` fire;
425/// and an id to key the row by. A LAN or WAN caller fills the hold only for an agent
426/// that can't work, and only with proof of its sender (`hold_applies_to_peer`).
427pub(super) fn hold_applies(
428    auth_via: super::ReactiveAuthVia,
429    req: &InjectionRequest,
430    resp: &crate::backend::reactive::types::InjectionResponse,
431) -> bool {
432    auth_via == super::ReactiveAuthVia::FullAuthKey
433        && req.delivery_tier.as_deref() == Some("host")
434        && req.source_agent.as_deref() != Some("cron")
435        && !resp.request_id.is_empty()
436}
437
438/// A verified WAN message to an agent here that can't work: kept for 24 h, as a local one is, and
439/// delivered when it can (the cross-machine operations spec, §4.5). `true` when it is kept, so the
440/// caller neither injects it into a turn that would fail nor hands it back to the relay. Its files are
441/// already in the attachment store (fetched before this), and the row keeps their list: the replay
442/// builds what the agent is given for them, as a delivery now would. Files that were dropped, with a
443/// note saying why, are left to the old path: the row has nowhere to keep that note.
444pub(crate) fn hold_wan_for_unavailable(
445    mstore: &crate::backend::storage::store::Store,
446    handler: &crate::backend::reactive::handler::ReactiveHandler,
447    req: &InjectionRequest,
448) -> bool {
449    use crate::backend::reactive::handler::LookupOutcome;
450    use crate::backend::storage::jekt_held::HoldOutcome;
451    let Some(id) = req.request_id.as_deref().filter(|id| !id.is_empty()) else {
452        return false;
453    };
454    if req.delivery_tier.as_deref() != Some("wan")
455        || !verified_peer(req)
456        || req.source_agent.as_deref() == Some("cron")
457        || (req.files.is_none() && req.files_delivery.is_some())
458    {
459        return false;
460    }
461    let Some(target) = crate::backend::reactive::sanitize::route_name(&req.target_agent) else {
462        return false;
463    };
464    let LookupOutcome::One(reg) = handler.lookup_delivery_target(&target) else {
465        return false;
466    };
467    if holding_unavailable(mstore, &reg.block_id).is_none() {
468        return false;
469    }
470    let Some((uid, _slug)) = defined_here(mstore, &req.target_agent) else {
471        return false;
472    };
473    let mut held = held_row(req, id.to_string(), agentmux_common::time::now_ms());
474    held.target_uid = uid;
475    let kept = matches!(mstore.jekt_held_insert(&held), Ok(HoldOutcome::Held | HoldOutcome::AlreadyHeld));
476    if kept {
477        // Not delivered: the inline budget `prepare` charged for this attempt goes back. The replay prepares its own.
478        super::jekt_files::settle(req, false);
479    }
480    kept
481}
482
483/// A relayed message that is not held ([`hold_wan_for_unavailable`] keeps a verified peer's) to an agent here
484/// that can't work now (out of quota, or signed out): not to be injected, because the turn it starts ends in
485/// an error. `true` tells the caller to give the message back to the relay, which offers it again on a later
486/// pull; nothing is stored here, so a message with no proof of its sender never reaches the hold table, whose
487/// replay would raise its tier. A periodic `cron` fire is left to the old path.
488pub(crate) fn give_back_for_unavailable(
489    mstore: &crate::backend::storage::store::Store,
490    handler: &crate::backend::reactive::handler::ReactiveHandler,
491    req: &InjectionRequest,
492) -> bool {
493    req.source_agent.as_deref() != Some("cron") && agent_unavailable(mstore, handler, &req.target_agent)
494}
495
496/// Whether the agent here that `target` names can't work now (out of quota, or signed out). `false` for a
497/// name no agent here answers to.
498pub(crate) fn agent_unavailable(
499    mstore: &crate::backend::storage::store::Store,
500    handler: &crate::backend::reactive::handler::ReactiveHandler,
501    target: &str,
502) -> bool {
503    use crate::backend::reactive::handler::LookupOutcome;
504    let Some(target) = crate::backend::reactive::sanitize::route_name(target) else {
505        return false;
506    };
507    let LookupOutcome::One(reg) = handler.lookup_delivery_target(&target) else {
508        return false;
509    };
510    holding_unavailable(mstore, &reg.block_id).is_some()
511}
512
513/// [`hold_applies`] for a verified message from another machine ([`verified_peer`]): the same
514/// exclusions (a cron fire, no id to key the row by), without the full-key, host-tier condition. A
515/// message with files is held with them: the files route reads them into the attachment store first
516/// ([`peer_files_wait`]), so the replay finds them.
517fn hold_applies_to_peer(
518    req: &InjectionRequest,
519    resp: &crate::backend::reactive::types::InjectionResponse,
520) -> bool {
521    verified_peer(req) && req.source_agent.as_deref() != Some("cron") && !resp.request_id.is_empty()
522}
523
524/// Whether a message with files from another machine, to an agent here that can't work, waits for it
525/// (`jekt_files::receive`): the files are read within the tier's limits and kept in the attachment
526/// store, and the message is held with them. Not when the files are withheld (the sender's signature
527/// failed), the sender did not prove itself, it is a cron fire, or there is no id to key the row by: those
528/// are refused before a byte is read, as they always were.
529pub(super) fn peer_files_wait(req: &InjectionRequest, files_withheld: bool) -> bool {
530    !files_withheld
531        && verified_peer(req)
532        && req.source_agent.as_deref() != Some("cron")
533        && req.request_id.as_deref().is_some_and(|id| !id.is_empty())
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539    use crate::backend::agent_availability::WaitReason;
540    use crate::backend::reactive::types::{WanInstanceInfo, WanInstanceStatus};
541
542    fn peer(tier: &str) -> InjectionRequest {
543        InjectionRequest { delivery_tier: Some(tier.into()), source_agent: Some("a".into()), ..Default::default() }
544    }
545    fn wan(status: WanInstanceStatus) -> InjectionRequest {
546        InjectionRequest {
547            wan_verified: Some(true),
548            wan_instance: Some(WanInstanceInfo { id: "I1".into(), label: "host~I1".into(), status }),
549            ..peer("wan")
550        }
551    }
552
553    #[test]
554    fn only_a_message_that_proved_its_sender_is_a_verified_peer() {
555        assert!(verified_peer(&InjectionRequest { lan_verified: Some(true), ..peer("lan") }));
556        assert!(!verified_peer(&peer("lan")), "the LAN key alone proves nothing");
557        assert!(!verified_peer(&InjectionRequest { lan_verified: Some(false), ..peer("lan") }));
558        assert!(verified_peer(&wan(WanInstanceStatus::Approved)));
559        assert!(!verified_peer(&wan(WanInstanceStatus::New)), "a new install is not approved");
560        assert!(!verified_peer(&wan(WanInstanceStatus::Revoked)));
561        assert!(!verified_peer(&InjectionRequest { wan_verified: Some(true), ..peer("wan") }), "no instance, no proof");
562        assert!(!verified_peer(&InjectionRequest { lan_verified: Some(true), ..peer("host") }));
563    }
564
565    #[test]
566    fn a_held_peer_message_keeps_its_tier_and_proof_and_replays_as_it_arrived() {
567        let lan = InjectionRequest { lan_verified: Some(true), ..peer("lan") };
568        let row = held_row(&lan, "r1".into(), 1);
569        assert_eq!(row.delivery_tier, "lan");
570        let back = super::super::jekt_held::request_from_held(&row);
571        assert_eq!((back.delivery_tier.as_deref(), back.lan_verified), (Some("lan"), Some(true)));
572
573        let row = held_row(&wan(WanInstanceStatus::Approved), "r2".into(), 1);
574        assert_eq!(row.delivery_tier, "wan");
575        let back = super::super::jekt_held::request_from_held(&row);
576        assert_eq!(back.delivery_tier.as_deref(), Some("wan"));
577        assert_eq!(back.wan_verified, Some(true));
578        assert_eq!(back.wan_instance.map(|i| i.status), Some(WanInstanceStatus::Approved));
579    }
580
581    #[test]
582    fn an_unproven_or_host_message_is_held_and_replayed_as_host_never_raised_to_more() {
583        let row = held_row(&peer("lan"), "r3".into(), 1);
584        assert_eq!(row.delivery_tier, "host", "stored as before; a peer without proof is not held at all");
585        let mut stored = row.clone();
586        stored.delivery_tier = "lan".into();
587        stored.lan_verified = None;
588        let back = super::super::jekt_held::request_from_held(&stored);
589        assert_eq!((back.delivery_tier.as_deref(), back.lan_verified), (Some("lan"), None));
590        stored.delivery_tier = "channel".into();
591        assert_eq!(super::super::jekt_held::request_from_held(&stored).delivery_tier.as_deref(), Some("host"));
592        stored.delivery_tier = "wan".into();
593        stored.wan_json = "not json".into();
594        let back = super::super::jekt_held::request_from_held(&stored);
595        assert_eq!((back.delivery_tier.as_deref(), back.wan_verified), (Some("wan"), None));
596    }
597
598    #[test]
599    fn a_verified_peer_waits_for_an_agent_that_cannot_work_but_not_for_a_cron_fire() {
600        let resp = crate::backend::reactive::types::InjectionResponse {
601            deferred: None,
602            success: false,
603            request_id: "id".into(),
604            block_id: None,
605            error: None,
606            timestamp: 0,
607            effective_tier: None,
608            requires_stop: None,
609            channel_verified: None,
610        };
611        let lan = InjectionRequest { lan_verified: Some(true), ..peer("lan") };
612        assert!(hold_applies_to_peer(&lan, &resp));
613        assert!(!hold_applies_to_peer(&InjectionRequest { source_agent: Some("cron".into()), ..lan.clone() }, &resp));
614        assert!(!hold_applies_to_peer(&peer("lan"), &resp));
615        let with_files = InjectionRequest { files: Some(vec![agentmux_common::jekt_files::JektFile { sha256: "0".repeat(64), name: "a.txt".into(), size: 1 }]), ..lan.clone() };
616        assert!(hold_applies_to_peer(&with_files, &resp), "its files are kept in the store first, so it is held with them");
617        let no_id = crate::backend::reactive::types::InjectionResponse { request_id: String::new(), ..resp };
618        assert!(!hold_applies_to_peer(&lan, &no_id));
619    }
620
621    #[test]
622    fn a_refusal_carries_its_reason_and_what_ends_the_wait_as_data() {
623        let body = with_refusal(json!({"success": false, "error": "agent unavailable: X needs to sign in again"}), WaitReason::NeedsLogin, None);
624        assert_eq!((body["refused_reason"].as_str(), body["retry_when"].as_str()), (Some("needs_login"), Some("sign_in")));
625        assert!(body.get("until_ms").is_none());
626        let limited = with_refusal(json!({"success": false}), WaitReason::UsageLimit, Some(42));
627        assert_eq!((limited["refused_reason"].as_str(), limited["retry_when"].as_str(), limited["until_ms"].as_u64()), (Some("usage_limit"), Some("reset_or_account_move"), Some(42)));
628    }
629
630    #[test]
631    fn a_peer_refusal_is_known_by_its_reason_or_by_the_old_wording() {
632        assert!(peer_refused(&json!({"refused_reason": "usage_limit", "error": "anything"})));
633        assert!(peer_refused(&json!({"error": "agent unavailable: X's account is out of quota"})));
634        assert!(peer_refused(&json!({"files_refused": true})));
635        assert!(peer_refused(&json!({"success": false, "held": true, "held_reason": "usage_limit"})), "held there is final");
636        assert!(!peer_refused(&json!({"error": "agent not found: X"})));
637    }
638
639    /// Spec D2: a message to an agent between turns waits while its model API is offline, and goes
640    /// when the API answers, when a turn is in flight, or when srv does not track the API.
641    #[test]
642    fn a_message_to_an_agent_between_turns_waits_for_its_offline_model_api() {
643        use crate::backend::agent_state::test_support::register_stub;
644        use crate::backend::blockcontroller::{delete_controller, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING};
645        use crate::connectivity::{ConnectivityStatus, Reachability, ServiceStatus};
646
647        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
648        let mut block = crate::backend::obj::Block::default();
649        block.oid = uuid::Uuid::new_v4().to_string();
650        block.meta.insert("agentProvider".into(), json!("claude"));
651        store.insert(&mut block).unwrap();
652        let service = crate::connectivity::model_api_of("claude").map(|api| crate::connectivity::service_for(api, None).id()).unwrap();
653        let net = |state| ConnectivityStatus {
654            revision: 1,
655            services: vec![ServiceStatus { service: service.clone(), label: "API".into(), state, since_ms: 1, last_error: None }],
656        };
657        let now = 1_000_000;
658
659        register_stub(&block.oid, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
660        assert!(api_is_offline_for(&store, &block.oid, &net(Reachability::Offline), now), "between turns, API offline");
661        assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Online), now));
662        assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Unknown), now), "not checked yet holds no message");
663        assert!(!api_is_offline_for(&store, &block.oid, &ConnectivityStatus { revision: 1, services: vec![] }, now), "an API srv does not track");
664        delete_controller(&block.oid);
665
666        register_stub(&block.oid, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, true);
667        assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Offline), now), "it joins the turn in flight");
668        delete_controller(&block.oid);
669    }
670}
671
672#[cfg(test)]
673#[path = "jekt_hold_files_tests.rs"]
674mod files_tests;