1use std::io::{Read, Write};
23use std::path::{Path, PathBuf};
24use std::process::{Child, ChildStdin, Command, Stdio};
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30use crate::sandbox::Profile;
31
32pub const HARNESS_ENV: &[&str] = &[
39 "GEMINI_API_KEY",
40 "GOOGLE_API_KEY",
41 "ANTHROPIC_API_KEY",
42 "OLLAMA_API_KEY",
43 "OLLAMA_HOST",
44 "OPENAI_API_KEY",
45 "OPENAI_BASE_URL",
46 "OPENROUTER_API_KEY",
47];
48
49const CREDENTIAL_SEGMENTS: &[&str] = &[
50 "TOKEN",
51 "SECRET",
52 "SECRETS",
53 "PASSWORD",
54 "PASSWD",
55 "PASS",
56 "KEY",
57 "CREDENTIAL",
58 "CREDENTIALS",
59 "AUTH",
60 "COOKIE",
61 "SESSION",
62];
63
64const CREDENTIAL_NAMES: &[&str] = &["AWS_PROFILE", "AWS_DEFAULT_PROFILE"];
67
68static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
69
70pub fn credential_like(name: &str, value: &str) -> bool {
73 let upper = name.to_ascii_uppercase();
74 if CREDENTIAL_NAMES.contains(&upper.as_str()) {
75 return true;
76 }
77 if upper
78 .split('_')
79 .any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
80 {
81 return true;
82 }
83 has_inline_credentials(value)
84}
85
86fn has_inline_credentials(value: &str) -> bool {
87 let mut rest = value;
88 while let Some(idx) = rest.find("://") {
89 let after_scheme = &rest[idx + 3..];
90 let len = after_scheme
91 .find(|c: char| c == '/' || c.is_whitespace())
92 .unwrap_or(after_scheme.len());
93 let authority_prefix = &after_scheme[..len];
94 if let Some((userinfo, _)) = authority_prefix.split_once('@') {
95 if let Some((_user, pass)) = userinfo.split_once(':') {
96 if !pass.is_empty() {
97 return true;
98 }
99 }
100 }
101 rest = after_scheme;
102 }
103 false
104}
105
106pub fn set_pass_env(names: Vec<String>) {
110 let _ = PASS_ENV.set(names);
111}
112
113pub fn withheld_env() -> Vec<String> {
115 let pass_env = PASS_ENV.get();
116 let mut withheld = Vec::new();
117 for (key, val) in std::env::vars_os() {
118 let name = key.to_string_lossy();
119 if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
120 continue;
121 }
122 if name.starts_with("BLYTE_") {
123 continue;
124 }
125 if let Some(passed) = pass_env {
126 if passed.iter().any(|p| p == name.as_ref()) {
127 continue;
128 }
129 }
130 let value = val.to_string_lossy();
131 if credential_like(&name, &value) {
132 withheld.push(name.into_owned());
133 }
134 }
135 withheld.sort();
136 withheld.dedup();
137 withheld
138}
139
140fn scrub_harness(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}
151
152fn scrub(cmd: &mut Command) {
154 scrub_harness(cmd);
155 for name in withheld_env() {
156 cmd.env_remove(name);
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct Output {
162 pub stdout: String,
163 pub stderr: String,
164 pub exit_code: i32,
165}
166
167impl Output {
168 pub fn merged(&self) -> String {
171 format!("{}{}", self.stdout, self.stderr)
172 }
173}
174
175pub trait Shell: Send + Sync {
176 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
178
179 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
183 self.exec(command, cwd, timeout)
184 }
185
186 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
187 let _ = (command, cwd, timeout);
188 Err("this shell cannot run a command outside the sandbox".into())
189 }
190
191 fn describe(&self) -> String;
194
195 fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
197 let probe = candidates
200 .iter()
201 .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
202 .collect::<Vec<_>>()
203 .join("; ");
204 match self.exec(&probe, cwd, Duration::from_secs(30)) {
205 Ok(o) => o
206 .stdout
207 .lines()
208 .map(|l| l.trim().to_string())
209 .filter(|l| !l.is_empty())
210 .collect(),
211 Err(_) => Vec::new(),
212 }
213 }
214}
215
216#[derive(Debug, Default)]
218pub struct CancelHandle {
219 cancelled: AtomicBool,
220 active_pgid: Mutex<Option<i32>>,
221}
222
223impl CancelHandle {
224 pub fn new() -> Self {
225 Self::default()
226 }
227
228 pub fn is_cancelled(&self) -> bool {
229 self.cancelled.load(Ordering::SeqCst)
230 }
231
232 pub fn flag(&self) -> &AtomicBool {
233 &self.cancelled
234 }
235
236 pub fn cancel(&self) {
237 let pgid = {
238 let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
239 self.cancelled.store(true, Ordering::SeqCst);
240 *guard
241 };
242 #[cfg(unix)]
243 if let Some(pgid) = pgid {
244 if pgid > 0 {
245 unsafe {
246 libc::kill(-pgid, libc::SIGKILL);
247 }
248 }
249 }
250 #[cfg(not(unix))]
251 let _ = pgid;
252 }
253
254 fn register_pgid(&self, pgid: i32) -> bool {
255 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
256 if self.cancelled.load(Ordering::SeqCst) {
257 return false;
258 }
259 *guard = Some(pgid);
260 true
261 }
262
263 fn clear_pgid(&self) {
264 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
265 *guard = None;
266 }
267}
268
269fn kill_child_group(child: &mut Child) {
270 #[cfg(unix)]
274 {
275 let pgid = child.id() as i32;
276 if pgid > 0 {
277 unsafe {
278 libc::kill(-pgid, libc::SIGKILL);
279 }
280 } else {
281 let _ = child.kill();
282 }
283 }
284 #[cfg(not(unix))]
285 {
286 let _ = child.kill();
287 }
288 let _ = child.wait();
289}
290
291fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
304 exec_command_cancellable(cmd, timeout, None)
305}
306
307fn exec_command_cancellable(
308 mut cmd: Command,
309 timeout: Duration,
310 cancel: Option<&CancelHandle>,
311) -> Result<Output, String> {
312 use std::process::Stdio;
313
314 if cancel.is_some_and(CancelHandle::is_cancelled) {
315 return Err("command cancelled".into());
316 }
317
318 cmd.stdin(Stdio::null())
322 .stdout(Stdio::piped())
323 .stderr(Stdio::piped());
324
325 #[cfg(unix)]
330 {
331 use std::os::unix::process::CommandExt;
332 cmd.process_group(0);
333 }
334
335 let mut child = cmd
336 .spawn()
337 .map_err(|e| format!("cannot run command: {e}"))?;
338
339 if let Some(handle) = cancel {
340 if !handle.register_pgid(child.id() as i32) {
341 kill_child_group(&mut child);
342 return Err("command cancelled".into());
343 }
344 }
345
346 let mut so = child.stdout.take().ok_or("no stdout")?;
349 let mut se = child.stderr.take().ok_or("no stderr")?;
350 let t_out = std::thread::spawn(move || {
351 let mut b = String::new();
352 let _ = so.read_to_string(&mut b);
353 b
354 });
355 let t_err = std::thread::spawn(move || {
356 let mut b = String::new();
357 let _ = se.read_to_string(&mut b);
358 b
359 });
360
361 let deadline = std::time::Instant::now() + timeout;
362 let mut was_cancelled = false;
363 let status = loop {
364 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
365 Some(s) => break Some(s),
366 None if cancel.is_some_and(CancelHandle::is_cancelled) => {
367 was_cancelled = true;
368 kill_child_group(&mut child);
369 break None;
370 }
371 None if std::time::Instant::now() >= deadline => {
372 kill_child_group(&mut child);
373 break None;
374 }
375 None => std::thread::sleep(Duration::from_millis(50)),
376 }
377 };
378
379 if let Some(handle) = cancel {
380 handle.clear_pgid();
381 }
382
383 let stdout = t_out.join().unwrap_or_default();
384 let stderr = t_err.join().unwrap_or_default();
385
386 if was_cancelled {
387 return Err("command cancelled".into());
388 }
389
390 match status {
391 Some(s) => Ok(Output {
392 stdout,
393 stderr,
394 exit_code: s.code().unwrap_or(-1),
395 }),
396 None => Ok(Output {
399 stdout,
400 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
401 exit_code: 124, }),
403 }
404}
405
406#[derive(Debug, Default, Clone, PartialEq, Eq)]
408pub struct LocalShell {
409 pub profile: Option<Profile>,
410}
411
412#[allow(non_upper_case_globals)]
413pub const LocalShell: LocalShell = LocalShell { profile: None };
414
415impl LocalShell {
416 pub fn new() -> Self {
418 Self { profile: None }
419 }
420
421 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
423 Self {
424 profile: Some(profile.into()),
425 }
426 }
427
428 fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
429 let full_command = inherited_path_prefix() + command;
430 let command = full_command.as_str();
431 let mut cmd = match &self.profile {
432 Some(Profile::Seatbelt(profile)) => {
433 let mut c = Command::new("/usr/bin/sandbox-exec");
434 c.args(["-p", profile, "bash", "-lc", command]);
435 c
436 }
437 Some(Profile::Landlock(paths)) => {
438 #[cfg(target_os = "linux")]
439 {
440 let mut c = Command::new("bash");
441 c.arg("-lc").arg(command);
442 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
443 .map_err(|e| e.to_string())?;
444 c
445 }
446 #[cfg(not(target_os = "linux"))]
447 {
448 let _ = paths;
449 return Err(std::io::Error::new(
450 std::io::ErrorKind::Unsupported,
451 "Landlock is only supported on Linux",
452 )
453 .to_string());
454 }
455 }
456 Some(Profile::LandlockOffline(paths)) => {
457 #[cfg(target_os = "linux")]
458 {
459 let mut c = Command::new("bash");
460 c.arg("-lc").arg(command);
461 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
462 .map_err(|e| e.to_string())?;
463 c
464 }
465 #[cfg(not(target_os = "linux"))]
466 {
467 let _ = paths;
468 return Err(std::io::Error::new(
469 std::io::ErrorKind::Unsupported,
470 "Landlock is only supported on Linux",
471 )
472 .to_string());
473 }
474 }
475 Some(Profile::LandlockConfined {
476 write,
477 read,
478 block_tcp,
479 }) => {
480 #[cfg(target_os = "linux")]
481 {
482 let mut c = Command::new("bash");
483 c.arg("-lc").arg(command);
484 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
485 .map_err(|e| e.to_string())?;
486 c
487 }
488 #[cfg(not(target_os = "linux"))]
489 {
490 let _ = (write, read, block_tcp);
491 return Err(std::io::Error::new(
492 std::io::ErrorKind::Unsupported,
493 "Landlock is only supported on Linux",
494 )
495 .to_string());
496 }
497 }
498 None => {
499 let mut c = Command::new("bash");
500 c.arg("-lc").arg(command);
501 c
502 }
503 };
504 cmd.current_dir(cwd);
505 scrub(&mut cmd);
506 Ok(cmd)
507 }
508}
509
510impl Shell for LocalShell {
511 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
512 let cmd = self.build_command(command, cwd)?;
513 exec_command(cmd, timeout)
514 }
515
516 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
517 let full_command = inherited_path_prefix() + command;
518 let mut cmd = Command::new("bash");
519 cmd.arg("-lc").arg(&full_command);
520 cmd.current_dir(cwd);
521 scrub_harness(&mut cmd);
522 exec_command(cmd, timeout)
523 }
524
525 fn describe(&self) -> String {
526 "Commands run directly on this machine, in the workspace directory.".into()
527 }
528}
529
530#[derive(Debug, Clone)]
532pub struct CancellableLocalShell {
533 pub inner: LocalShell,
534 pub cancel: Arc<CancelHandle>,
535}
536
537impl Shell for CancellableLocalShell {
538 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
539 let cmd = self.inner.build_command(command, cwd)?;
540 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
541 }
542
543 fn describe(&self) -> String {
544 self.inner.describe()
545 }
546}
547
548#[derive(Debug, Clone)]
553pub struct ContainerShell {
554 pub container_id: String,
555 pub workdir: PathBuf,
557}
558
559impl ContainerShell {
560 fn build_command(&self, command: &str) -> Command {
561 let mut cmd = Command::new("docker");
562 cmd.args(["exec", "-i", "-w"])
563 .arg(&self.workdir)
564 .arg(&self.container_id)
565 .args(["bash", "-lc", command]);
566 cmd
567 }
568}
569
570impl Shell for ContainerShell {
571 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
572 exec_command(self.build_command(command), timeout)
573 }
574
575 fn describe(&self) -> String {
576 format!(
577 "Commands run inside the project container at {}. Project dependencies are \
578 installed there, not on the host.",
579 self.workdir.display()
580 )
581 }
582}
583
584#[derive(Debug, Clone)]
586pub struct CancellableContainerShell {
587 pub inner: ContainerShell,
588 pub cancel: Arc<CancelHandle>,
589}
590
591impl Shell for CancellableContainerShell {
592 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
593 exec_command_cancellable(
594 self.inner.build_command(command),
595 timeout,
596 Some(&self.cancel),
597 )
598 }
599
600 fn describe(&self) -> String {
601 self.inner.describe()
602 }
603}
604
605fn quote(s: &str) -> String {
607 format!("'{}'", s.replace('\'', r"'\''"))
608}
609
610pub fn inherited_path_prefix() -> String {
612 match std::env::var("PATH") {
613 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
614 _ => String::new(),
615 }
616}
617
618#[derive(Debug, Clone)]
620pub enum Launcher {
621 Local {
623 root: PathBuf,
624 profile: Option<Profile>,
625 },
626 Container {
628 container_id: String,
629 workdir: PathBuf,
630 },
631}
632
633impl Launcher {
634 fn command(&self) -> std::io::Result<Command> {
635 match self {
636 Launcher::Local { root, profile } => {
637 let mut c = match profile {
638 Some(Profile::Seatbelt(p)) => {
639 let mut cmd = Command::new("/usr/bin/sandbox-exec");
640 cmd.args(["-p", p, "bash", "-l"]);
641 cmd
642 }
643 Some(Profile::Landlock(paths)) => {
644 #[cfg(target_os = "linux")]
645 {
646 let mut cmd = Command::new("bash");
647 cmd.arg("-l");
648 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
649 cmd
650 }
651 #[cfg(not(target_os = "linux"))]
652 {
653 let _ = paths;
654 return Err(std::io::Error::new(
655 std::io::ErrorKind::Unsupported,
656 "Landlock is only supported on Linux",
657 ));
658 }
659 }
660 Some(Profile::LandlockOffline(paths)) => {
661 #[cfg(target_os = "linux")]
662 {
663 let mut cmd = Command::new("bash");
664 cmd.arg("-l");
665 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
666 cmd
667 }
668 #[cfg(not(target_os = "linux"))]
669 {
670 let _ = paths;
671 return Err(std::io::Error::new(
672 std::io::ErrorKind::Unsupported,
673 "Landlock is only supported on Linux",
674 ));
675 }
676 }
677 Some(Profile::LandlockConfined {
678 write,
679 read,
680 block_tcp,
681 }) => {
682 #[cfg(target_os = "linux")]
683 {
684 let mut cmd = Command::new("bash");
685 cmd.arg("-l");
686 crate::sandbox::landlock_pre_exec(
687 &mut cmd,
688 write,
689 Some(read),
690 *block_tcp,
691 )?;
692 cmd
693 }
694 #[cfg(not(target_os = "linux"))]
695 {
696 let _ = (write, read, block_tcp);
697 return Err(std::io::Error::new(
698 std::io::ErrorKind::Unsupported,
699 "Landlock is only supported on Linux",
700 ));
701 }
702 }
703 None => {
704 let mut cmd = Command::new("bash");
705 cmd.arg("-l");
706 cmd
707 }
708 };
709 c.current_dir(root);
710 scrub(&mut c);
711 Ok(c)
712 }
713 Launcher::Container {
714 container_id,
715 workdir,
716 } => {
717 let mut c = Command::new("docker");
718 c.args(["exec", "-i", "-w"])
719 .arg(workdir)
720 .arg(container_id)
721 .args(["bash", "-l"]);
722 Ok(c)
723 }
724 }
725 }
726
727 fn fallback(&self) -> Box<dyn Shell> {
730 match self {
731 Launcher::Local { profile, .. } => match profile {
732 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
733 None => Box::new(LocalShell),
734 },
735 Launcher::Container {
736 container_id,
737 workdir,
738 } => Box::new(ContainerShell {
739 container_id: container_id.clone(),
740 workdir: workdir.clone(),
741 }),
742 }
743 }
744}
745
746pub enum RunResult {
748 Done(Output),
749 TimedOut {
751 out: String,
752 err: String,
753 },
754 Died {
756 out: String,
757 err: String,
758 },
759}
760
761pub struct Session {
766 child: Child,
767 stdin: ChildStdin,
768 chunks: Receiver<Vec<u8>>,
769 buf: Vec<u8>,
770 tmp: String,
771 next: u64,
772 nonce: String,
773}
774
775const READY: &str = "__BLYTE_READY__ ";
776
777fn nonce() -> String {
779 let t = std::time::SystemTime::now()
780 .duration_since(std::time::UNIX_EPOCH)
781 .map(|d| d.as_nanos())
782 .unwrap_or(0);
783 format!("{t:x}{:x}", std::process::id())
784}
785
786enum ReadErr {
787 Timeout,
788 Closed,
789}
790
791impl Session {
792 pub fn start(launcher: &Launcher) -> Result<Session, String> {
793 let mut cmd = launcher
794 .command()
795 .map_err(|e| format!("cannot start a shell session: {e}"))?;
796 cmd.stdin(Stdio::piped())
797 .stdout(Stdio::piped())
798 .stderr(Stdio::null());
799 #[cfg(unix)]
800 {
801 use std::os::unix::process::CommandExt;
802 cmd.process_group(0);
803 }
804 let mut child = cmd
805 .spawn()
806 .map_err(|e| format!("cannot start a shell session: {e}"))?;
807 let stdin = child.stdin.take().ok_or("no stdin")?;
808 let mut stdout = child.stdout.take().ok_or("no stdout")?;
809 let (tx, rx) = mpsc::channel();
810 std::thread::spawn(move || {
811 let mut chunk = vec![0u8; 64 * 1024];
812 loop {
813 match stdout.read(&mut chunk) {
814 Ok(0) | Err(_) => break,
815 Ok(n) => {
816 if tx.send(chunk[..n].to_vec()).is_err() {
817 break;
818 }
819 }
820 }
821 }
822 });
823 let mut s = Session {
824 child,
825 stdin,
826 chunks: rx,
827 buf: Vec::new(),
828 tmp: String::new(),
829 next: 0,
830 nonce: nonce(),
831 };
832 let init = match launcher {
833 Launcher::Local { .. } => inherited_path_prefix(),
834 Launcher::Container { .. } => String::new(),
835 };
836 s.send(&format!(
837 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
838 echo \"__BLYTE_READY__ $__blyte_t\"\n",
839 ))?;
840 let deadline = Instant::now() + Duration::from_secs(30);
841 loop {
842 match s.read_line(deadline) {
843 Ok(l) if l.starts_with(READY) => {
844 s.tmp = l[READY.len()..].trim().to_string();
845 return Ok(s);
846 }
847 Ok(_) => continue, Err(_) => {
849 s.kill();
850 return Err("the shell session did not start".into());
851 }
852 }
853 }
854 }
855
856 fn send(&mut self, script: &str) -> Result<(), String> {
857 self.stdin
858 .write_all(script.as_bytes())
859 .and_then(|_| self.stdin.flush())
860 .map_err(|e| format!("the shell session closed: {e}"))
861 }
862
863 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
864 match self
865 .chunks
866 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
867 {
868 Ok(c) => {
869 self.buf.extend_from_slice(&c);
870 Ok(())
871 }
872 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
873 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
874 }
875 }
876
877 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
879 loop {
880 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
881 let line: Vec<u8> = self.buf.drain(..=i).collect();
882 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
883 }
884 self.fill(deadline)?;
885 }
886 }
887
888 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
890 while self.buf.len() < n {
891 self.fill(deadline)?;
892 }
893 Ok(self.buf.drain(..n).collect())
894 }
895
896 pub fn kill(&mut self) {
898 #[cfg(unix)]
899 {
900 let pgid = self.child.id() as i32;
901 if pgid > 0 {
902 unsafe {
903 libc::kill(-pgid, libc::SIGKILL);
904 }
905 }
906 }
907 let _ = self.child.kill();
908 let _ = self.child.wait();
909 }
910
911 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
914 let id = self.next;
915 self.next += 1;
916 let (out, err) = (
917 format!("{}/{id}.o", self.tmp),
918 format!("{}/{id}.e", self.tmp),
919 );
920 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
921 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
922 let body = match cwd {
923 Some(d) => format!(
924 "( cd {} && eval \"$__blyte_c\" )",
925 quote(&d.to_string_lossy())
926 ),
927 None => "eval \"$__blyte_c\"".to_string(),
928 };
929 let script = format!(
934 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
935 mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
936 IFS= read -r -d '' __blyte_o <{qo} || true; \
937 IFS= read -r -d '' __blyte_e <{qe} || true; \
938 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
939 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
940 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
941 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
942 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
943 );
944 if self.send(&script).is_err() {
945 return RunResult::Died { out, err };
946 }
947 let marker = format!("__BLYTE_{id}__ ");
948 let deadline = Instant::now() + timeout;
949 let fail = |e: ReadErr, out: String, err: String| match e {
950 ReadErr::Timeout => RunResult::TimedOut { out, err },
951 ReadErr::Closed => RunResult::Died { out, err },
952 };
953 let header = loop {
954 match self.read_line(deadline) {
955 Ok(l) => {
956 if let Some(rest) = l.strip_prefix(&marker) {
957 break rest.to_string();
958 }
959 }
960 Err(e) => return fail(e, out, err),
961 }
962 };
963 let mut f = header.split(' ');
964 let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
965 let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
966 let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
967 match self.read_exact(no + ne, deadline) {
968 Ok(bytes) => RunResult::Done(Output {
969 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
970 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
971 exit_code,
972 }),
973 Err(e) => fail(e, out, err),
974 }
975 }
976
977 fn close(&mut self) {
979 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
980 let deadline = Instant::now() + Duration::from_millis(300);
981 while Instant::now() < deadline {
982 if let Ok(Some(_)) = self.child.try_wait() {
983 return;
984 }
985 std::thread::sleep(Duration::from_millis(10));
986 }
987 self.kill();
988 }
989}
990
991pub struct PersistentShell {
1000 launcher: Launcher,
1001 harness: Mutex<Option<Session>>,
1002 user: Mutex<Option<Session>>,
1003 fallback: Box<dyn Shell>,
1004}
1005
1006impl PersistentShell {
1007 pub fn new(launcher: Launcher) -> Self {
1008 let fallback = launcher.fallback();
1009 Self {
1010 launcher,
1011 harness: Mutex::new(None),
1012 user: Mutex::new(None),
1013 fallback,
1014 }
1015 }
1016
1017 pub fn local(root: PathBuf) -> Self {
1018 Self::new(Launcher::Local {
1019 root,
1020 profile: None,
1021 })
1022 }
1023
1024 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1025 Self::new(Launcher::Local {
1026 root,
1027 profile: Some(profile.into()),
1028 })
1029 }
1030
1031 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1032 Self::local_sandboxed(root, profile)
1033 }
1034
1035 pub fn container(container_id: String, workdir: PathBuf) -> Self {
1036 Self::new(Launcher::Container {
1037 container_id,
1038 workdir,
1039 })
1040 }
1041
1042 pub fn is_persistent(&self) -> bool {
1044 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1045 if g.is_none() {
1046 *g = Session::start(&self.launcher).ok();
1047 }
1048 g.is_some()
1049 }
1050
1051 fn run(
1053 &self,
1054 slot: &Mutex<Option<Session>>,
1055 command: &str,
1056 cwd: Option<&Path>,
1057 timeout: Duration,
1058 ) -> Option<Result<Output, String>> {
1059 let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
1060 if g.is_none() {
1061 *g = Session::start(&self.launcher).ok();
1062 }
1063 let session = g.as_mut()?;
1064 let (out, err, note, code) = match session.run(command, cwd, timeout) {
1065 RunResult::Done(o) => return Some(Ok(o)),
1066 RunResult::TimedOut { out, err } => (
1067 out,
1068 err,
1069 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1070 124,
1071 ),
1072 RunResult::Died { out, err } => (
1073 out,
1074 err,
1075 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1076 .to_string(),
1077 1,
1078 ),
1079 };
1080 session.kill();
1081 *g = None;
1082 drop(g);
1083 let cat = |p: &str| {
1085 self.fallback
1086 .exec(
1087 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1088 Path::new("/"),
1089 Duration::from_secs(30),
1090 )
1091 .map(|o| o.stdout)
1092 .unwrap_or_default()
1093 };
1094 let (stdout, stderr) = (cat(&out), cat(&err));
1095 Some(Ok(Output {
1096 stdout,
1097 stderr: format!("{stderr}{note}"),
1098 exit_code: code,
1099 }))
1100 }
1101}
1102
1103impl Shell for PersistentShell {
1104 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1105 self.run(&self.harness, command, Some(cwd), timeout)
1106 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1107 }
1108
1109 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1110 self.run(&self.user, command, None, timeout)
1111 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1112 }
1113
1114 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1115 self.fallback.exec_host(command, cwd, timeout)
1116 }
1117
1118 fn describe(&self) -> String {
1119 format!(
1120 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1121 later commands. File tools always resolve paths from the workspace root.",
1122 self.fallback.describe()
1123 )
1124 }
1125}
1126
1127impl Drop for PersistentShell {
1128 fn drop(&mut self) {
1129 for slot in [&self.harness, &self.user] {
1130 if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
1131 s.close();
1132 }
1133 }
1134 }
1135}