swiftide-agents 0.33.0

Composable LLM agents, typed task graphs, and streaming RAG pipelines in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
//! Local executor for running tools on the local machine.
//!
//! By default will use the current directory as the working directory.
use std::{
    borrow::Cow,
    collections::HashMap,
    io,
    path::{Path, PathBuf},
    process::Stdio,
    time::Duration,
};

use anyhow::Result;
use async_trait::async_trait;
use derive_builder::Builder;
use futures_util::{Stream, StreamExt as _, stream};
#[cfg(windows)]
use process_wrap::tokio::JobObject;
#[cfg(unix)]
use process_wrap::tokio::ProcessGroup;
use process_wrap::tokio::{CommandWrap, KillOnDrop};
use swiftide_core::{
    Command, CommandError, CommandOutput, CommandOutputChunk, CommandOutputSink, Loader,
    ToolExecutor, report_buffered_output,
};
use swiftide_indexing::loaders::FileLoader;
use tokio::{io::AsyncWriteExt as _, process::ChildStdin, time};
use tokio_util::io::ReaderStream;

const OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);

#[derive(Debug, Clone, Builder)]
pub struct LocalExecutor {
    #[builder(default = ".".into(), setter(into))]
    workdir: PathBuf,

    #[builder(default)]
    default_timeout: Option<Duration>,

    /// Clears env variables before executing commands.
    #[builder(default)]
    pub(crate) env_clear: bool,
    /// Remove these environment variables before executing commands.
    #[builder(default, setter(into))]
    pub(crate) env_remove: Vec<String>,
    ///  Set these environment variables before executing commands.
    #[builder(default, setter(into))]
    pub(crate) envs: HashMap<String, String>,
}

impl Default for LocalExecutor {
    fn default() -> Self {
        LocalExecutor {
            workdir: ".".into(),
            default_timeout: None,
            env_clear: false,
            env_remove: Vec::new(),
            envs: HashMap::new(),
        }
    }
}

impl LocalExecutor {
    pub fn new(workdir: impl Into<PathBuf>) -> Self {
        LocalExecutor {
            workdir: workdir.into(),
            default_timeout: None,
            env_clear: false,
            env_remove: Vec::new(),
            envs: HashMap::new(),
        }
    }

    pub fn builder() -> LocalExecutorBuilder {
        LocalExecutorBuilder::default()
    }

    fn resolve_workdir<'a>(&'a self, cmd: &'a Command) -> Cow<'a, Path> {
        match cmd.current_dir_path() {
            Some(path) if path.is_absolute() => Cow::Borrowed(path),
            Some(path) => Cow::Owned(self.workdir.join(path)),
            None => Cow::Borrowed(&self.workdir),
        }
    }

    fn resolve_timeout(&self, cmd: &Command) -> Option<Duration> {
        cmd.timeout_duration().copied().or(self.default_timeout)
    }

    async fn exec_shell(
        &self,
        cmd: &str,
        workdir: &Path,
        timeout: Option<Duration>,
        output_sink: &mut CommandOutputSink<'_>,
    ) -> Result<CommandOutput, CommandError> {
        let (mut command, input) = if let Some(script) = ShellScript::parse(cmd) {
            tracing::info!(interpreter = script.interpreter, "detected shebang");
            let mut command = tokio::process::Command::new(script.interpreter);
            if let Some(argument) = script.argument {
                command.arg(argument);
            }
            (command, Some(script.body.as_bytes()))
        } else {
            tracing::info!("no shebang detected; running as command");
            let mut command = tokio::process::Command::new("sh");
            command.arg("-c").arg(cmd);
            (command, None)
        };

        self.configure_command(&mut command);

        command
            .current_dir(workdir)
            .stdin(if input.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut command = CommandWrap::from(command);
        #[cfg(unix)]
        command.wrap(ProcessGroup::leader());
        #[cfg(windows)]
        command.wrap(JobObject);
        command.wrap(KillOnDrop);

        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) => return report_buffered_output(Err(error.into()), output_sink),
        };
        drop(command);
        let stdin = child.stdin().take();
        let stdout = ReaderStream::new(
            child
                .stdout()
                .take()
                .expect("stdout is configured as piped"),
        )
        .map(|chunk| chunk.map(CommandOutputChunk::Stdout));
        let stderr = ReaderStream::new(
            child
                .stderr()
                .take()
                .expect("stderr is configured as piped"),
        )
        .map(|chunk| chunk.map(CommandOutputChunk::Stderr));
        let mut output_stream = stream::select(stdout, stderr);
        let mut output_chunks = Vec::new();

