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
140pub const MODEL_SHELL_ENV: &str = "BLYTE_MODEL_SHELL";
141
142pub fn model_shell_refusal_message(command: &str) -> String {
143 format!(
144 "error: blyte {command} writes a record only the user or the harness may write, and cannot be run from a model's shell"
145 )
146}
147
148fn scrub_harness(cmd: &mut Command) {
149 cmd.env_remove(MODEL_SHELL_ENV);
150 for name in HARNESS_ENV {
151 cmd.env_remove(name);
152 }
153 for (name, _) in std::env::vars_os() {
154 let n = name.to_string_lossy();
155 if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
156 cmd.env_remove(&name);
157 }
158 }
159}
160
161fn scrub(cmd: &mut Command) {
163 scrub_harness(cmd);
164 for name in withheld_env() {
165 cmd.env_remove(name);
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct Output {
171 pub stdout: String,
172 pub stderr: String,
173 pub exit_code: i32,
174}
175
176impl Output {
177 pub fn merged(&self) -> String {
180 format!("{}{}", self.stdout, self.stderr)
181 }
182}
183
184pub trait Shell: Send + Sync {
185 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
187
188 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
192 self.exec(command, cwd, timeout)
193 }
194
195 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
196 let _ = (command, cwd, timeout);
197 Err("this shell cannot run a command outside the sandbox".into())
198 }
199
200 fn describe(&self) -> String;
203
204 fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
206 let probe = candidates
209 .iter()
210 .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
211 .collect::<Vec<_>>()
212 .join("; ");
213 match self.exec(&probe, cwd, Duration::from_secs(30)) {
214 Ok(o) => o
215 .stdout
216 .lines()
217 .map(|l| l.trim().to_string())
218 .filter(|l| !l.is_empty())
219 .collect(),
220 Err(_) => Vec::new(),
221 }
222 }
223}
224
225#[derive(Debug, Default)]
227pub struct CancelHandle {
228 cancelled: AtomicBool,
229 active_pgid: Mutex<Option<i32>>,
230}
231
232impl CancelHandle {
233 pub fn new() -> Self {
234 Self::default()
235 }
236
237 pub fn is_cancelled(&self) -> bool {
238 self.cancelled.load(Ordering::SeqCst)
239 }
240
241 pub fn flag(&self) -> &AtomicBool {
242 &self.cancelled
243 }
244
245 pub fn cancel(&self) {
246 let pgid = {
247 let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
248 self.cancelled.store(true, Ordering::SeqCst);
249 *guard
250 };
251 #[cfg(unix)]
252 if let Some(pgid) = pgid {
253 if pgid > 0 {
254 unsafe {
255 libc::kill(-pgid, libc::SIGKILL);
256 }
257 }
258 }
259 #[cfg(not(unix))]
260 let _ = pgid;
261 }
262
263 fn register_pgid(&self, pgid: i32) -> bool {
264 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
265 if self.cancelled.load(Ordering::SeqCst) {
266 return false;
267 }
268 *guard = Some(pgid);
269 true
270 }
271
272 fn clear_pgid(&self) {
273 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
274 *guard = None;
275 }
276}
277
278fn kill_child_group(child: &mut Child) {
279 #[cfg(unix)]
283 {
284 let pgid = child.id() as i32;
285 if pgid > 0 {
286 unsafe {
287 libc::kill(-pgid, libc::SIGKILL);
288 }
289 } else {
290 let _ = child.kill();
291 }
292 }
293 #[cfg(not(unix))]
294 {
295 let _ = child.kill();
296 }
297 let _ = child.wait();
298}
299
300pub const POLL_START: Duration = Duration::from_millis(1);
301
302pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
305 (
306 current.min(remaining),
307 (current * 2).min(Duration::from_millis(50)),
308 )
309}
310
311fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
324 exec_command_cancellable(cmd, timeout, None)
325}
326
327fn exec_command_cancellable(
328 mut cmd: Command,
329 timeout: Duration,
330 cancel: Option<&CancelHandle>,
331) -> Result<Output, String> {
332 use std::process::Stdio;
333
334 if cancel.is_some_and(CancelHandle::is_cancelled) {
335 return Err("command cancelled".into());
336 }
337
338 cmd.stdin(Stdio::null())
342 .stdout(Stdio::piped())
343 .stderr(Stdio::piped());
344
345 #[cfg(unix)]
350 {
351 use std::os::unix::process::CommandExt;
352 cmd.process_group(0);
353 }
354
355 let mut child = cmd
356 .spawn()
357 .map_err(|e| format!("cannot run command: {e}"))?;
358
359 if let Some(handle) = cancel {
360 if !handle.register_pgid(child.id() as i32) {
361 kill_child_group(&mut child);
362 return Err("command cancelled".into());
363 }
364 }
365
366 let mut so = child.stdout.take().ok_or("no stdout")?;
369 let mut se = child.stderr.take().ok_or("no stderr")?;
370 let t_out = std::thread::spawn(move || {
371 let mut b = String::new();
372 let _ = so.read_to_string(&mut b);
373 b
374 });
375 let t_err = std::thread::spawn(move || {
376 let mut b = String::new();
377 let _ = se.read_to_string(&mut b);
378 b
379 });
380
381 let deadline = std::time::Instant::now() + timeout;
382 let mut poll = POLL_START;
383 let mut was_cancelled = false;
384 let status = loop {
385 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
386 Some(s) => break Some(s),
387 None if cancel.is_some_and(CancelHandle::is_cancelled) => {
388 was_cancelled = true;
389 kill_child_group(&mut child);
390 break None;
391 }
392 None if std::time::Instant::now() >= deadline => {
393 kill_child_group(&mut child);
394 break None;
395 }
396 None => {
397 let remaining = deadline.saturating_duration_since(Instant::now());
398 let (sleep, next) = poll_backoff(poll, remaining);
399 std::thread::sleep(sleep);
400 poll = next;
401 }
402 }
403 };
404
405 if let Some(handle) = cancel {
406 handle.clear_pgid();
407 }
408
409 let stdout = t_out.join().unwrap_or_default();
410 let stderr = t_err.join().unwrap_or_default();
411
412 if was_cancelled {
413 return Err("command cancelled".into());
414 }
415
416 match status {
417 Some(s) => Ok(Output {
418 stdout,
419 stderr,
420 exit_code: s.code().unwrap_or(-1),
421 }),
422 None => Ok(Output {
425 stdout,
426 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
427 exit_code: 124, }),
429 }
430}
431
432#[derive(Debug, Default, Clone, PartialEq, Eq)]
434pub struct LocalShell {
435 pub profile: Option<Profile>,
436}
437
438#[allow(non_upper_case_globals)]
439pub const LocalShell: LocalShell = LocalShell { profile: None };
440
441impl LocalShell {
442 pub fn new() -> Self {
444 Self { profile: None }
445 }
446
447 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
449 Self {
450 profile: Some(profile.into()),
451 }
452 }
453
454 fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
455 let full_command = inherited_path_prefix() + command;
456 let command = full_command.as_str();
457 let mut cmd = match &self.profile {
458 Some(Profile::Seatbelt(profile)) => {
459 let mut c = Command::new("/usr/bin/sandbox-exec");
460 c.args(["-p", profile, "bash", "-lc", command]);
461 c
462 }
463 Some(Profile::Landlock(paths)) => {
464 #[cfg(target_os = "linux")]
465 {
466 let mut c = Command::new("bash");
467 c.arg("-lc").arg(command);
468 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
469 .map_err(|e| e.to_string())?;
470 c
471 }
472 #[cfg(not(target_os = "linux"))]
473 {
474 let _ = paths;
475 return Err(std::io::Error::new(
476 std::io::ErrorKind::Unsupported,
477 "Landlock is only supported on Linux",
478 )
479 .to_string());
480 }
481 }
482 Some(Profile::LandlockOffline(paths)) => {
483 #[cfg(target_os = "linux")]
484 {
485 let mut c = Command::new("bash");
486 c.arg("-lc").arg(command);
487 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
488 .map_err(|e| e.to_string())?;
489 c
490 }
491 #[cfg(not(target_os = "linux"))]
492 {
493 let _ = paths;
494 return Err(std::io::Error::new(
495 std::io::ErrorKind::Unsupported,
496 "Landlock is only supported on Linux",
497 )
498 .to_string());
499 }
500 }
501 Some(Profile::LandlockConfined {
502 write,
503 read,
504 block_tcp,
505 }) => {
506 #[cfg(target_os = "linux")]
507 {
508 let mut c = Command::new("bash");
509 c.arg("-lc").arg(command);
510 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
511 .map_err(|e| e.to_string())?;
512 c
513 }
514 #[cfg(not(target_os = "linux"))]
515 {
516 let _ = (write, read, block_tcp);
517 return Err(std::io::Error::new(
518 std::io::ErrorKind::Unsupported,
519 "Landlock is only supported on Linux",
520 )
521 .to_string());
522 }
523 }
524 None => {
525 let mut c = Command::new("bash");
526 c.arg("-lc").arg(command);
527 c
528 }
529 };
530 cmd.current_dir(cwd);
531 scrub(&mut cmd);
532 Ok(cmd)
533 }
534}
535
536impl Shell for LocalShell {
537 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
538 let cmd = self.build_command(command, cwd)?;
539 exec_command(cmd, timeout)
540 }
541
542 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
543 let mut cmd = self.build_command(command, cwd)?;
544 cmd.env(MODEL_SHELL_ENV, "1");
545 exec_command(cmd, timeout)
546 }
547
548 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
549 let full_command = inherited_path_prefix() + command;
550 let mut cmd = Command::new("bash");
551 cmd.arg("-lc").arg(&full_command);
552 cmd.current_dir(cwd);
553 scrub_harness(&mut cmd);
554 cmd.env(MODEL_SHELL_ENV, "1");
555 exec_command(cmd, timeout)
556 }
557
558 fn describe(&self) -> String {
559 "Commands run directly on this machine, in the workspace directory.".into()
560 }
561}
562
563#[derive(Debug, Clone)]
565pub struct CancellableLocalShell {
566 pub inner: LocalShell,
567 pub cancel: Arc<CancelHandle>,
568}
569
570impl Shell for CancellableLocalShell {
571 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
572 let cmd = self.inner.build_command(command, cwd)?;
573 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
574 }
575
576 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
577 let mut cmd = self.inner.build_command(command, cwd)?;
578 cmd.env(MODEL_SHELL_ENV, "1");
579 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
580 }
581
582 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
583 let full_command = inherited_path_prefix() + command;
584 let mut cmd = Command::new("bash");
585 cmd.arg("-lc").arg(&full_command);
586 cmd.current_dir(cwd);
587 scrub_harness(&mut cmd);
588 cmd.env(MODEL_SHELL_ENV, "1");
589 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
590 }
591
592 fn describe(&self) -> String {
593 self.inner.describe()
594 }
595}
596
597#[derive(Debug, Clone)]
602pub struct ContainerShell {
603 pub container_id: String,
604 pub workdir: PathBuf,
606}
607
608impl ContainerShell {
609 fn build_command(&self, command: &str, model_shell: bool) -> Command {
610 let mut cmd = Command::new("docker");
611 cmd.args(["exec", "-i"]);
612 if model_shell {
613 cmd.args(["-e", "BLYTE_MODEL_SHELL=1"]);
614 }
615 cmd.arg("-w")
616 .arg(&self.workdir)
617 .arg(&self.container_id)
618 .args(["bash", "-lc", command]);
619 cmd
620 }
621}
622
623impl Shell for ContainerShell {
624 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
625 exec_command(self.build_command(command, false), timeout)
626 }
627
628 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
629 exec_command(self.build_command(command, true), timeout)
630 }
631
632 fn describe(&self) -> String {
633 format!(
634 "Commands run inside the project container at {}. Project dependencies are \
635 installed there, not on the host.",
636 self.workdir.display()
637 )
638 }
639}
640
641#[derive(Debug, Clone)]
643pub struct CancellableContainerShell {
644 pub inner: ContainerShell,
645 pub cancel: Arc<CancelHandle>,
646}
647
648impl Shell for CancellableContainerShell {
649 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
650 exec_command_cancellable(
651 self.inner.build_command(command, false),
652 timeout,
653 Some(&self.cancel),
654 )
655 }
656
657 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
658 exec_command_cancellable(
659 self.inner.build_command(command, true),
660 timeout,
661 Some(&self.cancel),
662 )
663 }
664
665 fn describe(&self) -> String {
666 self.inner.describe()
667 }
668}
669
670fn quote(s: &str) -> String {
672 format!("'{}'", s.replace('\'', r"'\''"))
673}
674
675pub fn inherited_path_prefix() -> String {
677 match std::env::var("PATH") {
678 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
679 _ => String::new(),
680 }
681}
682
683#[derive(Debug, Clone)]
685pub enum Launcher {
686 Local {
688 root: PathBuf,
689 profile: Option<Profile>,
690 },
691 Container {
693 container_id: String,
694 workdir: PathBuf,
695 },
696}
697
698impl Launcher {
699 fn command(&self, model_shell: bool) -> std::io::Result<Command> {
700 match self {
701 Launcher::Local { root, profile } => {
702 let mut c = match profile {
703 Some(Profile::Seatbelt(p)) => {
704 let mut cmd = Command::new("/usr/bin/sandbox-exec");
705 cmd.args(["-p", p, "bash", "-l"]);
706 cmd
707 }
708 Some(Profile::Landlock(paths)) => {
709 #[cfg(target_os = "linux")]
710 {
711 let mut cmd = Command::new("bash");
712 cmd.arg("-l");
713 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
714 cmd
715 }
716 #[cfg(not(target_os = "linux"))]
717 {
718 let _ = paths;
719 return Err(std::io::Error::new(
720 std::io::ErrorKind::Unsupported,
721 "Landlock is only supported on Linux",
722 ));
723 }
724 }
725 Some(Profile::LandlockOffline(paths)) => {
726 #[cfg(target_os = "linux")]
727 {
728 let mut cmd = Command::new("bash");
729 cmd.arg("-l");
730 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
731 cmd
732 }
733 #[cfg(not(target_os = "linux"))]
734 {
735 let _ = paths;
736 return Err(std::io::Error::new(
737 std::io::ErrorKind::Unsupported,
738 "Landlock is only supported on Linux",
739 ));
740 }
741 }
742 Some(Profile::LandlockConfined {
743 write,
744 read,
745 block_tcp,
746 }) => {
747 #[cfg(target_os = "linux")]
748 {
749 let mut cmd = Command::new("bash");
750 cmd.arg("-l");
751 crate::sandbox::landlock_pre_exec(
752 &mut cmd,
753 write,
754 Some(read),
755 *block_tcp,
756 )?;
757 cmd
758 }
759 #[cfg(not(target_os = "linux"))]
760 {
761 let _ = (write, read, block_tcp);
762 return Err(std::io::Error::new(
763 std::io::ErrorKind::Unsupported,
764 "Landlock is only supported on Linux",
765 ));
766 }
767 }
768 None => {
769 let mut cmd = Command::new("bash");
770 cmd.arg("-l");
771 cmd
772 }
773 };
774 c.current_dir(root);
775 scrub(&mut c);
776 if model_shell {
777 c.env(MODEL_SHELL_ENV, "1");
778 }
779 Ok(c)
780 }
781 Launcher::Container {
782 container_id,
783 workdir,
784 } => {
785 let mut c = Command::new("docker");
786 c.args(["exec", "-i"]);
787 if model_shell {
788 c.args(["-e", "BLYTE_MODEL_SHELL=1"]);
789 }
790 c.arg("-w")
791 .arg(workdir)
792 .arg(container_id)
793 .args(["bash", "-l"]);
794 Ok(c)
795 }
796 }
797 }
798
799 fn with_profile(&self, profile: Profile) -> Self {
800 match self {
801 Launcher::Local { root, .. } => Launcher::Local {
802 root: root.clone(),
803 profile: Some(profile),
804 },
805 Launcher::Container {
806 container_id,
807 workdir,
808 } => Launcher::Container {
809 container_id: container_id.clone(),
810 workdir: workdir.clone(),
811 },
812 }
813 }
814
815 fn fallback(&self) -> Box<dyn Shell> {
818 match self {
819 Launcher::Local { profile, .. } => match profile {
820 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
821 None => Box::new(LocalShell),
822 },
823 Launcher::Container {
824 container_id,
825 workdir,
826 } => Box::new(ContainerShell {
827 container_id: container_id.clone(),
828 workdir: workdir.clone(),
829 }),
830 }
831 }
832}
833
834pub enum RunResult {
836 Done(Output),
837 TimedOut {
839 out: String,
840 err: String,
841 },
842 Died {
844 out: String,
845 err: String,
846 },
847}
848
849pub struct Session {
854 child: Child,
855 stdin: ChildStdin,
856 chunks: Receiver<Vec<u8>>,
857 buf: Vec<u8>,
858 tmp: String,
859 next: u64,
860 nonce: String,
861}
862
863const READY: &str = "__BLYTE_READY__ ";
864
865fn nonce() -> String {
867 let t = std::time::SystemTime::now()
868 .duration_since(std::time::UNIX_EPOCH)
869 .map(|d| d.as_nanos())
870 .unwrap_or(0);
871 format!("{t:x}{:x}", std::process::id())
872}
873
874enum ReadErr {
875 Timeout,
876 Closed,
877}
878
879impl Session {
880 pub fn start(launcher: &Launcher) -> Result<Session, String> {
881 Self::start_with_marker(launcher, false)
882 }
883
884 fn start_with_marker(launcher: &Launcher, model_shell: bool) -> Result<Session, String> {
885 let mut cmd = launcher
886 .command(model_shell)
887 .map_err(|e| format!("cannot start a shell session: {e}"))?;
888 cmd.stdin(Stdio::piped())
889 .stdout(Stdio::piped())
890 .stderr(Stdio::null());
891 #[cfg(unix)]
892 {
893 use std::os::unix::process::CommandExt;
894 cmd.process_group(0);
895 }
896 let mut child = cmd
897 .spawn()
898 .map_err(|e| format!("cannot start a shell session: {e}"))?;
899 let stdin = child.stdin.take().ok_or("no stdin")?;
900 let mut stdout = child.stdout.take().ok_or("no stdout")?;
901 let (tx, rx) = mpsc::channel();
902 std::thread::spawn(move || {
903 let mut chunk = vec![0u8; 64 * 1024];
904 loop {
905 match stdout.read(&mut chunk) {
906 Ok(0) | Err(_) => break,
907 Ok(n) => {
908 if tx.send(chunk[..n].to_vec()).is_err() {
909 break;
910 }
911 }
912 }
913 }
914 });
915 let mut s = Session {
916 child,
917 stdin,
918 chunks: rx,
919 buf: Vec::new(),
920 tmp: String::new(),
921 next: 0,
922 nonce: nonce(),
923 };
924 let init = match launcher {
925 Launcher::Local { .. } => inherited_path_prefix(),
926 Launcher::Container { .. } => String::new(),
927 };
928 s.send(&format!(
929 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
930 echo \"__BLYTE_READY__ $__blyte_t\"\n",
931 ))?;
932 let deadline = Instant::now() + Duration::from_secs(30);
933 loop {
934 match s.read_line(deadline) {
935 Ok(l) if l.starts_with(READY) => {
936 s.tmp = l[READY.len()..].trim().to_string();
937 return Ok(s);
938 }
939 Ok(_) => continue, Err(_) => {
941 s.kill();
942 return Err("the shell session did not start".into());
943 }
944 }
945 }
946 }
947
948 fn send(&mut self, script: &str) -> Result<(), String> {
949 self.stdin
950 .write_all(script.as_bytes())
951 .and_then(|_| self.stdin.flush())
952 .map_err(|e| format!("the shell session closed: {e}"))
953 }
954
955 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
956 match self
957 .chunks
958 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
959 {
960 Ok(c) => {
961 self.buf.extend_from_slice(&c);
962 Ok(())
963 }
964 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
965 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
966 }
967 }
968
969 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
971 loop {
972 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
973 let line: Vec<u8> = self.buf.drain(..=i).collect();
974 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
975 }
976 self.fill(deadline)?;
977 }
978 }
979
980 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
982 while self.buf.len() < n {
983 self.fill(deadline)?;
984 }
985 Ok(self.buf.drain(..n).collect())
986 }
987
988 pub fn kill(&mut self) {
990 #[cfg(unix)]
991 {
992 let pgid = self.child.id() as i32;
993 if pgid > 0 {
994 unsafe {
995 libc::kill(-pgid, libc::SIGKILL);
996 }
997 }
998 }
999 let _ = self.child.kill();
1000 let _ = self.child.wait();
1001 }
1002
1003 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
1006 let id = self.next;
1007 self.next += 1;
1008 let (out, err) = (
1009 format!("{}/{id}.o", self.tmp),
1010 format!("{}/{id}.e", self.tmp),
1011 );
1012 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
1013 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
1014 let body = match cwd {
1015 Some(d) => format!(
1016 "( cd {} && eval \"$__blyte_c\" )",
1017 quote(&d.to_string_lossy())
1018 ),
1019 None => "eval \"$__blyte_c\"".to_string(),
1020 };
1021 let script = format!(
1026 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
1027 [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
1028 IFS= read -r -d '' __blyte_o <{qo} || true; \
1029 IFS= read -r -d '' __blyte_e <{qe} || true; \
1030 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
1031 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
1032 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
1033 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
1034 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
1035 );
1036 if self.send(&script).is_err() {
1037 return RunResult::Died { out, err };
1038 }
1039 let marker = format!("__BLYTE_{id}__ ");
1040 let deadline = Instant::now() + timeout;
1041 let fail = |e: ReadErr, out: String, err: String| match e {
1042 ReadErr::Timeout => RunResult::TimedOut { out, err },
1043 ReadErr::Closed => RunResult::Died { out, err },
1044 };
1045 let header = loop {
1046 match self.read_line(deadline) {
1047 Ok(l) => {
1048 if let Some(rest) = l.strip_prefix(&marker) {
1049 break rest.to_string();
1050 }
1051 }
1052 Err(e) => return fail(e, out, err),
1053 }
1054 };
1055 let mut f = header.split(' ');
1056 let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
1057 let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
1058 let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
1059 match self.read_exact(no + ne, deadline) {
1060 Ok(bytes) => RunResult::Done(Output {
1061 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
1062 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
1063 exit_code,
1064 }),
1065 Err(e) => fail(e, out, err),
1066 }
1067 }
1068
1069 fn close(&mut self) {
1071 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
1072 let deadline = Instant::now() + Duration::from_millis(300);
1073 while Instant::now() < deadline {
1074 if let Ok(Some(_)) = self.child.try_wait() {
1075 return;
1076 }
1077 std::thread::sleep(Duration::from_millis(10));
1078 }
1079 self.kill();
1080 }
1081}
1082
1083pub type ProfileBuilder = Arc<dyn Fn() -> Result<Profile, String> + Send + Sync>;
1084
1085pub const SHELL_RESTART_NOTICE: &str =
1086 "blyte: the shell restarted because the open edits changed; exported variables were reset";
1087
1088struct UserSession {
1089 session: Session,
1090 profile: Option<Profile>,
1091}
1092
1093pub struct PersistentShell {
1102 launcher: Launcher,
1103 profile_builder: Option<ProfileBuilder>,
1104 harness: Mutex<Option<Session>>,
1105 user: Mutex<Option<UserSession>>,
1106 fallback: Box<dyn Shell>,
1107}
1108
1109impl PersistentShell {
1110 pub fn new(launcher: Launcher) -> Self {
1111 let fallback = launcher.fallback();
1112 Self {
1113 launcher,
1114 profile_builder: None,
1115 harness: Mutex::new(None),
1116 user: Mutex::new(None),
1117 fallback,
1118 }
1119 }
1120
1121 pub fn with_profile_builder(mut self, builder: ProfileBuilder) -> Self {
1122 self.profile_builder = Some(builder);
1123 self
1124 }
1125
1126 pub fn local(root: PathBuf) -> Self {
1127 Self::new(Launcher::Local {
1128 root,
1129 profile: None,
1130 })
1131 }
1132
1133 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1134 Self::new(Launcher::Local {
1135 root,
1136 profile: Some(profile.into()),
1137 })
1138 }
1139
1140 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1141 Self::local_sandboxed(root, profile)
1142 }
1143
1144 pub fn container(container_id: String, workdir: PathBuf) -> Self {
1145 Self::new(Launcher::Container {
1146 container_id,
1147 workdir,
1148 })
1149 }
1150
1151 pub fn is_persistent(&self) -> bool {
1153 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1154 if g.is_none() {
1155 *g = Session::start(&self.launcher).ok();
1156 }
1157 g.is_some()
1158 }
1159
1160 fn collect_aborted_output(
1161 &self,
1162 fallback: &dyn Shell,
1163 out: &str,
1164 err: &str,
1165 note: String,
1166 code: i32,
1167 ) -> Output {
1168 let cat = |p: &str| {
1169 fallback
1170 .exec(
1171 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1172 Path::new("/"),
1173 Duration::from_secs(30),
1174 )
1175 .map(|o| o.stdout)
1176 .unwrap_or_default()
1177 };
1178 let (stdout, stderr) = (cat(out), cat(err));
1179 Output {
1180 stdout,
1181 stderr: format!("{stderr}{note}"),
1182 exit_code: code,
1183 }
1184 }
1185
1186 fn run_harness(
1188 &self,
1189 command: &str,
1190 cwd: &Path,
1191 timeout: Duration,
1192 ) -> Option<Result<Output, String>> {
1193 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1194 if g.is_none() {
1195 *g = Session::start_with_marker(&self.launcher, false).ok();
1196 }
1197 let session = g.as_mut()?;
1198 let (out, err, note, code) = match session.run(command, Some(cwd), timeout) {
1199 RunResult::Done(o) => return Some(Ok(o)),
1200 RunResult::TimedOut { out, err } => (
1201 out,
1202 err,
1203 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1204 124,
1205 ),
1206 RunResult::Died { out, err } => (
1207 out,
1208 err,
1209 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1210 .to_string(),
1211 1,
1212 ),
1213 };
1214 session.kill();
1215 *g = None;
1216 drop(g);
1217 Some(Ok(self.collect_aborted_output(
1218 self.fallback.as_ref(),
1219 &out,
1220 &err,
1221 note,
1222 code,
1223 )))
1224 }
1225
1226 fn run_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1227 let desired_profile = match &self.profile_builder {
1228 Some(builder) => Some(builder()?),
1229 None => None,
1230 };
1231 let launcher = match &desired_profile {
1232 Some(profile) => self.launcher.with_profile(profile.clone()),
1233 None => self.launcher.clone(),
1234 };
1235
1236 let mut restarted = false;
1237 let mut g = self.user.lock().unwrap_or_else(|e| e.into_inner());
1238
1239 let mut saved_cwd = None;
1240 if let (Some(desired), Some(existing)) = (&desired_profile, g.as_mut()) {
1241 if existing.profile.as_ref() != Some(desired) {
1242 if let RunResult::Done(o) =
1243 existing.session.run("pwd", None, Duration::from_secs(5))
1244 {
1245 if o.exit_code == 0 {
1246 let dir = o.stdout.trim_end_matches(&['\n', '\r'][..]);
1247 if !dir.is_empty() {
1248 saved_cwd = Some(PathBuf::from(dir));
1249 }
1250 }
1251 }
1252 existing.session.close();
1253 *g = None;
1254 restarted = true;
1255 }
1256 }
1257
1258 if g.is_none() {
1259 match Session::start_with_marker(&launcher, true) {
1260 Ok(mut session) => {
1261 if let Some(dir) = saved_cwd {
1262 let _ = session.run(
1263 &format!("cd -- {}", quote(&dir.to_string_lossy())),
1264 None,
1265 Duration::from_secs(5),
1266 );
1267 }
1268 *g = Some(UserSession {
1269 session,
1270 profile: desired_profile,
1271 });
1272 }
1273 Err(_) => {
1274 drop(g);
1275 let mut out = if self.profile_builder.is_some() {
1276 launcher.fallback().exec_user(command, cwd, timeout)?
1277 } else {
1278 self.fallback.exec_user(command, cwd, timeout)?
1279 };
1280 if restarted {
1281 out.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", out.stdout);
1282 }
1283 return Ok(out);
1284 }
1285 }
1286 }
1287
1288 let user = g.as_mut().unwrap();
1289 let mut output = match user.session.run(command, None, timeout) {
1290 RunResult::Done(o) => o,
1291 RunResult::TimedOut { out, err } => {
1292 user.session.kill();
1293 *g = None;
1294 drop(g);
1295 let fallback = if self.profile_builder.is_some() {
1296 launcher.fallback()
1297 } else {
1298 self.launcher.fallback()
1299 };
1300 self.collect_aborted_output(
1301 fallback.as_ref(),
1302 &out,
1303 &err,
1304 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1305 124,
1306 )
1307 }
1308 RunResult::Died { out, err } => {
1309 user.session.kill();
1310 *g = None;
1311 drop(g);
1312 let fallback = if self.profile_builder.is_some() {
1313 launcher.fallback()
1314 } else {
1315 self.launcher.fallback()
1316 };
1317 self.collect_aborted_output(
1318 fallback.as_ref(),
1319 &out,
1320 &err,
1321 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1322 .to_string(),
1323 1,
1324 )
1325 }
1326 };
1327 if restarted {
1328 output.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", output.stdout);
1329 }
1330 Ok(output)
1331 }
1332}
1333
1334impl Shell for PersistentShell {
1335 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1336 self.run_harness(command, cwd, timeout)
1337 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1338 }
1339
1340 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1341 self.run_user(command, cwd, timeout)
1342 }
1343
1344 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1345 self.fallback.exec_host(command, cwd, timeout)
1346 }
1347
1348 fn describe(&self) -> String {
1349 format!(
1350 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1351 later commands. File tools always resolve paths from the workspace root.",
1352 self.fallback.describe()
1353 )
1354 }
1355}
1356
1357impl Drop for PersistentShell {
1358 fn drop(&mut self) {
1359 if let Some(mut s) = self
1360 .harness
1361 .lock()
1362 .unwrap_or_else(|e| e.into_inner())
1363 .take()
1364 {
1365 s.close();
1366 }
1367 if let Some(mut u) = self.user.lock().unwrap_or_else(|e| e.into_inner()).take() {
1368 u.session.close();
1369 }
1370 }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375 use super::*;
1376
1377 #[test]
1378 fn persistent_shell_profile_builder_error_fails_command() {
1379 let tmp = tempfile::tempdir().unwrap();
1380 let shell =
1381 PersistentShell::local(tmp.path().to_path_buf()).with_profile_builder(Arc::new(|| {
1382 Err("cannot read .wt: permission denied".into())
1383 }));
1384 let err = shell
1385 .exec_user("echo hi", tmp.path(), Duration::from_secs(5))
1386 .unwrap_err();
1387 assert_eq!(err, "cannot read .wt: permission denied");
1388 }
1389}