1use std::io::{Read, Write};
23use std::path::{Path, PathBuf};
24use std::process::{Child, ChildStdin, Command, Stdio};
25use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
26use std::sync::Mutex;
27use std::time::{Duration, Instant};
28
29use crate::sandbox::Profile;
30
31pub const HARNESS_ENV: &[&str] = &[
38 "GEMINI_API_KEY",
39 "GOOGLE_API_KEY",
40 "ANTHROPIC_API_KEY",
41 "OLLAMA_API_KEY",
42 "OLLAMA_HOST",
43 "OPENAI_API_KEY",
44 "OPENAI_BASE_URL",
45 "OPENROUTER_API_KEY",
46];
47
48const CREDENTIAL_SEGMENTS: &[&str] = &[
49 "TOKEN",
50 "SECRET",
51 "SECRETS",
52 "PASSWORD",
53 "PASSWD",
54 "PASS",
55 "KEY",
56 "CREDENTIAL",
57 "CREDENTIALS",
58 "AUTH",
59 "COOKIE",
60 "SESSION",
61];
62
63const CREDENTIAL_NAMES: &[&str] = &["AWS_PROFILE", "AWS_DEFAULT_PROFILE"];
66
67static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
68
69pub fn credential_like(name: &str, value: &str) -> bool {
72 let upper = name.to_ascii_uppercase();
73 if CREDENTIAL_NAMES.contains(&upper.as_str()) {
74 return true;
75 }
76 if upper
77 .split('_')
78 .any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
79 {
80 return true;
81 }
82 has_inline_credentials(value)
83}
84
85fn has_inline_credentials(value: &str) -> bool {
86 let mut rest = value;
87 while let Some(idx) = rest.find("://") {
88 let after_scheme = &rest[idx + 3..];
89 let len = after_scheme
90 .find(|c: char| c == '/' || c.is_whitespace())
91 .unwrap_or(after_scheme.len());
92 let authority_prefix = &after_scheme[..len];
93 if let Some((userinfo, _)) = authority_prefix.split_once('@') {
94 if let Some((_user, pass)) = userinfo.split_once(':') {
95 if !pass.is_empty() {
96 return true;
97 }
98 }
99 }
100 rest = after_scheme;
101 }
102 false
103}
104
105pub fn set_pass_env(names: Vec<String>) {
109 let _ = PASS_ENV.set(names);
110}
111
112pub fn withheld_env() -> Vec<String> {
114 let pass_env = PASS_ENV.get();
115 let mut withheld = Vec::new();
116 for (key, val) in std::env::vars_os() {
117 let name = key.to_string_lossy();
118 if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
119 continue;
120 }
121 if name.starts_with("BLYTE_") {
122 continue;
123 }
124 if let Some(passed) = pass_env {
125 if passed.iter().any(|p| p == name.as_ref()) {
126 continue;
127 }
128 }
129 let value = val.to_string_lossy();
130 if credential_like(&name, &value) {
131 withheld.push(name.into_owned());
132 }
133 }
134 withheld.sort();
135 withheld.dedup();
136 withheld
137}
138
139fn scrub(cmd: &mut Command) {
141 for name in HARNESS_ENV {
142 cmd.env_remove(name);
143 }
144 for (name, _) in std::env::vars_os() {
145 let n = name.to_string_lossy();
146 if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
147 cmd.env_remove(&name);
148 }
149 }
150 for name in withheld_env() {
151 cmd.env_remove(name);
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct Output {
157 pub stdout: String,
158 pub stderr: String,
159 pub exit_code: i32,
160}
161
162impl Output {
163 pub fn merged(&self) -> String {
166 format!("{}{}", self.stdout, self.stderr)
167 }
168}
169
170pub trait Shell: Send + Sync {
171 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
173
174 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
178 self.exec(command, cwd, timeout)
179 }
180
181 fn describe(&self) -> String;
184
185 fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
187 let probe = candidates
190 .iter()
191 .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
192 .collect::<Vec<_>>()
193 .join("; ");
194 match self.exec(&probe, cwd, Duration::from_secs(30)) {
195 Ok(o) => o
196 .stdout
197 .lines()
198 .map(|l| l.trim().to_string())
199 .filter(|l| !l.is_empty())
200 .collect(),
201 Err(_) => Vec::new(),
202 }
203 }
204}
205
206fn exec_command(mut cmd: Command, timeout: Duration) -> Result<Output, String> {
219 use std::process::Stdio;
220
221 cmd.stdin(Stdio::null())
225 .stdout(Stdio::piped())
226 .stderr(Stdio::piped());
227
228 #[cfg(unix)]
233 {
234 use std::os::unix::process::CommandExt;
235 cmd.process_group(0);
236 }
237
238 let mut child = cmd
239 .spawn()
240 .map_err(|e| format!("cannot run command: {e}"))?;
241
242 let mut so = child.stdout.take().ok_or("no stdout")?;
245 let mut se = child.stderr.take().ok_or("no stderr")?;
246 let t_out = std::thread::spawn(move || {
247 let mut b = String::new();
248 let _ = so.read_to_string(&mut b);
249 b
250 });
251 let t_err = std::thread::spawn(move || {
252 let mut b = String::new();
253 let _ = se.read_to_string(&mut b);
254 b
255 });
256
257 let deadline = std::time::Instant::now() + timeout;
258 let status = loop {
259 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
260 Some(s) => break Some(s),
261 None if std::time::Instant::now() >= deadline => {
262 #[cfg(unix)]
266 {
267 let pgid = child.id() as i32;
268 if pgid > 0 {
269 unsafe {
270 libc::kill(-pgid, libc::SIGKILL);
271 }
272 } else {
273 let _ = child.kill();
274 }
275 }
276 #[cfg(not(unix))]
277 {
278 let _ = child.kill();
279 }
280 let _ = child.wait();
281 break None;
282 }
283 None => std::thread::sleep(Duration::from_millis(50)),
284 }
285 };
286
287 let stdout = t_out.join().unwrap_or_default();
288 let stderr = t_err.join().unwrap_or_default();
289
290 match status {
291 Some(s) => Ok(Output {
292 stdout,
293 stderr,
294 exit_code: s.code().unwrap_or(-1),
295 }),
296 None => Ok(Output {
299 stdout,
300 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
301 exit_code: 124, }),
303 }
304}
305
306#[derive(Debug, Default, Clone, PartialEq, Eq)]
308pub struct LocalShell {
309 pub profile: Option<Profile>,
310}
311
312#[allow(non_upper_case_globals)]
313pub const LocalShell: LocalShell = LocalShell { profile: None };
314
315impl LocalShell {
316 pub fn new() -> Self {
318 Self { profile: None }
319 }
320
321 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
323 Self {
324 profile: Some(profile.into()),
325 }
326 }
327}
328
329impl Shell for LocalShell {
330 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
331 let full_command = inherited_path_prefix() + command;
332 let command = full_command.as_str();
333 let mut cmd = match &self.profile {
334 Some(Profile::Seatbelt(profile)) => {
335 let mut c = Command::new("/usr/bin/sandbox-exec");
336 c.args(["-p", profile, "bash", "-lc", command]);
337 c
338 }
339 Some(Profile::Landlock(paths)) => {
340 #[cfg(target_os = "linux")]
341 {
342 let mut c = Command::new("bash");
343 c.arg("-lc").arg(command);
344 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
345 .map_err(|e| e.to_string())?;
346 c
347 }
348 #[cfg(not(target_os = "linux"))]
349 {
350 let _ = paths;
351 return Err(std::io::Error::new(
352 std::io::ErrorKind::Unsupported,
353 "Landlock is only supported on Linux",
354 )
355 .to_string());
356 }
357 }
358 Some(Profile::LandlockOffline(paths)) => {
359 #[cfg(target_os = "linux")]
360 {
361 let mut c = Command::new("bash");
362 c.arg("-lc").arg(command);
363 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
364 .map_err(|e| e.to_string())?;
365 c
366 }
367 #[cfg(not(target_os = "linux"))]
368 {
369 let _ = paths;
370 return Err(std::io::Error::new(
371 std::io::ErrorKind::Unsupported,
372 "Landlock is only supported on Linux",
373 )
374 .to_string());
375 }
376 }
377 Some(Profile::LandlockConfined {
378 write,
379 read,
380 block_tcp,
381 }) => {
382 #[cfg(target_os = "linux")]
383 {
384 let mut c = Command::new("bash");
385 c.arg("-lc").arg(command);
386 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
387 .map_err(|e| e.to_string())?;
388 c
389 }
390 #[cfg(not(target_os = "linux"))]
391 {
392 let _ = (write, read, block_tcp);
393 return Err(std::io::Error::new(
394 std::io::ErrorKind::Unsupported,
395 "Landlock is only supported on Linux",
396 )
397 .to_string());
398 }
399 }
400 None => {
401 let mut c = Command::new("bash");
402 c.arg("-lc").arg(command);
403 c
404 }
405 };
406 cmd.current_dir(cwd);
407 scrub(&mut cmd);
408 exec_command(cmd, timeout)
409 }
410
411 fn describe(&self) -> String {
412 "Commands run directly on this machine, in the workspace directory.".into()
413 }
414}
415
416#[derive(Debug, Clone)]
421pub struct ContainerShell {
422 pub container_id: String,
423 pub workdir: PathBuf,
425}
426
427impl Shell for ContainerShell {
428 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
429 let mut cmd = Command::new("docker");
431 cmd.args(["exec", "-i", "-w"])
432 .arg(&self.workdir)
433 .arg(&self.container_id)
434 .args(["bash", "-lc", command]);
435 exec_command(cmd, timeout)
437 }
438
439 fn describe(&self) -> String {
440 format!(
441 "Commands run inside the project container at {}. Project dependencies are \
442 installed there, not on the host.",
443 self.workdir.display()
444 )
445 }
446}
447
448fn quote(s: &str) -> String {
450 format!("'{}'", s.replace('\'', r"'\''"))
451}
452
453pub fn inherited_path_prefix() -> String {
455 match std::env::var("PATH") {
456 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
457 _ => String::new(),
458 }
459}
460
461#[derive(Debug, Clone)]
463pub enum Launcher {
464 Local {
466 root: PathBuf,
467 profile: Option<Profile>,
468 },
469 Container {
471 container_id: String,
472 workdir: PathBuf,
473 },
474}
475
476impl Launcher {
477 fn command(&self) -> std::io::Result<Command> {
478 match self {
479 Launcher::Local { root, profile } => {
480 let mut c = match profile {
481 Some(Profile::Seatbelt(p)) => {
482 let mut cmd = Command::new("/usr/bin/sandbox-exec");
483 cmd.args(["-p", p, "bash", "-l"]);
484 cmd
485 }
486 Some(Profile::Landlock(paths)) => {
487 #[cfg(target_os = "linux")]
488 {
489 let mut cmd = Command::new("bash");
490 cmd.arg("-l");
491 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
492 cmd
493 }
494 #[cfg(not(target_os = "linux"))]
495 {
496 let _ = paths;
497 return Err(std::io::Error::new(
498 std::io::ErrorKind::Unsupported,
499 "Landlock is only supported on Linux",
500 ));
501 }
502 }
503 Some(Profile::LandlockOffline(paths)) => {
504 #[cfg(target_os = "linux")]
505 {
506 let mut cmd = Command::new("bash");
507 cmd.arg("-l");
508 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
509 cmd
510 }
511 #[cfg(not(target_os = "linux"))]
512 {
513 let _ = paths;
514 return Err(std::io::Error::new(
515 std::io::ErrorKind::Unsupported,
516 "Landlock is only supported on Linux",
517 ));
518 }
519 }
520 Some(Profile::LandlockConfined {
521 write,
522 read,
523 block_tcp,
524 }) => {
525 #[cfg(target_os = "linux")]
526 {
527 let mut cmd = Command::new("bash");
528 cmd.arg("-l");
529 crate::sandbox::landlock_pre_exec(
530 &mut cmd,
531 write,
532 Some(read),
533 *block_tcp,
534 )?;
535 cmd
536 }
537 #[cfg(not(target_os = "linux"))]
538 {
539 let _ = (write, read, block_tcp);
540 return Err(std::io::Error::new(
541 std::io::ErrorKind::Unsupported,
542 "Landlock is only supported on Linux",
543 ));
544 }
545 }
546 None => {
547 let mut cmd = Command::new("bash");
548 cmd.arg("-l");
549 cmd
550 }
551 };
552 c.current_dir(root);
553 scrub(&mut c);
554 Ok(c)
555 }
556 Launcher::Container {
557 container_id,
558 workdir,
559 } => {
560 let mut c = Command::new("docker");
561 c.args(["exec", "-i", "-w"])
562 .arg(workdir)
563 .arg(container_id)
564 .args(["bash", "-l"]);
565 Ok(c)
566 }
567 }
568 }
569
570 fn fallback(&self) -> Box<dyn Shell> {
573 match self {
574 Launcher::Local { profile, .. } => match profile {
575 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
576 None => Box::new(LocalShell),
577 },
578 Launcher::Container {
579 container_id,
580 workdir,
581 } => Box::new(ContainerShell {
582 container_id: container_id.clone(),
583 workdir: workdir.clone(),
584 }),
585 }
586 }
587}
588
589pub enum RunResult {
591 Done(Output),
592 TimedOut {
594 out: String,
595 err: String,
596 },
597 Died {
599 out: String,
600 err: String,
601 },
602}
603
604pub struct Session {
609 child: Child,
610 stdin: ChildStdin,
611 chunks: Receiver<Vec<u8>>,
612 buf: Vec<u8>,
613 tmp: String,
614 next: u64,
615 nonce: String,
616}
617
618const READY: &str = "__BLYTE_READY__ ";
619
620fn nonce() -> String {
622 let t = std::time::SystemTime::now()
623 .duration_since(std::time::UNIX_EPOCH)
624 .map(|d| d.as_nanos())
625 .unwrap_or(0);
626 format!("{t:x}{:x}", std::process::id())
627}
628
629enum ReadErr {
630 Timeout,
631 Closed,
632}
633
634impl Session {
635 pub fn start(launcher: &Launcher) -> Result<Session, String> {
636 let mut cmd = launcher
637 .command()
638 .map_err(|e| format!("cannot start a shell session: {e}"))?;
639 cmd.stdin(Stdio::piped())
640 .stdout(Stdio::piped())
641 .stderr(Stdio::null());
642 #[cfg(unix)]
643 {
644 use std::os::unix::process::CommandExt;
645 cmd.process_group(0);
646 }
647 let mut child = cmd
648 .spawn()
649 .map_err(|e| format!("cannot start a shell session: {e}"))?;
650 let stdin = child.stdin.take().ok_or("no stdin")?;
651 let mut stdout = child.stdout.take().ok_or("no stdout")?;
652 let (tx, rx) = mpsc::channel();
653 std::thread::spawn(move || {
654 let mut chunk = vec![0u8; 64 * 1024];
655 loop {
656 match stdout.read(&mut chunk) {
657 Ok(0) | Err(_) => break,
658 Ok(n) => {
659 if tx.send(chunk[..n].to_vec()).is_err() {
660 break;
661 }
662 }
663 }
664 }
665 });
666 let mut s = Session {
667 child,
668 stdin,
669 chunks: rx,
670 buf: Vec::new(),
671 tmp: String::new(),
672 next: 0,
673 nonce: nonce(),
674 };
675 let init = match launcher {
676 Launcher::Local { .. } => inherited_path_prefix(),
677 Launcher::Container { .. } => String::new(),
678 };
679 s.send(&format!(
680 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
681 echo \"__BLYTE_READY__ $__blyte_t\"\n",
682 ))?;
683 let deadline = Instant::now() + Duration::from_secs(30);
684 loop {
685 match s.read_line(deadline) {
686 Ok(l) if l.starts_with(READY) => {
687 s.tmp = l[READY.len()..].trim().to_string();
688 return Ok(s);
689 }
690 Ok(_) => continue, Err(_) => {
692 s.kill();
693 return Err("the shell session did not start".into());
694 }
695 }
696 }
697 }
698
699 fn send(&mut self, script: &str) -> Result<(), String> {
700 self.stdin
701 .write_all(script.as_bytes())
702 .and_then(|_| self.stdin.flush())
703 .map_err(|e| format!("the shell session closed: {e}"))
704 }
705
706 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
707 match self
708 .chunks
709 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
710 {
711 Ok(c) => {
712 self.buf.extend_from_slice(&c);
713 Ok(())
714 }
715 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
716 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
717 }
718 }
719
720 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
722 loop {
723 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
724 let line: Vec<u8> = self.buf.drain(..=i).collect();
725 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
726 }
727 self.fill(deadline)?;
728 }
729 }
730
731 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
733 while self.buf.len() < n {
734 self.fill(deadline)?;
735 }
736 Ok(self.buf.drain(..n).collect())
737 }
738
739 pub fn kill(&mut self) {
741 #[cfg(unix)]
742 {
743 let pgid = self.child.id() as i32;
744 if pgid > 0 {
745 unsafe {
746 libc::kill(-pgid, libc::SIGKILL);
747 }
748 }
749 }
750 let _ = self.child.kill();
751 let _ = self.child.wait();
752 }
753
754 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
757 let id = self.next;
758 self.next += 1;
759 let (out, err) = (
760 format!("{}/{id}.o", self.tmp),
761 format!("{}/{id}.e", self.tmp),
762 );
763 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
764 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
765 let body = match cwd {
766 Some(d) => format!(
767 "( cd {} && eval \"$__blyte_c\" )",
768 quote(&d.to_string_lossy())
769 ),
770 None => "eval \"$__blyte_c\"".to_string(),
771 };
772 let script = format!(
777 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
778 mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
779 IFS= read -r -d '' __blyte_o <{qo} || true; \
780 IFS= read -r -d '' __blyte_e <{qe} || true; \
781 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
782 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
783 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
784 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
785 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
786 );
787 if self.send(&script).is_err() {
788 return RunResult::Died { out, err };
789 }
790 let marker = format!("__BLYTE_{id}__ ");
791 let deadline = Instant::now() + timeout;
792 let fail = |e: ReadErr, out: String, err: String| match e {
793 ReadErr::Timeout => RunResult::TimedOut { out, err },
794 ReadErr::Closed => RunResult::Died { out, err },
795 };
796 let header = loop {
797 match self.read_line(deadline) {
798 Ok(l) => {
799 if let Some(rest) = l.strip_prefix(&marker) {
800 break rest.to_string();
801 }
802 }
803 Err(e) => return fail(e, out, err),
804 }
805 };
806 let mut f = header.split(' ');
807 let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
808 let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
809 let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
810 match self.read_exact(no + ne, deadline) {
811 Ok(bytes) => RunResult::Done(Output {
812 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
813 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
814 exit_code,
815 }),
816 Err(e) => fail(e, out, err),
817 }
818 }
819
820 fn close(&mut self) {
822 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
823 let deadline = Instant::now() + Duration::from_millis(300);
824 while Instant::now() < deadline {
825 if let Ok(Some(_)) = self.child.try_wait() {
826 return;
827 }
828 std::thread::sleep(Duration::from_millis(10));
829 }
830 self.kill();
831 }
832}
833
834pub struct PersistentShell {
843 launcher: Launcher,
844 harness: Mutex<Option<Session>>,
845 user: Mutex<Option<Session>>,
846 fallback: Box<dyn Shell>,
847}
848
849impl PersistentShell {
850 pub fn new(launcher: Launcher) -> Self {
851 let fallback = launcher.fallback();
852 Self {
853 launcher,
854 harness: Mutex::new(None),
855 user: Mutex::new(None),
856 fallback,
857 }
858 }
859
860 pub fn local(root: PathBuf) -> Self {
861 Self::new(Launcher::Local {
862 root,
863 profile: None,
864 })
865 }
866
867 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
868 Self::new(Launcher::Local {
869 root,
870 profile: Some(profile.into()),
871 })
872 }
873
874 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
875 Self::local_sandboxed(root, profile)
876 }
877
878 pub fn container(container_id: String, workdir: PathBuf) -> Self {
879 Self::new(Launcher::Container {
880 container_id,
881 workdir,
882 })
883 }
884
885 pub fn is_persistent(&self) -> bool {
887 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
888 if g.is_none() {
889 *g = Session::start(&self.launcher).ok();
890 }
891 g.is_some()
892 }
893
894 fn run(
896 &self,
897 slot: &Mutex<Option<Session>>,
898 command: &str,
899 cwd: Option<&Path>,
900 timeout: Duration,
901 ) -> Option<Result<Output, String>> {
902 let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
903 if g.is_none() {
904 *g = Session::start(&self.launcher).ok();
905 }
906 let session = g.as_mut()?;
907 let (out, err, note, code) = match session.run(command, cwd, timeout) {
908 RunResult::Done(o) => return Some(Ok(o)),
909 RunResult::TimedOut { out, err } => (
910 out,
911 err,
912 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
913 124,
914 ),
915 RunResult::Died { out, err } => (
916 out,
917 err,
918 "[the shell exited; the next command starts a fresh shell in the workspace root]"
919 .to_string(),
920 1,
921 ),
922 };
923 session.kill();
924 *g = None;
925 drop(g);
926 let cat = |p: &str| {
928 self.fallback
929 .exec(
930 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
931 Path::new("/"),
932 Duration::from_secs(30),
933 )
934 .map(|o| o.stdout)
935 .unwrap_or_default()
936 };
937 let (stdout, stderr) = (cat(&out), cat(&err));
938 Some(Ok(Output {
939 stdout,
940 stderr: format!("{stderr}{note}"),
941 exit_code: code,
942 }))
943 }
944}
945
946impl Shell for PersistentShell {
947 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
948 self.run(&self.harness, command, Some(cwd), timeout)
949 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
950 }
951
952 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
953 self.run(&self.user, command, None, timeout)
954 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
955 }
956
957 fn describe(&self) -> String {
958 format!(
959 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
960 later commands. File tools always resolve paths from the workspace root.",
961 self.fallback.describe()
962 )
963 }
964}
965
966impl Drop for PersistentShell {
967 fn drop(&mut self) {
968 for slot in [&self.harness, &self.user] {
969 if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
970 s.close();
971 }
972 }
973 }
974}