        let execution = async {
            let write_input = write_input(stdin, input);
            let read_output = collect_output(&mut output_stream, &mut output_chunks, output_sink);
            let (status, (), ()) = tokio::try_join!(child.wait(), read_output, write_input)?;
            Ok::<_, io::Error>(status)
        };

        let status = match timeout {
            Some(limit) => {
                let Ok(result) = time::timeout(limit, execution).await else {
                    tracing::warn!(?limit, "command exceeded timeout; terminating");
                    if let Err(error) = Box::into_pin(child.kill()).await
                        && error.kind() != io::ErrorKind::InvalidInput
                    {
                        tracing::warn!(?error, "failed to kill command");
                    }
                    drain_output(&mut output_stream, &mut output_chunks, output_sink).await;

                    return Err(CommandError::TimedOut {
                        timeout: limit,
                        output: CommandOutput::from_chunks(output_chunks),
                    });
                };
                result?
            }
            None => execution.await?,
        };

        let output = CommandOutput::from_chunks(output_chunks);
        if status.success() {
            Ok(output)
        } else {
            Err(CommandError::NonZeroExit(output))
        }
    }

    async fn exec_read_file(
        &self,
        workdir: &Path,
        path: &Path,
        timeout: Option<Duration>,
    ) -> Result<CommandOutput, CommandError> {
        let path = resolve_path(workdir, path);
        let read_future = fs_err::tokio::read(path.as_ref());
        let output = match timeout {
            Some(limit) => match time::timeout(limit, read_future).await {
                Ok(result) => result?,
                Err(_) => {
                    return Err(CommandError::TimedOut {
                        timeout: limit,
                        output: CommandOutput::empty(),
                    });
                }
            },
            None => read_future.await?,
        };

        Ok(output.into())
    }

    async fn exec_write_file(
        &self,
        workdir: &Path,
        path: &Path,
        content: &str,
        timeout: Option<Duration>,
    ) -> Result<CommandOutput, CommandError> {
        let path = resolve_path(workdir, path);
        if let Some(parent) = path.parent() {
            let _ = fs_err::tokio::create_dir_all(parent).await;
        }
        let write_future = fs_err::tokio::write(path.as_ref(), content);
        match timeout {
            Some(limit) => match time::timeout(limit, write_future).await {
                Ok(result) => result?,
                Err(_) => {
                    return Err(CommandError::TimedOut {
                        timeout: limit,
                        output: CommandOutput::empty(),
                    });
                }
            },
            None => write_future.await?,
        }

        Ok(CommandOutput::empty())
    }

    fn configure_command(&self, command: &mut tokio::process::Command) {
        if self.env_clear {
            tracing::info!("clearing environment variables");
            command.env_clear();
        }
        for var in &self.env_remove {
            tracing::info!(var, "clearing environment variable");
            command.env_remove(var);
        }
        for (key, value) in &self.envs {
            tracing::info!(key, "setting environment variable");
            command.env(key, value);
        }
    }
}

struct ShellScript<'a> {
    interpreter: &'a str,
    argument: Option<&'a str>,
    body: &'a str,
}

impl<'a> ShellScript<'a> {
    fn parse(command: &'a str) -> Option<Self> {
        let (shebang, body) = command.split_once('\n').unwrap_or((command, ""));
        let directive = shebang.strip_prefix("#!")?.trim();
        let split = directive.find(char::is_whitespace);
        let (interpreter, argument) = split.map_or((directive, None), |index| {
            let argument = directive[index..].trim();
            (
                &directive[..index],
                (!argument.is_empty()).then_some(argument),
            )
        });

        (!interpreter.is_empty()).then_some(Self {
            interpreter,
            argument,
            body,
        })
    }
}

