1use super::*;
9
10fn urgent_priority(arguments: &Value) -> Option<String> {
14 arguments.get("urgent").and_then(|v| v.as_bool()).unwrap_or(false).then(|| "urgent".to_string())
15}
16
17fn reply_arg(arguments: &Value) -> Option<String> {
20 (arguments.get("reply").and_then(|v| v.as_str()) == Some("none")).then(|| "none".to_string())
21}
22
23fn in_reply_to_arg(arguments: &Value) -> Option<String> {
25 arguments
26 .get("in_reply_to")
27 .and_then(|v| v.as_str())
28 .map(str::trim)
29 .filter(|id| !id.is_empty() && id.len() <= 128)
30 .map(str::to_string)
31}
32
33pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
34 match name {
35 "SendMessage" => run_send_message(arguments, cx).await,
36 "DiscoverAgents" | "FleetList" => run_discover_agents(arguments, false, cx).await,
37 "FleetBroadcast" => run_fleet_broadcast(arguments, cx).await,
38 "FleetBulkStop" => run_fleet_bulk_stop(arguments, cx).await,
39 _ => Err(not_in_family()),
40 }
41}
42
43async fn run_send_message(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
44 let ToolCtx { local_url, auth_key, client, .. } = *cx;
45 let to = arguments
46 .get("to")
47 .and_then(|v| v.as_str())
48 .filter(|s| !s.is_empty())
49 .ok_or_else(|| anyhow::anyhow!("missing required parameter: to"))?;
50 let message = arguments
51 .get("message")
52 .and_then(|v| v.as_str())
53 .filter(|s| !s.is_empty())
54 .ok_or_else(|| anyhow::anyhow!("missing required parameter: message"))?;
55
56 if local_url.is_empty() || auth_key.is_empty() {
57 anyhow::bail!(
58 "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
59 Is this agent pane opened via AgentMux?"
60 );
61 }
62
63 let source_agent = std::env::var("AGENTMUX_AGENT_ID")
64 .ok()
65 .filter(|s| !s.is_empty());
66
67 let url = format!(
68 "{}/agentmux/reactive/inject",
69 local_url.trim_end_matches('/')
70 );
71 let files = match super::send_files::files_arg(arguments)? {
74 Some(paths) => {
75 let local = super::send_files::check(&paths)?;
76 Some(super::send_files::upload(local, cx).await?)
77 }
78 None => None,
79 };
80 let sent_names: Vec<String> = files.iter().flatten().map(|f| f.name.clone()).collect();
81 let mut req = signed_jekt_with_files(source_agent, to, message, files);
82 req.priority = urgent_priority(arguments);
83 req.reply = reply_arg(arguments);
84 req.in_reply_to = in_reply_to_arg(arguments);
85
86 let resp = client
87 .post(&url)
88 .header(AUTH_KEY_HEADER, auth_key)
89 .json(&req)
90 .timeout(crate::tool_helpers::INJECT_TIMEOUT)
91 .send()
92 .await
93 .map_err(|e| anyhow::anyhow!("{}", crate::tool_helpers::inject_transport_error(&e)))?;
94
95 if !resp.status().is_success() {
96 let status = resp.status();
97 let text = resp.text().await.unwrap_or_default();
98 anyhow::bail!("inject failed: HTTP {status} — {text}");
99 }
100
101 let result: Value = resp
102 .json()
103 .await
104 .map_err(|e| anyhow::anyhow!("response parse failed: {e}"))?;
105
106 let outcome = send_message_outcome(to, &result)?;
107 Ok(if sent_names.is_empty() {
108 outcome
109 } else {
110 let arrived = result.get("files_delivered").and_then(Value::as_u64);
113 match arrived.filter(|n| (*n as usize) < sent_names.len()) {
114 Some(n) => format!("{outcome}\nFiles: {} ({n} of {} arrived)", sent_names.join(", "), sent_names.len()),
115 None => format!("{outcome}\nFiles: {}", sent_names.join(", ")),
116 }
117 })
118}
119
120const DISCOVERY_PARAMS: &[&str] = &["fields", "detail", "state", "model", "provider", "runtime", "account", "seat", "limit", "offset", "group_by"];
122
123pub(super) fn discovery_query(arguments: &Value, status: bool) -> Vec<(&'static str, String)> {
125 let mut query: Vec<(&'static str, String)> = DISCOVERY_PARAMS
126 .iter()
127 .filter_map(|key| {
128 let text = match arguments.get(*key)? {
129 Value::String(s) => s.trim().to_string(),
130 Value::Number(n) => n.to_string(),
131 _ => return None,
132 };
133 (!text.is_empty()).then_some((*key, text))
134 })
135 .collect();
136 if status {
137 query.push(("view", "status".to_string()));
138 }
139 query
140}
141
142pub(super) async fn run_discover_agents(arguments: &Value, status: bool, cx: &ToolCtx<'_>) -> Result<String> {
144 let result = discover_value(arguments, status, false, cx).await?;
145 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
146}
147
148pub(super) async fn discover_value(arguments: &Value, status: bool, all_hosts: bool, cx: &ToolCtx<'_>) -> Result<Value> {
150 let ToolCtx { local_url, auth_key, .. } = *cx;
151 if local_url.is_empty() || auth_key.is_empty() {
152 anyhow::bail!(
153 "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
154 Is this agent pane opened via AgentMux?"
155 );
156 }
157
158 let mut query = discovery_query(arguments, status);
159 if all_hosts {
160 query.push(("host", "all".to_string()));
161 }
162 let query: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
163 cx.get_json("/agentmux/discovery", &query, "discovery").await
164}
165
166async fn run_fleet_broadcast(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
167 let ToolCtx { local_url, auth_key, client, .. } = *cx;
168 let (targets, message) = broadcast_args(arguments)?;
169
170 if local_url.is_empty() || auth_key.is_empty() {
171 anyhow::bail!(
172 "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
173 Is this agent pane opened via AgentMux?"
174 );
175 }
176 let source_agent = std::env::var("AGENTMUX_AGENT_ID")
177 .ok()
178 .filter(|s| !s.is_empty());
179
180 let files = match super::send_files::files_arg(arguments)? {
186 Some(paths) => {
187 let local = super::send_files::check(&paths)?;
188 Some(super::send_files::upload(local, cx).await?)
189 }
190 None => None,
191 };
192 let sent_names: Vec<String> = files.iter().flatten().map(|f| f.name.clone()).collect();
193
194 let block_to_agent = discovered_block_to_agent(cx).await?;
195
196 const BROADCAST_CHUNK_SIZE: usize = 10;
212 const BROADCAST_CHUNK_PAUSE: std::time::Duration = std::time::Duration::from_millis(1100);
213
214 let url = format!("{}/agentmux/reactive/inject", local_url.trim_end_matches('/'));
215 let priority = urgent_priority(arguments);
216 let mut succeeded: Vec<String> = Vec::new();
217 let mut held: Vec<serde_json::Value> = Vec::new();
218 let mut queued: Vec<serde_json::Value> = Vec::new();
219 let mut failed: Vec<serde_json::Value> = Vec::new();
220 let mut files_short: Vec<serde_json::Value> = Vec::new();
222 for (chunk_idx, chunk) in targets.chunks(BROADCAST_CHUNK_SIZE).enumerate() {
223 if chunk_idx > 0 {
224 tokio::time::sleep(BROADCAST_CHUNK_PAUSE).await;
225 }
226 for target in chunk {
227 let target = target.clone();
228 let target_agent = block_to_agent.get(&target).cloned().unwrap_or_else(|| target.clone());
237 let mut req = signed_jekt_with_files(source_agent.clone(), &target_agent, message, files.clone());
238 req.priority = priority.clone();
239 req.reply = reply_arg(arguments);
240 let outcome = post_jekt(client, &url, auth_key, &req).await;
241 match outcome {
242 Ok(Sent::Delivered(arrived)) => {
243 if let Some(n) = arrived.filter(|n| (*n as usize) < sent_names.len()) {
246 files_short.push(json!({ "id": target, "arrived": n }));
247 }
248 succeeded.push(target);
249 }
250 Ok(Sent::Held(reason)) => held.push(json!({ "id": target, "held": reason })),
251 Ok(Sent::Queued(request_id)) => queued.push(json!({ "id": target, "request_id": request_id })),
252 Err(error) => failed.push(json!({ "id": target, "error": error })),
253 }
254 }
255 }
256
257 Ok(broadcast_report(succeeded, failed, held, queued, &sent_names, files_short))
258}
259
260fn broadcast_args(arguments: &Value) -> Result<(Vec<String>, &str)> {
262 let targets = arguments
263 .get("targets")
264 .and_then(|v| v.as_array())
265 .ok_or_else(|| anyhow::anyhow!("missing required parameter: targets"))?
266 .iter()
267 .filter_map(|v| v.as_str().map(str::to_string))
268 .collect::<Vec<_>>();
269 if targets.is_empty() {
270 anyhow::bail!("targets must be a non-empty array of block_id (host/cross-channel) or agent name (LAN/WAN) strings");
271 }
272 let message = arguments
273 .get("message")
274 .and_then(|v| v.as_str())
275 .filter(|s| !s.is_empty())
276 .ok_or_else(|| anyhow::anyhow!("missing required parameter: message"))?;
277 Ok((targets, message))
278}
279
280async fn discovered_block_to_agent(cx: &ToolCtx<'_>) -> Result<std::collections::HashMap<String, String>> {
315 let ToolCtx { local_url, auth_key, client, .. } = *cx;
316 let discovery_url = format!("{}/agentmux/discovery", local_url.trim_end_matches('/'));
317 let discovery_resp = client
318 .get(&discovery_url)
319 .header(AUTH_KEY_HEADER, auth_key)
320 .send()
321 .await
322 .map_err(|e| anyhow::anyhow!("discovery request failed: {e}"))?;
323 if !discovery_resp.status().is_success() {
324 let status = discovery_resp.status();
325 let text = discovery_resp.text().await.unwrap_or_default();
326 anyhow::bail!("discovery failed: HTTP {status} — {text}");
327 }
328 let discovery: Value = discovery_resp
329 .json()
330 .await
331 .map_err(|e| anyhow::anyhow!("discovery response parse failed: {e}"))?;
332 Ok(build_block_to_agent_map(&discovery))
333}
334
335async fn post_jekt(client: &reqwest::Client, url: &str, auth_key: &str, req: &InjectRequest) -> std::result::Result<Sent, String> {
337 let resp = client
338 .post(url)
339 .header(AUTH_KEY_HEADER, auth_key)
340 .json(req)
341 .timeout(crate::tool_helpers::INJECT_TIMEOUT)
342 .send()
343 .await
344 .map_err(|e| crate::tool_helpers::inject_transport_error(&e))?;
345 if !resp.status().is_success() {
346 let status = resp.status();
347 let text = resp.text().await.unwrap_or_default();
348 return Err(format!("HTTP {status} — {text}"));
349 }
350 let result: Value = resp
351 .json()
352 .await
353 .map_err(|e| format!("response parse failed: {e}"))?;
354 if result.get("success").and_then(|v| v.as_bool()) == Some(true) {
355 if result.get("block_id").and_then(|v| v.as_str()).is_none() {
358 let id = result.get("request_id").and_then(|v| v.as_str()).unwrap_or_default();
359 return Ok(Sent::Queued(id.to_string()));
360 }
361 Ok(Sent::Delivered(result.get("files_delivered").and_then(Value::as_u64)))
362 } else if let Some(reason) = crate::tool_helpers::held_until_active(&result) {
363 Ok(Sent::Held(reason))
365 } else {
366 Err(result
367 .get("error")
368 .and_then(|v| v.as_str())
369 .unwrap_or("unknown error")
370 .to_string())
371 }
372}
373
374fn broadcast_report(succeeded: Vec<String>, failed: Vec<Value>, held: Vec<Value>, queued: Vec<Value>, sent_names: &[String], files_short: Vec<Value>) -> String {
376 let mut result = json!({ "succeeded": succeeded, "failed": failed });
377 if !queued.is_empty() {
378 result["queued_unconfirmed"] = json!(queued);
379 result["queued_unconfirmed_note"] = json!(
380 "queued_unconfirmed: only queued at the cloud relay, NOT delivered: no pane has received it, and the relay drops it after 30 minutes; check the target is running and addressable (Agents list), or send it again later"
381 );
382 }
383 if !held.is_empty() {
384 result["held"] = json!(held);
385 result["held_note"] = json!(
386 "held: the message waits until the agent is next active (\"idle\": its session has been idle; \"quota\": quota mode is tight and it has no turn in flight, and the mode ending releases it too); send it again with urgent: true to deliver it now"
387 );
388 }
389 if !sent_names.is_empty() {
390 result["files"] = json!(sent_names);
391 result["files_short"] = json!(files_short);
392 }
393 serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
394}
395
396async fn run_fleet_bulk_stop(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
397 let ToolCtx { local_url, auth_key, .. } = *cx;
398 let targets = arguments
399 .get("targets")
400 .and_then(|v| v.as_array())
401 .ok_or_else(|| anyhow::anyhow!("missing required parameter: targets"))?
402 .iter()
403 .filter_map(|v| v.as_str().map(str::to_string))
404 .collect::<Vec<_>>();
405 if targets.is_empty() {
406 anyhow::bail!("targets must be a non-empty array of block_id strings");
407 }
408 let signal = arguments.get("signal").and_then(|v| v.as_str()).map(str::to_string);
409 let staged = arguments.get("staged").cloned();
410
411 if local_url.is_empty() || auth_key.is_empty() {
412 anyhow::bail!(
413 "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
414 Is this agent pane opened via AgentMux?"
415 );
416 }
417
418 let mut body = json!({ "targets": targets, "signal": signal });
419 if let Some(staged) = staged {
420 body["staged"] = staged;
421 }
422 if let Ok(auth) = sign_ui_automation_auth() {
424 body["auth"] = serde_json::to_value(auth).unwrap_or(Value::Null);
425 }
426 let mut result = cx.post_json("/api/v1/fleet/bulk-stop", &body, "fleet bulk-stop").await?;
427 if result["status"] == "pending_user_override" {
428 let pending = result["pending"].as_array().cloned().unwrap_or_default();
431 let windows = pending_windows(&pending, result["deadline_ms"].as_i64(), agentmux_common::time::now_ms());
432 let note = result["note"].as_str().map(str::to_string);
433 result = json!({ "succeeded": result["succeeded"], "failed": result["failed"], "pending": windows });
434 add_stop_notes(&mut result, note, &pending);
435 let said = result["note"].as_str().map_or_else(|| pending_note(30), |n| format!("{n}; {}", pending_note(30)));
436 result["note"] = json!(said);
437 } else if result.get("kept_by_user").is_none() {
438 result["kept_by_user"] = json!([]);
440 }
441
442 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
443}
444
445enum Sent {
447 Delivered(Option<u64>),
449 Held(&'static str),
451 Queued(String),
453}
454
455#[cfg(test)]
456mod call_tests;
457
458#[cfg(test)]
459mod broadcast_files_tests {
460 use super::*;
461 use std::io::{Read, Write};
462 use std::sync::{Arc, Mutex};
463
464 struct StubSrv {
468 url: String,
469 injected: Arc<Mutex<Vec<Value>>>,
470 }
471
472 fn read_request(conn: &mut std::net::TcpStream) -> (String, Vec<u8>) {
473 let mut raw = Vec::new();
474 let mut buf = [0u8; 4096];
475 let head_end = loop {
476 if let Some(i) = raw.windows(4).position(|w| w == b"\r\n\r\n") {
477 break i + 4;
478 }
479 let n = conn.read(&mut buf).unwrap();
480 assert!(n > 0, "connection closed before the headers ended");
481 raw.extend_from_slice(&buf[..n]);
482 };
483 let head = String::from_utf8_lossy(&raw[..head_end]).to_ascii_lowercase();
484 let request_line = head.lines().next().unwrap_or_default().to_string();
485 let length = head
486 .lines()
487 .find_map(|l| l.strip_prefix("content-length:"))
488 .and_then(|v| v.trim().parse::<usize>().ok());
489 let chunked = head.contains("transfer-encoding: chunked");
490 while match length {
492 Some(n) => raw.len() < head_end + n,
493 None => chunked && !raw.ends_with(b"0\r\n\r\n"),
494 } {
495 let n = conn.read(&mut buf).unwrap();
496 assert!(n > 0, "connection closed before the body ended");
497 raw.extend_from_slice(&buf[..n]);
498 }
499 (request_line, raw[head_end..].to_vec())
500 }
501
502 fn stub_srv(delivered: u64) -> StubSrv {
503 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
504 let url = format!("http://{}", listener.local_addr().unwrap());
505 let injected = Arc::new(Mutex::new(Vec::new()));
506 let seen = injected.clone();
507 std::thread::spawn(move || {
508 for conn in listener.incoming() {
509 let mut conn = conn.unwrap();
510 let seen = seen.clone();
511 std::thread::spawn(move || {
512 let (line, body) = read_request(&mut conn);
513 let answer = if line.contains("/agentmux/discovery") {
514 json!({ "host": { "addressable": [] } })
515 } else if line.contains("/attachments/upload") {
516 json!({ "id": "ab".repeat(32), "bytes": 5 })
517 } else {
518 let req: Value = serde_json::from_slice(&body).unwrap();
519 let relay_only = req["target_agent"].as_str().is_some_and(|t| t.starts_with("relay-"));
520 seen.lock().unwrap().push(req);
521 if relay_only {
522 json!({ "success": true, "request_id": "inj-7" })
524 } else {
525 json!({ "success": true, "block_id": "b1", "files_delivered": delivered })
526 }
527 }
528 .to_string();
529 let _ = write!(
530 conn,
531 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{answer}",
532 answer.len()
533 );
534 });
535 }
536 });
537 StubSrv { url, injected }
538 }
539
540 async fn broadcast(srv: &StubSrv, args: Value) -> Result<Value> {
541 let client = reqwest::Client::new();
542 let loops = LoopRegistry::default();
543 let counter = std::sync::atomic::AtomicU64::new(0);
544 let cx = ToolCtx { local_url: &srv.url, auth_key: "key", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
545 let out = call("FleetBroadcast", &args, &cx).await?;
546 Ok(serde_json::from_str(&out)?)
547 }
548
549 fn file_in(dir: &tempfile::TempDir) -> String {
550 let path = dir.path().join("report.txt");
551 std::fs::write(&path, b"hello").unwrap();
552 path.to_string_lossy().into_owned()
553 }
554
555 #[tokio::test]
558 async fn each_target_gets_the_files_signed_into_its_jekt() {
559 use agentmux_common::jekt_files::{msgid_binds, JektFile};
560 let (srv, dir) = (stub_srv(1), tempfile::tempdir().unwrap());
561 let out = broadcast(&srv, json!({ "targets": ["lan-a", "lan-b"], "message": "look", "files": [file_in(&dir)] })).await.unwrap();
562
563 assert_eq!(out["succeeded"], json!(["lan-a", "lan-b"]));
564 assert_eq!(out["failed"], json!([]));
565 assert_eq!(out["files"], json!(["report.txt"]));
566 assert_eq!(out["files_short"], json!([]));
567 let sent = srv.injected.lock().unwrap();
568 assert_eq!(sent.len(), 2);
569 for (req, target) in sent.iter().zip(["lan-a", "lan-b"]) {
570 assert_eq!(req["target_agent"], target);
571 let files: Vec<JektFile> = serde_json::from_value(req["files"].clone()).expect("the jekt carries its files");
572 assert_eq!(files.len(), 1);
573 assert_eq!(files[0].name, "report.txt");
574 assert!(msgid_binds(req["request_id"].as_str().unwrap(), &files));
575 }
576 assert_ne!(sent[0]["request_id"], sent[1]["request_id"], "each target is signed on its own");
577 }
578
579 #[tokio::test]
582 async fn a_target_that_got_fewer_files_is_named() {
583 let (srv, dir) = (stub_srv(0), tempfile::tempdir().unwrap());
584 let out = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "look", "files": [file_in(&dir)] })).await.unwrap();
585 assert_eq!(out["succeeded"], json!(["lan-a"]));
586 assert_eq!(out["files_short"], json!([{ "id": "lan-a", "arrived": 0 }]));
587 }
588
589 #[tokio::test]
592 async fn a_missing_file_sends_nothing() {
593 let (srv, dir) = (stub_srv(1), tempfile::tempdir().unwrap());
594 let missing = dir.path().join("nope.txt").to_string_lossy().into_owned();
595 let err = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "look", "files": [missing] })).await.unwrap_err().to_string();
596 assert!(err.contains("nope.txt"), "{err}");
597 assert!(srv.injected.lock().unwrap().is_empty());
598 }
599
600 #[tokio::test]
602 async fn a_relay_only_copy_is_not_reported_as_delivered() {
603 let srv = stub_srv(0);
604 let out = broadcast(&srv, json!({ "targets": ["lan-a", "relay-masty"], "message": "hi" })).await.unwrap();
605 assert_eq!(out["succeeded"], json!(["lan-a"]));
606 assert_eq!(out["queued_unconfirmed"], json!([{ "id": "relay-masty", "request_id": "inj-7" }]));
607 assert!(out["queued_unconfirmed_note"].as_str().unwrap().contains("NOT delivered"));
608 assert_eq!(out["failed"], json!([]));
609 }
610
611 #[tokio::test]
613 async fn a_broadcast_without_files_carries_none() {
614 let srv = stub_srv(0);
615 let out = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "hi" })).await.unwrap();
616 assert_eq!(out, json!({ "succeeded": ["lan-a"], "failed": [] }));
617 let sent = srv.injected.lock().unwrap();
618 assert!(sent[0].get("files").is_none_or(Value::is_null));
619 }
620}
621
622#[cfg(test)]
623mod urgent_tests {
624 #[test]
625 fn reply_none_and_in_reply_to_are_read_from_the_arguments() {
626 use super::{in_reply_to_arg, reply_arg};
627 use serde_json::json;
628 assert_eq!(reply_arg(&json!({ "reply": "none" })), Some("none".to_string()));
629 assert_eq!(reply_arg(&json!({ "reply": "ok" })), None);
630 assert_eq!(reply_arg(&json!({})), None);
631 assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": " m-1 " })), Some("m-1".to_string()));
632 assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": "" })), None);
633 assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": "x".repeat(200) })), None);
634 }
635
636 use super::*;
637 use serde_json::json;
638
639 #[test]
640 fn urgent_true_is_the_only_thing_that_sets_a_priority() {
641 assert_eq!(urgent_priority(&json!({ "urgent": true })), Some("urgent".to_string()));
642 assert_eq!(urgent_priority(&json!({ "urgent": false })), None);
643 assert_eq!(urgent_priority(&json!({})), None);
644 assert_eq!(urgent_priority(&json!({ "urgent": "yes" })), None, "not a boolean");
645 }
646}