1use agentmux_common::api_types::{ContainerAsk, CreateAgentRequest, ImportAgentRequest, RouteAsk, SpawnAgentRequest, SpawnManyRequest, SpawnWorkerSpec};
16
17use super::family::{pick, public_params, relabeled, Act};
18use super::*;
19
20pub(super) const ACTS: &[Act] = &[
21 Act { action: "list", tool: "DiscoverAgents", rename: &[] },
22 Act { action: "status", tool: "AgentStatus", rename: &[] },
23 Act { action: "conversations", tool: "ListConversations", rename: &[] },
24 Act { action: "transcript", tool: "GetAgentTranscript", rename: &[] },
25 Act { action: "open", tool: "OpenAgent", rename: &[("agent", "agent_id")] },
26 Act { action: "spawn", tool: "SpawnAgent", rename: &[] },
27 Act { action: "create", tool: "AgentCreate", rename: &[] },
28 Act { action: "workers", tool: "AgentWorkers", rename: &[] },
29 Act { action: "routes", tool: "AgentRoutes", rename: &[] },
30 Act { action: "start", tool: "AgentStart", rename: &[] },
31 Act { action: "stop", tool: "AgentStop", rename: &[] },
32 Act { action: "detach", tool: "AgentDetach", rename: &[] },
33 Act { action: "delete", tool: "AgentDelete", rename: &[] },
34 Act { action: "watch", tool: "AgentWatch", rename: &[] },
35 Act { action: "search_history", tool: "SearchHistory", rename: &[] },
36 Act { action: "context", tool: "AgentContext", rename: &[] },
37 Act { action: "compact", tool: "AgentCompact", rename: &[] },
38 Act { action: "fresh", tool: "AgentFresh", rename: &[] },
39 Act { action: "ready", tool: "AgentReady", rename: &[] },
40 Act { action: "env_get", tool: "AgentEnvGet", rename: &[] },
41 Act { action: "env_set", tool: "AgentEnvSet", rename: &[] },
42 Act { action: "set_seat", tool: "AgentSetSeat", rename: &[] },
43 Act { action: "ask_go_ahead", tool: "AgentAskGoAhead", rename: &[] },
44 Act { action: "ask_pin_change", tool: "AgentAskPinChange", rename: &[] },
45 Act { action: "rename", tool: "AgentRename", rename: &[] },
46 Act { action: "update", tool: "AgentUpdate", rename: &[] },
47 Act { action: "bundles", tool: "AgentBundles", rename: &[] },
48 Act { action: "hide", tool: "AgentHide", rename: &[] },
49 Act { action: "unhide", tool: "AgentUnhide", rename: &[] },
50 Act { action: "update_container", tool: "AgentUpdateContainer", rename: &[] },
51 Act { action: "message_stats", tool: "AgentMessageStats", rename: &[] },
52 Act { action: "set_container_limits", tool: "AgentSetContainerLimits", rename: &[] },
53 Act { action: "container_caches", tool: "AgentContainerCaches", rename: &[] },
54 Act { action: "migrate_ids", tool: "AgentMigrateIds", rename: &[] },
55 Act { action: "rotate_token", tool: "AgentRotateToken", rename: &[] },
56 Act { action: "mute_quiet", tool: "AgentMuteQuiet", rename: &[] },
57 Act { action: "export", tool: "AgentExport", rename: &[] },
58 Act { action: "import", tool: "AgentImport", rename: &[] },
59 Act { action: "bring_back", tool: "AgentBringBack", rename: &[] },
60 Act { action: "move_status", tool: "AgentMoveStatus", rename: &[] },
61 Act { action: "move", tool: "AgentMove", rename: &[] },
62];
63
64pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
65 match name {
66 "Agents" => {
67 let (act, args) = pick("Agents", ACTS, arguments)?;
68 if act.action == "search_history" && args.get("agent").is_some() {
71 anyhow::bail!(
72 "Agents search_history searches only your own history and takes no agent; \
73 another agent's conversation is shared through its own visibility setting"
74 );
75 }
76 if act.action == "open" && wants_view(&args) && remote_op::host_arg(&args).is_none() {
78 anyhow::bail!("Agents open: view shows another computer's agent, so it needs host (the computer's name as Agents list shows it)");
79 }
80 if let Some(host) = remote_op::host_arg(&args).filter(|_| act.action != "move") {
81 let result = match act.action {
82 "list" | "status" => agents_hosts::across(cx, &args, act.action == "status", &host).await,
83 "open" if wants_view(&args) => open_view(cx, &args, &host).await,
84 _ => remote_agents(cx, act.action, &args, &host).await,
85 };
86 let result = result.map_err(|e| anyhow::anyhow!(public_params(&format!("{e:#}"), act.rename)));
87 return relabeled("Agents", ACTS, result);
88 }
89 let result = match act.tool {
90 "DiscoverAgents" => fleet::call(act.tool, &args, cx).await,
91 "AgentStatus" => fleet::run_discover_agents(&args, true, cx).await,
92 "OpenAgent" if args.get("agents").is_some_and(|a| !a.is_null()) => open_many(&args, cx).await,
93 "OpenAgent" => panes::call(act.tool, &args, cx).await,
94 "SpawnAgent" if args.get("workers").is_some_and(|w| !w.is_null()) => spawn_many(&args, cx).await,
95 "SpawnAgent" => spawn(&args, cx).await,
96 "AgentCreate" => create_agent(&args, cx).await,
97 "AgentWorkers" => workers(cx).await,
98 "AgentRoutes" => routes(cx, &args).await,
99 "AgentStart" => lifecycle(cx, "start", &args).await,
100 "AgentStop" => lifecycle(cx, "stop", &args).await,
101 "AgentDetach" => lifecycle(cx, "detach", &args).await,
102 "AgentDelete" => lifecycle(cx, "delete", &args).await,
103 "AgentRotateToken" => lifecycle(cx, "rotate-token", &args).await,
104 "AgentWatch" => watch(cx, &args).await,
105 "AgentContext" => own_context(cx, "context", None).await,
106 "AgentCompact" => own_context(cx, "compact", str_arg(&args, "keep")).await,
107 "AgentFresh" => match str_arg(&args, "handoff") {
108 Some(handoff) => own_context(cx, "fresh", Some(handoff)).await,
109 None => Err(anyhow::anyhow!("Agents fresh needs a handoff: what your next session must know")),
110 },
111 "AgentReady" => ready(cx, &args).await,
112 "AgentEnvGet" => env(cx, "get", &args).await,
113 "AgentEnvSet" => env(cx, "set", &args).await,
114 "AgentSetSeat" => set_seats(cx, &args).await,
115 "AgentAskGoAhead" => ask_go_ahead(cx, &args).await,
116 "AgentAskPinChange" => ask_pin_change(cx, &args).await,
117 "AgentRename" => rename_agent(cx, &args).await,
118 "AgentUpdate" => definition_action(cx, "update", &args).await,
119 "AgentBundles" => definition_action(cx, "bundles", &args).await,
120 "AgentHide" => definition_action(cx, "hide", &args).await,
121 "AgentUnhide" => definition_action(cx, "unhide", &args).await,
122 "AgentUpdateContainer" => update_container(cx, &args).await,
123 "AgentMessageStats" => message_stats(cx, &args).await,
124 "AgentSetContainerLimits" => set_container_limits(cx, &args).await,
125 "AgentContainerCaches" => container_caches(cx, &args).await,
126 "AgentMigrateIds" => migrate_ids(cx, &args).await,
127 "AgentMuteQuiet" => mute_quiet(cx, &args).await,
128 "AgentExport" => export_agent(cx, &args).await,
129 "AgentImport" => import_agent(&args, cx).await,
130 "AgentBringBack" => handover_action(cx, "bring_back", &args).await,
131 "AgentMoveStatus" => handover_action(cx, "move_status", &args).await,
132 "AgentMove" => move_action(cx, &args).await,
133 _ => history::call(act.tool, &args, cx).await,
134 };
135 let result = result.map_err(|e| anyhow::anyhow!(public_params(&format!("{e:#}"), act.rename)));
136 relabeled("Agents", ACTS, result)
137 }
138 _ => Err(not_in_family()),
139 }
140}
141
142fn wants_view(args: &Value) -> bool {
144 args.get("view").and_then(Value::as_bool) == Some(true)
145}
146
147async fn open_view(cx: &ToolCtx<'_>, args: &Value, host: &str) -> Result<String> {
151 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
152 let agent = str_arg(args, "agent_id").ok_or_else(|| anyhow::anyhow!("missing required parameter: agent"))?;
154 let mut result = cx.post_json("/api/v1/agent/open_view", &json!({ "host": host, "agent": agent, "block_id": cx.block_id }), "agent open view").await?;
155 if let Some(body) = result.as_object_mut() {
156 body.insert("note".into(), json!("a watching view of the other computer's agent; only its person can turn on driving"));
157 }
158 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
159}
160
161async fn remote_agents(cx: &ToolCtx<'_>, action: &str, args: &Value, host: &str) -> Result<String> {
165 if action == "update" {
167 refuse_operator_fields(args)?;
168 }
169 let params = if action == "update" { definition_params(args) } else { match action {
170 "start" | "stop" | "env_get" => json!({ "agent": str_arg(args, "agent") }),
171 "open" => json!({ "agent": str_arg(args, "agent_id") }),
173 "env_set" => json!({
174 "agent": str_arg(args, "agent"),
175 "lines": args.get("lines"),
176 "set": args.get("set"),
177 "unset": args.get("unset"),
178 }),
179 "set_seat" => json!({ "seats": args.get("seats") }),
180 "rename" => json!({ "agent": str_arg(args, "agent"), "name": str_arg(args, "name") }),
181 other => anyhow::bail!("Agents {other}: host applies to start, open, stop, set_seat, rename, update (model and effort), env_get and env_set; the other actions run on this machine"),
182 } };
183 let op = format!("agents.{action}");
184 let reason = str_arg(args, "reason").unwrap_or_else(|| format!("Agents {action}"));
185 let answer = remote_op::remote_op_call(cx, host, &op, params, &reason).await?;
186 match remote_op::explain_not_done(host, &op, &answer) {
187 Some(problem) => anyhow::bail!("{problem}"),
188 None => Ok(remote_op::pretty(host, &answer)),
189 }
190}
191
192const SPAWN_WAIT: std::time::Duration = std::time::Duration::from_secs(360);
197
198async fn spawn(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
203 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
204 let brief = str_arg(arguments, "brief").ok_or_else(|| anyhow::anyhow!("missing required parameter: brief"))?;
205 let request = SpawnAgentRequest {
206 auth: sign_ui_automation_auth()?,
207 name: str_arg(arguments, "name"),
208 model: str_arg(arguments, "model"),
209 effort: str_arg(arguments, "effort"),
210 brief: brief.clone(),
211 account: str_arg(arguments, "account"),
212 container: container_ask(arguments),
213 route: route_ask(arguments),
214 user_instruction: str_arg(arguments, "user_instruction").unwrap_or_default(),
215 };
216 let url = format!("{}/api/v1/agent/spawn", cx.local_url.trim_end_matches('/'));
217 let resp = cx
220 .client
221 .post(&url)
222 .timeout(SPAWN_WAIT)
223 .header(AUTH_KEY_HEADER, cx.auth_key)
224 .json(&request)
225 .send()
226 .await
227 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
228 let status = resp.status();
229 let mut body: Value = resp.json().await.unwrap_or(Value::Null);
230 if !status.is_success() {
231 anyhow::bail!("SpawnAgent: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
232 }
233 let to = body["message_to"].as_str().unwrap_or_default().to_string();
234 let leader = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
235 let worker = body["name"].as_str().unwrap_or_default();
236 let sent = super::fleet::call("SendMessage", &json!({ "to": to, "message": brief_message(&leader, worker, &to, &brief) }), cx).await;
237 body["brief"] = json!(match sent {
238 Ok(outcome) => outcome,
239 Err(e) => format!("NOT SENT: {e:#}. The worker is open but has no task: send it the brief with Message send"),
240 });
241 Ok(serde_json::to_string_pretty(&body)?)
242}
243
244fn route_ask(args: &Value) -> RouteAsk {
246 RouteAsk { harness: str_arg(args, "harness"), route: str_arg(args, "route") }
247}
248
249fn container_ask(args: &Value) -> ContainerAsk {
251 ContainerAsk {
252 runtime: str_arg(args, "runtime"),
253 container_image: str_arg(args, "container_image"),
254 memory_mb: args.get("memory_mb").filter(|v| !v.is_null()).cloned(),
255 cpus: args.get("cpus").filter(|v| !v.is_null()).cloned(),
256 }
257}
258
259async fn create_agent(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
262 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
263 let name = str_arg(arguments, "name").ok_or_else(|| anyhow::anyhow!("Agents create needs name: the new agent's name"))?;
264 let template = str_arg(arguments, "template").ok_or_else(|| anyhow::anyhow!("Agents create needs template: a template's id, slug or name"))?;
265 let request = CreateAgentRequest {
266 auth: sign_ui_automation_auth()?,
267 name,
268 template,
269 account: str_arg(arguments, "account"),
270 container: container_ask(arguments),
271 model: str_arg(arguments, "model"),
272 route: route_ask(arguments),
273 user_instruction: str_arg(arguments, "user_instruction").unwrap_or_default(),
274 };
275 let url = format!("{}/api/v1/agent/create", cx.local_url.trim_end_matches('/'));
276 let resp = cx
277 .client
278 .post(&url)
279 .timeout(SPAWN_WAIT)
280 .header(AUTH_KEY_HEADER, cx.auth_key)
281 .json(&request)
282 .send()
283 .await
284 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
285 let status = resp.status();
286 let body: Value = resp.json().await.unwrap_or(Value::Null);
287 if !status.is_success() {
288 anyhow::bail!("Agents create: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
289 }
290 Ok(serde_json::to_string_pretty(&body)?)
291}
292
293async fn spawn_many(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
297 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
298 let Some(asked) = arguments.get("workers").and_then(Value::as_array) else {
299 anyhow::bail!("Agents spawn: workers must be a list of {{brief, name?, model?, effort?, account?}}");
300 };
301 if ["brief", "name", "model", "effort", "account", "runtime", "container_image", "harness", "route"].iter().any(|k| str_arg(arguments, k).is_some())
302 || ["memory_mb", "cpus"].iter().any(|k| arguments.get(k).is_some_and(|v| !v.is_null()))
303 {
304 anyhow::bail!("Agents spawn: give either workers or brief (with name, model, effort, account, runtime, container_image, harness, route, memory_mb, cpus), not both");
305 }
306 let mut specs = Vec::with_capacity(asked.len());
307 for (i, w) in asked.iter().enumerate() {
308 let brief = str_arg(w, "brief").ok_or_else(|| anyhow::anyhow!("Agents spawn: workers[{i}] needs a brief"))?;
309 specs.push(SpawnWorkerSpec { name: str_arg(w, "name"), model: str_arg(w, "model"), effort: str_arg(w, "effort"), account: str_arg(w, "account"), brief, container: container_ask(w), route: route_ask(w) });
310 }
311 let briefs: Vec<String> = specs.iter().map(|s| s.brief.clone()).collect();
312 let request = SpawnManyRequest { auth: sign_ui_automation_auth()?, workers: specs, user_instruction: str_arg(arguments, "user_instruction").unwrap_or_default() };
313 let url = format!("{}/api/v1/agent/spawn_many", cx.local_url.trim_end_matches('/'));
314 let resp = cx
315 .client
316 .post(&url)
317 .timeout(SPAWN_WAIT * 2)
318 .header(AUTH_KEY_HEADER, cx.auth_key)
319 .json(&request)
320 .send()
321 .await
322 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
323 let status = resp.status();
324 let mut body: Value = resp.json().await.unwrap_or(Value::Null);
325 if !status.is_success() {
326 anyhow::bail!("SpawnAgent: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
327 }
328 let leader = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
329 let mut workers = body["workers"].as_array().cloned().unwrap_or_default();
330 for (worker, brief) in workers.iter_mut().zip(&briefs) {
331 let to = worker["message_to"].as_str().unwrap_or_default().to_string();
332 let name = worker["name"].as_str().unwrap_or_default().to_string();
333 let sent = super::fleet::call("SendMessage", &json!({ "to": to, "message": brief_message(&leader, &name, &to, brief) }), cx).await;
334 worker["brief"] = json!(match sent {
335 Ok(outcome) => outcome,
336 Err(e) => format!("NOT SENT: {e:#}. The worker is open but has no task: send it the brief with Message send"),
337 });
338 }
339 body["workers"] = json!(workers);
340 Ok(serde_json::to_string_pretty(&body)?)
341}
342
343async fn open_many(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
345 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
346 let Some(asked) = arguments.get("agents").and_then(Value::as_array) else {
347 anyhow::bail!("Agents open: agents must be a list of {{agent, tab_id?, focus?}}");
348 };
349 if str_arg(arguments, "agent_id").is_some() {
350 anyhow::bail!("Agents open: give either agents or agent, not both");
351 }
352 let (tab_id, focus) = (str_arg(arguments, "tab_id"), arguments.get("focus").and_then(Value::as_bool));
353 let mut items = Vec::with_capacity(asked.len());
354 for (i, a) in asked.iter().enumerate() {
355 let agent = str_arg(a, "agent").or_else(|| str_arg(a, "agent_id")).ok_or_else(|| anyhow::anyhow!("Agents open: agents[{i}] needs an agent"))?;
356 items.push(json!({ "agent_id": agent, "tab_id": str_arg(a, "tab_id").or_else(|| tab_id.clone()), "focus": a.get("focus").and_then(Value::as_bool).or(focus) }));
357 }
358 let url = format!("{}/api/v1/agent/open_many", cx.local_url.trim_end_matches('/'));
359 let resp = cx
360 .client
361 .post(&url)
362 .timeout(SPAWN_WAIT)
363 .header(AUTH_KEY_HEADER, cx.auth_key)
364 .json(&json!({ "agents": items }))
365 .send()
366 .await
367 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
368 let status = resp.status();
369 let body: Value = resp.json().await.unwrap_or(Value::Null);
370 if !status.is_success() {
371 anyhow::bail!("Agents open: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
372 }
373 Ok(serde_json::to_string_pretty(&body)?)
374}
375
376fn brief_message(leader: &str, worker: &str, slug: &str, brief: &str) -> String {
390 let me = agentmux_common::slug::agent_route_name(worker);
391 format!(
392 "You are {worker} (AGENTMUX_AGENT_ID {slug}), a worker of {leader}, started to do the task below. Report to \
393 {leader} with the agentmux MCP server's Message tool (mcp__agentmux__Message in Claude Code; action \
394 \"send\", to \"{leader}\"), never a built-in SendMessage, when you finish, get stuck, or need a decision.\n\n\
395 Sign what you publish as yourself, {me}, never as {leader}: a PR title starts \"{me}@<host>: \", its \
396 \"Agent:\" line reads \"Agent: {me}@<host>\", and the agent_id tag in its body is {slug}. Where a file you \
397 read shows another agent's name as an example, use yours.\n\n{brief}"
398 )
399}
400
401async fn workers(cx: &ToolCtx<'_>) -> Result<String> {
403 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
404 let request = agentmux_common::api_types::AgentWorkersRequest { auth: sign_ui_automation_auth()? };
405 let url = format!("{}/api/v1/agent/workers", cx.local_url.trim_end_matches('/'));
406 let resp = cx
407 .client
408 .post(&url)
409 .header(AUTH_KEY_HEADER, cx.auth_key)
410 .json(&request)
411 .send()
412 .await
413 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
414 let status = resp.status();
415 let body: Value = resp.json().await.unwrap_or(Value::Null);
416 if !status.is_success() {
417 anyhow::bail!("AgentWorkers: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
418 }
419 Ok(serde_json::to_string_pretty(&body)?)
420}
421
422async fn routes(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
424 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
425 let url = format!("{}/api/v1/agent/routes", cx.local_url.trim_end_matches('/'));
426 let resp = cx
427 .client
428 .post(&url)
429 .header(AUTH_KEY_HEADER, cx.auth_key)
430 .json(&json!({ "harness": str_arg(args, "harness") }))
431 .send()
432 .await
433 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
434 let status = resp.status();
435 let body: Value = resp.json().await.unwrap_or(Value::Null);
436 if !status.is_success() {
437 anyhow::bail!("Agents routes: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
438 }
439 Ok(serde_json::to_string_pretty(&body)?)
440}
441
442async fn own_context(cx: &ToolCtx<'_>, route: &str, focus: Option<String>) -> Result<String> {
446 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
447 let url = format!("{}/api/v1/agent/self/{route}", cx.local_url.trim_end_matches('/'));
448 let resp = cx
449 .client
450 .post(&url)
451 .header(AUTH_KEY_HEADER, cx.auth_key)
452 .json(&json!({ "agent": crate::identity::agent_slug()?, "focus": focus }))
453 .send()
454 .await
455 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
456 let status = resp.status();
457 let body: Value = resp.json().await.unwrap_or(Value::Null);
458 if !status.is_success() {
459 anyhow::bail!("Agents {route}: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
460 }
461 Ok(serde_json::to_string_pretty(&body)?)
462}
463
464async fn ready(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
467 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
468 let (handoff, more_time) = (str_arg(args, "handoff"), args.get("more_time").and_then(Value::as_bool).unwrap_or(false));
469 if handoff.is_none() && !more_time {
470 anyhow::bail!("Agents ready needs handoff (what is in flight, what you wait on, the next step), or more_time true with why");
471 }
472 let url = format!("{}/api/v1/agent/self/ready", cx.local_url.trim_end_matches('/'));
473 let resp = cx
474 .client
475 .post(&url)
476 .header(AUTH_KEY_HEADER, cx.auth_key)
477 .json(&json!({ "agent": crate::identity::agent_slug()?, "handoff": handoff, "more_time": more_time, "why": str_arg(args, "why") }))
478 .send()
479 .await
480 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
481 let status = resp.status();
482 let body: Value = resp.json().await.unwrap_or(Value::Null);
483 if !status.is_success() {
484 anyhow::bail!("Agents ready: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
485 }
486 Ok(serde_json::to_string_pretty(&body)?)
487}
488
489fn env_request(action: &str, args: &Value) -> Result<Value> {
494 let mut set = None;
495 if let Some(given) = args.get("set").filter(|v| !v.is_null()) {
496 let Some(object) = given.as_object() else {
497 anyhow::bail!("Agents env_set: set is an object of NAME: value");
498 };
499 let mut texts = serde_json::Map::new();
500 for (name, value) in object {
501 let text = match value {
502 Value::String(t) => t.clone(),
503 Value::Number(n) => n.to_string(),
504 Value::Bool(b) => b.to_string(),
505 _ => anyhow::bail!("Agents env_set: the value of {name} must be text"),
506 };
507 texts.insert(name.clone(), Value::String(text));
508 }
509 set = Some(Value::Object(texts));
510 }
511 Ok(json!({
512 "action": action,
513 "agent": str_arg(args, "agent"),
514 "lines": args.get("lines").and_then(Value::as_str),
515 "set": set,
516 "unset": args.get("unset").filter(|v| !v.is_null()),
517 }))
518}
519
520async fn update_container(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
524 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
525 let Some(agent) = str_arg(args, "agent") else {
526 anyhow::bail!("Agents update_container needs agent: the container agent's id or slug");
527 };
528 let url = format!("{}/api/v1/agent/container/update", cx.local_url.trim_end_matches('/'));
529 let resp = cx
530 .client
531 .post(&url)
532 .header(AUTH_KEY_HEADER, cx.auth_key)
533 .json(&match str_arg(args, "container_image") {
534 Some(image) => json!({ "agent": agent, "container_image": image }),
535 None => json!({ "agent": agent }),
536 })
537 .send()
538 .await
539 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
540 let status = resp.status();
541 let body: Value = resp.json().await.unwrap_or(Value::Null);
542 if !status.is_success() {
543 anyhow::bail!("Agents update_container: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
544 }
545 Ok(serde_json::to_string_pretty(&body)?)
546}
547
548async fn set_container_limits(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
551 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
552 let Some(agent) = str_arg(args, "agent") else {
553 anyhow::bail!("Agents set_container_limits needs agent: the container agent's id or slug");
554 };
555 let url = format!("{}/api/v1/agent/container/limits", cx.local_url.trim_end_matches('/'));
556 let resp = cx
557 .client
558 .post(&url)
559 .header(AUTH_KEY_HEADER, cx.auth_key)
560 .json(&json!({
561 "agent": agent,
562 "memory_mb": args.get("memory_mb").filter(|v| !v.is_null()),
563 "cpus": args.get("cpus").filter(|v| !v.is_null()),
564 }))
565 .send()
566 .await
567 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
568 let status = resp.status();
569 let body: Value = resp.json().await.unwrap_or(Value::Null);
570 if !status.is_success() {
571 anyhow::bail!("Agents set_container_limits: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
572 }
573 Ok(serde_json::to_string_pretty(&body)?)
574}
575
576async fn container_caches(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
579 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
580 let Some(agent) = str_arg(args, "agent") else {
581 anyhow::bail!("Agents container_caches needs agent: the container agent's id or slug");
582 };
583 let url = format!("{}/api/v1/agent/container/caches", cx.local_url.trim_end_matches('/'));
584 let resp = cx
585 .client
586 .post(&url)
587 .header(AUTH_KEY_HEADER, cx.auth_key)
588 .json(&json!({ "agent": agent, "clear": args.get("clear").and_then(Value::as_bool).unwrap_or(false) }))
589 .send()
590 .await
591 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
592 let status = resp.status();
593 let body: Value = resp.json().await.unwrap_or(Value::Null);
594 if !status.is_success() {
595 anyhow::bail!("Agents container_caches: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
596 }
597 Ok(serde_json::to_string_pretty(&body)?)
598}
599
600async fn set_seats(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
604 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
605 let seats = args.get("seats").filter(|v| v.is_array()).ok_or_else(|| {
606 anyhow::anyhow!("Agents set_seat needs seats: [{{agent, seat}}], seat null to clear an agent's seat")
607 })?;
608 let url = format!("{}/api/v1/agent/seats", cx.local_url.trim_end_matches('/'));
609 let resp = cx
610 .client
611 .post(&url)
612 .header(AUTH_KEY_HEADER, cx.auth_key)
613 .json(&json!({ "seats": seats }))
614 .send()
615 .await
616 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
617 let status = resp.status();
618 let body: Value = resp.json().await.unwrap_or(Value::Null);
619 if !status.is_success() {
620 anyhow::bail!("Agents set_seat: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
621 }
622 Ok(serde_json::to_string_pretty(&body)?)
623}
624
625async fn ask_go_ahead(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
628 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
629 let (Some(host), Some(container)) = (str_arg(args, "host_agent"), str_arg(args, "container_agent")) else {
630 anyhow::bail!("Agents ask_go_ahead needs host_agent (the host agent) and container_agent (the container agent), each an id or slug");
631 };
632 let url = format!("{}/api/v1/agent/folder-overlap-ask", cx.local_url.trim_end_matches('/'));
633 let resp = cx
634 .client
635 .post(&url)
636 .header(AUTH_KEY_HEADER, cx.auth_key)
637 .json(&json!({ "host": host, "container": container }))
638 .send()
639 .await
640 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
641 let status = resp.status();
642 let body: Value = resp.json().await.unwrap_or(Value::Null);
643 if !status.is_success() {
644 anyhow::bail!("Agents ask_go_ahead: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
645 }
646 Ok(serde_json::to_string_pretty(&body)?)
647}
648
649async fn ask_pin_change(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
652 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
653 let (Some(change), Some(kind), Some(agent_id)) = (str_arg(args, "pin_change"), str_arg(args, "pin_kind"), str_arg(args, "pin_agent")) else {
654 anyhow::bail!("Agents ask_pin_change needs pin_change (move or forget), pin_kind (lan or wan) and pin_agent (the name the pin is for), and a reason");
655 };
656 let url = format!("{}/api/v1/agent/pin-ask", cx.local_url.trim_end_matches('/'));
657 let body = json!({
658 "change": change,
659 "kind": kind,
660 "agent_id": agent_id,
661 "channel": str_arg(args, "pin_channel"),
662 "expect": str_arg(args, "pin_expect"),
663 "reason": str_arg(args, "reason").unwrap_or_default(),
664 });
665 let resp = cx.client.post(&url).header(AUTH_KEY_HEADER, cx.auth_key).json(&body).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
666 let status = resp.status();
667 let body: Value = resp.json().await.unwrap_or(Value::Null);
668 if !status.is_success() {
669 anyhow::bail!("Agents ask_pin_change: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
670 }
671 Ok(serde_json::to_string_pretty(&body)?)
672}
673
674async fn migrate_ids(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
678 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
679 let step = str_arg(args, "step").unwrap_or_else(|| "plan".to_string());
680 let mut body = json!({ "step": step });
681 if let Some(choices) = args.get("choices").filter(|v| v.is_array()) {
682 body["choices"] = choices.clone();
683 }
684 let url = format!("{}/api/v1/agent/migrate-ids", cx.local_url.trim_end_matches('/'));
685 let resp = cx
686 .client
687 .post(&url)
688 .header(AUTH_KEY_HEADER, cx.auth_key)
689 .json(&body)
690 .send()
691 .await
692 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
693 let status = resp.status();
694 let answer: Value = resp.json().await.unwrap_or(Value::Null);
695 if !status.is_success() {
696 anyhow::bail!("Agents migrate_ids: {}", answer["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {answer}")));
697 }
698 Ok(serde_json::to_string_pretty(&answer)?)
699}
700
701async fn rename_agent(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
704 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
705 let agent = str_arg(args, "agent").ok_or_else(|| anyhow::anyhow!("missing required parameter: agent"))?;
706 let name = str_arg(args, "name").ok_or_else(|| anyhow::anyhow!("missing required parameter: name (the agent's new name)"))?;
707 let url = format!("{}/api/v1/agent/rename", cx.local_url.trim_end_matches('/'));
708 let resp = cx
709 .client
710 .post(&url)
711 .header(AUTH_KEY_HEADER, cx.auth_key)
712 .json(&json!({ "agent": agent, "name": name }))
713 .send()
714 .await
715 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
716 let status = resp.status();
717 let body: Value = resp.json().await.unwrap_or(Value::Null);
718 if !status.is_success() {
719 anyhow::bail!("{}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Agents rename: srv answered {status}: {body}")));
720 }
721 Ok(serde_json::to_string_pretty(&body)?)
722}
723
724async fn export_agent(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
727 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
728 let mut body = serde_json::Map::new();
729 for key in ["agent", "include", "scrub", "to", "hand_over"] {
730 if let Some(v) = args.get(key).filter(|v| !v.is_null()) {
731 body.insert(key.to_string(), v.clone());
732 }
733 }
734 let url = format!("{}/api/v1/agent/export", cx.local_url.trim_end_matches('/'));
735 let resp = cx
736 .client
737 .post(&url)
738 .timeout(SPAWN_WAIT)
739 .header(AUTH_KEY_HEADER, cx.auth_key)
740 .json(&Value::Object(body))
741 .send()
742 .await
743 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
744 let status = resp.status();
745 let body: Value = resp.json().await.unwrap_or(Value::Null);
746 if !status.is_success() {
747 anyhow::bail!("{}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Agents export: srv answered {status}: {body}")));
748 }
749 Ok(serde_json::to_string_pretty(&body)?)
750}
751
752async fn move_action(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
755 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
756 let Some(host) = args.get("host").and_then(Value::as_str).map(str::trim).filter(|h| !h.is_empty()) else {
757 anyhow::bail!("Agents move needs host: the computer to move the agent to, by the name Agents list shows");
758 };
759 let mut body = serde_json::Map::new();
760 body.insert("host".to_string(), json!(host));
761 for key in ["agent", "dry_run", "resume"] {
762 if let Some(v) = args.get(key).filter(|v| !v.is_null()) {
763 body.insert(key.to_string(), v.clone());
764 }
765 }
766 let url = format!("{}/api/v1/agent/move", cx.local_url.trim_end_matches('/'));
767 let resp = cx
769 .client
770 .post(&url)
771 .header(AUTH_KEY_HEADER, cx.auth_key)
772 .timeout(std::time::Duration::from_secs(60 * 30))
773 .json(&Value::Object(body))
774 .send()
775 .await
776 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
777 let status = resp.status();
778 let body: Value = resp.json().await.unwrap_or(Value::Null);
779 if !status.is_success() {
780 anyhow::bail!("{}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Agents move: srv answered {status}: {body}")));
781 }
782 Ok(serde_json::to_string_pretty(&body)?)
783}
784
785async fn handover_action(cx: &ToolCtx<'_>, action: &str, args: &Value) -> Result<String> {
787 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
788 let mut body = serde_json::Map::new();
789 for key in ["agent", "force"] {
790 if let Some(v) = args.get(key).filter(|v| !v.is_null()) {
791 body.insert(key.to_string(), v.clone());
792 }
793 }
794 let url = format!("{}/api/v1/agent/{action}", cx.local_url.trim_end_matches('/'));
795 let resp = cx
796 .client
797 .post(&url)
798 .header(AUTH_KEY_HEADER, cx.auth_key)
799 .json(&Value::Object(body))
800 .send()
801 .await
802 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
803 let status = resp.status();
804 let body: Value = resp.json().await.unwrap_or(Value::Null);
805 if !status.is_success() {
806 anyhow::bail!("{}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Agents {action}: srv answered {status}: {body}")));
807 }
808 Ok(serde_json::to_string_pretty(&body)?)
809}
810
811async fn import_agent(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
814 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
815 let file = str_arg(arguments, "file").ok_or_else(|| anyhow::anyhow!("Agents import needs file: the archive, a name or path ending .abf under your working folder"))?;
816 let request = ImportAgentRequest {
817 auth: sign_ui_automation_auth()?,
818 file,
819 mode: str_arg(arguments, "mode"),
820 name: str_arg(arguments, "name"),
821 dry_run: arguments.get("dry_run").and_then(Value::as_bool).unwrap_or(false),
822 user_instruction: str_arg(arguments, "user_instruction").unwrap_or_default(),
823 };
824 let url = format!("{}/api/v1/agent/import", cx.local_url.trim_end_matches('/'));
825 let resp = cx
826 .client
827 .post(&url)
828 .timeout(SPAWN_WAIT)
829 .header(AUTH_KEY_HEADER, cx.auth_key)
830 .json(&request)
831 .send()
832 .await
833 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
834 let status = resp.status();
835 let body: Value = resp.json().await.unwrap_or(Value::Null);
836 if !status.is_success() {
837 anyhow::bail!("Agents import: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
838 }
839 Ok(serde_json::to_string_pretty(&body)?)
840}
841
842const DEFINITION_FIELDS: &[&str] = &["description", "icon", "auto_start", "restart_on_crash", "idle_timeout_minutes", "route", "model", "effort", "spend_cap_usd", "reset_spend_today", "fresh", "handoff"];
845const OPERATOR_FIELDS: &[&str] = &["shell", "provider_flags", "working_directory", "model_vendor_base_url"];
848
849fn refuse_operator_fields(args: &Value) -> Result<()> {
852 if let Some(field) = OPERATOR_FIELDS.iter().find(|f| args.get(**f).is_some_and(|v| !v.is_null())) {
853 anyhow::bail!("Agents update does not take {field}: shell, provider_flags, working_directory and model_vendor_base_url decide what an agent runs, where its traffic goes and which project files it reads, so the operator sets them in My Agents");
854 }
855 Ok(())
856}
857
858fn definition_params(args: &Value) -> Value {
860 let mut params = json!({ "agent": str_arg(args, "agent") });
861 for field in DEFINITION_FIELDS {
862 if let Some(v) = args.get(*field).filter(|v| !v.is_null()) {
863 params[*field] = v.clone();
864 }
865 }
866 params
867}
868
869async fn definition_action(cx: &ToolCtx<'_>, action: &str, args: &Value) -> Result<String> {
873 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
874 let need = |key: &str| str_arg(args, key).ok_or_else(|| anyhow::anyhow!("missing required parameter: {key}"));
875 let body = match action {
876 "update" => {
877 refuse_operator_fields(args)?;
878 need("agent")?;
879 definition_params(args)
880 }
881 "bundles" => json!({ "agent": need("agent")?, "bundle_ids": args.get("bundle_ids").filter(|v| !v.is_null()) }),
882 _ => json!({ "template": need("template")? }),
883 };
884 let url = format!("{}/api/v1/agent/{action}", cx.local_url.trim_end_matches('/'));
885 let resp = cx
886 .client
887 .post(&url)
888 .header(AUTH_KEY_HEADER, cx.auth_key)
889 .json(&body)
890 .send()
891 .await
892 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
893 let status = resp.status();
894 let answer: Value = resp.json().await.unwrap_or(Value::Null);
895 if !status.is_success() {
896 anyhow::bail!("{}", answer["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Agents {action}: srv answered {status}: {answer}")));
897 }
898 Ok(serde_json::to_string_pretty(&answer)?)
899}
900
901async fn lifecycle(cx: &ToolCtx<'_>, action: &str, args: &Value) -> Result<String> {
904 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
905 let agent = str_arg(args, "agent").ok_or_else(|| anyhow::anyhow!("missing required parameter: agent"))?;
906 let url = format!("{}/api/v1/agent/{action}", cx.local_url.trim_end_matches('/'));
907 let resp = cx
908 .client
909 .post(&url)
910 .header(AUTH_KEY_HEADER, cx.auth_key)
911 .json(&json!({ "agent": agent }))
912 .send()
913 .await
914 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
915 let status = resp.status();
916 let body: Value = resp.json().await.unwrap_or(Value::Null);
917 if !status.is_success() {
918 let tool = if action == "rotate-token" { "AgentRotateToken".to_string() } else { format!("Agent{}", capitalised(action)) };
919 anyhow::bail!("{tool}: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
920 }
921 Ok(serde_json::to_string_pretty(&body)?)
922}
923
924async fn mute_quiet(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
926 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
927 let agent = str_arg(args, "agent").ok_or_else(|| anyhow::anyhow!("missing required parameter: agent"))?;
928 let minutes = args.get("minutes").and_then(Value::as_u64).ok_or_else(|| anyhow::anyhow!("missing required parameter: minutes (1 to 240; 0 lifts a mute)"))?;
929 let url = format!("{}/api/v1/agent/mute-quiet", cx.local_url.trim_end_matches('/'));
930 let resp = cx
931 .client
932 .post(&url)
933 .header(AUTH_KEY_HEADER, cx.auth_key)
934 .json(&json!({ "agent": agent, "minutes": minutes, "reason": str_arg(args, "reason").unwrap_or_default() }))
935 .send()
936 .await
937 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
938 let status = resp.status();
939 let body: Value = resp.json().await.unwrap_or(Value::Null);
940 if !status.is_success() {
941 anyhow::bail!("AgentMuteQuiet: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
942 }
943 Ok(serde_json::to_string_pretty(&body)?)
944}
945
946async fn watch(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
949 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
950 let agent = str_arg(args, "agent").ok_or_else(|| anyhow::anyhow!("missing required parameter: agent"))?;
951 let wait = args.get("wait_seconds").and_then(Value::as_u64).unwrap_or(0).min(25);
952 let url = format!("{}/api/v1/agent/watch", cx.local_url.trim_end_matches('/'));
953 let resp = cx
954 .client
955 .post(&url)
956 .timeout(std::time::Duration::from_secs(wait + 15))
957 .header(AUTH_KEY_HEADER, cx.auth_key)
958 .json(&json!({
959 "agent": agent,
960 "max_lines": args.get("max_lines").and_then(Value::as_u64),
961 "after": args.get("after").and_then(Value::as_u64),
962 "gen": str_arg(args, "gen"),
963 "wait_seconds": wait,
964 }))
965 .send()
966 .await
967 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
968 let status = resp.status();
969 let body: Value = resp.json().await.unwrap_or(Value::Null);
970 if !status.is_success() {
971 anyhow::bail!("AgentWatch: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
972 }
973 Ok(serde_json::to_string_pretty(&body)?)
974}
975
976fn capitalised(word: &str) -> String {
977 let mut chars = word.chars();
978 chars.next().map(|c| c.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default()
979}
980
981async fn env(cx: &ToolCtx<'_>, action: &str, args: &Value) -> Result<String> {
985 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
986 let request = env_request(action, args)?;
987 let url = format!("{}/api/v1/agent/env", cx.local_url.trim_end_matches('/'));
988 let resp = cx
989 .client
990 .post(&url)
991 .header(AUTH_KEY_HEADER, cx.auth_key)
992 .json(&request)
993 .send()
994 .await
995 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
996 let status = resp.status();
997 let body: Value = resp.json().await.unwrap_or(Value::Null);
998 if !status.is_success() {
999 anyhow::bail!("Agents env_{action}: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
1000 }
1001 Ok(serde_json::to_string_pretty(&body)?)
1002}
1003
1004async fn message_stats(cx: &ToolCtx<'_>, args: &Value) -> Result<String> {
1006 let ToolCtx { local_url, auth_key, .. } = *cx;
1007 if local_url.is_empty() || auth_key.is_empty() {
1008 anyhow::bail!("AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. Is this agent pane opened via AgentMux?");
1009 }
1010 let days = args.get("days").and_then(|d| d.as_u64()).map(|d| d.to_string());
1011 let query: Vec<(&str, &str)> = days.as_deref().map(|d| ("days", d)).into_iter().collect();
1012 let result = cx.get_json("/api/v1/message-stats", &query, Named::with_hyphen("message stats")).await?;
1013 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
1014}
1015
1016#[cfg(test)]
1017mod tests {
1018 use super::*;
1019
1020 #[test]
1021 fn every_action_is_in_the_schema() {
1022 let schema: Value = serde_json::from_str(crate::tool_schemas::AGENTS_TOOL).unwrap();
1023 let mut listed: Vec<&str> = schema["inputSchema"]["properties"]["action"]["enum"]
1024 .as_array()
1025 .unwrap()
1026 .iter()
1027 .filter_map(|v| v.as_str())
1028 .collect();
1029 let mut want = super::super::family::action_names(ACTS);
1030 listed.sort();
1031 want.sort();
1032 assert_eq!(listed, want);
1033 }
1034
1035 #[test]
1036 fn the_schema_offers_workers_for_spawn_and_agents_for_open() {
1037 let schema: Value = serde_json::from_str(crate::tool_schemas::AGENTS_TOOL).unwrap();
1038 let props = &schema["inputSchema"]["properties"];
1039 assert_eq!(props["workers"]["items"]["required"], json!(["brief"]));
1040 assert_eq!(props["agents"]["items"]["required"], json!(["agent"]));
1041 let d = schema["description"].as_str().unwrap();
1042 assert!(d.contains("To start several workers") && d.contains("To open several at once"), "the description names the batch forms");
1043 }
1044
1045 #[tokio::test]
1047 async fn a_bad_batch_is_refused_before_srv_is_asked() {
1048 let client = reqwest::Client::new();
1049 let loops = LoopRegistry::default();
1050 let counter = std::sync::atomic::AtomicU64::new(0);
1051 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1052 let e = spawn_many(&json!({ "workers": [{ "name": "a" }] }), &cx).await.unwrap_err().to_string();
1053 assert!(e.contains("workers[0] needs a brief"), "{e}");
1054 let e = spawn_many(&json!({ "workers": [{ "brief": "x" }], "brief": "y" }), &cx).await.unwrap_err().to_string();
1055 assert!(e.contains("either workers or brief"), "{e}");
1056 let e = open_many(&json!({ "agents": [{ "tab_id": "t" }] }), &cx).await.unwrap_err().to_string();
1057 assert!(e.contains("agents[0] needs an agent"), "{e}");
1058 let e = open_many(&json!({ "agents": [{ "agent": "a" }], "agent_id": "b" }), &cx).await.unwrap_err().to_string();
1059 assert!(e.contains("either agents or agent"), "{e}");
1060 }
1061
1062 #[test]
1063 fn start_stop_and_detach_name_the_agent_and_run_their_own_handlers() {
1064 for (action, tool) in [("start", "AgentStart"), ("stop", "AgentStop"), ("detach", "AgentDetach"), ("delete", "AgentDelete"), ("rotate_token", "AgentRotateToken")] {
1065 let (act, args) = pick("Agents", ACTS, &json!({ "action": action, "agent": "korp" })).unwrap();
1066 assert_eq!((act.tool, args), (tool, json!({ "agent": "korp" })));
1067 }
1068 assert_eq!(capitalised("start"), "Start");
1069 }
1070
1071 #[test]
1072 fn the_definition_actions_are_picked_with_their_arguments() {
1073 for (action, tool) in [("update", "AgentUpdate"), ("bundles", "AgentBundles"), ("hide", "AgentHide"), ("unhide", "AgentUnhide")] {
1074 let (act, _) = pick("Agents", ACTS, &json!({ "action": action, "agent": "pulse", "template": "t" })).unwrap();
1075 assert_eq!(act.tool, tool, "{action}");
1076 }
1077 }
1078
1079 #[tokio::test]
1080 async fn update_refuses_what_decides_what_runs_before_anything_is_sent() {
1081 let client = reqwest::Client::new();
1082 let loops = LoopRegistry::default();
1083 let counter = std::sync::atomic::AtomicU64::new(0);
1084 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1085 for field in ["shell", "provider_flags", "working_directory", "model_vendor_base_url"] {
1086 let e = call("Agents", &json!({ "action": "update", "agent": "pulse", field: "x" }), &cx).await.unwrap_err().to_string();
1087 assert!(e.contains(&format!("does not take {field}")), "{field}: {e}");
1088 let e = call("Agents", &json!({ "action": "update", "agent": "pulse", "host": "narko", "model": "sonnet", field: "x" }), &cx).await.unwrap_err().to_string();
1090 assert!(e.contains(&format!("does not take {field}")), "host {field}: {e}");
1091 }
1092 }
1093
1094 #[tokio::test]
1095 async fn the_definition_actions_need_their_target_before_anything_is_sent() {
1096 let client = reqwest::Client::new();
1097 let loops = LoopRegistry::default();
1098 let counter = std::sync::atomic::AtomicU64::new(0);
1099 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1100 for (action, missing) in [("update", "agent"), ("bundles", "agent"), ("hide", "template"), ("unhide", "template")] {
1101 let e = call("Agents", &json!({ "action": action }), &cx).await.unwrap_err().to_string();
1102 assert!(e.contains(&format!("missing required parameter: {missing}")), "{action}: {e}");
1103 }
1104 }
1105
1106 #[test]
1107 fn rename_names_the_agent_and_the_new_name_and_has_a_remote_form() {
1108 let (act, args) = pick("Agents", ACTS, &json!({ "action": "rename", "agent": "pulse", "name": "Pulp" })).unwrap();
1109 assert_eq!((act.tool, args), ("AgentRename", json!({ "agent": "pulse", "name": "Pulp" })));
1110 }
1111
1112 #[tokio::test]
1113 async fn a_rename_needs_an_agent_and_a_name() {
1114 let client = reqwest::Client::new();
1115 let loops = LoopRegistry::default();
1116 let counter = std::sync::atomic::AtomicU64::new(0);
1117 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1118 let e = call("Agents", &json!({ "action": "rename", "name": "Pulp" }), &cx).await.unwrap_err().to_string();
1119 assert!(e.contains("missing required parameter: agent"), "{e}");
1120 let e = call("Agents", &json!({ "action": "rename", "agent": "pulse" }), &cx).await.unwrap_err().to_string();
1121 assert!(e.contains("missing required parameter: name"), "{e}");
1122 }
1123
1124 #[test]
1125 fn watch_passes_its_cursor_and_wait_to_its_handler() {
1126 let (act, args) = pick("Agents", ACTS, &json!({ "action": "watch", "agent": "korp", "after": 42, "wait_seconds": 10 })).unwrap();
1127 assert_eq!((act.tool, args), ("AgentWatch", json!({ "agent": "korp", "after": 42, "wait_seconds": 10 })));
1128 }
1129
1130 #[tokio::test]
1131 async fn a_lifecycle_action_needs_an_agent_to_act_on() {
1132 let client = reqwest::Client::new();
1133 let loops = LoopRegistry::default();
1134 let counter = std::sync::atomic::AtomicU64::new(0);
1135 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1136 let e = call("Agents", &json!({ "action": "stop" }), &cx).await.unwrap_err().to_string();
1137 assert!(e.contains("missing required parameter: agent"), "{e}");
1138 }
1139
1140 #[tokio::test]
1141 async fn ready_needs_a_handoff_or_more_time_before_anything_is_sent() {
1142 let client = reqwest::Client::new();
1143 let loops = LoopRegistry::default();
1144 let counter = std::sync::atomic::AtomicU64::new(0);
1145 let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
1146 let e = ready(&cx, &json!({ "why": "x" })).await.unwrap_err().to_string();
1147 assert!(e.contains("needs handoff"), "{e}");
1148 let (act, args) = pick("Agents", ACTS, &json!({ "action": "ready", "handoff": "In flight: PR 7", "more_time": false })).unwrap();
1149 assert_eq!((act.tool, str_arg(&args, "handoff").as_deref()), ("AgentReady", Some("In flight: PR 7")));
1150 }
1151
1152 #[tokio::test]
1155 async fn a_host_on_an_action_without_a_remote_form_is_refused_before_anything_is_sent() {
1156 let client = reqwest::Client::new();
1157 let loops = LoopRegistry::default();
1158 let counter = std::sync::atomic::AtomicU64::new(0);
1159 let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
1160 for action in ["spawn", "detach", "watch", "rotate_token"] {
1161 let e = call("Agents", &json!({ "action": action, "host": "narko" }), &cx).await.unwrap_err().to_string();
1162 assert!(e.contains("host applies to start, open, stop, set_seat, rename, update (model and effort), env_get and env_set"), "{action}: {e}");
1163 }
1164 }
1165
1166 #[test]
1167 fn update_container_names_the_agent_and_needs_one() {
1168 let (act, args) = pick("Agents", ACTS, &json!({ "action": "update_container", "agent": "Korp" })).unwrap();
1169 assert_eq!(act.tool, "AgentUpdateContainer");
1170 assert_eq!(str_arg(&args, "agent").as_deref(), Some("Korp"));
1171 assert_eq!(str_arg(&json!({}), "agent"), None);
1172 }
1173
1174 #[test]
1175 fn update_container_carries_a_container_image_when_one_is_given() {
1176 let (_, args) = pick("Agents", ACTS, &json!({ "action": "update_container", "agent": "Korp", "container_image": "ghcr.io/agentmuxai/agent-base:developer" })).unwrap();
1177 assert_eq!(str_arg(&args, "container_image").as_deref(), Some("ghcr.io/agentmuxai/agent-base:developer"));
1178 let (_, plain) = pick("Agents", ACTS, &json!({ "action": "update_container", "agent": "Korp" })).unwrap();
1179 assert_eq!(str_arg(&plain, "container_image"), None);
1180 }
1181
1182 #[test]
1183 fn set_container_limits_names_the_agent_and_carries_the_limits_as_given() {
1184 let (act, args) = pick("Agents", ACTS, &json!({ "action": "set_container_limits", "agent": "Korp", "memory_mb": 8192, "cpus": "auto" })).unwrap();
1185 assert_eq!(act.tool, "AgentSetContainerLimits");
1186 assert_eq!(str_arg(&args, "agent").as_deref(), Some("Korp"));
1187 assert_eq!((args["memory_mb"].as_u64(), args["cpus"].as_str()), (Some(8192), Some("auto")));
1188 }
1189
1190 #[test]
1191 fn open_takes_the_agent_as_its_handler_names_it() {
1192 let (act, args) = pick("Agents", ACTS, &json!({ "action": "open", "agent": "Korp", "focus": false })).unwrap();
1193 assert_eq!(act.tool, "OpenAgent");
1194 assert_eq!(args, json!({ "agent_id": "Korp", "focus": false }));
1195 let (_, args) = pick("Agents", ACTS, &json!({ "action": "transcript", "agent": "Korp" })).unwrap();
1196 assert_eq!(args, json!({ "agent": "Korp" }));
1197 }
1198
1199 #[test]
1200 fn the_brief_tells_the_worker_who_it_reports_to() {
1201 let m = brief_message("loap-3", "Loap-4", "loap-4", "Implement SPEC_X.");
1202 assert!(
1203 m.starts_with(
1204 "You are Loap-4 (AGENTMUX_AGENT_ID loap-4), a worker of loap-3, started to do the task below. Report to \
1205 loap-3 with the agentmux MCP server's Message tool (mcp__agentmux__Message in Claude Code; action \"send\", \
1206 to \"loap-3\"), never a built-in SendMessage, when you finish, get stuck, or need a decision."
1207 ),
1208 "{m}"
1209 );
1210 assert!(m.ends_with("\n\nImplement SPEC_X."), "{m}");
1211 assert!(!m.contains(" "), "{m}");
1212 }
1213
1214 #[test]
1216 fn the_brief_names_the_workers_own_signature_and_forbids_its_leaders() {
1217 let m = brief_message("camper", "QTimer", "qtimer", "Add the side buttons.");
1218 assert!(m.contains("Sign what you publish as yourself, QTimer, never as camper"), "{m}");
1219 assert!(m.contains("a PR title starts \"QTimer@<host>: \""), "{m}");
1220 assert!(m.contains("\"Agent: QTimer@<host>\""), "{m}");
1221 assert!(m.contains("the agent_id tag in its body is qtimer"), "{m}");
1222 assert!(!m.contains("camper@"), "{m}");
1224 assert!(m.contains("Where a file you read shows another agent's name as an example, use yours."), "{m}");
1225 }
1226
1227 #[test]
1229 fn the_brief_signs_a_workers_name_in_route_form() {
1230 let m = brief_message("loap", "Loap #4", "loap-4", "b");
1231 assert!(m.contains("a PR title starts \"Loap-4@<host>: \""), "{m}");
1232 assert!(m.contains("You are Loap #4 (AGENTMUX_AGENT_ID loap-4)"), "{m}");
1233 }
1234
1235 #[test]
1236 fn container_caches_names_the_agent_and_clears_only_when_asked() {
1237 let (act, args) = pick("Agents", ACTS, &json!({ "action": "container_caches", "agent": "Korp", "clear": true })).unwrap();
1238 assert_eq!(act.tool, "AgentContainerCaches");
1239 assert_eq!(args, json!({ "agent": "Korp", "clear": true }));
1240 }
1241
1242 #[test]
1243 fn routes_has_its_handler_and_spawn_create_and_workers_carry_the_harness_and_route() {
1244 let (act, _) = pick("Agents", ACTS, &json!({ "action": "routes" })).unwrap();
1245 assert_eq!(act.tool, "AgentRoutes");
1246 let ask = route_ask(&json!({ "harness": "claude", "route": "openrouter", "model": "m" }));
1247 assert_eq!((ask.harness.as_deref(), ask.route.as_deref()), (Some("claude"), Some("openrouter")));
1248 let none = route_ask(&json!({}));
1249 assert!(none.harness.is_none() && none.route.is_none());
1250 let wire = serde_json::to_value(&ask).unwrap();
1251 assert_eq!(wire, json!({ "harness": "claude", "route": "openrouter" }), "flattened into the request as two fields");
1252 }
1253
1254 #[test]
1255 fn spawn_runs_its_own_handler_with_its_arguments() {
1256 let (act, args) = pick("Agents", ACTS, &json!({ "action": "spawn", "name": "Loap-4", "model": "sonnet", "brief": "b" })).unwrap();
1257 assert_eq!(act.tool, "SpawnAgent");
1258 assert_eq!(args, json!({ "name": "Loap-4", "model": "sonnet", "brief": "b" }));
1259 }
1260
1261 #[tokio::test]
1264 async fn search_history_takes_no_agent() {
1265 let client = reqwest::Client::new();
1266 let loops = LoopRegistry::default();
1267 let counter = std::sync::atomic::AtomicU64::new(0);
1268 let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
1269 let e = call("Agents", &json!({ "action": "search_history", "query": "x", "agent": "Korp" }), &cx)
1270 .await
1271 .unwrap_err()
1272 .to_string();
1273 assert!(e.starts_with("Agents search_history searches only your own history"), "{e}");
1274 }
1275
1276 #[test]
1277 fn env_actions_run_their_handlers() {
1278 for (action, tool) in [("env_get", "AgentEnvGet"), ("env_set", "AgentEnvSet")] {
1279 let (act, args) = pick("Agents", ACTS, &json!({ "action": action, "agent": "korp" })).unwrap();
1280 assert_eq!((act.tool, args), (tool, json!({ "agent": "korp" })));
1281 }
1282 }
1283
1284 #[test]
1285 fn an_env_get_names_the_agent_or_leaves_it_to_srv() {
1286 assert_eq!(
1287 env_request("get", &json!({ "agent": " korp " })).unwrap(),
1288 json!({ "action": "get", "agent": "korp", "lines": null, "set": null, "unset": null })
1289 );
1290 assert_eq!(env_request("get", &json!({})).unwrap()["agent"], Value::Null);
1291 }
1292
1293 #[test]
1294 fn an_env_set_sends_the_text_as_written_or_the_edits() {
1295 let text = "# note
1296
1297EDITOR=vim
1298";
1299 let sent = env_request("set", &json!({ "lines": text })).unwrap();
1300 assert_eq!(sent["lines"], text);
1301 assert_eq!((sent["set"].clone(), sent["unset"].clone()), (Value::Null, Value::Null));
1302 let sent = env_request("set", &json!({ "agent": "korp", "set": { "A": "1", "B": 2, "C": true }, "unset": ["D"] })).unwrap();
1303 assert_eq!(sent["set"], json!({ "A": "1", "B": "2", "C": "true" }));
1304 assert_eq!((sent["unset"].clone(), sent["lines"].clone(), sent["agent"].clone()), (json!(["D"]), Value::Null, json!("korp")));
1305 assert_eq!(env_request("set", &json!({ "lines": "" })).unwrap()["lines"], "");
1307 }
1308
1309 #[test]
1310 fn an_env_set_value_that_is_not_text_is_refused_before_anything_is_sent() {
1311 let e = env_request("set", &json!({ "set": { "A": ["x"] } })).unwrap_err().to_string();
1312 assert_eq!(e, "Agents env_set: the value of A must be text");
1313 let e = env_request("set", &json!({ "set": "A=1" })).unwrap_err().to_string();
1314 assert_eq!(e, "Agents env_set: set is an object of NAME: value");
1315 }
1316
1317 #[tokio::test]
1319 async fn env_set_needs_an_agent_pane() {
1320 let client = reqwest::Client::new();
1321 let loops = LoopRegistry::default();
1322 let counter = std::sync::atomic::AtomicU64::new(0);
1323 let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
1324 assert!(call("Agents", &json!({ "action": "env_set", "set": { "A": "1" } }), &cx).await.is_err());
1325 }
1326}