1use std::collections::{BTreeMap, VecDeque};
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::sync::{Arc, Mutex};
11use std::time::Duration;
12
13use async_process::Child;
14use serde::{Deserialize, Serialize};
15use std::pin::pin;
16
17use crate::{Client, Conductor, LineDirection, Role, line_direction::DebugCallback};
18
19const STDERR_CAPTURE_LIMIT: usize = 64 * 1024;
20const STDERR_READ_BUFFER_SIZE: usize = 8 * 1024;
21const STDERR_LINE_TRUNCATION_MARKER: &str = "… [stderr line truncated]";
22const SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(1);
25#[cfg(unix)]
34const TERMINATE_GRACE_PERIOD: Duration = Duration::from_secs(2);
35
36#[derive(Clone, Copy, Debug)]
41struct ShutdownTimeouts {
42 exit: Duration,
44 #[cfg(unix)]
46 terminate: Duration,
47}
48
49impl Default for ShutdownTimeouts {
50 fn default() -> Self {
51 Self {
52 exit: SHUTDOWN_GRACE_PERIOD,
53 #[cfg(unix)]
54 terminate: TERMINATE_GRACE_PERIOD,
55 }
56 }
57}
58
59#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
78#[serde(rename_all = "camelCase", deny_unknown_fields)]
79#[non_exhaustive]
80pub struct AcpAgentConfig {
81 command: PathBuf,
82 #[serde(default, skip_serializing_if = "Vec::is_empty")]
83 args: Vec<String>,
84 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
85 env: BTreeMap<String, String>,
86}
87
88impl AcpAgentConfig {
89 #[must_use]
91 pub fn new(command: impl Into<PathBuf>) -> Self {
92 Self {
93 command: command.into(),
94 args: Vec::new(),
95 env: BTreeMap::new(),
96 }
97 }
98
99 #[must_use]
101 pub fn arg(mut self, arg: impl Into<String>) -> Self {
102 self.args.push(arg.into());
103 self
104 }
105
106 #[must_use]
108 pub fn args<I, S>(mut self, args: I) -> Self
109 where
110 I: IntoIterator<Item = S>,
111 S: Into<String>,
112 {
113 self.args.extend(args.into_iter().map(Into::into));
114 self
115 }
116
117 #[must_use]
119 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
120 self.env.insert(name.into(), value.into());
121 self
122 }
123
124 #[must_use]
126 pub fn envs<I, K, V>(mut self, env: I) -> Self
127 where
128 I: IntoIterator<Item = (K, V)>,
129 K: Into<String>,
130 V: Into<String>,
131 {
132 self.env.extend(
133 env.into_iter()
134 .map(|(name, value)| (name.into(), value.into())),
135 );
136 self
137 }
138
139 #[must_use]
141 pub fn command(&self) -> &Path {
142 &self.command
143 }
144
145 #[must_use]
147 pub fn arguments(&self) -> &[String] {
148 &self.args
149 }
150
151 #[must_use]
153 pub fn environment(&self) -> &BTreeMap<String, String> {
154 &self.env
155 }
156}
157
158pub struct AcpAgent {
211 config: AcpAgentConfig,
212 debug_callback: Option<DebugCallback>,
213 shutdown_timeouts: ShutdownTimeouts,
214}
215
216impl std::fmt::Debug for AcpAgent {
217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 f.debug_struct("AcpAgent")
219 .field("config", &self.config)
220 .field(
221 "debug_callback",
222 &self.debug_callback.as_ref().map(|_| "..."),
223 )
224 .field("shutdown_timeouts", &self.shutdown_timeouts)
225 .finish()
226 }
227}
228
229impl AcpAgent {
230 #[must_use]
232 pub fn new(config: AcpAgentConfig) -> Self {
233 Self {
234 config,
235 debug_callback: None,
236 shutdown_timeouts: ShutdownTimeouts::default(),
237 }
238 }
239
240 #[must_use]
242 pub fn config(&self) -> &AcpAgentConfig {
243 &self.config
244 }
245
246 #[must_use]
248 pub fn into_config(self) -> AcpAgentConfig {
249 self.config
250 }
251
252 #[must_use]
270 pub fn with_debug<F>(mut self, callback: F) -> Self
271 where
272 F: Fn(&str, LineDirection) + Send + Sync + 'static,
273 {
274 self.debug_callback = Some(Arc::new(callback));
275 self
276 }
277
278 pub(crate) fn spawn_process(
283 &self,
284 ) -> Result<
285 (
286 async_process::ChildStdin,
287 async_process::ChildStdout,
288 async_process::ChildStderr,
289 Child,
290 ),
291 crate::Error,
292 > {
293 let mut std_cmd = std::process::Command::new(&self.config.command);
294 std_cmd.args(&self.config.args);
295 std_cmd.envs(&self.config.env);
296 #[cfg(unix)]
297 {
298 use std::os::unix::process::CommandExt as _;
299
300 std_cmd.process_group(0);
307 }
308 let mut cmd = async_process::Command::from(std_cmd);
309 #[cfg(windows)]
310 {
311 use async_process::windows::CommandExt as _;
312
313 cmd.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
314 }
315 cmd.stdin(std::process::Stdio::piped())
316 .stdout(std::process::Stdio::piped())
317 .stderr(std::process::Stdio::piped());
318
319 let mut child = cmd.spawn().map_err(crate::Error::into_internal_error)?;
320
321 let child_stdin = child
322 .stdin
323 .take()
324 .ok_or_else(|| crate::util::internal_error("Failed to open stdin"))?;
325 let child_stdout = child
326 .stdout
327 .take()
328 .ok_or_else(|| crate::util::internal_error("Failed to open stdout"))?;
329 let child_stderr = child
330 .stderr
331 .take()
332 .ok_or_else(|| crate::util::internal_error("Failed to open stderr"))?;
333
334 Ok((child_stdin, child_stdout, child_stderr, child))
335 }
336}
337
338#[cfg(unix)]
345fn signal_process_group(pid: u32, signal: rustix::process::Signal) {
346 if let Some(pid) = rustix::process::Pid::from_raw(pid.cast_signed()) {
347 let _result = rustix::process::kill_process_group(pid, signal);
348 }
349}
350
351struct ChildGuard(Child);
360
361impl ChildGuard {
362 async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
363 self.0.status().await
364 }
365
366 fn terminate(&mut self) {
367 #[cfg(unix)]
371 signal_process_group(self.0.id(), rustix::process::Signal::KILL);
372 drop(self.0.kill());
375 }
376}
377
378impl Drop for ChildGuard {
379 fn drop(&mut self) {
380 self.terminate();
381 }
382}
383
384#[derive(Default)]
385struct StderrTail {
386 bytes: VecDeque<u8>,
387 truncated: bool,
388}
389
390impl StderrTail {
391 fn push(&mut self, bytes: &[u8]) {
392 if bytes.len() >= STDERR_CAPTURE_LIMIT {
393 self.truncated |= !self.bytes.is_empty() || bytes.len() > STDERR_CAPTURE_LIMIT;
394 self.bytes.clear();
395 self.bytes
396 .extend(bytes[bytes.len() - STDERR_CAPTURE_LIMIT..].iter().copied());
397 return;
398 }
399
400 let overflow = self
401 .bytes
402 .len()
403 .saturating_add(bytes.len())
404 .saturating_sub(STDERR_CAPTURE_LIMIT);
405 if overflow > 0 {
406 self.truncated = true;
407 drop(self.bytes.drain(..overflow));
408 }
409 self.bytes.extend(bytes.iter().copied());
410 }
411
412 fn into_string(mut self) -> String {
413 let truncated = self.truncated;
414 let stderr = String::from_utf8_lossy(self.bytes.make_contiguous());
415 if truncated {
416 format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]\n{stderr}")
417 } else {
418 stderr.into_owned()
419 }
420 }
421}
422
423#[derive(Clone, Default)]
425struct StderrCapture(Arc<Mutex<StderrTail>>);
426
427impl StderrCapture {
428 fn push(&self, bytes: &[u8]) {
429 self.0
430 .lock()
431 .expect("stderr capture lock poisoned")
432 .push(bytes);
433 }
434
435 fn take(&self) -> String {
436 let tail = std::mem::take(&mut *self.0.lock().expect("stderr capture lock poisoned"));
437 tail.into_string()
438 }
439}
440
441#[derive(Default)]
442struct StderrDebugLines {
443 current: Vec<u8>,
444 truncated: bool,
445 pending_carriage_return: bool,
446}
447
448impl StderrDebugLines {
449 fn push(&mut self, bytes: &[u8], callback: &DebugCallback) {
450 for &byte in bytes {
451 if self.pending_carriage_return {
452 if byte == b'\n' {
453 self.pending_carriage_return = false;
454 self.emit(callback);
455 continue;
456 }
457
458 self.push_byte(b'\r');
459 self.pending_carriage_return = false;
460 }
461
462 match byte {
463 b'\r' => self.pending_carriage_return = true,
464 b'\n' => self.emit(callback),
465 byte => self.push_byte(byte),
466 }
467 }
468 }
469
470 fn finish(&mut self, callback: &DebugCallback) {
471 if self.pending_carriage_return {
472 self.push_byte(b'\r');
473 self.pending_carriage_return = false;
474 }
475 if !self.current.is_empty() || self.truncated {
476 self.emit(callback);
477 }
478 }
479
480 fn push_byte(&mut self, byte: u8) {
481 if self.current.len() < STDERR_CAPTURE_LIMIT {
482 self.current.push(byte);
483 } else {
484 self.truncated = true;
485 }
486 }
487
488 fn emit(&mut self, callback: &DebugCallback) {
489 let line = String::from_utf8_lossy(&self.current);
490
491 if self.truncated {
492 let mut line = line.into_owned();
493 line.push_str(STDERR_LINE_TRUNCATION_MARKER);
494 callback(&line, LineDirection::Stderr);
495 } else {
496 callback(line.as_ref(), LineDirection::Stderr);
497 }
498
499 self.current.clear();
500 self.truncated = false;
501 }
502}
503
504async fn drain_stderr(
505 mut stderr: impl futures::AsyncRead + Unpin,
506 debug_callback: Option<DebugCallback>,
507 capture: StderrCapture,
508) -> Option<std::io::Error> {
509 use futures::AsyncReadExt as _;
510
511 let mut debug_lines = debug_callback.as_ref().map(|_| StderrDebugLines::default());
512 let mut buffer = [0; STDERR_READ_BUFFER_SIZE];
513
514 let read_error = loop {
515 match stderr.read(&mut buffer).await {
516 Ok(0) => break None,
517 Ok(read) => {
518 let bytes = &buffer[..read];
519 capture.push(bytes);
522 if let (Some(lines), Some(callback)) =
523 (debug_lines.as_mut(), debug_callback.as_ref())
524 {
525 lines.push(bytes, callback);
526 }
527 }
528 Err(error) => break Some(error),
529 }
530 };
531
532 if let (Some(lines), Some(callback)) = (debug_lines.as_mut(), debug_callback.as_ref()) {
533 lines.finish(callback);
534 }
535
536 read_error
537}
538
539struct ExitedChild {
540 guard: ChildGuard,
541 status: std::process::ExitStatus,
542 stderr_rx: futures::channel::oneshot::Receiver<()>,
543 stderr_capture: StderrCapture,
544}
545
546async fn wait_for_child(
549 mut guard: ChildGuard,
550 stderr_rx: futures::channel::oneshot::Receiver<()>,
551 stderr_capture: StderrCapture,
552) -> Result<ExitedChild, crate::Error> {
553 let status = guard
554 .wait()
555 .await
556 .map_err(|e| crate::util::internal_error(format!("Failed to wait for process: {e}")))?;
557
558 Ok(ExitedChild {
559 guard,
560 status,
561 stderr_rx,
562 stderr_capture,
563 })
564}
565
566async fn finish_child_exit(child: ExitedChild) -> Result<(), crate::Error> {
569 let ExitedChild {
570 mut guard,
571 status,
572 stderr_rx,
573 stderr_capture,
574 } = child;
575
576 guard.terminate();
579
580 if status.success() {
581 Ok(())
582 } else {
583 match futures::future::select(stderr_rx, async_io::Timer::after(SHUTDOWN_GRACE_PERIOD))
584 .await
585 {
586 futures::future::Either::Left((_, _)) => {}
587 futures::future::Either::Right((_, stderr_rx)) => {
588 tracing::debug!(
589 grace = ?SHUTDOWN_GRACE_PERIOD,
590 "Agent stderr remained open after process exit; reporting stderr captured so far"
591 );
592 drop(stderr_rx);
593 }
594 }
595 let stderr = stderr_capture.take();
598
599 let message = if stderr.is_empty() {
600 format!("Process exited with {status}")
601 } else {
602 format!("Process exited with {status}: {stderr}")
603 };
604
605 Err(crate::util::internal_error(message))
606 }
607}
608
609async fn await_protocol_shutdown_after_successful_child_exit<F>(
610 protocol_future: F,
611 grace: Duration,
612) -> Result<(), crate::Error>
613where
614 F: std::future::Future<Output = Result<(), crate::Error>> + Unpin,
615{
616 match futures::future::select(protocol_future, async_io::Timer::after(grace)).await {
617 futures::future::Either::Left((result, _)) => result,
618 futures::future::Either::Right((_, protocol_future)) => {
619 tracing::debug!(
620 ?grace,
621 "Protocol transport remained open after successful agent process exit; stopping it"
622 );
623 drop(protocol_future);
624 Ok(())
625 }
626 }
627}
628
629async fn terminate_unresponsive_child<F>(
640 child_wait: F,
641 #[cfg(unix)] child_pid: u32,
642 timeouts: ShutdownTimeouts,
643) -> Result<(), crate::Error>
644where
645 F: std::future::Future<Output = Result<ExitedChild, crate::Error>> + Unpin,
646{
647 #[cfg(unix)]
648 {
649 tracing::debug!(
650 grace = ?timeouts.exit,
651 "Agent process did not exit after its stdin closed; sending SIGTERM"
652 );
653 signal_process_group(child_pid, rustix::process::Signal::TERM);
656 match futures::future::select(child_wait, async_io::Timer::after(timeouts.terminate)).await
657 {
658 futures::future::Either::Left((child, _)) => {
659 let ExitedChild {
660 mut guard, status, ..
661 } = child?;
662 tracing::debug!(%status, "Agent process exited after SIGTERM");
663 guard.terminate();
666 }
667 futures::future::Either::Right((_, child_wait)) => {
668 tracing::debug!(
669 grace = ?timeouts.terminate,
670 "Agent process did not exit after SIGTERM; sending SIGKILL"
671 );
672 drop(child_wait);
674 }
675 }
676 }
677 #[cfg(not(unix))]
678 {
679 tracing::debug!(
680 grace = ?timeouts.exit,
681 "Agent process did not exit after its stdin closed; terminating it"
682 );
683 drop(child_wait);
685 }
686 Ok(())
687}
688
689async fn write_line_with_shutdown_timeout<W>(
690 writer: &mut W,
691 line: String,
692 stdout_eof_rx: &mut Option<futures::channel::oneshot::Receiver<()>>,
693 stdout_eof_seen: &mut bool,
694 grace: Duration,
695) -> std::io::Result<()>
696where
697 W: futures::AsyncWrite + Unpin + ?Sized,
698{
699 let write = Box::pin(crate::jsonrpc::write_line(writer, line));
700
701 if *stdout_eof_seen {
702 return await_write_during_shutdown(write, grace).await;
703 }
704
705 let Some(stdout_eof) = stdout_eof_rx.as_mut() else {
706 return write.await;
707 };
708
709 match futures::future::select(write, stdout_eof).await {
710 futures::future::Either::Left((result, _)) => result,
711 futures::future::Either::Right((stdout_eof, write)) => {
712 *stdout_eof_rx = None;
713 if stdout_eof.is_err() {
714 return write.await;
717 }
718
719 *stdout_eof_seen = true;
720 await_write_during_shutdown(write, grace).await
721 }
722 }
723}
724
725async fn await_write_during_shutdown<F>(write: F, grace: Duration) -> std::io::Result<()>
726where
727 F: std::future::Future<Output = std::io::Result<()>> + Unpin,
728{
729 match futures::future::select(write, async_io::Timer::after(grace)).await {
730 futures::future::Either::Left((result, _)) => result,
731 futures::future::Either::Right((_, write)) => {
732 tracing::debug!(
733 ?grace,
734 "Pending protocol output did not drain after agent stdout closed"
735 );
736 drop(write);
737 Err(std::io::Error::new(
738 std::io::ErrorKind::TimedOut,
739 format!(
740 "Agent closed its protocol output but pending protocol output did not drain within {grace:?}"
741 ),
742 ))
743 }
744 }
745}
746
747pub trait AcpAgentCounterpartRole: Role {}
749
750impl AcpAgentCounterpartRole for Client {}
751
752impl AcpAgentCounterpartRole for Conductor {}
753
754impl<Counterpart: AcpAgentCounterpartRole> crate::ConnectTo<Counterpart> for AcpAgent {
755 async fn connect_to(
756 self,
757 client: impl crate::ConnectTo<Counterpart::Counterpart>,
758 ) -> Result<(), crate::Error> {
759 let (lines, process) = self.spawn_connection()?;
760 process
761 .supervise(crate::ConnectTo::<Counterpart>::connect_to(lines, client))
762 .await
763 }
764
765 fn into_channel_and_future(self) -> (crate::Channel, Option<crate::ConnectionDriver>) {
773 match self.spawn_connection() {
774 Ok((lines, process)) => {
775 let (channel, driver) =
776 crate::ConnectTo::<Counterpart>::into_channel_and_future(lines);
777 let driver = driver
778 .expect("the line transport owns its I/O")
779 .map_future(|work| process.supervise(work));
780 (channel, Some(driver))
781 }
782 Err(error) => {
783 let (channel, peer) = crate::Channel::duplex();
784 let driver = crate::ConnectionDriver::new(async move {
785 drop(peer);
786 Err(error)
787 });
788 (channel, Some(driver))
789 }
790 }
791 }
792}
793
794type AgentOutgoingLines =
795 std::pin::Pin<Box<dyn futures::Sink<String, Error = std::io::Error> + Send>>;
796type AgentIncomingLines =
797 std::pin::Pin<Box<dyn futures::Stream<Item = std::io::Result<String>> + Send>>;
798
799struct AgentProcess {
802 stderr_future: futures::future::BoxFuture<'static, ()>,
803 child_wait: futures::future::BoxFuture<'static, Result<ExitedChild, crate::Error>>,
804 #[cfg(unix)]
805 child_pid: u32,
806 shutdown_timeouts: ShutdownTimeouts,
807}
808
809impl AcpAgent {
810 fn spawn_connection(
813 self,
814 ) -> Result<
815 (
816 crate::Lines<AgentOutgoingLines, AgentIncomingLines>,
817 AgentProcess,
818 ),
819 crate::Error,
820 > {
821 use futures::StreamExt;
822
823 let (child_stdin, child_stdout, child_stderr, child) = self.spawn_process()?;
824
825 let (stderr_tx, stderr_rx) = futures::channel::oneshot::channel();
828 let stderr_capture = StderrCapture::default();
829
830 let debug_callback = self.debug_callback.clone();
834 let capture = stderr_capture.clone();
835 let stderr_future = async move {
836 let read_error = drain_stderr(child_stderr, debug_callback, capture).await;
837 let _ = stderr_tx.send(());
838
839 if let Some(error) = read_error {
840 tracing::warn!(
841 ?error,
842 "Failed to read process stderr; stderr will no longer be captured"
843 );
844 }
845 };
846
847 let shutdown_timeouts = self.shutdown_timeouts;
848 #[cfg(unix)]
849 let child_pid = child.id();
850
851 let child_wait = wait_for_child(ChildGuard(child), stderr_rx, stderr_capture);
854
855 let incoming_lines: std::pin::Pin<
857 Box<dyn futures::Stream<Item = std::io::Result<String>> + Send>,
858 > = if let Some(callback) = self.debug_callback.clone() {
859 Box::pin(
860 crate::jsonrpc::lossy_lines(child_stdout).inspect(move |result| {
861 if let Ok(line) = result {
862 callback(line, LineDirection::Stdout);
863 }
864 }),
865 )
866 } else {
867 Box::pin(crate::jsonrpc::lossy_lines(child_stdout))
868 };
869
870 let (stdout_eof_tx, stdout_eof_rx) = futures::channel::oneshot::channel();
875 let mut stdout_eof_tx = Some(stdout_eof_tx);
876 let mut incoming_lines = incoming_lines;
877 let incoming_lines: AgentIncomingLines = Box::pin(futures::stream::poll_fn(move |cx| {
878 let next = incoming_lines.as_mut().poll_next(cx);
879 if matches!(next, std::task::Poll::Ready(None))
880 && let Some(stdout_eof_tx) = stdout_eof_tx.take()
881 {
882 let _ = stdout_eof_tx.send(());
883 }
884 next
885 }));
886
887 let outgoing_sink: AgentOutgoingLines = Box::pin(futures::sink::unfold(
889 (
890 child_stdin,
891 self.debug_callback.clone(),
892 Some(stdout_eof_rx),
893 false,
894 ),
895 async move |(mut writer, callback, mut stdout_eof_rx, mut stdout_eof_seen),
896 line: String| {
897 if let Some(callback) = callback.as_ref() {
898 callback(&line, LineDirection::Stdin);
899 }
900 write_line_with_shutdown_timeout(
901 &mut writer,
902 line,
903 &mut stdout_eof_rx,
904 &mut stdout_eof_seen,
905 SHUTDOWN_GRACE_PERIOD,
906 )
907 .await?;
908 Ok::<_, std::io::Error>((writer, callback, stdout_eof_rx, stdout_eof_seen))
909 },
910 ));
911
912 Ok((
913 crate::Lines::new(outgoing_sink, incoming_lines),
914 AgentProcess {
915 stderr_future: Box::pin(stderr_future),
916 child_wait: Box::pin(child_wait),
917 #[cfg(unix)]
918 child_pid,
919 shutdown_timeouts,
920 },
921 ))
922 }
923}
924
925impl AgentProcess {
926 async fn supervise(
929 self,
930 protocol_future: impl std::future::Future<Output = Result<(), crate::Error>>,
931 ) -> Result<(), crate::Error> {
932 let Self {
933 stderr_future,
934 child_wait,
935 #[cfg(unix)]
936 child_pid,
937 shutdown_timeouts,
938 } = self;
939 let protocol_future = Box::pin(protocol_future);
941
942 let main_race = async {
947 match futures::future::select(protocol_future, child_wait).await {
948 futures::future::Either::Left((result, child_wait)) => {
949 result?;
950 match futures::future::select(
955 child_wait,
956 async_io::Timer::after(shutdown_timeouts.exit),
957 )
958 .await
959 {
960 futures::future::Either::Left((child, _)) => {
961 finish_child_exit(child?).await
962 }
963 futures::future::Either::Right((_, child_wait)) => {
964 terminate_unresponsive_child(
965 child_wait,
966 #[cfg(unix)]
967 child_pid,
968 shutdown_timeouts,
969 )
970 .await
971 }
972 }
973 }
974 futures::future::Either::Right((child, protocol_future)) => {
975 finish_child_exit(child?).await?;
976 await_protocol_shutdown_after_successful_child_exit(
977 protocol_future,
978 SHUTDOWN_GRACE_PERIOD,
979 )
980 .await
981 }
982 }
983 };
984
985 let main_race = pin!(main_race);
988 match futures::future::select(main_race, stderr_future).await {
989 futures::future::Either::Left((result, _)) => result,
990 futures::future::Either::Right(((), main_race)) => main_race.await,
991 }
992 }
993}
994
995impl AcpAgent {
996 pub fn from_args<I, T>(args: I) -> Result<Self, crate::Error>
1019 where
1020 I: IntoIterator<Item = T>,
1021 T: ToString,
1022 {
1023 let args: Vec<String> = args.into_iter().map(|s| s.to_string()).collect();
1024
1025 if args.is_empty() {
1026 return Err(crate::util::internal_error("Arguments cannot be empty"));
1027 }
1028
1029 let mut env = BTreeMap::new();
1030 let mut command_idx = 0;
1031
1032 for (i, arg) in args.iter().enumerate() {
1033 if let Some((name, value)) = parse_env_var(arg) {
1034 env.insert(name, value);
1035 command_idx = i + 1;
1036 } else {
1037 break;
1038 }
1039 }
1040
1041 if command_idx >= args.len() {
1042 return Err(crate::util::internal_error(
1043 "No command found (only environment variables provided)",
1044 ));
1045 }
1046
1047 let command = PathBuf::from(&args[command_idx]);
1048 let cmd_args = args[command_idx + 1..].to_vec();
1049
1050 Ok(Self::new(
1051 AcpAgentConfig::new(command).args(cmd_args).envs(env),
1052 ))
1053 }
1054}
1055
1056fn parse_env_var(s: &str) -> Option<(String, String)> {
1058 let eq_pos = s.find('=')?;
1059 if eq_pos == 0 {
1060 return None;
1061 }
1062
1063 let name = &s[..eq_pos];
1064 let value = &s[eq_pos + 1..];
1065
1066 let mut chars = name.chars();
1067 let first = chars.next()?;
1068 if !first.is_ascii_alphabetic() && first != '_' {
1069 return None;
1070 }
1071 if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
1072 return None;
1073 }
1074
1075 Some((name.to_string(), value.to_string()))
1076}
1077
1078impl FromStr for AcpAgent {
1079 type Err = crate::Error;
1080
1081 fn from_str(s: &str) -> Result<Self, Self::Err> {
1082 let trimmed = s.trim();
1083
1084 if trimmed.starts_with('{') {
1085 let config = serde_json::from_str(trimmed)
1086 .map_err(|e| crate::util::internal_error(format!("Failed to parse JSON: {e}")))?;
1087 return Ok(Self::new(config));
1088 }
1089
1090 let parts = shell_words::split(trimmed)
1091 .map_err(|e| crate::util::internal_error(format!("Failed to parse command: {e}")))?;
1092
1093 Self::from_args(parts)
1094 }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100 use std::sync::Mutex;
1101 use std::sync::atomic::{AtomicUsize, Ordering};
1102
1103 fn recording_debug_callback() -> (DebugCallback, Arc<Mutex<Vec<String>>>) {
1104 let lines = Arc::new(Mutex::new(Vec::new()));
1105 let recorded = lines.clone();
1106 let callback = Arc::new(move |line: &str, direction| {
1107 assert_eq!(direction, LineDirection::Stderr);
1108 recorded.lock().unwrap().push(line.to_owned());
1109 });
1110 (callback, lines)
1111 }
1112
1113 #[test]
1114 fn stderr_tail_keeps_last_bytes() {
1115 let initial = vec![b'a'; STDERR_CAPTURE_LIMIT];
1116
1117 let mut exact = StderrTail::default();
1118 exact.push(&initial);
1119 assert_eq!(exact.into_string(), String::from_utf8(initial).unwrap());
1120
1121 let mut truncated = StderrTail::default();
1122 truncated.push(&vec![b'a'; STDERR_CAPTURE_LIMIT]);
1123 truncated.push(b"the end");
1124 let captured = truncated.into_string();
1125 let (notice, tail) = captured.split_once('\n').unwrap();
1126 assert_eq!(
1127 notice,
1128 format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]")
1129 );
1130 assert_eq!(tail.len(), STDERR_CAPTURE_LIMIT);
1131 assert!(tail.ends_with("the end"));
1132 }
1133
1134 #[test]
1135 fn stderr_debug_callback_preserves_lines() {
1136 let (callback, recorded) = recording_debug_callback();
1137 let mut lines = StderrDebugLines::default();
1138
1139 lines.push(b"one\r", &callback);
1140 lines.push(b"\n\ntw", &callback);
1141 lines.push(b"o\nbad\xff\nlast\r", &callback);
1142 lines.finish(&callback);
1143
1144 assert_eq!(
1145 *recorded.lock().unwrap(),
1146 ["one", "", "two", "bad\u{fffd}", "last\r"]
1147 );
1148 }
1149
1150 #[test]
1151 fn stderr_debug_callback_truncates_oversized_lines() {
1152 let (callback, recorded) = recording_debug_callback();
1153 let mut lines = StderrDebugLines::default();
1154 let exact = vec![b'y'; STDERR_CAPTURE_LIMIT];
1155 let oversized = vec![b'x'; STDERR_CAPTURE_LIMIT + 1];
1156
1157 lines.push(&exact, &callback);
1158 lines.push(b"\r\n", &callback);
1159 lines.push(&oversized, &callback);
1160 assert_eq!(lines.current.len(), STDERR_CAPTURE_LIMIT);
1161 assert!(lines.truncated);
1162 lines.push(b"\nnext\n", &callback);
1163
1164 let recorded = recorded.lock().unwrap();
1165 assert_eq!(recorded.len(), 3);
1166 assert_eq!(recorded[0].len(), STDERR_CAPTURE_LIMIT);
1167 assert!(!recorded[0].ends_with(STDERR_LINE_TRUNCATION_MARKER));
1168 assert_eq!(
1169 recorded[1].len(),
1170 STDERR_CAPTURE_LIMIT + STDERR_LINE_TRUNCATION_MARKER.len()
1171 );
1172 assert!(recorded[1].ends_with(STDERR_LINE_TRUNCATION_MARKER));
1173 assert_eq!(recorded[2], "next");
1174 }
1175
1176 struct ErrorAfterData {
1177 polls: Arc<AtomicUsize>,
1178 }
1179
1180 impl futures::AsyncRead for ErrorAfterData {
1181 fn poll_read(
1182 self: std::pin::Pin<&mut Self>,
1183 _cx: &mut std::task::Context<'_>,
1184 buffer: &mut [u8],
1185 ) -> std::task::Poll<std::io::Result<usize>> {
1186 match self.polls.fetch_add(1, Ordering::SeqCst) {
1187 0 => {
1188 buffer[..7].copy_from_slice(b"partial");
1189 std::task::Poll::Ready(Ok(7))
1190 }
1191 1 => std::task::Poll::Ready(Err(std::io::Error::other("read failed"))),
1192 _ => panic!("stderr reader was polled again after an error"),
1193 }
1194 }
1195 }
1196
1197 struct HeldOpenStderr(futures::io::Cursor<Vec<u8>>);
1198
1199 impl futures::AsyncRead for HeldOpenStderr {
1200 fn poll_read(
1201 self: std::pin::Pin<&mut Self>,
1202 cx: &mut std::task::Context<'_>,
1203 buffer: &mut [u8],
1204 ) -> std::task::Poll<std::io::Result<usize>> {
1205 match std::pin::Pin::new(&mut self.get_mut().0).poll_read(cx, buffer) {
1206 std::task::Poll::Ready(Ok(0)) => std::task::Poll::Pending,
1208 result => result,
1209 }
1210 }
1211 }
1212
1213 #[test]
1214 fn stderr_capture_is_available_before_eof_and_outside_callback_locks() {
1215 use futures::FutureExt as _;
1216
1217 let capture = StderrCapture::default();
1218 let (record, recorded) = recording_debug_callback();
1219 let callback: DebugCallback = Arc::new({
1220 let capture = capture.clone();
1221 move |line, direction| {
1222 assert!(
1223 capture.0.try_lock().is_ok(),
1224 "debug callbacks must not run under the capture lock"
1225 );
1226 record(line, direction);
1227 }
1228 });
1229 let mut drain = pin!(drain_stderr(
1230 HeldOpenStderr(futures::io::Cursor::new(b"diagnostic\npartial".to_vec())),
1231 Some(callback),
1232 capture.clone(),
1233 ));
1234 assert!((&mut drain).now_or_never().is_none());
1235 assert_eq!(capture.take(), "diagnostic\npartial");
1236 assert_eq!(*recorded.lock().unwrap(), ["diagnostic"]);
1237 }
1238
1239 #[cfg(unix)]
1240 #[tokio::test]
1241 async fn nonzero_exit_preserves_captured_stderr_without_eof() {
1242 let agent = AcpAgent::from_args(["/bin/sh", "-c", "exit 17"]).unwrap();
1243 let (stdin, stdout, stderr, child) = agent.spawn_process().unwrap();
1244 drop((stdin, stdout, stderr));
1245
1246 let mut bytes = vec![b'x'; STDERR_CAPTURE_LIMIT + 1024];
1247 bytes.extend_from_slice(b"\nACP_BUFFERED_ERROR\nunterminated");
1248 let (callback, recorded) = recording_debug_callback();
1249 let (stderr_tx, stderr_rx) = futures::channel::oneshot::channel();
1250 let stderr_capture = StderrCapture::default();
1251 let capture = stderr_capture.clone();
1252 let drain = Box::pin(async move {
1253 let _error = drain_stderr(
1254 HeldOpenStderr(futures::io::Cursor::new(bytes)),
1255 Some(callback),
1256 capture,
1257 )
1258 .await;
1259 let _ = stderr_tx.send(());
1260 });
1261 let report = async move {
1262 let child = wait_for_child(ChildGuard(child), stderr_rx, stderr_capture).await?;
1263 finish_child_exit(child).await
1264 };
1265
1266 let error = tokio::time::timeout(std::time::Duration::from_secs(5), async {
1267 match futures::future::select(pin!(report), drain).await {
1268 futures::future::Either::Left((result, _)) => result,
1269 futures::future::Either::Right(_) => panic!("stderr must remain open"),
1270 }
1271 })
1272 .await
1273 .expect("stderr reporting must remain bounded")
1274 .expect_err("nonzero child exit should be reported");
1275
1276 assert!(
1277 recorded
1278 .lock()
1279 .unwrap()
1280 .iter()
1281 .any(|line| line == "ACP_BUFFERED_ERROR"),
1282 "the diagnostic was read before reporting the exit"
1283 );
1284 let detail = error
1285 .data
1286 .as_ref()
1287 .and_then(serde_json::Value::as_str)
1288 .unwrap();
1289 assert!(detail.contains("exit status: 17"), "{error:?}");
1290 assert!(detail.contains("ACP_BUFFERED_ERROR"), "{error:?}");
1291 assert!(
1292 detail.contains("[stderr truncated; showing last"),
1293 "{error:?}"
1294 );
1295 assert!(detail.ends_with("unterminated"), "{error:?}");
1296 assert_eq!(
1297 detail.split_once('\n').unwrap().1.len(),
1298 STDERR_CAPTURE_LIMIT
1299 );
1300 }
1301
1302 #[tokio::test]
1303 async fn stderr_drain_stops_after_read_error() {
1304 let polls = Arc::new(AtomicUsize::new(0));
1305 let (callback, recorded) = recording_debug_callback();
1306 let capture = StderrCapture::default();
1307
1308 let error = drain_stderr(
1309 ErrorAfterData {
1310 polls: polls.clone(),
1311 },
1312 Some(callback),
1313 capture.clone(),
1314 )
1315 .await;
1316
1317 assert_eq!(capture.take(), "partial");
1318 assert_eq!(error.unwrap().to_string(), "read failed");
1319 assert_eq!(polls.load(Ordering::SeqCst), 2);
1320 assert_eq!(*recorded.lock().unwrap(), ["partial"]);
1321 }
1322
1323 #[tokio::test]
1324 async fn successful_child_exit_bounds_protocol_shutdown_cleanly() {
1325 let grace = std::time::Duration::from_millis(10);
1326 tokio::time::timeout(
1327 std::time::Duration::from_secs(1),
1328 await_protocol_shutdown_after_successful_child_exit(
1329 futures::future::pending::<Result<(), crate::Error>>(),
1330 grace,
1331 ),
1332 )
1333 .await
1334 .expect("protocol shutdown wait should be bounded")
1335 .expect("a successful child exit should stop the pending protocol cleanly");
1336 }
1337
1338 #[tokio::test]
1339 async fn successful_child_exit_preserves_ready_protocol_error() {
1340 let error = await_protocol_shutdown_after_successful_child_exit(
1341 futures::future::ready(Err(crate::util::internal_error(
1342 "protocol failed during shutdown",
1343 ))),
1344 std::time::Duration::from_secs(1),
1345 )
1346 .await
1347 .expect_err("a ready protocol error should remain authoritative");
1348 let detail = error
1349 .data
1350 .as_ref()
1351 .and_then(serde_json::Value::as_str)
1352 .unwrap_or_default();
1353
1354 assert!(
1355 detail.contains("protocol failed during shutdown"),
1356 "unexpected protocol error: {error:?}"
1357 );
1358 }
1359
1360 #[cfg(unix)]
1361 #[tokio::test]
1362 async fn large_unterminated_stderr_is_fully_drained() {
1363 let agent = AcpAgent::from_args([
1364 "/bin/sh",
1365 "-c",
1366 r#"i=0; while [ "$i" -lt 4096 ]; do printf '%01024d' 0; i=$((i + 1)); done >&2; printf ACP_END >&2; exit 17"#,
1367 ])
1368 .unwrap();
1369 let (child_stdin, child_stdout, child_stderr, child) = agent.spawn_process().unwrap();
1370 drop(child_stdin);
1371 drop(child_stdout);
1372 let mut guard = ChildGuard(child);
1373 let capture = StderrCapture::default();
1374
1375 let (read_error, status) =
1376 tokio::time::timeout(std::time::Duration::from_secs(10), async {
1377 futures::join!(
1378 drain_stderr(child_stderr, None, capture.clone()),
1379 guard.wait()
1380 )
1381 })
1382 .await
1383 .expect("stderr drain should not block after its retained tail is full");
1384
1385 assert_eq!(status.unwrap().code(), Some(17));
1386 assert!(read_error.is_none());
1387 let captured = capture.take();
1388 let (notice, tail) = captured.split_once('\n').unwrap();
1389 assert_eq!(
1390 notice,
1391 format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]")
1392 );
1393 assert_eq!(tail.len(), STDERR_CAPTURE_LIMIT);
1394 assert!(tail.ends_with("ACP_END"));
1395 }
1396
1397 #[cfg(unix)]
1398 #[tokio::test]
1399 async fn protocol_eof_still_reports_nonzero_child_exit() {
1400 let agent = AcpAgent::from_args([
1401 "/bin/sh",
1402 "-c",
1403 "exec 1>&-; cat >/dev/null; printf ACP_TEST_FAILURE_AFTER_STDOUT_EOF >&2; exit 17",
1404 ])
1405 .unwrap();
1406
1407 let error = tokio::time::timeout(
1408 std::time::Duration::from_secs(5),
1409 Client.v1().connect_to(agent),
1410 )
1411 .await
1412 .expect("connection should finish after the child exits")
1413 .expect_err("nonzero child exit after protocol EOF should be reported");
1414 let detail = error
1415 .data
1416 .as_ref()
1417 .map(serde_json::Value::to_string)
1418 .unwrap_or_default();
1419
1420 assert!(
1421 detail.contains("exit status: 17"),
1422 "child exit status should be preserved: {error:?}"
1423 );
1424 assert!(
1425 detail.contains("ACP_TEST_FAILURE_AFTER_STDOUT_EOF"),
1426 "child stderr should be preserved: {error:?}"
1427 );
1428 }
1429
1430 #[cfg(unix)]
1431 #[tokio::test]
1432 async fn successful_child_exit_does_not_cancel_active_foreground() {
1433 let agent = AcpAgent::from_args(["/bin/sh", "-c", "exit 0"]).unwrap();
1434 let (started_tx, started_rx) = futures::channel::oneshot::channel();
1435 let (closed_tx, closed_rx) = futures::channel::oneshot::channel();
1436 let (close_release_tx, close_release_rx) = futures::channel::oneshot::channel();
1437 let (release_tx, release_rx) = futures::channel::oneshot::channel();
1438 let connection = tokio::spawn(
1439 Client
1440 .v1()
1441 .on_close(async move |_cx| {
1442 closed_tx.send(()).map_err(|()| {
1443 crate::Error::internal_error().data("close observer dropped")
1444 })?;
1445 close_release_rx.await.map_err(|_| {
1446 crate::Error::internal_error().data("close callback release dropped")
1447 })
1448 })
1449 .connect_with(agent, async move |_cx| {
1450 started_tx.send(()).map_err(|()| {
1451 crate::Error::internal_error().data("foreground observer dropped")
1452 })?;
1453 release_rx.await.map_err(|_| {
1454 crate::Error::internal_error().data("foreground release dropped")
1455 })
1456 }),
1457 );
1458
1459 tokio::time::timeout(std::time::Duration::from_secs(5), started_rx)
1460 .await
1461 .expect("foreground should start")
1462 .expect("foreground should report that it started");
1463
1464 tokio::time::timeout(std::time::Duration::from_secs(5), closed_rx)
1465 .await
1466 .expect("successful child exit should close the protocol transport")
1467 .expect("successful child exit should invoke close callbacks");
1468
1469 tokio::time::sleep(SHUTDOWN_GRACE_PERIOD + std::time::Duration::from_millis(250)).await;
1470 assert!(
1471 !connection.is_finished(),
1472 "successful child exit canceled active cleanup"
1473 );
1474
1475 close_release_tx
1476 .send(())
1477 .expect("clean child exit should preserve close callbacks");
1478 release_tx
1479 .send(())
1480 .expect("clean child exit should preserve the foreground");
1481 tokio::time::timeout(std::time::Duration::from_secs(5), connection)
1482 .await
1483 .expect("released foreground should finish")
1484 .expect("connection task should not panic")
1485 .expect("successful child exit should remain a clean EOF");
1486 }
1487
1488 #[cfg(unix)]
1489 struct KillOnDrop(Option<rustix::process::Pid>);
1490
1491 #[cfg(unix)]
1492 impl KillOnDrop {
1493 fn disarm(&mut self) {
1494 self.0 = None;
1495 }
1496 }
1497
1498 #[cfg(unix)]
1499 impl Drop for KillOnDrop {
1500 fn drop(&mut self) {
1501 if let Some(pid) = self.0 {
1502 let _result = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
1503 }
1504 }
1505 }
1506
1507 #[cfg(unix)]
1508 fn wrapper_agent(script: &str) -> (AcpAgent, tokio::sync::mpsc::UnboundedReceiver<String>) {
1509 let (pid_tx, pid_rx) = tokio::sync::mpsc::unbounded_channel();
1510 let agent = AcpAgent::from_args(["/bin/sh", "-c", script])
1511 .unwrap()
1512 .with_debug(move |line, direction| {
1513 if direction == LineDirection::Stderr {
1514 drop(pid_tx.send(line.to_owned()));
1515 }
1516 });
1517 (agent, pid_rx)
1518 }
1519
1520 #[cfg(unix)]
1521 fn process_is_running(pid: rustix::process::Pid) -> bool {
1522 if rustix::process::test_kill_process(pid).is_err() {
1523 return false;
1524 }
1525
1526 match std::process::Command::new("ps")
1529 .args(["-o", "stat=", "-p", &pid.to_string()])
1530 .output()
1531 {
1532 Ok(output) if output.status.success() => {
1533 let state = String::from_utf8_lossy(&output.stdout);
1534 !state.trim().is_empty() && !state.trim_start().starts_with('Z')
1535 }
1536 Ok(_) => false,
1537 Err(_) => true,
1538 }
1539 }
1540
1541 #[cfg(unix)]
1542 async fn reported_descendant_pid(
1543 connection: &mut (impl Future<Output = Result<(), crate::Error>> + Unpin),
1544 pid_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
1545 ) -> rustix::process::Pid {
1546 tokio::time::timeout(std::time::Duration::from_secs(5), async {
1547 loop {
1548 tokio::select! {
1549 biased;
1550 line = pid_rx.recv() => {
1551 let line = line.expect("wrapper stderr should remain open");
1552 if let Some(pid) = line.strip_prefix("ACP_TEST_CHILD_PID=") {
1553 let pid = pid.parse::<i32>().expect("valid descendant PID");
1554 break rustix::process::Pid::from_raw(pid)
1555 .expect("nonzero descendant PID");
1556 }
1557 }
1558 result = &mut *connection => {
1559 panic!("agent connection exited before reporting descendant PID: {result:?}");
1560 }
1561 }
1562 }
1563 })
1564 .await
1565 .expect("wrapper should report descendant PID")
1566 }
1567
1568 #[cfg(unix)]
1569 async fn assert_process_exits(pid: rustix::process::Pid) {
1570 let exited = tokio::time::timeout(std::time::Duration::from_secs(5), async {
1571 while process_is_running(pid) {
1572 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1573 }
1574 })
1575 .await
1576 .is_ok();
1577 assert!(exited, "descendant process {pid} remained alive");
1578 }
1579
1580 #[cfg(unix)]
1581 #[tokio::test]
1582 async fn protocol_eof_terminates_a_child_that_does_not_exit() {
1583 let (agent, mut pid_rx) =
1584 wrapper_agent("echo ACP_TEST_CHILD_PID=$$ >&2; exec 1>&-; while :; do sleep 30; done");
1585 let mut connection: futures::future::BoxFuture<'static, Result<(), crate::Error>> =
1586 Box::pin(Client.v1().connect_to(agent));
1587 let child_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;
1588 let mut cleanup = KillOnDrop(Some(child_pid));
1589
1590 assert!(process_is_running(child_pid));
1591 tokio::time::timeout(std::time::Duration::from_secs(5), &mut connection)
1592 .await
1593 .expect("protocol shutdown should bound its child-exit wait")
1594 .expect("clean protocol shutdown should terminate a non-exiting child");
1595 assert_process_exits(child_pid).await;
1596 cleanup.disarm();
1597 }
1598
1599 #[cfg(unix)]
1600 #[tokio::test]
1601 async fn protocol_eof_bounds_a_blocked_outgoing_drain() {
1602 let (agent, mut pid_rx) = wrapper_agent(
1603 "echo ACP_TEST_CHILD_PID=$$ >&2; exec 1>&-; sleep 30 & child=$!; wait \"$child\"",
1604 );
1605 let (channel, connection) = crate::ConnectTo::<Client>::into_channel_and_future(agent);
1606 let mut connection = connection.expect("AcpAgent owns its process connection");
1607 let crate::Channel {
1608 rx: _incoming,
1609 tx: outgoing,
1610 } = channel;
1611
1612 let response = crate::RawJsonRpcMessage::response(
1613 crate::RawJsonRpcId::Number(1),
1614 Ok(serde_json::json!({ "payload": "x".repeat(4 * 1024 * 1024) })),
1615 );
1616 outgoing
1617 .unbounded_send(crate::TransportFrame::Single(response))
1618 .expect("response should be accepted before the connection starts");
1619 outgoing.close_channel();
1620
1621 let child_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;
1622 let mut cleanup = KillOnDrop(Some(child_pid));
1623
1624 let error = tokio::time::timeout(std::time::Duration::from_secs(5), &mut connection)
1625 .await
1626 .expect("stdout EOF should bound a blocked outgoing drain")
1627 .expect_err("an undelivered accepted response must not report success");
1628 let detail = error
1629 .data
1630 .as_ref()
1631 .and_then(serde_json::Value::as_str)
1632 .unwrap_or_default();
1633 assert!(
1634 detail.contains("pending protocol output did not drain"),
1635 "the error should identify the blocked outgoing drain: {error:?}"
1636 );
1637
1638 assert_process_exits(child_pid).await;
1639 cleanup.disarm();
1640 }
1641
1642 #[cfg(unix)]
1643 #[tokio::test]
1644 async fn test_connection_drop_kills_wrapper_descendant() {
1645 let (agent, mut pid_rx) = wrapper_agent(
1646 "sleep 30 & child=$!; echo ACP_TEST_CHILD_PID=$child >&2; wait \"$child\"",
1647 );
1648 let (_channel, connection) = crate::ConnectTo::<Client>::into_channel_and_future(agent);
1649 let mut connection = connection.expect("AcpAgent owns its process connection");
1650 let descendant_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;
1651 let mut cleanup = KillOnDrop(Some(descendant_pid));
1652
1653 assert!(process_is_running(descendant_pid));
1654 drop(connection);
1655 assert_process_exits(descendant_pid).await;
1656 cleanup.disarm();
1657 }
1658
1659 #[cfg(unix)]
1660 #[tokio::test]
1661 async fn test_launcher_exit_kills_descendant_before_stderr_wait() {
1662 let (agent, mut pid_rx) = wrapper_agent(
1663 "sh -c 'trap \"\" HUP; exec sleep 30' >/dev/null & child=$!; echo ACP_TEST_CHILD_PID=$child >&2; exit 17",
1664 );
1665 let (_channel, connection) = crate::ConnectTo::<Client>::into_channel_and_future(agent);
1666 let mut connection = connection.expect("AcpAgent owns its process connection");
1667 let descendant_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;
1668 let mut cleanup = KillOnDrop(Some(descendant_pid));
1669
1670 let result = tokio::time::timeout(std::time::Duration::from_secs(5), &mut connection)
1671 .await
1672 .expect("connection should observe the launcher exit");
1673 let error = result.expect_err("nonzero launcher exit should be an error");
1674 let detail = error
1675 .data
1676 .as_ref()
1677 .and_then(serde_json::Value::as_str)
1678 .unwrap_or_default();
1679 assert!(
1680 detail.contains("ACP_TEST_CHILD_PID="),
1681 "launcher stderr should be preserved: {error:?}"
1682 );
1683 assert_process_exits(descendant_pid).await;
1684 cleanup.disarm();
1685 }
1686
1687 #[cfg(unix)]
1690 struct ShutdownMarkers {
1691 dir: PathBuf,
1692 }
1693
1694 #[cfg(unix)]
1695 impl ShutdownMarkers {
1696 fn new(name: &str) -> Self {
1697 static NEXT: AtomicUsize = AtomicUsize::new(0);
1698 let dir = std::env::temp_dir().join(format!(
1699 "acp-shutdown-{name}-{}-{}",
1700 std::process::id(),
1701 NEXT.fetch_add(1, Ordering::Relaxed)
1702 ));
1703 std::fs::create_dir_all(&dir).unwrap();
1704 Self { dir }
1705 }
1706
1707 fn pid_path(&self) -> PathBuf {
1708 self.dir.join("pid")
1709 }
1710
1711 fn term_path(&self) -> PathBuf {
1712 self.dir.join("term")
1713 }
1714
1715 fn agent(&self, script: &str, timeouts: ShutdownTimeouts) -> AcpAgent {
1720 let mut agent = AcpAgent::from_args([
1721 "/bin/sh",
1722 "-c",
1723 script,
1724 "sh",
1725 self.pid_path().to_str().unwrap(),
1726 self.term_path().to_str().unwrap(),
1727 ])
1728 .unwrap();
1729 agent.shutdown_timeouts = timeouts;
1730 agent
1731 }
1732
1733 fn pid(&self) -> rustix::process::Pid {
1734 let pid = std::fs::read_to_string(self.pid_path()).expect("agent wrote its PID");
1735 rustix::process::Pid::from_raw(pid.trim().parse().unwrap()).unwrap()
1736 }
1737
1738 fn received_sigterm(&self) -> bool {
1739 self.term_path().exists()
1740 }
1741 }
1742
1743 #[cfg(unix)]
1744 impl Drop for ShutdownMarkers {
1745 fn drop(&mut self) {
1746 let _result = std::fs::remove_dir_all(&self.dir);
1747 }
1748 }
1749
1750 #[cfg(unix)]
1754 async fn shut_down_once_started(
1755 agent: AcpAgent,
1756 markers: &ShutdownMarkers,
1757 ) -> (Result<(), crate::Error>, Duration) {
1758 let pid_path = markers.pid_path();
1759 let (stopped_tx, stopped_rx) = futures::channel::oneshot::channel();
1760 let connection = Client.v1().connect_with(agent, async move |_cx| {
1761 while !pid_path.exists() {
1762 tokio::time::sleep(Duration::from_millis(10)).await;
1763 }
1764 let _sent = stopped_tx.send(std::time::Instant::now());
1765 Ok(())
1766 });
1767 let result = tokio::time::timeout(Duration::from_secs(10), connection)
1768 .await
1769 .expect("agent shutdown should be bounded");
1770 let stopped = stopped_rx.await.expect("the foreground ran");
1771 (result, stopped.elapsed())
1772 }
1773
1774 #[cfg(unix)]
1775 #[tokio::test]
1776 async fn graceful_shutdown_child_exiting_on_stdin_eof_never_receives_sigterm() {
1777 let markers = ShutdownMarkers::new("eof");
1778 let agent = markers.agent(
1779 r#"trap 'echo term > "$2"' TERM; echo $$ > "$1"; cat >/dev/null; echo eof > "$1.eof"; exit 0"#,
1780 ShutdownTimeouts {
1781 exit: Duration::from_secs(5),
1782 terminate: Duration::from_secs(5),
1783 },
1784 );
1785
1786 let (result, elapsed) = shut_down_once_started(agent, &markers).await;
1787
1788 result.expect("an agent that exits on stdin EOF shuts down cleanly");
1789 assert!(
1790 elapsed < Duration::from_secs(5),
1791 "the agent should exit on stdin EOF, not after the grace period ({elapsed:?})"
1792 );
1793 assert!(!markers.received_sigterm(), "the agent received SIGTERM");
1794 assert!(
1795 markers.dir.join("pid.eof").exists(),
1796 "the agent should have read EOF on its stdin"
1797 );
1798 assert_process_exits(markers.pid()).await;
1799 }
1800
1801 #[cfg(unix)]
1802 #[tokio::test]
1803 async fn graceful_shutdown_sigterms_child_ignoring_stdin_eof() {
1804 let markers = ShutdownMarkers::new("term");
1805 let agent = markers.agent(
1806 r#"trap 'echo term > "$2"; exit 0' TERM; echo $$ > "$1"; while :; do sleep 1; done"#,
1807 ShutdownTimeouts {
1808 exit: Duration::from_millis(200),
1809 terminate: Duration::from_secs(5),
1810 },
1811 );
1812
1813 let (result, elapsed) = shut_down_once_started(agent, &markers).await;
1814 let pid = markers.pid();
1815 let mut cleanup = KillOnDrop(Some(pid));
1816
1817 result.expect("an agent stopped by SIGTERM shuts down cleanly");
1818 assert!(markers.received_sigterm(), "the agent did not get SIGTERM");
1819 assert!(
1820 elapsed < Duration::from_secs(5),
1821 "the agent should exit on SIGTERM, not wait for SIGKILL ({elapsed:?})"
1822 );
1823 assert_process_exits(pid).await;
1824 cleanup.disarm();
1825 }
1826
1827 #[cfg(unix)]
1828 #[tokio::test]
1829 async fn graceful_shutdown_sigkills_child_ignoring_sigterm() {
1830 let markers = ShutdownMarkers::new("kill");
1831 let agent = markers.agent(
1837 r#"trap 'echo term > "$2"' TERM; echo $$ > "$1"; while :; do sleep 1; done"#,
1838 ShutdownTimeouts {
1839 exit: Duration::from_millis(100),
1840 terminate: Duration::from_secs(1),
1841 },
1842 );
1843
1844 let (result, elapsed) = shut_down_once_started(agent, &markers).await;
1845 let pid = markers.pid();
1846 let mut cleanup = KillOnDrop(Some(pid));
1847
1848 result.expect("an agent killed during shutdown is not an error");
1849 assert!(markers.received_sigterm(), "SIGTERM should precede SIGKILL");
1850 assert!(
1851 elapsed >= Duration::from_millis(1100),
1852 "SIGKILL should wait for the SIGTERM grace period ({elapsed:?})"
1853 );
1854 assert_process_exits(pid).await;
1855 cleanup.disarm();
1856 }
1857
1858 #[test]
1859 fn test_parse_simple_command() {
1860 let agent = AcpAgent::from_str("python agent.py").unwrap();
1861 let config = agent.config();
1862 assert_eq!(config.command(), Path::new("python"));
1863 assert_eq!(config.arguments(), ["agent.py"]);
1864 assert!(config.environment().is_empty());
1865 }
1866
1867 #[test]
1868 fn test_parse_environment_from_args() {
1869 let agent =
1870 AcpAgent::from_args(["RUST_LOG=debug", "NO_COLOR=1", "python", "agent.py"]).unwrap();
1871 let config = agent.config();
1872
1873 assert_eq!(config.command(), Path::new("python"));
1874 assert_eq!(config.arguments(), ["agent.py"]);
1875 assert_eq!(
1876 config.environment(),
1877 &BTreeMap::from([
1878 ("NO_COLOR".to_owned(), "1".to_owned()),
1879 ("RUST_LOG".to_owned(), "debug".to_owned()),
1880 ])
1881 );
1882 }
1883
1884 #[test]
1885 fn test_new_accepts_agent_configuration() {
1886 let config = AcpAgentConfig::new("/usr/bin/agent")
1887 .arg("--verbose")
1888 .env("RUST_LOG", "debug");
1889 let agent = AcpAgent::new(config.clone());
1890
1891 assert_eq!(agent.into_config(), config);
1892 }
1893
1894 #[test]
1895 fn test_parse_command_with_args() {
1896 let agent = AcpAgent::from_str("node server.js --port 8080 --verbose").unwrap();
1897 let config = agent.config();
1898 assert_eq!(config.command(), Path::new("node"));
1899 assert_eq!(
1900 config.arguments(),
1901 ["server.js", "--port", "8080", "--verbose"]
1902 );
1903 assert!(config.environment().is_empty());
1904 }
1905
1906 #[test]
1907 fn test_parse_command_with_quotes() {
1908 let agent = AcpAgent::from_str(r#"python "my agent.py" --name "Test Agent""#).unwrap();
1909 let config = agent.into_config();
1910 assert_eq!(config.command(), Path::new("python"));
1911 assert_eq!(config.arguments(), ["my agent.py", "--name", "Test Agent"]);
1912 assert!(config.environment().is_empty());
1913 }
1914
1915 #[test]
1916 fn test_parse_json_config() {
1917 let json = r#"{
1918 "command": "/usr/bin/python",
1919 "args": ["agent.py", "--verbose"],
1920 "env": {"RUST_LOG": "debug"}
1921 }"#;
1922 let agent = AcpAgent::from_str(json).unwrap();
1923 let config = agent.config();
1924 assert_eq!(config.command(), Path::new("/usr/bin/python"));
1925 assert_eq!(config.arguments(), ["agent.py", "--verbose"]);
1926 assert_eq!(
1927 config.environment().get("RUST_LOG").map(String::as_str),
1928 Some("debug")
1929 );
1930 }
1931
1932 #[test]
1933 fn test_config_json_round_trip() {
1934 let config = AcpAgentConfig::new("agent")
1935 .args(["--mode", "fast"])
1936 .envs([("RUST_LOG", "debug"), ("NO_COLOR", "1")]);
1937
1938 let json = serde_json::to_value(&config).unwrap();
1939 assert_eq!(
1940 json,
1941 serde_json::json!({
1942 "command": "agent",
1943 "args": ["--mode", "fast"],
1944 "env": {
1945 "NO_COLOR": "1",
1946 "RUST_LOG": "debug"
1947 }
1948 })
1949 );
1950 assert_eq!(
1951 serde_json::from_value::<AcpAgentConfig>(json).unwrap(),
1952 config
1953 );
1954 }
1955
1956 #[test]
1957 fn test_config_json_defaults_and_omits_empty_collections() {
1958 let config = serde_json::from_value::<AcpAgentConfig>(serde_json::json!({
1959 "command": "agent"
1960 }))
1961 .unwrap();
1962
1963 assert_eq!(config.arguments(), &[] as &[String]);
1964 assert!(config.environment().is_empty());
1965 assert_eq!(
1966 serde_json::to_value(config).unwrap(),
1967 serde_json::json!({ "command": "agent" })
1968 );
1969 }
1970
1971 #[test]
1972 fn test_reject_mcp_server_json() {
1973 let json = r#"{
1974 "type": "stdio",
1975 "name": "my-agent",
1976 "command": "/usr/bin/python",
1977 "args": ["agent.py"],
1978 "env": []
1979 }"#;
1980 let error = AcpAgent::from_str(json).unwrap_err();
1981 assert!(
1982 error
1983 .data
1984 .as_ref()
1985 .and_then(serde_json::Value::as_str)
1986 .is_some_and(|message| message.contains("unknown field")),
1987 "unexpected error: {error:?}"
1988 );
1989 }
1990}