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