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
291pub const POLL_START: Duration = Duration::from_millis(1);
292
293pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
296 (
297 current.min(remaining),
298 (current * 2).min(Duration::from_millis(50)),
299 )
300}
301
302fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
315 exec_command_cancellable(cmd, timeout, None)
316}
317
318fn exec_command_cancellable(
319 mut cmd: Command,
320 timeout: Duration,
321 cancel: Option<&CancelHandle>,
322) -> Result<Output, String> {
323 use std::process::Stdio;
324
325 if cancel.is_some_and(CancelHandle::is_cancelled) {
326 return Err("command cancelled".into());
327 }
328
329 cmd.stdin(Stdio::null())
333 .stdout(Stdio::piped())
334 .stderr(Stdio::piped());
335
336 #[cfg(unix)]
341 {
342 use std::os::unix::process::CommandExt;
343 cmd.process_group(0);
344 }
345
346 let mut child = cmd
347 .spawn()
348 .map_err(|e| format!("cannot run command: {e}"))?;
349
350 if let Some(handle) = cancel {
351 if !handle.register_pgid(child.id() as i32) {
352 kill_child_group(&mut child);
353 return Err("command cancelled".into());
354 }
355 }
356
357 let mut so = child.stdout.take().ok_or("no stdout")?;
360 let mut se = child.stderr.take().ok_or("no stderr")?;
361 let t_out = std::thread::spawn(move || {
362 let mut b = String::new();
363 let _ = so.read_to_string(&mut b);
364 b
365 });
366 let t_err = std::thread::spawn(move || {
367 let mut b = String::new();
368 let _ = se.read_to_string(&mut b);
369 b
370 });
371
372 let deadline = std::time::Instant::now() + timeout;
373 let mut poll = POLL_START;
374 let mut was_cancelled = false;
375 let status = loop {
376 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
377 Some(s) => break Some(s),
378 None if cancel.is_some_and(CancelHandle::is_cancelled) => {
379 was_cancelled = true;
380 kill_child_group(&mut child);
381 break None;
382 }
383 None if std::time::Instant::now() >= deadline => {
384 kill_child_group(&mut child);
385 break None;
386 }
387 None => {
388 let remaining = deadline.saturating_duration_since(Instant::now());
389 let (sleep, next) = poll_backoff(poll, remaining);
390 std::thread::sleep(sleep);
391 poll = next;
392 }
393 }
394 };
395
396 if let Some(handle) = cancel {
397 handle.clear_pgid();
398 }
399
400 let stdout = t_out.join().unwrap_or_default();
401 let stderr = t_err.join().unwrap_or_default();
402
403 if was_cancelled {
404 return Err("command cancelled".into());
405 }
406
407 match status {
408 Some(s) => Ok(Output {
409 stdout,
410 stderr,
411 exit_code: s.code().unwrap_or(-1),
412 }),
413 None => Ok(Output {
416 stdout,
417 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
418 exit_code: 124, }),
420 }
421}
422
423#[derive(Debug, Default, Clone, PartialEq, Eq)]
425pub struct LocalShell {
426 pub profile: Option<Profile>,
427}
428
429#[allow(non_upper_case_globals)]
430pub const LocalShell: LocalShell = LocalShell { profile: None };
431
432impl LocalShell {
433 pub fn new() -> Self {
435 Self { profile: None }
436 }
437
438 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
440 Self {
441 profile: Some(profile.into()),
442 }
443 }
444
445 fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
446 let full_command = inherited_path_prefix() + command;
447 let command = full_command.as_str();
448 let mut cmd = match &self.profile {
449 Some(Profile::Seatbelt(profile)) => {
450 let mut c = Command::new("/usr/bin/sandbox-exec");
451 c.args(["-p", profile, "bash", "-lc", command]);
452 c
453 }
454 Some(Profile::Landlock(paths)) => {
455 #[cfg(target_os = "linux")]
456 {
457 let mut c = Command::new("bash");
458 c.arg("-lc").arg(command);
459 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
460 .map_err(|e| e.to_string())?;
461 c
462 }
463 #[cfg(not(target_os = "linux"))]
464 {
465 let _ = paths;
466 return Err(std::io::Error::new(
467 std::io::ErrorKind::Unsupported,
468 "Landlock is only supported on Linux",
469 )
470 .to_string());
471 }
472 }
473 Some(Profile::LandlockOffline(paths)) => {
474 #[cfg(target_os = "linux")]
475 {
476 let mut c = Command::new("bash");
477 c.arg("-lc").arg(command);
478 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
479 .map_err(|e| e.to_string())?;
480 c
481 }
482 #[cfg(not(target_os = "linux"))]
483 {
484 let _ = paths;
485 return Err(std::io::Error::new(
486 std::io::ErrorKind::Unsupported,
487 "Landlock is only supported on Linux",
488 )
489 .to_string());
490 }
491 }
492 Some(Profile::LandlockConfined {
493 write,
494 read,
495 block_tcp,
496 }) => {
497 #[cfg(target_os = "linux")]
498 {
499 let mut c = Command::new("bash");
500 c.arg("-lc").arg(command);
501 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
502 .map_err(|e| e.to_string())?;
503 c
504 }
505 #[cfg(not(target_os = "linux"))]
506 {
507 let _ = (write, read, block_tcp);
508 return Err(std::io::Error::new(
509 std::io::ErrorKind::Unsupported,
510 "Landlock is only supported on Linux",
511 )
512 .to_string());
513 }
514 }
515 None => {
516 let mut c = Command::new("bash");
517 c.arg("-lc").arg(command);
518 c
519 }
520 };
521 cmd.current_dir(cwd);
522 scrub(&mut cmd);
523 Ok(cmd)
524 }
525}
526
527impl Shell for LocalShell {
528 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
529 let cmd = self.build_command(command, cwd)?;
530 exec_command(cmd, timeout)
531 }
532
533 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
534 let full_command = inherited_path_prefix() + command;
535 let mut cmd = Command::new("bash");
536 cmd.arg("-lc").arg(&full_command);
537 cmd.current_dir(cwd);
538 scrub_harness(&mut cmd);
539 exec_command(cmd, timeout)
540 }
541
542 fn describe(&self) -> String {
543 "Commands run directly on this machine, in the workspace directory.".into()
544 }
545}
546
547#[derive(Debug, Clone)]
549pub struct CancellableLocalShell {
550 pub inner: LocalShell,
551 pub cancel: Arc<CancelHandle>,
552}
553
554impl Shell for CancellableLocalShell {
555 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
556 let cmd = self.inner.build_command(command, cwd)?;
557 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
558 }
559
560 fn describe(&self) -> String {
561 self.inner.describe()
562 }
563}
564
565#[derive(Debug, Clone)]
570pub struct ContainerShell {
571 pub container_id: String,
572 pub workdir: PathBuf,
574}
575
576impl ContainerShell {
577 fn build_command(&self, command: &str) -> Command {
578 let mut cmd = Command::new("docker");
579 cmd.args(["exec", "-i", "-w"])
580 .arg(&self.workdir)
581 .arg(&self.container_id)
582 .args(["bash", "-lc", command]);
583 cmd
584 }
585}
586
587impl Shell for ContainerShell {
588 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
589 exec_command(self.build_command(command), timeout)
590 }
591
592 fn describe(&self) -> String {
593 format!(
594 "Commands run inside the project container at {}. Project dependencies are \
595 installed there, not on the host.",
596 self.workdir.display()
597 )
598 }
599}
600
601#[derive(Debug, Clone)]
603pub struct CancellableContainerShell {
604 pub inner: ContainerShell,
605 pub cancel: Arc<CancelHandle>,
606}
607
608impl Shell for CancellableContainerShell {
609 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
610 exec_command_cancellable(
611 self.inner.build_command(command),
612 timeout,
613 Some(&self.cancel),
614 )
615 }
616
617 fn describe(&self) -> String {
618 self.inner.describe()
619 }
620}
621
622fn quote(s: &str) -> String {
624 format!("'{}'", s.replace('\'', r"'\''"))
625}
626
627pub fn inherited_path_prefix() -> String {
629 match std::env::var("PATH") {
630 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
631 _ => String::new(),
632 }
633}
634
635#[derive(Debug, Clone)]
637pub enum Launcher {
638 Local {
640 root: PathBuf,
641 profile: Option<Profile>,
642 },
643 Container {
645 container_id: String,
646 workdir: PathBuf,
647 },
648}
649
650impl Launcher {
651 fn command(&self) -> std::io::Result<Command> {
652 match self {
653 Launcher::Local { root, profile } => {
654 let mut c = match profile {
655 Some(Profile::Seatbelt(p)) => {
656 let mut cmd = Command::new("/usr/bin/sandbox-exec");
657 cmd.args(["-p", p, "bash", "-l"]);
658 cmd
659 }
660 Some(Profile::Landlock(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, false)?;
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::LandlockOffline(paths)) => {
678 #[cfg(target_os = "linux")]
679 {
680 let mut cmd = Command::new("bash");
681 cmd.arg("-l");
682 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
683 cmd
684 }
685 #[cfg(not(target_os = "linux"))]
686 {
687 let _ = paths;
688 return Err(std::io::Error::new(
689 std::io::ErrorKind::Unsupported,
690 "Landlock is only supported on Linux",
691 ));
692 }
693 }
694 Some(Profile::LandlockConfined {
695 write,
696 read,
697 block_tcp,
698 }) => {
699 #[cfg(target_os = "linux")]
700 {
701 let mut cmd = Command::new("bash");
702 cmd.arg("-l");
703 crate::sandbox::landlock_pre_exec(
704 &mut cmd,
705 write,
706 Some(read),
707 *block_tcp,
708 )?;
709 cmd
710 }
711 #[cfg(not(target_os = "linux"))]
712 {
713 let _ = (write, read, block_tcp);
714 return Err(std::io::Error::new(
715 std::io::ErrorKind::Unsupported,
716 "Landlock is only supported on Linux",
717 ));
718 }
719 }
720 None => {
721 let mut cmd = Command::new("bash");
722 cmd.arg("-l");
723 cmd
724 }
725 };
726 c.current_dir(root);
727 scrub(&mut c);
728 Ok(c)
729 }
730 Launcher::Container {
731 container_id,
732 workdir,
733 } => {
734 let mut c = Command::new("docker");
735 c.args(["exec", "-i", "-w"])
736 .arg(workdir)
737 .arg(container_id)
738 .args(["bash", "-l"]);
739 Ok(c)
740 }
741 }
742 }
743
744 fn fallback(&self) -> Box<dyn Shell> {
747 match self {
748 Launcher::Local { profile, .. } => match profile {
749 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
750 None => Box::new(LocalShell),
751 },
752 Launcher::Container {
753 container_id,
754 workdir,
755 } => Box::new(ContainerShell {
756 container_id: container_id.clone(),
757 workdir: workdir.clone(),
758 }),
759 }
760 }
761}
762
763pub enum RunResult {
765 Done(Output),
766 TimedOut {
768 out: String,
769 err: String,
770 },
771 Died {
773 out: String,
774 err: String,
775 },
776}
777
778pub struct Session {
783 child: Child,
784 stdin: ChildStdin,
785 chunks: Receiver<Vec<u8>>,
786 buf: Vec<u8>,
787 tmp: String,
788 next: u64,
789 nonce: String,
790}
791
792const READY: &str = "__BLYTE_READY__ ";
793
794fn nonce() -> String {
796 let t = std::time::SystemTime::now()
797 .duration_since(std::time::UNIX_EPOCH)
798 .map(|d| d.as_nanos())
799 .unwrap_or(0);
800 format!("{t:x}{:x}", std::process::id())
801}
802
803enum ReadErr {
804 Timeout,
805 Closed,
806}
807
808impl Session {
809 pub fn start(launcher: &Launcher) -> Result<Session, String> {
810 let mut cmd = launcher
811 .command()
812 .map_err(|e| format!("cannot start a shell session: {e}"))?;
813 cmd.stdin(Stdio::piped())
814 .stdout(Stdio::piped())
815 .stderr(Stdio::null());
816 #[cfg(unix)]
817 {
818 use std::os::unix::process::CommandExt;
819 cmd.process_group(0);
820 }
821 let mut child = cmd
822 .spawn()
823 .map_err(|e| format!("cannot start a shell session: {e}"))?;
824 let stdin = child.stdin.take().ok_or("no stdin")?;
825 let mut stdout = child.stdout.take().ok_or("no stdout")?;
826 let (tx, rx) = mpsc::channel();
827 std::thread::spawn(move || {
828 let mut chunk = vec![0u8; 64 * 1024];
829 loop {
830 match stdout.read(&mut chunk) {
831 Ok(0) | Err(_) => break,
832 Ok(n) => {
833 if tx.send(chunk[..n].to_vec()).is_err() {
834 break;
835 }
836 }
837 }
838 }
839 });
840 let mut s = Session {
841 child,
842 stdin,
843 chunks: rx,
844 buf: Vec::new(),
845 tmp: String::new(),
846 next: 0,
847 nonce: nonce(),
848 };
849 let init = match launcher {
850 Launcher::Local { .. } => inherited_path_prefix(),
851 Launcher::Container { .. } => String::new(),
852 };
853 s.send(&format!(
854 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
855 echo \"__BLYTE_READY__ $__blyte_t\"\n",
856 ))?;
857 let deadline = Instant::now() + Duration::from_secs(30);
858 loop {
859 match s.read_line(deadline) {
860 Ok(l) if l.starts_with(READY) => {
861 s.tmp = l[READY.len()..].trim().to_string();
862 return Ok(s);
863 }
864 Ok(_) => continue, Err(_) => {
866 s.kill();
867 return Err("the shell session did not start".into());
868 }
869 }
870 }
871 }
872
873 fn send(&mut self, script: &str) -> Result<(), String> {
874 self.stdin
875 .write_all(script.as_bytes())
876 .and_then(|_| self.stdin.flush())
877 .map_err(|e| format!("the shell session closed: {e}"))
878 }
879
880 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
881 match self
882 .chunks
883 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
884 {
885 Ok(c) => {
886 self.buf.extend_from_slice(&c);
887 Ok(())
888 }
889 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
890 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
891 }
892 }
893
894 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
896 loop {
897 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
898 let line: Vec<u8> = self.buf.drain(..=i).collect();
899 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
900 }
901 self.fill(deadline)?;
902 }
903 }
904
905 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
907 while self.buf.len() < n {
908 self.fill(deadline)?;
909 }
910 Ok(self.buf.drain(..n).collect())
911 }
912
913 pub fn kill(&mut self) {
915 #[cfg(unix)]
916 {
917 let pgid = self.child.id() as i32;
918 if pgid > 0 {
919 unsafe {
920 libc::kill(-pgid, libc::SIGKILL);
921 }
922 }
923 }
924 let _ = self.child.kill();
925 let _ = self.child.wait();
926 }
927
928 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
931 let id = self.next;
932 self.next += 1;
933 let (out, err) = (
934 format!("{}/{id}.o", self.tmp),
935 format!("{}/{id}.e", self.tmp),
936 );
937 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
938 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
939 let body = match cwd {
940 Some(d) => format!(
941 "( cd {} && eval \"$__blyte_c\" )",
942 quote(&d.to_string_lossy())
943 ),
944 None => "eval \"$__blyte_c\"".to_string(),
945 };
946 let script = format!(
951 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
952 [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
953 IFS= read -r -d '' __blyte_o <{qo} || true; \
954 IFS= read -r -d '' __blyte_e <{qe} || true; \
955 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
956 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
957 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
958 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
959 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
960 );
961 if self.send(&script).is_err() {
962 return RunResult::Died { out, err };
963 }
964 let marker = format!("__BLYTE_{id}__ ");
965 let deadline = Instant::now() + timeout;
966 let fail = |e: ReadErr, out: String, err: String| match e {
967 ReadErr::Timeout => RunResult::TimedOut { out, err },
968 ReadErr::Closed => RunResult::Died { out, err },
969 };
970 let header = loop {
971 match self.read_line(deadline) {
972 Ok(l) => {
973 if let Some(rest) = l.strip_prefix(&marker) {
974 break rest.to_string();
975 }
976 }
977 Err(e) => return fail(e, out, err),
978 }
979 };
980 let mut f = header.split(' ');
981 let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
982 let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
983 let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
984 match self.read_exact(no + ne, deadline) {
985 Ok(bytes) => RunResult::Done(Output {
986 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
987 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
988 exit_code,
989 }),
990 Err(e) => fail(e, out, err),
991 }
992 }
993
994 fn close(&mut self) {
996 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
997 let deadline = Instant::now() + Duration::from_millis(300);
998 while Instant::now() < deadline {
999 if let Ok(Some(_)) = self.child.try_wait() {
1000 return;
1001 }
1002 std::thread::sleep(Duration::from_millis(10));
1003 }
1004 self.kill();
1005 }
1006}
1007
1008pub struct PersistentShell {
1017 launcher: Launcher,
1018 harness: Mutex<Option<Session>>,
1019 user: Mutex<Option<Session>>,
1020 fallback: Box<dyn Shell>,
1021}
1022
1023impl PersistentShell {
1024 pub fn new(launcher: Launcher) -> Self {
1025 let fallback = launcher.fallback();
1026 Self {
1027 launcher,
1028 harness: Mutex::new(None),
1029 user: Mutex::new(None),
1030 fallback,
1031 }
1032 }
1033
1034 pub fn local(root: PathBuf) -> Self {
1035 Self::new(Launcher::Local {
1036 root,
1037 profile: None,
1038 })
1039 }
1040
1041 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1042 Self::new(Launcher::Local {
1043 root,
1044 profile: Some(profile.into()),
1045 })
1046 }
1047
1048 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1049 Self::local_sandboxed(root, profile)
1050 }
1051
1052 pub fn container(container_id: String, workdir: PathBuf) -> Self {
1053 Self::new(Launcher::Container {
1054 container_id,
1055 workdir,
1056 })
1057 }
1058
1059 pub fn is_persistent(&self) -> bool {
1061 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1062 if g.is_none() {
1063 *g = Session::start(&self.launcher).ok();
1064 }
1065 g.is_some()
1066 }
1067
1068 fn run(
1070 &self,
1071 slot: &Mutex<Option<Session>>,
1072 command: &str,
1073 cwd: Option<&Path>,
1074 timeout: Duration,
1075 ) -> Option<Result<Output, String>> {
1076 let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
1077 if g.is_none() {
1078 *g = Session::start(&self.launcher).ok();
1079 }
1080 let session = g.as_mut()?;
1081 let (out, err, note, code) = match session.run(command, cwd, timeout) {
1082 RunResult::Done(o) => return Some(Ok(o)),
1083 RunResult::TimedOut { out, err } => (
1084 out,
1085 err,
1086 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1087 124,
1088 ),
1089 RunResult::Died { out, err } => (
1090 out,
1091 err,
1092 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1093 .to_string(),
1094 1,
1095 ),
1096 };
1097 session.kill();
1098 *g = None;
1099 drop(g);
1100 let cat = |p: &str| {
1102 self.fallback
1103 .exec(
1104 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1105 Path::new("/"),
1106 Duration::from_secs(30),
1107 )
1108 .map(|o| o.stdout)
1109 .unwrap_or_default()
1110 };
1111 let (stdout, stderr) = (cat(&out), cat(&err));
1112 Some(Ok(Output {
1113 stdout,
1114 stderr: format!("{stderr}{note}"),
1115 exit_code: code,
1116 }))
1117 }
1118}
1119
1120impl Shell for PersistentShell {
1121 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1122 self.run(&self.harness, command, Some(cwd), timeout)
1123 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1124 }
1125
1126 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1127 self.run(&self.user, command, None, timeout)
1128 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1129 }
1130
1131 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1132 self.fallback.exec_host(command, cwd, timeout)
1133 }
1134
1135 fn describe(&self) -> String {
1136 format!(
1137 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1138 later commands. File tools always resolve paths from the workspace root.",
1139 self.fallback.describe()
1140 )
1141 }
1142}
1143
1144impl Drop for PersistentShell {
1145 fn drop(&mut self) {
1146 for slot in [&self.harness, &self.user] {
1147 if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
1148 s.close();
1149 }
1150 }
1151 }
1152}