fn resolve_path<'a>(workdir: &'a Path, path: &'a Path) -> Cow<'a, Path> {
    if path.is_absolute() {
        Cow::Borrowed(path)
    } else {
        Cow::Owned(workdir.join(path))
    }
}

async fn write_input(mut stdin: Option<ChildStdin>, input: Option<&[u8]>) -> io::Result<()> {
    if let (Some(stdin), Some(input)) = (&mut stdin, input) {
        stdin.write_all(input).await?;
    }
    Ok(())
}

async fn collect_output<S>(
    stream: &mut S,
    chunks: &mut Vec<CommandOutputChunk>,
    output_sink: &mut CommandOutputSink<'_>,
) -> io::Result<()>
where
    S: Stream<Item = io::Result<CommandOutputChunk>> + Unpin,
{
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        output_sink(&chunk);
        chunks.push(chunk);
    }
    Ok(())
}

async fn drain_output<S>(
    stream: &mut S,
    chunks: &mut Vec<CommandOutputChunk>,
    output_sink: &mut CommandOutputSink<'_>,
) where
    S: Stream<Item = io::Result<CommandOutputChunk>> + Unpin,
{
    match time::timeout(
        OUTPUT_DRAIN_TIMEOUT,
        collect_output(stream, chunks, output_sink),
    )
    .await
    {
        Ok(Ok(())) => {}
        Ok(Err(error)) => tracing::warn!(?error, "failed to drain command output"),
        Err(_) => tracing::warn!("timed out draining command output"),
    }
}

#[async_trait]
impl ToolExecutor for LocalExecutor {
    /// Execute a `Command` on the local machine
    async fn exec_cmd(&self, cmd: &Command) -> Result<swiftide_core::CommandOutput, CommandError> {
        self.exec_cmd_streaming(cmd, &mut |_| {}).await
    }

    /// Shell commands stream as they run; file commands report their output once finished.
    #[tracing::instrument(skip_all, fields(?cmd))]
    async fn exec_cmd_streaming(
        &self,
        cmd: &Command,
        output: &mut CommandOutputSink<'_>,
    ) -> Result<swiftide_core::CommandOutput, CommandError> {
        let workdir = __self.resolve_workdir(cmd);
        let timeout = __self.resolve_timeout(cmd);
        let buffered = match cmd {
            Command::Shell { command, .. } => {
                return __self.exec_shell(command, &workdir, timeout, output).await;
            }
            Command::ReadFile { path, .. } => __self.exec_read_file(&workdir, path, timeout).await,
            Command::WriteFile { path, content, .. } => {
                __self
                    .exec_write_file(&workdir, path, content, timeout)
                    .await
            }
            _ => unimplemented!("Unsupported command: {cmd:?}"),
        };
        report_buffered_output(buffered, output)
    }

    async fn stream_files(
        &self,
        path: &Path,
        extensions: Option<Vec<String>>,
    ) -> Result<swiftide_core::indexing::IndexingStream<String>> {
        let mut loader = FileLoader::new(path);

        if let Some(extensions) = extensions {
            loader = loader.with_extensions(&extensions);
        }

        Ok(loader.into_stream())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;
    use std::{path::Path, sync::Arc, time::Duration};
    use swiftide_core::{Command, ExecutorExt, ToolExecutor};
    use temp_dir::TempDir;
    use tokio::sync::mpsc;

    fn stream_string<'a, T: AsRef<[u8]> + 'a>(chunks: impl Iterator<Item = &'a T>) -> String {
        String::from_utf8_lossy(&chunks.flat_map(AsRef::as_ref).copied().collect::<Vec<_>>())
            .into_owned()
    }

    #[tokio::test]
    async fn streams_shell_output_before_the_command_finishes() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());
        let (streamed, mut received) = mpsc::unbounded_channel();
        let command = Command::shell("printf first; sleep 0.2; printf second >&2");

