Skip to main content

agentmux_mcp/
tool_helpers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Helpers the tool handlers share: cron, durations, quit-self and bulk-stop outcomes, delivery text.
5//! Split out of main.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.2).
6
7use super::*;
8
9pub(crate) async fn cron_set_enabled(
10    client: &reqwest::Client,
11    local_url: &str,
12    auth_key: &str,
13    id: &str,
14    action: &str,
15) -> Result<String> {
16    let url = format!("{}/agentmux/jobs/{}", local_url.trim_end_matches('/'), id);
17    let body = serde_json::json!({"action": action});
18    let resp = client.patch(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
19        .map_err(|e| anyhow::anyhow!("cron {action} request failed: {e}"))?;
20    let status = resp.status();
21    if status.as_u16() == 404 {
22        return Ok(format!("Job '{id}' not found"));
23    }
24    if !status.is_success() {
25        let text = resp.text().await.unwrap_or_default();
26        anyhow::bail!("Cron{} failed: HTTP {status} — {text}", if action == "pause" { "Pause" } else { "Resume" });
27    }
28    Ok(format!("Cron job {id} {}", if action == "pause" { "paused" } else { "resumed" }))
29}
30
31/// Parse a loop interval string into a `Duration`. Accepts a number with an
32/// optional unit suffix: `s` (seconds), `m` (minutes), `h` (hours); a bare
33/// number is treated as minutes. Clamped to [10s, 24h].
34pub(crate) fn parse_interval(s: &str) -> Result<Duration> {
35    let s = s.trim();
36    if s.is_empty() {
37        anyhow::bail!("interval is empty");
38    }
39    let (num_part, mult_secs) = if let Some(n) = s.strip_suffix('s').or_else(|| s.strip_suffix('S')) {
40        (n, 1.0_f64)
41    } else if let Some(n) = s.strip_suffix('m').or_else(|| s.strip_suffix('M')) {
42        (n, 60.0)
43    } else if let Some(n) = s.strip_suffix('h').or_else(|| s.strip_suffix('H')) {
44        (n, 3600.0)
45    } else {
46        (s, 60.0) // bare number → minutes
47    };
48    let val: f64 = num_part
49        .trim()
50        .parse()
51        .map_err(|_| anyhow::anyhow!("invalid interval '{s}' (expected e.g. 30s, 5m, 1h)"))?;
52    if !val.is_finite() || val <= 0.0 {
53        anyhow::bail!("interval must be a positive number: '{s}'");
54    }
55    let secs = (val * mult_secs).round() as u64;
56    Ok(Duration::from_secs(secs.clamp(10, 24 * 3600)))
57}
58
59/// Human-readable representation of a clamped Duration — used in the Loop
60/// success message so the reported cadence matches the actual run cadence.
61pub(crate) fn format_duration(d: Duration) -> String {
62    let s = d.as_secs();
63    if s % 3600 == 0 {
64        format!("{}h", s / 3600)
65    } else if s % 60 == 0 {
66        format!("{}m", s / 60)
67    } else {
68        format!("{}s", s)
69    }
70}
71
72/// What `QuitSelf` tells the agent, from srv's answer (§4.2, §6.3).
73pub(crate) fn quit_self_result(status: u16, body: &Value) -> anyhow::Result<String> {
74    match status {
75        202 => Ok("Quit scheduled. Your session ends when this turn finishes: give the user a one-line goodbye and start no new work.".to_string()),
76        200 => Ok("Already quitting — nothing more to do.".to_string()),
77        403 => anyhow::bail!(
78            "QuitSelf refused ({}): only the user's own message that started this turn can ask you to quit, and nothing else may have been delivered since. Do NOT retry. Tell the user they can type /quit in your pane.",
79            body.get("refused").and_then(|v| v.as_str()).unwrap_or("not allowed")
80        ),
81        _ => anyhow::bail!("QuitSelf failed: HTTP {status} — {}", body),
82    }
83}
84
85/// Polls srv for a shutdown waiting on the user's override
86/// (SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.5) until it leaves `pending` — and
87/// `proceeding` too when `to_the_end` — and returns the last status seen. One
88/// long request instead would outlast the client's own timeout.
89pub(crate) async fn await_shutdown(client: &reqwest::Client, local_url: &str, auth_key: &str, request_id: &str, to_the_end: bool) -> Value {
90    await_shutdown_of(client, local_url, auth_key, request_id, to_the_end, None).await
91}
92
93/// [`await_shutdown`] for a caller whose own pane may be one of several in a request: it also stops
94/// waiting once the user has answered for `own` (kept it), which the request's shared status does
95/// not say until every other agent has been dealt with.
96pub(crate) async fn await_shutdown_of(
97    client: &reqwest::Client,
98    local_url: &str,
99    auth_key: &str,
100    request_id: &str,
101    to_the_end: bool,
102    own: Option<&str>,
103) -> Value {
104    let url = format!("{}/api/v1/agent/shutdown/{request_id}", local_url.trim_end_matches('/'));
105    // The window, the turn end a self-quit waits for (30 s) and the graceful
106    // stop itself, with room to spare.
107    let give_up = std::time::Instant::now() + std::time::Duration::from_secs(90);
108    let mut last = Value::Null;
109    while std::time::Instant::now() < give_up {
110        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
111        if let Ok(r) = client.get(&url).header(AUTH_KEY_HEADER, auth_key).send().await {
112            last = r.json().await.unwrap_or(last);
113        }
114        if own.is_some_and(|b| own_outcome(last.clone(), b)["status"] == "kept_by_user") {
115            break;
116        }
117        match last["status"].as_str().unwrap_or("") {
118            "" | "pending" => {}
119            "proceeding" if to_the_end => {}
120            _ => break,
121        }
122    }
123    last
124}
125
126/// srv's name for a pending shutdown's tool (its audit log keeps the endpoint
127/// names) as agents call it now.
128pub(crate) fn public_stop(via: &str) -> &str {
129    match via {
130        "QuitSelf" => "Stop self",
131        "ClosePane" => "Stop pane",
132        "FleetBulkStop" => "Stop agents",
133        other => other,
134    }
135}
136
137/// What srv said about the pane when it took the close of a tab (`pane_closes`): whether the pane goes with it.
138pub(crate) fn pane_goes_note(pane_closes: Option<bool>) -> &'static str {
139    match pane_closes {
140        Some(true) => " It was the pane's last tab, so the pane closes with it.",
141        Some(false) => " The pane stays, with its other tabs.",
142        None => "",
143    }
144}
145
146/// `close_pane_outcome` for an answer that did not carry `pane_closes`.
147pub(crate) fn close_pane_outcome(block: &str, now: &Value) -> anyhow::Result<String> {
148    close_pane_outcome_for(block, now, None)
149}
150
151/// What `ClosePane block_id=` and `Browser close` tell the agent once the tab's user has
152/// answered (§6.5): the tab is named, and so is whether its pane went with it.
153pub(crate) fn close_pane_outcome_for(block: &str, now: &Value, pane_closes: Option<bool>) -> anyhow::Result<String> {
154    // Joined a shutdown already under way that does less than close the pane. Browser close is a pane close too.
155    if let Some(via) = now["via"].as_str().filter(|v| !matches!(*v, "ClosePane" | "Browser close")).map(public_stop) {
156        let by = now["by"].as_str().unwrap_or("another agent");
157        return match now["status"].as_str().unwrap_or("") {
158            "kept_by_user" => Ok(format!("Not closed: the user chose to keep tab {block:?} running.")),
159            // Found gone (closed, or its agent already stopped): retrying
160            // would only find it gone again.
161            "superseded" => Ok(format!("Tab {block:?} was already closed, or its agent already stopped: nothing more to do.")),
162            "failed" => anyhow::bail!("close failed: {}", now["error"].as_str().unwrap_or("no detail")),
163            "" | "pending" => anyhow::bail!("close of {block:?}: no answer from the user's override window"),
164            state => Ok(format!(
165                "{by}'s {via} was already shutting pane {block:?}'s agent down ({state}); the pane itself may still be open — check Pane layout, and close an agent with Stop action \"agents\" or any other pane with action \"pane\"."
166            )),
167        };
168    }
169    match now["status"].as_str().unwrap_or("") {
170        "shut_down" => Ok(format!("Closed tab {block:?}. Its user was given a few seconds to keep it and did not.{}", pane_goes_note(pane_closes))),
171        "kept_by_user" => Ok(format!("Not closed: the user chose to keep tab {block:?} running.")),
172        "superseded" => Ok(format!("Tab {block:?} was already closed.")),
173        "proceeding" => Ok(format!("Tab {block:?} is closing. Its user was given a few seconds to keep it and did not.{}", pane_goes_note(pane_closes))),
174        "failed" => anyhow::bail!("close failed: {}", now["error"].as_str().unwrap_or("no detail")),
175        _ => anyhow::bail!("close of {block:?}: no answer from the user's override window"),
176    }
177}
178
179/// One target's own answer from a settled request over several agents: srv lists what became of each
180/// agent (`outcomes`), while the request's own `status` is for all of them. A request for one agent
181/// has no list, and its answer is the target's own.
182pub(crate) fn own_outcome(now: Value, block: &str) -> Value {
183    let Some(o) = now["outcomes"].as_array().and_then(|all| all.iter().find(|o| o["block_id"].as_str() == Some(block))) else {
184        return now;
185    };
186    let mut own = now.clone();
187    own["status"] = o["outcome"].clone();
188    own["error"] = o.get("error").cloned().unwrap_or(Value::Null);
189    own
190}
191
192/// What `Stop pane` and `Stop agents` say instead of waiting for the user's window: the call returns
193/// at once, srv runs the window, and the agent is told by one `[AgentMux]` note only if the user keeps
194/// what it asked to close or the close fails.
195pub(crate) fn pending_note(secs: u64) -> String {
196    format!("Not closed yet: the user has {secs} s to keep it running, and it closes after that unless they do. Don't wait or poll: you get one [AgentMux] note only if they keep it or the close fails.")
197}
198
199/// The windows a stop opened, one per request id (several targets can share one): their targets and
200/// when each closes unless the user keeps it. `pending` is srv's list of {block_id, request_id,
201/// deadline_ms?}; `fallback_deadline_ms` is the answer's own deadline, for an entry without one.
202pub(crate) fn pending_windows(pending: &[Value], fallback_deadline_ms: Option<i64>, now_ms: i64) -> Vec<Value> {
203    let mut windows: Vec<(String, Vec<String>, Option<i64>)> = Vec::new();
204    for p in pending {
205        let id = p["request_id"].as_str().unwrap_or_default().to_string();
206        let block = p["block_id"].as_str().unwrap_or_default().to_string();
207        let deadline = p["deadline_ms"].as_i64().or(fallback_deadline_ms);
208        match windows.iter_mut().find(|w| w.0 == id) {
209            Some(w) => w.1.push(block),
210            None => windows.push((id, vec![block], deadline)),
211        }
212    }
213    windows
214        .into_iter()
215        .map(|(id, targets, deadline)| {
216            let mut w = json!({ "id": id, "targets": targets });
217            if let Some(at) = deadline {
218                w["closes_at"] = json!(at);
219                w["closes_in_s"] = json!(((at - now_ms).max(0) + 999) / 1000);
220            }
221            w
222        })
223        .collect()
224}
225
226/// `Stop pane` on another pane: srv's 202 answer, as the agent sees it. A request that joined a
227/// shutdown already under way (`via` is not a pane close) says whose it is and that the pane may
228/// outlive it.
229pub(crate) fn close_pane_pending(block: &str, body: &Value, now_ms: i64) -> String {
230    let entry = json!({ "block_id": block, "request_id": body["request_id"], "deadline_ms": body["deadline_ms"] });
231    // A browser pane's window is shorter than the 30 s of the rest: say what srv set.
232    let secs = body["deadline_ms"].as_i64().map_or(30, |d| ((d - now_ms).max(0) as u64).div_ceil(1000));
233    let mut note = pending_note(secs);
234    note.push_str(pane_goes_note(body["pane_closes"].as_bool()));
235    if let Some(via) = body["via"].as_str().filter(|v| !matches!(*v, "ClosePane" | "Browser close")).map(public_stop) {
236        let by = body["by"].as_str().unwrap_or("another agent");
237        note.push_str(&format!(" It joined {by}'s {via}, already under way, which may leave the pane itself open: check Pane layout."));
238    }
239    let mut out = json!({ "status": "pending", "pending": pending_windows(&[entry], None, now_ms), "note": note });
240    // The tab closed, and whether its pane goes with it, named as srv answered.
241    if let Some(tab) = body["tab"].as_str() {
242        out["tab"] = json!(tab);
243    }
244    if let Some(closes) = body["pane_closes"].as_bool() {
245        out["pane_closes"] = json!(closes);
246    }
247    serde_json::to_string_pretty(&out).unwrap_or_else(|_| out.to_string())
248}
249
250/// The `note` of a `Stop agents` result: what srv said (a passed `signal` or
251/// `staged` no longer applies) and, for a target on an older AgentMux on this
252/// machine, which only stops (its answer names the `effect` `stop`), that its
253/// pane was left open.
254pub(crate) fn add_stop_notes(result: &mut Value, srv_note: Option<String>, pending: &[Value]) {
255    let older: Vec<&str> = pending
256        .iter()
257        .filter(|p| p["effect"].as_str() == Some("stop"))
258        .filter_map(|p| p["block_id"].as_str())
259        .collect();
260    let mut notes: Vec<String> = srv_note.into_iter().collect();
261    if !older.is_empty() {
262        notes.push(format!(
263            "{} run on an older AgentMux on this machine: stopped, but the pane was left open; the user has to close it",
264            older.join(", ")
265        ));
266    }
267    if !notes.is_empty() {
268        result["note"] = json!(notes.join("; "));
269    }
270}
271
272/// What `QuitSelf` tells the agent once the user's override window has
273/// settled (§6.5).
274pub(crate) fn quit_self_outcome(state: &str, body: &Value) -> anyhow::Result<String> {
275    match state {
276        "kept_by_user" => Ok("The user chose to keep you running. Do NOT quit and do not call Stop self again for this; carry on.".to_string()),
277        "proceeding" | "shut_down" => Ok("The user didn't stop it: you shut down when this turn ends. Give the user a one-line goodbye and start no new work.".to_string()),
278        "superseded" => Ok("The user closed you themselves meanwhile.".to_string()),
279        _ => anyhow::bail!(
280            "QuitSelf: the shutdown {state}: {}",
281            body.get("error").and_then(|v| v.as_str()).unwrap_or("no detail")
282        ),
283    }
284}
285
286/// `SendMessage`'s answer when srv accepted the message but queued it: the target's process is
287/// starting up, restarting or stopping (SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md §2.1), or it runs
288/// one turn at a time (a container agent, a Codex or Gemini agent) and is in one now, so the message
289/// waits for that turn to end. A persistent agent that is up gets it at once, mid-turn included, and
290/// is reported as delivered.
291pub(crate) fn deferred_delivery_text(to: &str) -> String {
292    format!(
293        "QUEUED for {to} — their agent cannot take it yet: it is starting up, restarting or \
294         stopping, or it handles one turn at a time and is in one now. It has not reached them. \
295         Their AgentMux delivers it as soon as their agent can. Don't resend it."
296    )
297}
298
299/// `held_reason` of a message kept for a session gone cold (srv's
300/// `cold_hold::REASON_IDLE`).
301pub(crate) const HELD_IDLE: &str = "idle";
302
303/// `held_reason` of a routine message kept back by quota mode (srv's `cold_hold::REASON_QUOTA`).
304pub(crate) const HELD_QUOTA: &str = "quota";
305
306/// Which of the two "kept until the agent is next active" holds srv's answer names, for a send to
307/// many: a held message is not a failed one.
308pub(crate) fn held_until_active(result: &Value) -> Option<&'static str> {
309    match result.get("held_reason").and_then(|v| v.as_str()) {
310        Some(HELD_IDLE) => Some(HELD_IDLE),
311        Some(HELD_QUOTA) => Some(HELD_QUOTA),
312        _ => None,
313    }
314}
315
316/// How long a send waits for srv's answer. srv's own tiers for an agent it does not run (a LAN peer, the cloud
317/// relay, then the hold) can add up to more than the client's default 10 s, and srv finishes the delivery anyway.
318pub(crate) const INJECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45);
319
320/// What a send tells the sender when srv's answer did not arrive, in place of the transport's own words
321/// ("error sending request for url ..."), which say nothing about whether the message was kept.
322pub(crate) fn inject_transport_error(e: &reqwest::Error) -> String {
323    if e.is_connect() {
324        format!("srv could not be reached, so nothing was sent ({e})")
325    } else if e.is_timeout() {
326        format!(
327            "srv gave no answer within {} s. It carries on with the message (delivers it or holds it for the agent), so look at Agents conversations before sending it again",
328            INJECT_TIMEOUT.as_secs()
329        )
330    } else {
331        format!("the answer from srv was lost ({e}). The message may have been delivered or held: look at Agents conversations before sending it again")
332    }
333}
334
335/// What `SendMessage` tells the sender, from srv's `/agentmux/reactive/inject`
336/// body. Each answer keeps its first word (`Delivered`, `QUEUED`, `HELD`) so
337/// existing prompts keep working, and adds the message id and the receiver's
338/// condition where srv's answer already implies it
339/// (SPEC_JEKT_DELIVERY_STATES_AND_MAILBOX_2026_10_01.md §5.2, Phase 0 item 3).
340pub(crate) fn send_message_outcome(to: &str, result: &Value) -> Result<String> {
341    // srv echoes the sender's own msgid, or the cloud relay's injection id on
342    // the relay branch; it is the id the receiver's `MSGID=` shows.
343    let id = match result.get("request_id").and_then(|v| v.as_str()) {
344        Some(id) if !id.is_empty() => format!(" id={id}"),
345        _ => String::new(),
346    };
347    // srv refused it before delivery (a reply that says nothing): nothing was sent, no turn started.
348    if result.get("refused").and_then(|v| v.as_bool()) == Some(true) {
349        let why = result.get("error").and_then(|v| v.as_str()).unwrap_or("Not sent.");
350        return Ok(format!("NOT SENT to {to} — {why}"));
351    }
352    if result.get("success").and_then(|v| v.as_bool()) == Some(true) {
353        return sent_text(to, result, &id);
354    }
355    if result.get("held").and_then(|v| v.as_bool()) == Some(true) {
356        return held_text(to, result, &id);
357    }
358    delivery_failure(to, result)
359}
360
361/// The reply to `success: true`, which is either a delivery or a message queued at the relay.
362fn sent_text(to: &str, result: &Value, id: &str) -> Result<String> {
363    // `success: true` spans two very different outcomes and the old
364    // message conflated them, which made agent-to-agent delivery
365    // unfalsifiable from the sender side: a name that exists on no
366    // machine anywhere reported exactly the same string as a message
367    // injected into a live conversation. Verified against a running
368    // srv — `SendMessage(to="definitely-not-a-real-agent-xyz123")`
369    // returned "Message sent to ...", and the server log showed "cloud
370    // relay: queued for WAN delivery" for it, identical to a real remote
371    // agent.
372    //
373    // The response already carries the distinction: the handler sets
374    // `block_id` to the receiving block on local/host delivery
375    // (backend/reactive/handler.rs), while the cloud-relay path leaves it
376    // `None` because no receiver has seen the message yet
377    // (server/reactive.rs, `try_cloud_relay` — "Queued is not delivered").
378    if result.get("block_id").and_then(|v| v.as_str()).is_some() {
379        // srv queues a message while the target's process is starting
380        // up, restarting or stopping (SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md
381        // §2.1) and says so with `deferred`; "injected" would be untrue.
382        if result.get("deferred").and_then(|v| v.as_bool()) == Some(true) {
383            return Ok(format!("{}{id}", deferred_delivery_text(to)));
384        }
385        return Ok(format!("Delivered to {to} — injected into their running conversation.{id}"));
386    }
387    // The relay accepts any name; it says when the target is not one of
388    // the sender's own account's agents. An agent
389    // counts once it has run while signed in, so one of the sender's own
390    // that hasn't yet still gets `false` and can still receive it (Codex
391    // P2 on #4249): a hint, never "only another account".
392    let not_yours = if result.get("target_in_account").and_then(|v| v.as_bool()) == Some(false) {
393        " No agent of that name has signed in from your account yet, so check the spelling. \
394         It is still delivered if one of your agents with that name signs in within 30 \
395         minutes, or if another account has an agent with that name."
396    } else {
397        ""
398    };
399    // What srv could see when it queued the message: the target runs on no LAN peer (or it would
400    // have been delivered there), so only an install of the sender's elsewhere can pick it up.
401    let nowhere_near = match result.get("lan_peers").and_then(|v| v.as_array()) {
402        Some(peers) => {
403            let seen: Vec<&str> = peers.iter().filter_map(|p| p.as_str()).collect();
404            let peers_said = if seen.is_empty() { "no LAN peers found".to_string() } else { format!("LAN peers: {}", seen.join("; ")) };
405            format!(
406                " {to} is not running on this machine or on any LAN peer ({peers_said}), so it \
407                 arrives only if an install of yours elsewhere runs {to} and is online."
408            )
409        }
410        None => String::new(),
411    };
412    // The ids srv found closest to a name that answers to no agent here: a typo, or the workspace folder's form.
413    let close: Vec<&str> = result.get("did_you_mean").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|i| i.as_str()).collect()).unwrap_or_default();
414    let meant = match close.as_slice() {
415        [] => String::new(),
416        [one] => format!(" Did you mean \"{one}\"? It is an agent on this machine."),
417        many => format!(" Did you mean one of: {}? They are agents on this machine.", many.iter().map(|i| format!("\"{i}\"")).collect::<Vec<_>>().join(", ")),
418    };
419    Ok(format!(
420        "QUEUED for {to} via the cloud relay (unconfirmed, expires in 30 min) — NOT yet \
421         delivered. The relay accepted it; their AgentMux picks it up when it next syncs, \
422         and the relay drops it after 30 minutes if nothing does (which is what happens if \
423         that instance stays offline). If {to} has not written to you by then, you get a note \
424         that it was never confirmed. You get this same result for an agent name that \
425         does not exist anywhere, so check the spelling against Agents list if you \
426         expected local delivery.{meant}{nowhere_near}{not_yours}{id}"
427    ))
428}
429
430/// The reply to `held: true`: srv kept the message and says why and until when.
431fn held_text(to: &str, result: &Value, id: &str) -> Result<String> {
432    // SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md: the target is a known
433    // agent that is not running anywhere srv can reach, so srv kept the
434    // message and delivers it when the agent starts. Since Phase 0 item 4
435    // it also holds for a receiver that is here but not signed in.
436    // SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §5: the agent is here but
437    // its account is out of quota.
438    if result.get("held_reason").and_then(|v| v.as_str()) == Some("usage_limit") {
439        let until = match result.get("held_until").and_then(|v| v.as_str()) {
440            Some(t) => format!(", until {t}"),
441            None => String::new(),
442        };
443        return Ok(format!(
444            "HELD for {to} (usage_limit{until}) — not delivered yet. {to}'s account is out of \
445             quota; this AgentMux instance (channel) keeps the message and delivers it when \
446             {to} can work again (an account move or the reset), for up to 24 hours. Do not \
447             resend it.{id}"
448        ));
449    }
450    if result.get("held_reason").and_then(|v| v.as_str()) == Some(HELD_IDLE) {
451        return Ok(format!(
452            "HELD for {to} (idle) — not delivered yet. {to}'s session has been idle for about an \
453             hour, so waking it costs a full restart of its context; this AgentMux instance \
454             (channel) keeps the message and delivers it when {to} is next active, for up to 24 \
455             hours. If it is work for {to} or cannot wait, pass urgent: true (send it again) \
456             to wake it now; the held copy is dropped. Otherwise do not resend it.{id}"
457        ));
458    }
459    if result.get("held_reason").and_then(|v| v.as_str()) == Some(HELD_QUOTA) {
460        return Ok(format!(
461            "HELD for {to} (quota) — not delivered yet. Quota mode is tight and {to} has no turn in \
462             flight, so this routine message would start one; this AgentMux instance (channel) keeps \
463             it and delivers it when {to} is next active or the mode is off, for up to 24 hours. If it \
464             is work for {to} or cannot wait, pass urgent: true (send it again) to deliver it now; the \
465             held copy is dropped. Otherwise do not resend it.{id}"
466        ));
467    }
468    if result.get("held_reason").and_then(|v| v.as_str()) == Some("needs_login") {
469        return Ok(format!(
470            "HELD for {to} (needs_login) — not delivered yet. {to}'s agent needs to sign in \
471             again; this AgentMux instance (channel) keeps the message \
472             and delivers it within about a minute of their signing in, for up to 24 hours. \
473             Do not resend it.{id}"
474        ));
475    }
476    if result.get("held_reason").and_then(|v| v.as_str()) == Some("peer_offline") {
477        let host = result.get("held_host").and_then(|v| v.as_str()).map_or_else(|| "its machine".to_string(), str::to_string);
478        return Ok(format!(
479            "HELD for {to} (peer_offline) — not delivered yet. {to} runs on {host}, which is not \
480             answering on the LAN; this AgentMux instance (channel) keeps the message and \
481             delivers it when {host} is seen again, for up to 24 hours (the cloud relay would drop \
482             it after 30 minutes). Do not resend it.{id}"
483        ));
484    }
485    if let Some(why) = result.get("start_blocked").and_then(|v| v.as_str()) {
486        return Ok(format!(
487            "HELD for {to} (not_running, capacity) — not delivered yet. {to} was stopped and AgentMux \
488             did not start it: {why}. It keeps the message for up to 24 hours and delivers it when {to} \
489             starts; the start is tried again when the next message for {to} arrives, or start it with \
490             Agents start once there is room. Do not resend it.{id}"
491        ));
492    }
493    if result.get("starting").and_then(|v| v.as_bool()) == Some(true) {
494        return Ok(format!(
495            "HELD for {to} (not_running, starting) — not delivered yet. {to} was stopped; \
496             AgentMux is starting it now and delivers this message as soon as it is up, \
497             normally within a few seconds (kept for up to 24 hours if the start fails). Do \
498             not resend it.{id}"
499        ));
500    }
501    Ok(format!(
502        "HELD for {to} (not_running) — not delivered yet. {to} is not running; this \
503         AgentMux instance (channel) keeps the message and delivers it when {to} starts \
504         here, for up to 24 hours. Do not resend it.{id}"
505    ))
506}
507
508/// The error for a message srv neither delivered nor held.
509fn delivery_failure(to: &str, result: &Value) -> Result<String> {
510    let err = result.get("error").and_then(|v| v.as_str()).unwrap_or("unknown error");
511    // Two failures the sender can act on differently. A spawn-gate refusal is
512    // recoverable (the receiver signs in). srv now holds it (`needs_login`
513    // above); this answer remains for an older srv, a cron sender or a
514    // non-host tier, which are not held.
515    if err.starts_with("identity spawn gate")
516        || (result.get("refused_reason").and_then(|v| v.as_str()) == Some("needs_login") && !err.starts_with("agent unavailable: "))
517    {
518        anyhow::bail!(
519            "Message delivery failed (needs_login): {to}'s agent cannot start because it is not \
520             signed in, and the message was NOT kept. Send it again after they sign in. ({err})"
521        )
522    }
523    if err.starts_with("agent not found") {
524        anyhow::bail!("Message delivery failed (not_found): {err}")
525    }
526    // An agent out of quota or signed out, where it can't be held (a LAN or
527    // cross-channel hop): srv's `UNAVAILABLE_PREFIX`.
528    if let Some(why) = err.strip_prefix("agent unavailable: ") {
529        // What ends the wait is data in the answer (`retry_when`); a srv from before it
530        // is read from the wording.
531        let signs_in = match result.get("retry_when").and_then(|v| v.as_str()) {
532            Some(when) => when == "sign_in",
533            None => why.ends_with(" needs to sign in again"),
534        };
535        let retry = if signs_in {
536            "after they sign in".to_string()
537        } else {
538            format!("when {to} can work (an account move or the reset)")
539        };
540        anyhow::bail!(
541            "Message delivery failed (unavailable): {why}, and the message was NOT kept. Send it \
542             again {retry}."
543        )
544    }
545    anyhow::bail!("Message delivery failed: {err}")
546}
547
548#[cfg(test)]
549mod close_answer_tests {
550    use super::*;
551    use serde_json::json;
552
553    /// The person is given a window to keep a pane the agent closes; a pane that closed says it closed, and why the person's
554    /// silence did not stop it, not a sentence that reads like an error.
555    #[test]
556    fn a_closed_pane_says_it_closed_and_that_its_user_did_not_keep_it() {
557        let closed = close_pane_outcome("b1", &json!({ "status": "shut_down" })).unwrap();
558        assert!(closed.starts_with("Closed tab \"b1\"."), "{closed}");
559        assert!(closed.contains("was given a few seconds to keep it and did not"), "{closed}");
560        assert!(!closed.contains("in time"), "{closed}");
561        let closing = close_pane_outcome("b1", &json!({ "status": "proceeding" })).unwrap();
562        assert!(closing.starts_with("Tab \"b1\" is closing."), "{closing}");
563    }
564
565    #[test]
566    fn a_pane_the_person_kept_still_says_so() {
567        let kept = close_pane_outcome("b1", &json!({ "status": "kept_by_user" })).unwrap();
568        assert!(kept.starts_with("Not closed: the user chose to keep tab"), "{kept}");
569    }
570}