1use 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
31pub(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) };
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
59pub(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
72pub(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
85pub(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
93pub(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 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
126pub(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
137pub(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
146pub(crate) fn close_pane_outcome(block: &str, now: &Value) -> anyhow::Result<String> {
148 close_pane_outcome_for(block, now, None)
149}
150
151pub(crate) fn close_pane_outcome_for(block: &str, now: &Value, pane_closes: Option<bool>) -> anyhow::Result<String> {
154 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 "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
179pub(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
192pub(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
199pub(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
226pub(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 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 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
250pub(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
272pub(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
286pub(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
299pub(crate) const HELD_IDLE: &str = "idle";
302
303pub(crate) const HELD_QUOTA: &str = "quota";
305
306pub(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
316pub(crate) const INJECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45);
319
320pub(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
335pub(crate) fn send_message_outcome(to: &str, result: &Value) -> Result<String> {
341 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 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
361fn sent_text(to: &str, result: &Value, id: &str) -> Result<String> {
363 if result.get("block_id").and_then(|v| v.as_str()).is_some() {
379 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 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 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 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
430fn held_text(to: &str, result: &Value, id: &str) -> Result<String> {
432 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
508fn 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 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 if let Some(why) = err.strip_prefix("agent unavailable: ") {
529 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 #[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}