        let execution = async {
            executor
                .exec_cmd_streaming(&command, &mut |chunk| streamed.send(chunk.clone()).unwrap())
                .await
        };
        tokio::pin!(execution);

        let first_chunk = tokio::select! {
            result = &mut execution => anyhow::bail!("command finished before streaming output: {result:?}"),
            chunk = received.recv() => chunk.expect("sink is alive while the command runs"),
        };
        assert_eq!(first_chunk.as_bytes(), b"first".as_slice());

        let final_output = execution.await?;
        assert_eq!(final_output.as_bytes(), b"firstsecond".as_slice());

        let mut chunks = vec![first_chunk];
        while let Ok(chunk) = received.try_recv() {
            chunks.push(chunk);
        }
        assert_eq!(CommandOutput::from_chunks(chunks), final_output);
        Ok(())
    }

    #[tokio::test]
    async fn streams_buffered_error_output() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());
        let commands = [
            Command::read_file("missing.txt"),
            // writing to a directory fails
            Command::write_file(temp_dir.path(), "content"),
            Command::shell("#!/missing/interpreter\necho unreachable"),
        ];

        for command in commands {
            let mut streamed = Vec::new();
            let result = executor
                .exec_cmd_streaming(&command, &mut |chunk| {
                    streamed.push(chunk.clone());
                })
                .await;
            let Err(CommandError::NonZeroExit(command_output)) = result else {
                anyhow::bail!("expected {command:?} to fail, got {result:?}");
            };

            assert!(!command_output.is_empty());
            assert_eq!(CommandOutput::from_chunks(streamed), command_output);
        }

        Ok(())
    }

    #[cfg(unix)]
    async fn wait_for_process_exit(pid: i32) -> anyhow::Result<()> {
        time::timeout(Duration::from_secs(2), async {
            while std::process::Command::new("kill")
                .args(["-0", &pid.to_string()])
                .status()
                .is_ok_and(|status| status.success())
            {
                time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_write_and_read_file() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // Define the file path and content
        let file_path = temp_path.join("test_file.txt");
        let file_content = "Hello, world!";

        // Write a shell command to create a file with the specified content
        let write_cmd =
            Command::shell(format!("echo '{}' > {}", file_content, file_path.display()));

        // Execute the write command
        executor.exec_cmd(&write_cmd).await?;

        // Verify that the file was created successfully
        assert!(file_path.exists());

        // Write a shell command to read the file's content
        let read_cmd = Command::shell(format!("cat {}", file_path.display()));

        // Execute the read command
        let output = executor.exec_cmd(&read_cmd).await?;

        // Verify that the content read from the file matches the expected content
        assert_eq!(output.to_string_lossy(), format!("{file_content}\n"));

        let output = executor
            .exec_cmd(&Command::read_file(&file_path))
            .await
            .unwrap();
        assert_eq!(output.to_string_lossy(), format!("{file_content}\n"));

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_echo_hello_world() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // Define the echo command
        let echo_cmd = Command::shell("echo 'hello world'");

        // Execute the echo command
        let output = executor.exec_cmd(&echo_cmd).await?;

        // Verify that the output matches the expected content
        assert_eq!(output.to_string_lossy().trim(), "hello world");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_preserves_stderr_only_failure() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        match executor
            .exec_cmd(&Command::shell("printf 'boom' >&2; exit 1"))
            .await
        {
            Err(CommandError::NonZeroExit(output)) => {
                assert!(stream_string(output.stdout()).is_empty());
                assert_eq!(stream_string(output.stderr()), "boom");
            }
            other => anyhow::bail!("expected non-zero exit, got {other:?}"),
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_retains_observed_chunk_order() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());

        let output = executor
            .exec_cmd(&Command::shell(
                "printf 'one'; sleep 0.05; printf 'two' >&2; sleep 0.05; printf 'three'",
            ))
            .await?;

        assert_eq!(output.to_string(), "onetwothree");
        assert_eq!(stream_string(output.stdout()), "onethree");
        assert_eq!(stream_string(output.stderr()), "two");
        assert!(matches!(
            output.chunks(),
            [
                CommandOutputChunk::Stdout(_),
                CommandOutputChunk::Stderr(_),
                CommandOutputChunk::Stdout(_)
            ]
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_does_not_invent_or_remove_newlines() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());

        let output = executor
            .exec_cmd(&Command::shell(
                "printf 'one\\n'; printf 'two\\r\\n' >&2; printf '\\n'",
            ))
            .await?;

        assert_eq!(stream_string(output.stdout()), "one\n\n");
        assert_eq!(stream_string(output.stderr()), "two\r\n");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_preserves_partial_output_on_timeout() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor {
            workdir: temp_dir.path().to_path_buf(),
            ..Default::default()
        };
        let command = Command::shell("printf 'one'; printf 'two' >&2; sleep 1")
            .with_timeout(Duration::from_millis(100));

        match executor.exec_cmd(&command).await {
            Err(CommandError::TimedOut { output, .. }) => {
                assert_eq!(stream_string(output.stdout()), "one");
                assert_eq!(stream_string(output.stderr()), "two");
            }
            other => anyhow::bail!("expected timeout, got {other:?}"),
        }

        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn timing_out_execution_kills_spawned_processes() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let pid_file = temp_dir.path().join("child.pid");
        let executor = LocalExecutor::new(temp_dir.path());
        let command = Command::shell(format!(
            "sleep 30 & echo $! > '{}'; wait",
            pid_file.display()
        ))
        .with_timeout(Duration::from_millis(500));

        assert!(matches!(
            executor.exec_cmd(&command).await,
            Err(CommandError::TimedOut { .. })
        ));
        let pid = fs_err::tokio::read_to_string(pid_file)
            .await?
            .trim()
            .parse()?;
        wait_for_process_exit(pid).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_passes_shebang_argument() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());

        match executor
            .exec_cmd(&Command::shell(
                "#!/bin/sh -e\nprintf before\nfalse\nprintf after",
            ))
            .await
        {
            Err(CommandError::NonZeroExit(output)) => {
                assert_eq!(output.to_string_lossy(), "before");
            }
            other => anyhow::bail!("expected non-zero exit, got {other:?}"),
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_does_not_wait_for_redirected_background_processes()
    -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let executor = LocalExecutor::new(temp_dir.path());
        let command =
            Command::shell("sleep 5 >/dev/null 2>&1 &").with_timeout(Duration::from_millis(500));

        let output = executor.exec_cmd(&command).await?;

        assert!(output.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_shell_timeout() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        let mut cmd = Command::shell("echo ready && sleep 1 && echo done");
        cmd.timeout(Duration::from_millis(100));

        match executor.exec_cmd(&cmd).await {
            Err(CommandError::TimedOut { timeout, output }) => {
                assert_eq!(timeout, Duration::from_millis(100));
                assert!(output.to_string_lossy().contains("ready"));
            }
            other => anyhow::bail!("expected timeout error, got {other:?}"),
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_default_timeout_applies() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        let executor = LocalExecutorBuilder::default()
            .workdir(temp_path.to_path_buf())
            .default_timeout(Some(Duration::from_millis(100)))
            .build()?;

        match executor.exec_cmd(&Command::shell("sleep 1")).await {
            Err(CommandError::TimedOut { timeout, output }) => {
                assert_eq!(timeout, Duration::from_millis(100));
                assert!(output.is_empty());
            }
            other => anyhow::bail!("expected default timeout, got {other:?}"),
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_clear_env() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            env_clear: true,
            ..Default::default()
        };

        // Define the echo command
        let echo_cmd = Command::shell("printenv");

        // Execute the echo command
        let result = executor.exec_cmd(&echo_cmd).await?;
        let output = result.to_string_lossy();

        // Verify that the output matches the expected content
        // assert_eq!(output.to_string().trim(), "");
        assert!(!output.contains("CARGO_PKG_VERSION"), "{output}");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_add_env() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            envs: HashMap::from([("TEST_ENV".to_string(), "HELLO".to_string())]),
            ..Default::default()
        };

        // Define the echo command
        let echo_cmd = Command::shell("printenv");

        // Execute the echo command
        let result = executor.exec_cmd(&echo_cmd).await?;
        let output = result.to_string_lossy();

        // Verify that the output matches the expected content
        // assert_eq!(output.to_string().trim(), "");
        assert!(output.contains("TEST_ENV=HELLO"), "{output}");
        // Double tap its included by default
        assert!(output.contains("CARGO_PKG_VERSION"), "{output}");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_env_remove() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            env_remove: vec!["CARGO_PKG_VERSION".to_string()],
            ..Default::default()
        };

        // Define the echo command
        let echo_cmd = Command::shell("printenv");

        // Execute the echo command
        let result = executor.exec_cmd(&echo_cmd).await?;
        let output = result.to_string_lossy();

        // Verify that the output matches the expected content
        // assert_eq!(output.to_string().trim(), "");
        assert!(!output.contains("CARGO_PKG_VERSION="), "{output}");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_run_shebang() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        let script = r#"#!/usr/bin/env python3
print("hello from python")
print(1 + 2)"#;

        // Execute the echo command
        let result = executor.exec_cmd(&Command::shell(script)).await?;
        let output = result.to_string_lossy();

        // Verify that the output matches the expected content
        assert!(output.contains("hello from python"));
        assert!(output.contains('3'));

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_multiline_with_quotes() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // Define the file path and content
        let file_path = "test_file2.txt";
        let file_content = indoc! {r#"
            fn main() {
                println!("Hello, world!");
            }
        "#};

        // Write a shell command to create a file with the specified content
        let write_cmd = Command::shell(format!("echo '{file_content}' > {file_path}"));

        // Execute the write command
        executor.exec_cmd(&write_cmd).await?;

        // Write a shell command to read the file's content
        let read_cmd = Command::shell(format!("cat {file_path}"));

        // Execute the read command
        let output = executor.exec_cmd(&read_cmd).await?;

        // Verify that the content read from the file matches the expected content
        assert_eq!(output.to_string_lossy(), format!("{file_content}\n"));

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_write_and_read_file_commands() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // Define the file path and content
        let file_path = temp_path.join("test_file.txt");
        let file_content = "Hello, world!";

        // Assert that the file does not exist and it gives the correct error
        let cmd = Command::read_file(file_path.clone());
        let result = executor.exec_cmd(&cmd).await;

        if let Err(err) = result {
            assert!(matches!(err, CommandError::NonZeroExit(..)));
        } else {
            panic!("Expected error but got {result:?}");
        }

        // Create a write command
        let write_cmd = Command::write_file(file_path.clone(), file_content.to_string());

        // Execute the write command
        executor.exec_cmd(&write_cmd).await?;

        // Verify that the file was created successfully
        assert!(file_path.exists());

        // Create a read command
        let read_cmd = Command::read_file(file_path.clone());

        // Execute the read command
        let output = executor.exec_cmd(&read_cmd).await?;
        let output = output.to_string_lossy();

        // Verify that the content read from the file matches the expected content
        assert_eq!(output, file_content);

        Ok(())
    }

    #[tokio::test]
    async fn read_file_preserves_invalid_utf8() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let file = temp_dir.path().join("bytes.bin");
        fs_err::tokio::write(&file, b"valid\xff").await?;
        let executor = LocalExecutor::new(temp_dir.path());

        let output = executor.exec_cmd(&Command::read_file(file)).await?;

        assert_eq!(output.as_bytes().as_ref(), b"valid\xff");
        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_stream_files() -> anyhow::Result<()> {
        // Create a temporary directory
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Create some test files in the temporary directory
        fs_err::write(temp_path.join("file1.txt"), "Content of file 1")?;
        fs_err::write(temp_path.join("file2.txt"), "Content of file 2")?;
        fs_err::write(temp_path.join("file3.rs"), "Content of file 3")?;

        // Instantiate LocalExecutor with the temporary directory as workdir
        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // Stream files with no extensions filter
        let stream = executor.stream_files(temp_path, None).await?;
        let files: Vec<_> = stream.collect().await;

        assert_eq!(files.len(), 3);

        // Stream files with a specific extension filter
        let stream = executor
            .stream_files(temp_path, Some(vec!["txt".to_string()]))
            .await?;
        let txt_files: Vec<_> = stream.collect().await;

        assert_eq!(txt_files.len(), 2);

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_honors_workdir() -> anyhow::Result<()> {
        use std::fs;
        use temp_dir::TempDir;

        // 1. Create a temp dir and instantiate executor
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: temp_path.to_path_buf(),
            ..Default::default()
        };

        // 2. Run a shell command in workdir and check output is workdir
        let pwd_cmd = Command::shell("pwd");
        let pwd_result = executor.exec_cmd(&pwd_cmd).await?;
        let pwd_output = pwd_result.to_string_lossy();
        let pwd_path = std::fs::canonicalize(pwd_output.trim())?;
        let temp_path = std::fs::canonicalize(temp_path)?;
        assert_eq!(pwd_path, temp_path);

        // 3. Write a file using WriteFile (should land in workdir)
        let fname = "workdir_check.txt";
        let write_cmd = Command::write_file(fname, "test123");
        executor.exec_cmd(&write_cmd).await?;

        // 4. Assert file exists in workdir, not current dir
        let expected_path = temp_path.join(fname);
        assert!(expected_path.exists());
        assert!(!Path::new(fname).exists());

        // 5. Write/read using ReadFile
        let read_cmd = Command::read_file(fname);
        let read_result = executor.exec_cmd(&read_cmd).await?;
        let read_output = read_result.to_string_lossy();
        assert_eq!(read_output.trim(), "test123");

        // 6. Clean up
        fs::remove_file(&expected_path)?;

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_command_current_dir() -> anyhow::Result<()> {
        use std::fs;
        use temp_dir::TempDir;

        let temp_dir = TempDir::new()?;
        let base_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: base_path.to_path_buf(),
            ..Default::default()
        };

        let nested_dir = base_path.join("nested");
        fs::create_dir_all(&nested_dir)?;

        let mut pwd_cmd = Command::shell("pwd");
        pwd_cmd.current_dir(Path::new("nested"));
        let pwd_result = executor.exec_cmd(&pwd_cmd).await?;
        let pwd_output = pwd_result.to_string_lossy();
        let pwd_path = std::fs::canonicalize(pwd_output.trim())?;
        assert_eq!(pwd_path, std::fs::canonicalize(&nested_dir)?);

        let mut write_cmd = Command::write_file("file.txt", "hello");
        write_cmd.current_dir(Path::new("nested"));
        executor.exec_cmd(&write_cmd).await?;

        assert!(!base_path.join("file.txt").exists());
        assert!(nested_dir.join("file.txt").exists());

        let mut read_cmd = Command::read_file("file.txt");
        read_cmd.current_dir(Path::new("nested"));
        let read_result = executor.exec_cmd(&read_cmd).await?;
        let read_output = read_result.to_string_lossy();
        assert_eq!(read_output.trim(), "hello");

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_current_dir() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let base_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: base_path.to_path_buf(),
            ..Default::default()
        };

        let nested = executor.scoped("nested");
        nested
            .exec_cmd(&Command::write_file("file.txt", "hello"))
            .await?;

        assert!(!base_path.join("file.txt").exists());
        assert!(base_path.join("nested").join("file.txt").exists());
        assert_eq!(executor.workdir, base_path);

        Ok(())
    }

    #[tokio::test]
    async fn test_local_executor_current_dir_dyn() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let base_path = temp_dir.path();

        let executor = LocalExecutor {
            workdir: base_path.to_path_buf(),
            ..Default::default()
        };

        let dyn_exec: Arc<dyn swiftide_core::ToolExecutor> = Arc::new(executor.clone());
        let nested = dyn_exec.scoped("nested");

        nested
            .exec_cmd(&Command::write_file("nested_file.txt", "hello"))
            .await?;

        assert!(base_path.join("nested").join("nested_file.txt").exists());
        assert!(!base_path.join("nested_file.txt").exists());

        Ok(())
    }
}