1#[cfg(windows)]
5use agentmux_common::win32::NoWindow;
6use std::sync::Arc;
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10 COMMAND_SHELL_EXEC, COMMAND_SHELL_STOP, COMMAND_SHELL_STATUS,
11 CommandShellExecData, ShellExecResult, CommandShellStopData, CommandShellStatusData,
12 ShellStopResult, ShellStatusResult,
13};
14use crate::backend::base::{expand_home_dir_safe, msys_to_windows_path};
15
16use super::AppState;
17
18const TIMEOUT_SECS: u64 = 300;
21const MAX_OUTPUT: u64 = 1_000_000;
24
25fn format_output(bytes: Vec<u8>, cap: u64) -> String {
28 if bytes.len() > cap as usize {
29 let s = String::from_utf8_lossy(&bytes[..cap as usize]);
30 format!("{s}…[output capped at {cap} bytes]")
31 } else {
32 String::from_utf8_lossy(&bytes).into_owned()
33 }
34}
35
36pub(crate) fn shell_stop(state: &AppState, req: CommandShellStopData) -> Result<ShellStopResult, String> {
40 let registry = &state.shell_sessions;
41 let stopped = registry.stop(&req.shell_id);
42 tracing::info!(shell_id = %req.shell_id, stopped, "shellstop");
43 Ok(ShellStopResult { stopped })
44}
45
46pub(crate) fn shell_status(state: &AppState, req: CommandShellStatusData) -> Result<ShellStatusResult, String> {
61 Ok(match state.shell_sessions.get_status_if_known(&req.shell_id) {
62 Some(s) => ShellStatusResult {
63 known: true,
64 running: s.running,
65 exit_code: s.exit_code,
66 line_count: s.line_count,
67 },
68 None => ShellStatusResult {
73 known: false,
74 running: false,
75 exit_code: None,
76 line_count: 0,
77 },
78 })
79}
80
81async fn container_exec_collect(
85 cm: &crate::backend::container::ContainerManager,
86 container_name: &str,
87 command: &str,
88) -> Result<(String, Vec<u8>, Vec<u8>), String> {
89 let session = cm.exec(
90 container_name,
91 &["sh".to_string(), "-c".to_string(), command.to_string()],
92 None, &[], false, ).await.map_err(|e| format!("shellexec: container exec failed: {e}"))?;
96
97 let exec_id = session.exec_id.clone();
98 drop(session.input);
100
101 let mut stdout_buf: Vec<u8> = Vec::new();
102 let mut stderr_buf: Vec<u8> = Vec::new();
103
104 use futures_util::StreamExt as _;
105 use bollard::container::LogOutput;
106
107 let timeout_result = tokio::time::timeout(
108 std::time::Duration::from_secs(TIMEOUT_SECS),
109 async {
110 let mut output = std::pin::pin!(session.output);
111 while let Some(item) = output.next().await {
112 match item {
113 Err(e) => return Err(format!(
114 "shellexec: container output read: {e}"
115 )),
116 Ok(log) => match log {
117 LogOutput::StdOut { message } => {
118 let cap = (MAX_OUTPUT + 1) as usize;
122 let take = cap
123 .saturating_sub(stdout_buf.len())
124 .min(message.len());
125 stdout_buf.extend_from_slice(&message[..take]);
126 }
127 LogOutput::StdErr { message } => {
128 let cap = (MAX_OUTPUT + 1) as usize;
129 let take = cap
130 .saturating_sub(stderr_buf.len())
131 .min(message.len());
132 stderr_buf.extend_from_slice(&message[..take]);
133 }
134 _ => {} }
136 }
137 }
138 Ok(())
139 }
140 ).await;
141
142 if timeout_result.is_err() {
143 let kill_pattern = format!("sh -c {command}");
152 cm.signal_exec_process(container_name, &kill_pattern, true).await.ok();
153 return Err(format!("shellexec: timed out after {TIMEOUT_SECS}s"));
154 }
155 timeout_result.unwrap()?;
156 Ok((exec_id, stdout_buf, stderr_buf))
157}
158
159async fn shell_exec_container(
161 state: &AppState,
162 cmd: &CommandShellExecData,
163 block: &crate::backend::obj::Block,
164) -> Result<ShellExecResult, String> {
165 let cm = state.container_manager.get_or_explain().await.map_err(|e| format!("shellexec: {e}"))?;
166
167 let agent_id = crate::backend::obj::meta_get_string(
168 &block.meta, "agentId", "",
169 );
170 if agent_id.is_empty() {
171 return Err("shellexec: container agent missing agentId in block meta".to_string());
172 }
173 let container_name =
174 crate::backend::container::container_name_for_slug(&agent_id);
175
176 let (exec_id, stdout_buf, stderr_buf) = container_exec_collect(&cm, &container_name, &cmd.command).await?;
177
178 let exit_code = cm.inspect_exec(&exec_id).await
181 .ok()
182 .flatten()
183 .unwrap_or(1) as i32;
184
185 tracing::debug!(
186 block_id = %cmd.blockid,
187 container = %container_name,
188 exit_code,
189 "ShellExec container done",
190 );
191
192 let result = ShellExecResult {
193 exit_code,
194 stdout: format_output(stdout_buf, MAX_OUTPUT),
195 stderr: format_output(stderr_buf, MAX_OUTPUT),
196 };
197 Ok(result)
198}
199
200fn host_working_dir(working_dir: &str) -> Result<Option<std::path::PathBuf>, String> {
202 if working_dir.is_empty() {
203 return Ok(None);
204 }
205 let native = msys_to_windows_path(working_dir);
210 let expanded = expand_home_dir_safe(&native);
211 if !expanded.is_absolute() {
216 return Err(format!(
217 "shellexec: working_dir must be absolute, got: {}",
218 expanded.display()
219 ));
220 }
221 let canonical = expanded.canonicalize()
227 .map_err(|e| format!(
228 "shellexec: cannot resolve working directory '{}': {e}",
229 expanded.display()
230 ))?;
231 Ok(Some(canonical))
232}
233
234fn host_command(shell: std::path::PathBuf, command: &str, cwd: Option<&std::path::Path>) -> tokio::process::Command {
237 let mut proc = {
238 let mut c = tokio::process::Command::new(&shell);
239 c.args(["-c", command]);
240 crate::backend::pane_env::sanitize_process_command(&mut c);
246 #[cfg(windows)]
253 {
254 c.no_window();
255 }
256 c
257 };
258 proc.stdin(std::process::Stdio::null());
267 proc.stdout(std::process::Stdio::piped());
268 proc.stderr(std::process::Stdio::piped());
269 proc.kill_on_drop(true);
273 #[cfg(unix)]
279 {
280 proc.process_group(0);
281 }
282 if let Some(dir) = cwd {
283 proc.current_dir(dir);
284 }
285 proc
286}
287
288async fn collect_host_output(
291 child: &mut tokio::process::Child,
292 stdout_pipe: &mut tokio::process::ChildStdout,
293 stderr_pipe: &mut tokio::process::ChildStderr,
294 stdout_buf: &mut Vec<u8>,
295 stderr_buf: &mut Vec<u8>,
296) -> Result<Result<std::process::ExitStatus, String>, tokio::time::error::Elapsed> {
297 use tokio::io::AsyncReadExt as _;
298 tokio::time::timeout(
311 std::time::Duration::from_secs(TIMEOUT_SECS),
312 async {
313 let (sout, serr, wait) = tokio::join!(
314 async {
316 let mut take = (&mut *stdout_pipe).take(MAX_OUTPUT + 1);
317 take.read_to_end(stdout_buf).await
318 .map_err(|e| format!("shellexec: stdout read: {e}"))?;
319 drop(take); let mut sink = tokio::io::sink();
321 tokio::io::copy(&mut *stdout_pipe, &mut sink).await
322 .map_err(|e| format!("shellexec: drain stdout: {e}"))?;
323 Ok::<(), String>(())
324 },
325 async {
327 let mut take = (&mut *stderr_pipe).take(MAX_OUTPUT + 1);
328 take.read_to_end(stderr_buf).await
329 .map_err(|e| format!("shellexec: stderr read: {e}"))?;
330 drop(take);
331 let mut sink = tokio::io::sink();
332 tokio::io::copy(&mut *stderr_pipe, &mut sink).await
333 .map_err(|e| format!("shellexec: drain stderr: {e}"))?;
334 Ok::<(), String>(())
335 },
336 child.wait(),
337 );
338 sout?;
339 serr?;
340 wait.map_err(|e| format!("shellexec: wait: {e}"))
341 }
342 )
343 .await
344}
345
346async fn shell_exec_host(cmd: &CommandShellExecData) -> Result<ShellExecResult, String> {
348 let cwd = host_working_dir(&cmd.working_dir)?;
349
350 let shell = crate::backend::posix_shell::resolve_posix_shell()
357 .map_err(|e| format!("shellexec: {e}"))?;
358 let mut proc = host_command(shell.clone(), &cmd.command, cwd.as_deref());
359
360 let mut child = crate::backend::process_tracker::registry::spawn_tracked(&cmd.blockid, &mut proc, crate::backend::process_tracker::registry::Join::Adopted)
363 .map_err(|e| format!("shellexec: spawn failed ({}): {e}", shell.display()))?;
364
365 #[cfg(unix)]
368 let child_pgid = child.id().map(|id| id as libc::pid_t);
369
370 let mut stdout_pipe = child.stdout.take().expect("stdout piped");
371 let mut stderr_pipe = child.stderr.take().expect("stderr piped");
372
373 let mut stdout_buf: Vec<u8> = Vec::new();
374 let mut stderr_buf: Vec<u8> = Vec::new();
375
376 let timeout_result = collect_host_output(&mut child, &mut stdout_pipe, &mut stderr_pipe, &mut stdout_buf, &mut stderr_buf).await;
377
378 #[cfg(unix)]
384 if timeout_result.is_err() {
385 if let Some(pgid) = child_pgid {
386 unsafe { libc::kill(-pgid, libc::SIGKILL); }
389 }
390 }
391
392 let status = timeout_result
393 .map_err(|_| format!("shellexec: timed out after {TIMEOUT_SECS}s"))??;
394
395 let result = ShellExecResult {
396 exit_code: status.code().unwrap_or(1),
397 stdout: format_output(stdout_buf, MAX_OUTPUT),
398 stderr: format_output(stderr_buf, MAX_OUTPUT),
399 };
400 Ok(result)
401}
402
403pub(crate) async fn shell_exec(state: &AppState, cmd: CommandShellExecData) -> Result<ShellExecResult, String> {
413 tracing::info!(block_id = %cmd.blockid, "ShellExec");
417 tracing::debug!(command = %cmd.command, "ShellExec command");
418
419 let block: crate::backend::obj::Block = state.mstore
420 .get(&cmd.blockid)
421 .map_err(|e| format!("shellexec: load block: {e}"))?
422 .ok_or_else(|| format!("shellexec: block {} not found", cmd.blockid))?;
423 let agent_mode = crate::backend::obj::meta_get_string(
424 &block.meta, "agentMode", "host",
425 );
426
427 if crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&agent_mode).is_container() {
428 return shell_exec_container(state, &cmd, &block).await;
429 }
430 shell_exec_host(&cmd).await
431}
432
433pub fn register_shell_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
434 let s = state.clone();
435 engine.register_typed(COMMAND_SHELL_STOP, move |req: CommandShellStopData, _ctx| {
436 let s = s.clone();
437 async move { shell_stop(&s, req) }
438 });
439
440 let s = state.clone();
441 engine.register_typed(COMMAND_SHELL_STATUS, move |req: CommandShellStatusData, _ctx| {
442 let s = s.clone();
443 async move { shell_status(&s, req) }
444 });
445
446 let s = state.clone();
447 engine.register_typed(COMMAND_SHELL_EXEC, move |cmd: CommandShellExecData, _ctx| {
448 let s = s.clone();
449 async move { shell_exec(&s, cmd).await }
450 });
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456
457 #[tokio::test]
463 async fn register_typed_records_every_shell_command() {
464 let state = crate::server::tests::test_state();
465 let (engine, _rx) = WshRpcEngine::new();
466 register_shell_handlers(&engine, &state);
467 let schema = engine.schema_json();
468 let rows = schema.as_array().unwrap();
469 let find = |cmd: &str| {
470 rows.iter()
471 .find(|r| r["command"] == cmd)
472 .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
473 };
474
475 for (cmd, req, resp) in [
476 (COMMAND_SHELL_EXEC, "CommandShellExecData", "ShellExecResult"),
477 (COMMAND_SHELL_STOP, "CommandShellStopData", "ShellStopResult"),
478 (COMMAND_SHELL_STATUS, "CommandShellStatusData", "ShellStatusResult"),
479 ] {
480 let row = find(cmd);
481 assert_eq!(row["requestName"], req, "{cmd} request");
482 assert_eq!(row["responseName"], resp, "{cmd} response");
483 }
484 }
485
486 #[test]
500 fn shellstatus_always_sends_exit_code_even_when_null() {
501 let unknown = ShellStatusResult {
502 known: false,
503 running: false,
504 exit_code: None,
505 line_count: 0,
506 };
507 let v = serde_json::to_value(&unknown).unwrap();
508 assert!(
509 v.get("exit_code").is_some(),
510 "exit_code must be present-and-null, not omitted: {v}",
511 );
512 assert!(v["exit_code"].is_null());
513 assert_eq!(v["known"], false);
514
515 let exited = ShellStatusResult {
516 known: true,
517 running: false,
518 exit_code: Some(0),
519 line_count: 12,
520 };
521 let v = serde_json::to_value(&exited).unwrap();
522 assert_eq!(v["exit_code"], 0, "a real exit 0 is not the same as unknown");
523 assert_eq!(v["known"], true);
524 }
525
526 use crate::backend::rpc_types::RpcMessage;
527 use crate::backend::shell_node::ShellStatusInfo;
528 use parking_lot::Mutex;
529
530 fn seed_status(state: &AppState, shell_id: &str, running: bool, exit_code: Option<i32>) {
535 let (tx, _rx) = tokio::sync::oneshot::channel::<()>();
536 let status = Arc::new(Mutex::new(ShellStatusInfo {
537 running,
538 exit_code,
539 line_count: 3,
540 ..Default::default()
541 }));
542 state.shell_sessions.register_full(shell_id.to_string(), tx, None, status);
543 }
544
545 async fn call_shellstatus(state: &AppState, shell_id: &str) -> serde_json::Value {
546 let (engine, mut output_rx) = WshRpcEngine::new();
547 register_shell_handlers(&engine, state);
548 engine.handle_message(RpcMessage {
549 command: "shellstatus".to_string(),
550 reqid: "req-shellstatus".to_string(),
551 data: Some(serde_json::json!({ "shell_id": shell_id })),
552 ..Default::default()
553 });
554 let resp = tokio::time::timeout(std::time::Duration::from_secs(1), output_rx.recv())
555 .await
556 .unwrap()
557 .unwrap();
558 resp.data.unwrap()
559 }
560
561 #[tokio::test]
562 async fn shellstatus_reports_running_shell() {
563 let state = crate::server::tests::test_state();
564 seed_status(&state, "sh-running", true, None);
565 let data = call_shellstatus(&state, "sh-running").await;
566 assert_eq!(data["known"], serde_json::json!(true));
567 assert_eq!(data["running"], serde_json::json!(true));
568 assert_eq!(data["line_count"], serde_json::json!(3));
569 assert!(data.get("exit_code").map_or(true, |v| v.is_null()));
570 }
571
572 #[tokio::test]
573 async fn shellstatus_reports_exited_shell_with_exit_code() {
574 let state = crate::server::tests::test_state();
575 seed_status(&state, "sh-exited", false, Some(0));
576 let data = call_shellstatus(&state, "sh-exited").await;
577 assert_eq!(data["known"], serde_json::json!(true));
578 assert_eq!(data["running"], serde_json::json!(false));
579 assert_eq!(data["exit_code"], serde_json::json!(0));
580 }
581
582 #[tokio::test]
583 async fn shellstatus_reports_exited_err_shell() {
584 let state = crate::server::tests::test_state();
585 seed_status(&state, "sh-failed", false, Some(1));
586 let data = call_shellstatus(&state, "sh-failed").await;
587 assert_eq!(data["known"], serde_json::json!(true));
588 assert_eq!(data["running"], serde_json::json!(false));
589 assert_eq!(data["exit_code"], serde_json::json!(1));
590 }
591
592 #[tokio::test]
601 async fn shellstatus_unknown_id_reports_known_false() {
602 let state = crate::server::tests::test_state();
603 let data = call_shellstatus(&state, "sh-never-existed").await;
604 assert_eq!(data["known"], serde_json::json!(false));
605 assert_eq!(data["running"], serde_json::json!(false));
606 assert!(data.get("exit_code").map_or(true, |v| v.is_null()));
607 }
608
609 fn insert_block(state: &AppState, block_id: &str, meta: &[(&str, &str)]) {
610 let mut m = crate::backend::obj::MetaMapType::new();
611 for (k, v) in meta {
612 m.insert(k.to_string(), serde_json::json!(v));
613 }
614 let mut block = crate::backend::obj::Block {
615 oid: block_id.to_string(),
616 parentoref: String::new(),
617 version: 0,
618 runtimeopts: None,
619 stickers: None,
620 meta: m,
621 subblockids: None,
622 };
623 state.mstore.insert(&mut block).unwrap();
624 }
625
626 fn exec_req(block_id: &str, command: &str, working_dir: &str) -> CommandShellExecData {
627 serde_json::from_value(serde_json::json!({ "blockid": block_id, "command": command, "working_dir": working_dir })).unwrap()
628 }
629
630 #[tokio::test]
633 async fn shell_stop_and_status_answer_directly() {
634 let state = crate::server::tests::test_state();
635 assert!(!shell_stop(&state, serde_json::from_value(serde_json::json!({ "shell_id": "never" })).unwrap()).unwrap().stopped);
636
637 seed_status(&state, "sh-direct", false, Some(2));
638 let known = shell_status(&state, serde_json::from_value(serde_json::json!({ "shell_id": "sh-direct" })).unwrap()).unwrap();
639 assert!(known.known && !known.running);
640 assert_eq!(known.exit_code, Some(2));
641 let unknown = shell_status(&state, serde_json::from_value(serde_json::json!({ "shell_id": "sh-unknown" })).unwrap()).unwrap();
642 assert!(!unknown.known && unknown.exit_code.is_none() && unknown.line_count == 0);
643 }
644
645 #[tokio::test]
646 async fn shell_exec_of_a_missing_block_is_an_error() {
647 let state = crate::server::tests::test_state();
648 let err = shell_exec(&state, exec_req("no-such-block", "echo hi", "")).await.unwrap_err();
649 assert_eq!(err, "shellexec: block no-such-block not found");
650 }
651
652 #[tokio::test]
653 async fn shell_exec_refuses_a_relative_working_directory() {
654 let state = crate::server::tests::test_state();
655 insert_block(&state, "exec-rel", &[]);
656 let err = shell_exec(&state, exec_req("exec-rel", "echo hi", "../etc")).await.unwrap_err();
657 assert!(err.starts_with("shellexec: working_dir must be absolute"), "{err}");
658 }
659
660 #[tokio::test]
662 async fn shell_exec_of_a_container_block_without_an_agent_id_is_refused() {
663 let state = crate::server::tests::test_state();
664 insert_block(&state, "exec-container", &[("agentMode", "container")]);
665 let err = shell_exec(&state, exec_req("exec-container", "echo hi", "")).await.unwrap_err();
666 assert!(err.starts_with("shellexec:"), "{err}");
668 }
669
670 #[cfg(unix)]
671 #[tokio::test]
672 async fn shell_exec_runs_a_host_command_and_reports_streams_and_exit_code() {
673 let state = crate::server::tests::test_state();
674 insert_block(&state, "exec-host", &[]);
675 let dir = tempfile::tempdir().unwrap();
676 let wd = dir.path().canonicalize().unwrap();
677 let out = shell_exec(&state, exec_req("exec-host", "pwd; echo err >&2; exit 3", wd.to_str().unwrap())).await.unwrap();
678 assert_eq!(out.exit_code, 3);
679 assert_eq!(out.stdout.trim(), wd.to_string_lossy());
680 assert_eq!(out.stderr.trim(), "err");
681 }
682
683 #[cfg(unix)]
685 #[tokio::test]
686 async fn shell_exec_caps_runaway_output() {
687 let state = crate::server::tests::test_state();
688 insert_block(&state, "exec-cap", &[]);
689 let out = shell_exec(&state, exec_req("exec-cap", "head -c 1500000 /dev/zero | tr '\\0' a", "")).await.unwrap();
690 assert_eq!(out.exit_code, 0);
691 assert!(out.stdout.ends_with("…[output capped at 1000000 bytes]"), "tail: {:?}", &out.stdout[out.stdout.len().saturating_sub(40)..]);
692 }
693}