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_harness(cmd: &mut Command) {
140 for name in HARNESS_ENV {
141 cmd.env_remove(name);
142 }
143 for (name, _) in std::env::vars_os() {
144 let n = name.to_string_lossy();
145 if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
146 cmd.env_remove(&name);
147 }
148 }
149}
150
151fn scrub(cmd: &mut Command) {
153 scrub_harness(cmd);
154 for name in withheld_env() {
155 cmd.env_remove(name);
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct Output {
161 pub stdout: String,
162 pub stderr: String,
163 pub exit_code: i32,
164}
165
166impl Output {
167 pub fn merged(&self) -> String {
170 format!("{}{}", self.stdout, self.stderr)
171 }
172}
173
174pub trait Shell: Send + Sync {
175 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
177
178 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
182 self.exec(command, cwd, timeout)
183 }
184
185 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
186 let _ = (command, cwd, timeout);
187 Err("this shell cannot run a command outside the sandbox".into())
188 }
189
190 fn describe(&self) -> String;
193
194 fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
196 let probe = candidates
199 .iter()
200 .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
201 .collect::<Vec<_>>()
202 .join("; ");
203 match self.exec(&probe, cwd, Duration::from_secs(30)) {
204 Ok(o) => o
205 .stdout
206 .lines()
207 .map(|l| l.trim().to_string())
208 .filter(|l| !l.is_empty())
209 .collect(),
210 Err(_) => Vec::new(),
211 }
212 }
213}
214
215fn exec_command(mut cmd: Command, timeout: Duration) -> Result<Output, String> {
228 use std::process::Stdio;
229
230 cmd.stdin(Stdio::null())
234 .stdout(Stdio::piped())
235 .stderr(Stdio::piped());
236
237 #[cfg(unix)]
242 {
243 use std::os::unix::process::CommandExt;
244 cmd.process_group(0);
245 }
246
247 let mut child = cmd
248 .spawn()
249 .map_err(|e| format!("cannot run command: {e}"))?;
250
251 let mut so = child.stdout.take().ok_or("no stdout")?;
254 let mut se = child.stderr.take().ok_or("no stderr")?;
255 let t_out = std::thread::spawn(move || {
256 let mut b = String::new();
257 let _ = so.read_to_string(&mut b);
258 b
259 });
260 let t_err = std::thread::spawn(move || {
261 let mut b = String::new();
262 let _ = se.read_to_string(&mut b);
263 b
264 });
265
266 let deadline = std::time::Instant::now() + timeout;
267 let status = loop {
268 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
269 Some(s) => break Some(s),
270 None if std::time::Instant::now() >= deadline => {
271 #[cfg(unix)]
275 {
276 let pgid = child.id() as i32;
277 if pgid > 0 {
278 unsafe {
279 libc::kill(-pgid, libc::SIGKILL);
280 }
281 } else {
282 let _ = child.kill();
283 }
284 }
285 #[cfg(not(unix))]
286 {
287 let _ = child.kill();
288 }
289 let _ = child.wait();
290 break None;
291 }
292 None => std::thread::sleep(Duration::from_millis(50)),
293 }
294 };
295
296 let stdout = t_out.join().unwrap_or_default();
297 let stderr = t_err.join().unwrap_or_default();
298
299 match status {
300 Some(s) => Ok(Output {
301 stdout,
302 stderr,
303 exit_code: s.code().unwrap_or(-1),
304 }),
305 None => Ok(Output {
308 stdout,
309 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
310 exit_code: 124, }),
312 }
313}
314
315#[derive(Debug, Default, Clone, PartialEq, Eq)]
317pub struct LocalShell {
318 pub profile: Option<Profile>,
319}
320
321#[allow(non_upper_case_globals)]
322pub const LocalShell: LocalShell = LocalShell { profile: None };
323
324impl LocalShell {
325 pub fn new() -> Self {
327 Self { profile: None }
328 }
329
330 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
332 Self {
333 profile: Some(profile.into()),
334 }
335 }
336}
337
338impl Shell for LocalShell {
339 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
340 let full_command = inherited_path_prefix() + command;
341 let command = full_command.as_str();
342 let mut cmd = match &self.profile {
343 Some(Profile::Seatbelt(profile)) => {
344 let mut c = Command::new("/usr/bin/sandbox-exec");
345 c.args(["-p", profile, "bash", "-lc", command]);
346 c
347 }
348 Some(Profile::Landlock(paths)) => {
349 #[cfg(target_os = "linux")]
350 {
351 let mut c = Command::new("bash");
352 c.arg("-lc").arg(command);
353 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
354 .map_err(|e| e.to_string())?;
355 c
356 }
357 #[cfg(not(target_os = "linux"))]
358 {
359 let _ = paths;
360 return Err(std::io::Error::new(
361 std::io::ErrorKind::Unsupported,
362 "Landlock is only supported on Linux",
363 )
364 .to_string());
365 }
366 }
367 Some(Profile::LandlockOffline(paths)) => {
368 #[cfg(target_os = "linux")]
369 {
370 let mut c = Command::new("bash");
371 c.arg("-lc").arg(command);
372 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
373 .map_err(|e| e.to_string())?;
374 c
375 }
376 #[cfg(not(target_os = "linux"))]
377 {
378 let _ = paths;
379 return Err(std::io::Error::new(
380 std::io::ErrorKind::Unsupported,
381 "Landlock is only supported on Linux",
382 )
383 .to_string());
384 }
385 }
386 Some(Profile::LandlockConfined {
387 write,
388 read,
389 block_tcp,
390 }) => {
391 #[cfg(target_os = "linux")]
392 {
393 let mut c = Command::new("bash");
394 c.arg("-lc").arg(command);
395 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
396 .map_err(|e| e.to_string())?;
397 c
398 }
399 #[cfg(not(target_os = "linux"))]
400 {
401 let _ = (write, read, block_tcp);
402 return Err(std::io::Error::new(
403 std::io::ErrorKind::Unsupported,
404 "Landlock is only supported on Linux",
405 )
406 .to_string());
407 }
408 }
409 None => {
410 let mut c = Command::new("bash");
411 c.arg("-lc").arg(command);
412 c
413 }
414 };
415 cmd.current_dir(cwd);
416 scrub(&mut cmd);
417 exec_command(cmd, timeout)
418 }
419
420 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
421 let full_command = inherited_path_prefix() + command;
422 let mut cmd = Command::new("bash");
423 cmd.arg("-lc").arg(&full_command);
424 cmd.current_dir(cwd);
425 scrub_harness(&mut cmd);
426 exec_command(cmd, timeout)
427 }
428
429 fn describe(&self) -> String {
430 "Commands run directly on this machine, in the workspace directory.".into()
431 }
432}
433
434#[derive(Debug, Clone)]
439pub struct ContainerShell {
440 pub container_id: String,
441 pub workdir: PathBuf,
443}
444
445impl Shell for ContainerShell {
446 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
447 let mut cmd = Command::new("docker");
449 cmd.args(["exec", "-i", "-w"])
450 .arg(&self.workdir)
451 .arg(&self.container_id)
452 .args(["bash", "-lc", command]);
453 exec_command(cmd, timeout)
455 }
456
457 fn describe(&self) -> String {
458 format!(
459 "Commands run inside the project container at {}. Project dependencies are \
460 installed there, not on the host.",
461 self.workdir.display()
462 )
463 }
464}
465
466fn quote(s: &str) -> String {
468 format!("'{}'", s.replace('\'', r"'\''"))
469}
470
471pub fn inherited_path_prefix() -> String {
473 match std::env::var("PATH") {
474 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
475 _ => String::new(),
476 }
477}
478
479#[derive(Debug, Clone)]
481pub enum Launcher {
482 Local {
484 root: PathBuf,
485 profile: Option<Profile>,
486 },
487 Container {
489 container_id: String,
490 workdir: PathBuf,
491 },
492}
493
494impl Launcher {
495 fn command(&self) -> std::io::Result<Command> {
496 match self {
497 Launcher::Local { root, profile } => {
498 let mut c = match profile {
499 Some(Profile::Seatbelt(p)) => {
500 let mut cmd = Command::new("/usr/bin/sandbox-exec");
501 cmd.args(["-p", p, "bash", "-l"]);
502 cmd
503 }
504 Some(Profile::Landlock(paths)) => {
505 #[cfg(target_os = "linux")]
506 {
507 let mut cmd = Command::new("bash");
508 cmd.arg("-l");
509 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
510 cmd
511 }
512 #[cfg(not(target_os = "linux"))]
513 {
514 let _ = paths;
515 return Err(std::io::Error::new(
516 std::io::ErrorKind::Unsupported,
517 "Landlock is only supported on Linux",
518 ));
519 }
520 }
521 Some(Profile::LandlockOffline(paths)) => {
522 #[cfg(target_os = "linux")]
523 {
524 let mut cmd = Command::new("bash");
525 cmd.arg("-l");
526 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
527 cmd
528 }
529 #[cfg(not(target_os = "linux"))]
530 {
531 let _ = paths;
532 return Err(std::io::Error::new(
533 std::io::ErrorKind::Unsupported,
534 "Landlock is only supported on Linux",
535 ));
536 }
537 }
538 Some(Profile::LandlockConfined {
539 write,
540 read,
541 block_tcp,
542 }) => {
543 #[cfg(target_os = "linux")]
544 {
545 let mut cmd = Command::new("bash");
546 cmd.arg("-l");
547 crate::sandbox::landlock_pre_exec(
548 &mut cmd,
549 write,
550 Some(read),
551 *block_tcp,
552 )?;
553 cmd
554 }
555 #[cfg(not(target_os = "linux"))]
556 {
557 let _ = (write, read, block_tcp);
558 return Err(std::io::Error::new(
559 std::io::ErrorKind::Unsupported,
560 "Landlock is only supported on Linux",
561 ));
562 }
563 }
564 None => {
565 let mut cmd = Command::new("bash");
566 cmd.arg("-l");
567 cmd
568 }
569 };
570 c.current_dir(root);
571 scrub(&mut c);
572 Ok(c)
573 }
574 Launcher::Container {
575 container_id,
576 workdir,
577 } => {
578 let mut c = Command::new("docker");
579 c.args(["exec", "-i", "-w"])
580 .arg(workdir)
581 .arg(container_id)
582 .args(["bash", "-l"]);
583 Ok(c)
584 }
585 }
586 }
587
588 fn fallback(&self) -> Box<dyn Shell> {
591 match self {
592 Launcher::Local { profile, .. } => match profile {
593 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
594 None => Box::new(LocalShell),
595 },
596 Launcher::Container {
597 container_id,
598 workdir,
599 } => Box::new(ContainerShell {
600 container_id: container_id.clone(),
601 workdir: workdir.clone(),
602 }),
603 }
604 }
605}
606
607pub enum RunResult {
609 Done(Output),
610 TimedOut {
612 out: String,
613 err: String,
614 },
615 Died {
617 out: String,
618 err: String,
619 },
620}
621
622pub struct Session {
627 child: Child,
628 stdin: ChildStdin,
629 chunks: Receiver<Vec<u8>>,
630 buf: Vec<u8>,
631 tmp: String,
632 next: u64,
633 nonce: String,
634}
635
636const READY: &str = "__BLYTE_READY__ ";
637
638fn nonce() -> String {
640 let t = std::time::SystemTime::now()
641 .duration_since(std::time::UNIX_EPOCH)
642 .map(|d| d.as_nanos())
643 .unwrap_or(0);
644 format!("{t:x}{:x}", std::process::id())
645}
646
647enum ReadErr {
648 Timeout,
649 Closed,
650}
651
652impl Session {
653 pub fn start(launcher: &Launcher) -> Result<Session, String> {
654 let mut cmd = launcher
655 .command()
656 .map_err(|e| format!("cannot start a shell session: {e}"))?;
657 cmd.stdin(Stdio::piped())
658 .stdout(Stdio::piped())
659 .stderr(Stdio::null());
660 #[cfg(unix)]
661 {
662 use std::os::unix::process::CommandExt;
663 cmd.process_group(0);
664 }
665 let mut child = cmd
666 .spawn()
667 .map_err(|e| format!("cannot start a shell session: {e}"))?;
668 let stdin = child.stdin.take().ok_or("no stdin")?;
669 let mut stdout = child.stdout.take().ok_or("no stdout")?;
670 let (tx, rx) = mpsc::channel();
671 std::thread::spawn(move || {
672 let mut chunk = vec![0u8; 64 * 1024];
673 loop {
674 match stdout.read(&mut chunk) {
675 Ok(0) | Err(_) => break,
676 Ok(n) => {
677 if tx.send(chunk[..n].to_vec()).is_err() {
678 break;
679 }
680 }
681 }
682 }
683 });
684 let mut s = Session {
685 child,
686 stdin,
687 chunks: rx,
688 buf: Vec::new(),
689 tmp: String::new(),
690 next: 0,
691 nonce: nonce(),
692 };
693 let init = match launcher {
694 Launcher::Local { .. } => inherited_path_prefix(),
695 Launcher::Container { .. } => String::new(),
696 };
697 s.send(&format!(
698 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
699 echo \"__BLYTE_READY__ $__blyte_t\"\n",
700 ))?;
701 let deadline = Instant::now() + Duration::from_secs(30);
702 loop {
703 match s.read_line(deadline) {
704 Ok(l) if l.starts_with(READY) => {
705 s.tmp = l[READY.len()..].trim().to_string();
706 return Ok(s);
707 }
708 Ok(_) => continue, Err(_) => {
710 s.kill();
711 return Err("the shell session did not start".into());
712 }
713 }
714 }
715 }
716
717 fn send(&mut self, script: &str) -> Result<(), String> {
718 self.stdin
719 .write_all(script.as_bytes())
720 .and_then(|_| self.stdin.flush())
721 .map_err(|e| format!("the shell session closed: {e}"))
722 }
723
724 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
725 match self
726 .chunks
727 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
728 {
729 Ok(c) => {
730 self.buf.extend_from_slice(&c);
731 Ok(())
732 }
733 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
734 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
735 }
736 }
737
738 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
740 loop {
741 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
742 let line: Vec<u8> = self.buf.drain(..=i).collect();
743 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
744 }
745 self.fill(deadline)?;
746 }
747 }
748
749 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
751 while self.buf.len() < n {
752 self.fill(deadline)?;
753 }
754 Ok(self.buf.drain(..n).collect())
755 }
756
757 pub fn kill(&mut self) {
759 #[cfg(unix)]
760 {
761 let pgid = self.child.id() as i32;
762 if pgid > 0 {
763 unsafe {
764 libc::kill(-pgid, libc::SIGKILL);
765 }
766 }
767 }
768 let _ = self.child.kill();
769 let _ = self.child.wait();
770 }
771
772 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
775 let id = self.next;
776 self.next += 1;
777 let (out, err) = (
778 format!("{}/{id}.o", self.tmp),
779 format!("{}/{id}.e", self.tmp),
780 );
781 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
782 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
783 let body = match cwd {
784 Some(d) => format!(
785 "( cd {} && eval \"$__blyte_c\" )",
786 quote(&d.to_string_lossy())
787 ),
788 None => "eval \"$__blyte_c\"".to_string(),
789 };
790 let script = format!(
795 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
796 mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
797 IFS= read -r -d '' __blyte_o <{qo} || true; \
798 IFS= read -r -d '' __blyte_e <{qe} || true; \
799 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
800 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
801 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
802 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
803 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
804 );
805 if self.send(&script).is_err() {
806 return RunResult::Died { out, err };
807 }
808 let marker = format!("__BLYTE_{id}__ ");
809 let deadline = Instant::now() + timeout;
810 let fail = |e: ReadErr, out: String, err: String| match e {
811 ReadErr::Timeout => RunResult::TimedOut { out, err },
812 ReadErr::Closed => RunResult::Died { out, err },
813 };
814 let header = loop {
815 match self.read_line(deadline) {
816 Ok(l) => {
817 if let Some(rest) = l.strip_prefix(&marker) {
818 break rest.to_string();
819 }
820 }
821 Err(e) => return fail(e, out, err),
822 }
823 };
824 let mut f = header.split(' ');
825 let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
826 let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
827 let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
828 match self.read_exact(no + ne, deadline) {
829 Ok(bytes) => RunResult::Done(Output {
830 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
831 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
832 exit_code,
833 }),
834 Err(e) => fail(e, out, err),
835 }
836 }
837
838 fn close(&mut self) {
840 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
841 let deadline = Instant::now() + Duration::from_millis(300);
842 while Instant::now() < deadline {
843 if let Ok(Some(_)) = self.child.try_wait() {
844 return;
845 }
846 std::thread::sleep(Duration::from_millis(10));
847 }
848 self.kill();
849 }
850}
851
852pub struct PersistentShell {
861 launcher: Launcher,
862 harness: Mutex<Option<Session>>,
863 user: Mutex<Option<Session>>,
864 fallback: Box<dyn Shell>,
865}
866
867impl PersistentShell {
868 pub fn new(launcher: Launcher) -> Self {
869 let fallback = launcher.fallback();
870 Self {
871 launcher,
872 harness: Mutex::new(None),
873 user: Mutex::new(None),
874 fallback,
875 }
876 }
877
878 pub fn local(root: PathBuf) -> Self {
879 Self::new(Launcher::Local {
880 root,
881 profile: None,
882 })
883 }
884
885 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
886 Self::new(Launcher::Local {
887 root,
888 profile: Some(profile.into()),
889 })
890 }
891
892 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
893 Self::local_sandboxed(root, profile)
894 }
895
896 pub fn container(container_id: String, workdir: PathBuf) -> Self {
897 Self::new(Launcher::Container {
898 container_id,
899 workdir,
900 })
901 }
902
903 pub fn is_persistent(&self) -> bool {
905 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
906 if g.is_none() {
907 *g = Session::start(&self.launcher).ok();
908 }
909 g.is_some()
910 }
911
912 fn run(
914 &self,
915 slot: &Mutex<Option<Session>>,
916 command: &str,
917 cwd: Option<&Path>,
918 timeout: Duration,
919 ) -> Option<Result<Output, String>> {
920 let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
921 if g.is_none() {
922 *g = Session::start(&self.launcher).ok();
923 }
924 let session = g.as_mut()?;
925 let (out, err, note, code) = match session.run(command, cwd, timeout) {
926 RunResult::Done(o) => return Some(Ok(o)),
927 RunResult::TimedOut { out, err } => (
928 out,
929 err,
930 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
931 124,
932 ),
933 RunResult::Died { out, err } => (
934 out,
935 err,
936 "[the shell exited; the next command starts a fresh shell in the workspace root]"
937 .to_string(),
938 1,
939 ),
940 };
941 session.kill();
942 *g = None;
943 drop(g);
944 let cat = |p: &str| {
946 self.fallback
947 .exec(
948 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
949 Path::new("/"),
950 Duration::from_secs(30),
951 )
952 .map(|o| o.stdout)
953 .unwrap_or_default()
954 };
955 let (stdout, stderr) = (cat(&out), cat(&err));
956 Some(Ok(Output {
957 stdout,
958 stderr: format!("{stderr}{note}"),
959 exit_code: code,
960 }))
961 }
962}
963
964impl Shell for PersistentShell {
965 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
966 self.run(&self.harness, command, Some(cwd), timeout)
967 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
968 }
969
970 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
971 self.run(&self.user, command, None, timeout)
972 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
973 }
974
975 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
976 self.fallback.exec_host(command, cwd, timeout)
977 }
978
979 fn describe(&self) -> String {
980 format!(
981 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
982 later commands. File tools always resolve paths from the workspace root.",
983 self.fallback.describe()
984 )
985 }
986}
987
988impl Drop for PersistentShell {
989 fn drop(&mut self) {
990 for slot in [&self.harness, &self.user] {
991 if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
992 s.close();
993 }
994 }
995 }
996}