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] = &[
67 "AWS_PROFILE",
68 "AWS_DEFAULT_PROFILE",
69 "SSH_AUTH_SOCK",
70 "SSH_AGENT_PID",
71];
72
73static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
74
75pub fn credential_like(name: &str, value: &str) -> bool {
78 let upper = name.to_ascii_uppercase();
79 if CREDENTIAL_NAMES.contains(&upper.as_str()) {
80 return true;
81 }
82 if upper
83 .split('_')
84 .any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
85 {
86 return true;
87 }
88 has_inline_credentials(value)
89}
90
91fn has_inline_credentials(value: &str) -> bool {
92 let mut rest = value;
93 while let Some(idx) = rest.find("://") {
94 let after_scheme = &rest[idx + 3..];
95 let len = after_scheme
96 .find(|c: char| c == '/' || c.is_whitespace())
97 .unwrap_or(after_scheme.len());
98 let authority_prefix = &after_scheme[..len];
99 if let Some((userinfo, _)) = authority_prefix.split_once('@') {
100 if let Some((_user, pass)) = userinfo.split_once(':') {
101 if !pass.is_empty() {
102 return true;
103 }
104 }
105 }
106 rest = after_scheme;
107 }
108 false
109}
110
111pub fn set_pass_env(names: Vec<String>) {
115 let _ = PASS_ENV.set(names);
116}
117
118pub fn is_pass_env(name: &str) -> bool {
120 PASS_ENV
121 .get()
122 .is_some_and(|passed| passed.iter().any(|p| p == name))
123}
124
125pub fn withheld_env() -> Vec<String> {
127 let mut withheld = Vec::new();
128 for (key, val) in std::env::vars_os() {
129 let name = key.to_string_lossy();
130 if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
131 continue;
132 }
133 if name.starts_with("BLYTE_") {
134 continue;
135 }
136 if is_pass_env(&name) {
137 continue;
138 }
139 let value = val.to_string_lossy();
140 if credential_like(&name, &value) {
141 withheld.push(name.into_owned());
142 }
143 }
144 withheld.sort();
145 withheld.dedup();
146 withheld
147}
148
149pub const MODEL_SHELL_ENV: &str = "BLYTE_MODEL_SHELL";
150
151pub fn model_shell_refusal_message(command: &str) -> String {
152 format!(
153 "error: blyte {command} writes a record only the user or the harness may write, and cannot be run from a model's shell"
154 )
155}
156
157pub fn scrub_harness(cmd: &mut Command) {
160 cmd.env_remove(MODEL_SHELL_ENV);
161 for name in HARNESS_ENV {
162 cmd.env_remove(name);
163 }
164 for (name, _) in std::env::vars_os() {
165 let n = name.to_string_lossy();
166 if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
167 cmd.env_remove(&name);
168 }
169 }
170}
171
172fn scrub(cmd: &mut Command) {
174 scrub_harness(cmd);
175 for name in withheld_env() {
176 cmd.env_remove(name);
177 }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct Output {
182 pub stdout: String,
183 pub stderr: String,
184 pub exit_code: i32,
185}
186
187impl Output {
188 pub fn merged(&self) -> String {
191 format!("{}{}", self.stdout, self.stderr)
192 }
193}
194
195pub trait Shell: Send + Sync {
196 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
198
199 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
203 self.exec(command, cwd, timeout)
204 }
205
206 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
207 let _ = (command, cwd, timeout);
208 Err("this shell cannot run a command outside the sandbox".into())
209 }
210
211 fn describe(&self) -> String;
214
215 fn available_binaries(
217 &self,
218 cwd: &Path,
219 candidates: &[&'static str],
220 ) -> Result<Vec<String>, String> {
221 let probe = if candidates.is_empty() {
224 "true".to_string()
225 } else {
226 candidates
227 .iter()
228 .map(|b| format!("if command -v {b} >/dev/null 2>&1; then echo {b}; fi"))
229 .collect::<Vec<_>>()
230 .join("; ")
231 };
232 let o = self
233 .exec(&probe, cwd, Duration::from_secs(30))
234 .map_err(|e| format!("environment probe `{probe}` failed: {e}"))?;
235 if o.exit_code != 0 {
236 let detail = o.stderr.trim();
237 return Err(if detail.is_empty() {
238 format!(
239 "environment probe `{probe}` failed with exit status {}",
240 o.exit_code
241 )
242 } else {
243 format!(
244 "environment probe `{probe}` failed with exit status {}: {detail}",
245 o.exit_code
246 )
247 });
248 }
249 Ok(o.stdout
250 .lines()
251 .map(|l| l.trim().to_string())
252 .filter(|l| !l.is_empty())
253 .collect())
254 }
255}
256
257#[derive(Debug, Default)]
259pub struct CancelHandle {
260 cancelled: AtomicBool,
261 active_pgid: Mutex<Option<i32>>,
262}
263
264impl CancelHandle {
265 pub fn new() -> Self {
266 Self::default()
267 }
268
269 pub fn is_cancelled(&self) -> bool {
270 self.cancelled.load(Ordering::SeqCst)
271 }
272
273 pub fn flag(&self) -> &AtomicBool {
274 &self.cancelled
275 }
276
277 pub fn cancel(&self) {
278 let pgid = {
279 let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
280 self.cancelled.store(true, Ordering::SeqCst);
281 *guard
282 };
283 #[cfg(unix)]
284 if let Some(pgid) = pgid {
285 if pgid > 0 {
286 unsafe {
287 libc::kill(-pgid, libc::SIGKILL);
288 }
289 }
290 }
291 #[cfg(not(unix))]
292 let _ = pgid;
293 }
294
295 fn register_pgid(&self, pgid: i32) -> bool {
296 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
297 if self.cancelled.load(Ordering::SeqCst) {
298 return false;
299 }
300 *guard = Some(pgid);
301 true
302 }
303
304 fn clear_pgid(&self) {
305 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
306 *guard = None;
307 }
308}
309
310fn kill_child_group(child: &mut Child) {
311 #[cfg(unix)]
315 {
316 let pgid = child.id() as i32;
317 if pgid > 0 {
318 unsafe {
319 libc::kill(-pgid, libc::SIGKILL);
320 }
321 } else {
322 let _ = child.kill();
323 }
324 }
325 #[cfg(not(unix))]
326 {
327 let _ = child.kill();
328 }
329 let _ = child.wait();
330}
331
332pub const POLL_START: Duration = Duration::from_millis(1);
333
334pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
337 (
338 current.min(remaining),
339 (current * 2).min(Duration::from_millis(50)),
340 )
341}
342
343fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
356 exec_command_cancellable(cmd, timeout, None)
357}
358
359fn exec_command_cancellable(
360 mut cmd: Command,
361 timeout: Duration,
362 cancel: Option<&CancelHandle>,
363) -> Result<Output, String> {
364 use std::process::Stdio;
365
366 if cancel.is_some_and(CancelHandle::is_cancelled) {
367 return Err("command cancelled".into());
368 }
369
370 cmd.stdin(Stdio::null())
374 .stdout(Stdio::piped())
375 .stderr(Stdio::piped());
376
377 #[cfg(unix)]
382 {
383 use std::os::unix::process::CommandExt;
384 cmd.process_group(0);
385 }
386
387 let program = cmd.get_program().to_string_lossy().into_owned();
388 let mut child = cmd
389 .spawn()
390 .map_err(|e| format!("cannot run command `{program}`: {e}"))?;
391
392 if let Some(handle) = cancel {
393 if !handle.register_pgid(child.id() as i32) {
394 kill_child_group(&mut child);
395 return Err("command cancelled".into());
396 }
397 }
398
399 let mut so = child.stdout.take().ok_or("no stdout")?;
402 let mut se = child.stderr.take().ok_or("no stderr")?;
403 let t_out = std::thread::spawn(move || {
404 let mut b = String::new();
405 let _ = so.read_to_string(&mut b);
406 b
407 });
408 let t_err = std::thread::spawn(move || {
409 let mut b = String::new();
410 let _ = se.read_to_string(&mut b);
411 b
412 });
413
414 let deadline = std::time::Instant::now() + timeout;
415 let mut poll = POLL_START;
416 let mut was_cancelled = false;
417 let status = loop {
418 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
419 Some(s) => break Some(s),
420 None if cancel.is_some_and(CancelHandle::is_cancelled) => {
421 was_cancelled = true;
422 kill_child_group(&mut child);
423 break None;
424 }
425 None if std::time::Instant::now() >= deadline => {
426 kill_child_group(&mut child);
427 break None;
428 }
429 None => {
430 let remaining = deadline.saturating_duration_since(Instant::now());
431 let (sleep, next) = poll_backoff(poll, remaining);
432 std::thread::sleep(sleep);
433 poll = next;
434 }
435 }
436 };
437
438 if let Some(handle) = cancel {
439 handle.clear_pgid();
440 }
441
442 let stdout = t_out.join().unwrap_or_default();
443 let stderr = t_err.join().unwrap_or_default();
444
445 if was_cancelled {
446 return Err("command cancelled".into());
447 }
448
449 match status {
450 Some(s) => Ok(Output {
451 stdout,
452 stderr,
453 exit_code: s.code().unwrap_or(-1),
454 }),
455 None => Ok(Output {
458 stdout,
459 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
460 exit_code: 124, }),
462 }
463}
464
465#[derive(Debug, Default, Clone, PartialEq, Eq)]
467pub struct LocalShell {
468 pub profile: Option<Profile>,
469 pub tmpdir: Option<PathBuf>,
470}
471
472#[allow(non_upper_case_globals)]
473pub const LocalShell: LocalShell = LocalShell {
474 profile: None,
475 tmpdir: None,
476};
477
478impl LocalShell {
479 pub fn new() -> Self {
481 Self {
482 profile: None,
483 tmpdir: None,
484 }
485 }
486
487 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
489 Self {
490 profile: Some(profile.into()),
491 tmpdir: None,
492 }
493 }
494
495 pub fn with_tmpdir(mut self, tmpdir: Option<PathBuf>) -> Self {
497 self.tmpdir = tmpdir;
498 self
499 }
500
501 fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
502 let full_command = inherited_path_prefix() + command;
503 let command = full_command.as_str();
504 let mut cmd = match &self.profile {
505 Some(Profile::Seatbelt(profile)) => {
506 let mut c = Command::new("/usr/bin/sandbox-exec");
507 c.args(["-p", profile, "bash", "-lc", command]);
508 c
509 }
510 Some(Profile::Landlock(paths)) => {
511 #[cfg(target_os = "linux")]
512 {
513 let mut c = Command::new("bash");
514 c.arg("-lc").arg(command);
515 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
516 .map_err(|e| e.to_string())?;
517 c
518 }
519 #[cfg(not(target_os = "linux"))]
520 {
521 let _ = paths;
522 return Err(std::io::Error::new(
523 std::io::ErrorKind::Unsupported,
524 "Landlock is only supported on Linux",
525 )
526 .to_string());
527 }
528 }
529 Some(Profile::LandlockOffline(paths)) => {
530 #[cfg(target_os = "linux")]
531 {
532 let mut c = Command::new("bash");
533 c.arg("-lc").arg(command);
534 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
535 .map_err(|e| e.to_string())?;
536 c
537 }
538 #[cfg(not(target_os = "linux"))]
539 {
540 let _ = paths;
541 return Err(std::io::Error::new(
542 std::io::ErrorKind::Unsupported,
543 "Landlock is only supported on Linux",
544 )
545 .to_string());
546 }
547 }
548 Some(Profile::LandlockConfined {
549 write,
550 read,
551 block_tcp,
552 }) => {
553 #[cfg(target_os = "linux")]
554 {
555 let mut c = Command::new("bash");
556 c.arg("-lc").arg(command);
557 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
558 .map_err(|e| e.to_string())?;
559 c
560 }
561 #[cfg(not(target_os = "linux"))]
562 {
563 let _ = (write, read, block_tcp);
564 return Err(std::io::Error::new(
565 std::io::ErrorKind::Unsupported,
566 "Landlock is only supported on Linux",
567 )
568 .to_string());
569 }
570 }
571 None => {
572 let mut c = Command::new("bash");
573 c.arg("-lc").arg(command);
574 c
575 }
576 };
577 cmd.current_dir(cwd);
578 scrub(&mut cmd);
579 if let Some(ref tmpdir) = self.tmpdir {
580 cmd.env("TMPDIR", tmpdir);
581 }
582 Ok(cmd)
583 }
584}
585
586impl Shell for LocalShell {
587 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
588 let cmd = self.build_command(command, cwd)?;
589 exec_command(cmd, timeout)
590 }
591
592 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
593 let mut cmd = self.build_command(command, cwd)?;
594 cmd.env(MODEL_SHELL_ENV, "1");
595 exec_command(cmd, timeout)
596 }
597
598 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
599 let full_command = inherited_path_prefix() + command;
600 let mut cmd = Command::new("bash");
601 cmd.arg("-lc").arg(&full_command);
602 cmd.current_dir(cwd);
603 scrub_harness(&mut cmd);
604 cmd.env(MODEL_SHELL_ENV, "1");
605 exec_command(cmd, timeout)
606 }
607
608 fn describe(&self) -> String {
609 "Commands run directly on this machine, in the workspace directory.".into()
610 }
611}
612
613#[derive(Debug, Clone)]
615pub struct CancellableLocalShell {
616 pub inner: LocalShell,
617 pub cancel: Arc<CancelHandle>,
618}
619
620impl Shell for CancellableLocalShell {
621 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
622 let cmd = self.inner.build_command(command, cwd)?;
623 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
624 }
625
626 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
627 let mut cmd = self.inner.build_command(command, cwd)?;
628 cmd.env(MODEL_SHELL_ENV, "1");
629 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
630 }
631
632 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
633 let full_command = inherited_path_prefix() + command;
634 let mut cmd = Command::new("bash");
635 cmd.arg("-lc").arg(&full_command);
636 cmd.current_dir(cwd);
637 scrub_harness(&mut cmd);
638 cmd.env(MODEL_SHELL_ENV, "1");
639 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
640 }
641
642 fn describe(&self) -> String {
643 self.inner.describe()
644 }
645}
646
647#[derive(Debug, Clone)]
652pub struct ContainerShell {
653 pub container_id: String,
654 pub workdir: PathBuf,
656}
657
658impl ContainerShell {
659 fn build_command(&self, command: &str, model_shell: bool) -> Command {
660 let mut cmd = Command::new("docker");
661 cmd.args(["exec", "-i"]);
662 if model_shell {
663 cmd.args(["-e", "BLYTE_MODEL_SHELL=1"]);
664 }
665 cmd.arg("-w")
666 .arg(&self.workdir)
667 .arg(&self.container_id)
668 .args(["bash", "-lc", command]);
669 cmd
670 }
671}
672
673impl Shell for ContainerShell {
674 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
675 exec_command(self.build_command(command, false), timeout)
676 }
677
678 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
679 exec_command(self.build_command(command, true), timeout)
680 }
681
682 fn describe(&self) -> String {
683 format!(
684 "Commands run inside the project container at {}. Project dependencies are \
685 installed there, not on the host.",
686 self.workdir.display()
687 )
688 }
689}
690
691#[derive(Debug, Clone)]
693pub struct CancellableContainerShell {
694 pub inner: ContainerShell,
695 pub cancel: Arc<CancelHandle>,
696}
697
698impl Shell for CancellableContainerShell {
699 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
700 exec_command_cancellable(
701 self.inner.build_command(command, false),
702 timeout,
703 Some(&self.cancel),
704 )
705 }
706
707 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
708 exec_command_cancellable(
709 self.inner.build_command(command, true),
710 timeout,
711 Some(&self.cancel),
712 )
713 }
714
715 fn describe(&self) -> String {
716 self.inner.describe()
717 }
718}
719
720fn quote(s: &str) -> String {
722 format!("'{}'", s.replace('\'', r"'\''"))
723}
724
725pub fn inherited_path_prefix() -> String {
727 match std::env::var("PATH") {
728 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
729 _ => String::new(),
730 }
731}
732
733#[derive(Debug, Clone)]
735pub enum Launcher {
736 Local {
738 root: PathBuf,
739 profile: Option<Profile>,
740 tmpdir: Option<PathBuf>,
741 },
742 Container {
744 container_id: String,
745 workdir: PathBuf,
746 },
747}
748
749impl Launcher {
750 fn command(&self, model_shell: bool) -> std::io::Result<Command> {
751 match self {
752 Launcher::Local {
753 root,
754 profile,
755 tmpdir,
756 } => {
757 let mut c = match profile {
758 Some(Profile::Seatbelt(p)) => {
759 let mut cmd = Command::new("/usr/bin/sandbox-exec");
760 cmd.args(["-p", p, "bash", "-l"]);
761 cmd
762 }
763 Some(Profile::Landlock(paths)) => {
764 #[cfg(target_os = "linux")]
765 {
766 let mut cmd = Command::new("bash");
767 cmd.arg("-l");
768 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
769 cmd
770 }
771 #[cfg(not(target_os = "linux"))]
772 {
773 let _ = paths;
774 return Err(std::io::Error::new(
775 std::io::ErrorKind::Unsupported,
776 "Landlock is only supported on Linux",
777 ));
778 }
779 }
780 Some(Profile::LandlockOffline(paths)) => {
781 #[cfg(target_os = "linux")]
782 {
783 let mut cmd = Command::new("bash");
784 cmd.arg("-l");
785 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
786 cmd
787 }
788 #[cfg(not(target_os = "linux"))]
789 {
790 let _ = paths;
791 return Err(std::io::Error::new(
792 std::io::ErrorKind::Unsupported,
793 "Landlock is only supported on Linux",
794 ));
795 }
796 }
797 Some(Profile::LandlockConfined {
798 write,
799 read,
800 block_tcp,
801 }) => {
802 #[cfg(target_os = "linux")]
803 {
804 let mut cmd = Command::new("bash");
805 cmd.arg("-l");
806 crate::sandbox::landlock_pre_exec(
807 &mut cmd,
808 write,
809 Some(read),
810 *block_tcp,
811 )?;
812 cmd
813 }
814 #[cfg(not(target_os = "linux"))]
815 {
816 let _ = (write, read, block_tcp);
817 return Err(std::io::Error::new(
818 std::io::ErrorKind::Unsupported,
819 "Landlock is only supported on Linux",
820 ));
821 }
822 }
823 None => {
824 let mut cmd = Command::new("bash");
825 cmd.arg("-l");
826 cmd
827 }
828 };
829 c.current_dir(root);
830 scrub(&mut c);
831 if let Some(ref tmpdir) = tmpdir {
832 c.env("TMPDIR", tmpdir);
833 }
834 if model_shell {
835 c.env(MODEL_SHELL_ENV, "1");
836 }
837 Ok(c)
838 }
839 Launcher::Container {
840 container_id,
841 workdir,
842 } => {
843 let mut c = Command::new("docker");
844 c.args(["exec", "-i"]);
845 if model_shell {
846 c.args(["-e", "BLYTE_MODEL_SHELL=1"]);
847 }
848 c.arg("-w")
849 .arg(workdir)
850 .arg(container_id)
851 .args(["bash", "-l"]);
852 Ok(c)
853 }
854 }
855 }
856
857 fn with_profile(&self, profile: Profile) -> Self {
858 match self {
859 Launcher::Local { root, tmpdir, .. } => Launcher::Local {
860 root: root.clone(),
861 profile: Some(profile),
862 tmpdir: tmpdir.clone(),
863 },
864 Launcher::Container {
865 container_id,
866 workdir,
867 } => Launcher::Container {
868 container_id: container_id.clone(),
869 workdir: workdir.clone(),
870 },
871 }
872 }
873
874 fn fallback(&self) -> Box<dyn Shell> {
877 match self {
878 Launcher::Local {
879 profile, tmpdir, ..
880 } => match profile {
881 Some(p) => Box::new(LocalShell::sandboxed(p.clone()).with_tmpdir(tmpdir.clone())),
882 None => Box::new(LocalShell::new().with_tmpdir(tmpdir.clone())),
883 },
884 Launcher::Container {
885 container_id,
886 workdir,
887 } => Box::new(ContainerShell {
888 container_id: container_id.clone(),
889 workdir: workdir.clone(),
890 }),
891 }
892 }
893}
894
895pub enum RunResult {
897 Done(Output),
898 TimedOut {
900 out: String,
901 err: String,
902 },
903 Died {
905 out: String,
906 err: String,
907 },
908 Failed(String),
909}
910
911pub struct Session {
916 child: Child,
917 stdin: ChildStdin,
918 chunks: Receiver<Vec<u8>>,
919 buf: Vec<u8>,
920 tmp: String,
921 next: u64,
922 nonce: String,
923}
924
925const READY: &str = "__BLYTE_READY__ ";
926
927fn nonce() -> String {
929 let t = std::time::SystemTime::now()
930 .duration_since(std::time::UNIX_EPOCH)
931 .map(|d| d.as_nanos())
932 .unwrap_or(0);
933 format!("{t:x}{:x}", std::process::id())
934}
935
936enum ReadErr {
937 Timeout,
938 Closed,
939 Malformed(String),
940}
941
942fn parse_header(header: &str) -> Result<(i32, usize, usize), String> {
943 let malformed = || format!("shell returned a malformed result header: {header}");
944 let mut f = header.split(' ');
945 let exit_code: i32 = f
946 .next()
947 .ok_or_else(malformed)?
948 .parse()
949 .map_err(|_| malformed())?;
950 let no: usize = f
951 .next()
952 .ok_or_else(malformed)?
953 .parse()
954 .map_err(|_| malformed())?;
955 let ne: usize = f
956 .next()
957 .ok_or_else(malformed)?
958 .parse()
959 .map_err(|_| malformed())?;
960 if f.next().is_some() || no.checked_add(ne).is_none() {
961 return Err(malformed());
962 }
963 Ok((exit_code, no, ne))
964}
965
966impl Session {
967 pub fn start(launcher: &Launcher) -> Result<Session, String> {
968 Self::start_with_marker(launcher, false)
969 }
970
971 fn start_with_marker(launcher: &Launcher, model_shell: bool) -> Result<Session, String> {
972 let mut cmd = launcher
973 .command(model_shell)
974 .map_err(|e| format!("cannot start a shell session: {e}"))?;
975 cmd.stdin(Stdio::piped())
976 .stdout(Stdio::piped())
977 .stderr(Stdio::null());
978 #[cfg(unix)]
979 {
980 use std::os::unix::process::CommandExt;
981 cmd.process_group(0);
982 }
983 let mut child = cmd
984 .spawn()
985 .map_err(|e| format!("cannot start a shell session: {e}"))?;
986 let stdin = child.stdin.take().ok_or("no stdin")?;
987 let mut stdout = child.stdout.take().ok_or("no stdout")?;
988 let (tx, rx) = mpsc::channel();
989 std::thread::spawn(move || {
990 let mut chunk = vec![0u8; 64 * 1024];
991 loop {
992 match stdout.read(&mut chunk) {
993 Ok(0) | Err(_) => break,
994 Ok(n) => {
995 if tx.send(chunk[..n].to_vec()).is_err() {
996 break;
997 }
998 }
999 }
1000 }
1001 });
1002 let mut s = Session {
1003 child,
1004 stdin,
1005 chunks: rx,
1006 buf: Vec::new(),
1007 tmp: String::new(),
1008 next: 0,
1009 nonce: nonce(),
1010 };
1011 let init = match launcher {
1012 Launcher::Local { .. } => inherited_path_prefix(),
1013 Launcher::Container { .. } => String::new(),
1014 };
1015 s.send(&format!(
1016 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
1017 echo \"__BLYTE_READY__ $__blyte_t\"\n",
1018 ))?;
1019 let deadline = Instant::now() + Duration::from_secs(30);
1020 loop {
1021 match s.read_line(deadline) {
1022 Ok(l) if l.starts_with(READY) => {
1023 s.tmp = l[READY.len()..].trim().to_string();
1024 return Ok(s);
1025 }
1026 Ok(_) => continue, Err(_) => {
1028 s.kill();
1029 return Err("the shell session did not start".into());
1030 }
1031 }
1032 }
1033 }
1034
1035 fn send(&mut self, script: &str) -> Result<(), String> {
1036 self.stdin
1037 .write_all(script.as_bytes())
1038 .and_then(|_| self.stdin.flush())
1039 .map_err(|e| format!("the shell session closed: {e}"))
1040 }
1041
1042 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
1043 match self
1044 .chunks
1045 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
1046 {
1047 Ok(c) => {
1048 self.buf.extend_from_slice(&c);
1049 Ok(())
1050 }
1051 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
1052 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
1053 }
1054 }
1055
1056 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
1058 loop {
1059 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
1060 let line: Vec<u8> = self.buf.drain(..=i).collect();
1061 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
1062 }
1063 self.fill(deadline)?;
1064 }
1065 }
1066
1067 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
1069 while self.buf.len() < n {
1070 self.fill(deadline)?;
1071 }
1072 Ok(self.buf.drain(..n).collect())
1073 }
1074
1075 pub fn kill(&mut self) {
1077 #[cfg(unix)]
1078 {
1079 let pgid = self.child.id() as i32;
1080 if pgid > 0 {
1081 unsafe {
1082 libc::kill(-pgid, libc::SIGKILL);
1083 }
1084 }
1085 }
1086 let _ = self.child.kill();
1087 let _ = self.child.wait();
1088 }
1089
1090 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
1093 let id = self.next;
1094 self.next += 1;
1095 let (out, err) = (
1096 format!("{}/{id}.o", self.tmp),
1097 format!("{}/{id}.e", self.tmp),
1098 );
1099 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
1100 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
1101 let body = match cwd {
1102 Some(d) => format!(
1103 "( cd {} && eval \"$__blyte_c\" )",
1104 quote(&d.to_string_lossy())
1105 ),
1106 None => "eval \"$__blyte_c\"".to_string(),
1107 };
1108 let script = format!(
1113 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
1114 [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
1115 IFS= read -r -d '' __blyte_o <{qo} || true; \
1116 IFS= read -r -d '' __blyte_e <{qe} || true; \
1117 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
1118 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
1119 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
1120 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
1121 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
1122 );
1123 if self.send(&script).is_err() {
1124 return RunResult::Died { out, err };
1125 }
1126 let marker = format!("__BLYTE_{id}__ ");
1127 let deadline = Instant::now() + timeout;
1128 let fail = |e: ReadErr, out: String, err: String| match e {
1129 ReadErr::Timeout => RunResult::TimedOut { out, err },
1130 ReadErr::Closed => RunResult::Died { out, err },
1131 ReadErr::Malformed(msg) => RunResult::Failed(msg),
1132 };
1133 let header = loop {
1134 match self.read_line(deadline) {
1135 Ok(l) => {
1136 if let Some(rest) = l.strip_prefix(&marker) {
1137 break rest.to_string();
1138 }
1139 }
1140 Err(e) => return fail(e, out, err),
1141 }
1142 };
1143 let (exit_code, no, ne) = match parse_header(&header) {
1144 Ok(parsed) => parsed,
1145 Err(msg) => return fail(ReadErr::Malformed(msg), out, err),
1146 };
1147 match self.read_exact(no + ne, deadline) {
1148 Ok(bytes) => RunResult::Done(Output {
1149 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
1150 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
1151 exit_code,
1152 }),
1153 Err(e) => fail(e, out, err),
1154 }
1155 }
1156
1157 fn close(&mut self) {
1159 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
1160 let deadline = Instant::now() + Duration::from_millis(300);
1161 while Instant::now() < deadline {
1162 if let Ok(Some(_)) = self.child.try_wait() {
1163 return;
1164 }
1165 std::thread::sleep(Duration::from_millis(10));
1166 }
1167 self.kill();
1168 }
1169}
1170
1171pub type ProfileBuilder = Arc<dyn Fn() -> Result<Profile, String> + Send + Sync>;
1172
1173pub const SHELL_RESTART_NOTICE: &str =
1174 "blyte: the shell restarted because the open edits changed; exported variables were reset";
1175
1176struct UserSession {
1177 session: Session,
1178 profile: Option<Profile>,
1179}
1180
1181pub struct PersistentShell {
1190 launcher: Launcher,
1191 profile_builder: Option<ProfileBuilder>,
1192 harness: Mutex<Option<Session>>,
1193 user: Mutex<Option<UserSession>>,
1194 fallback: Box<dyn Shell>,
1195}
1196
1197impl PersistentShell {
1198 pub fn new(launcher: Launcher) -> Self {
1199 let fallback = launcher.fallback();
1200 Self {
1201 launcher,
1202 profile_builder: None,
1203 harness: Mutex::new(None),
1204 user: Mutex::new(None),
1205 fallback,
1206 }
1207 }
1208
1209 pub fn with_profile_builder(mut self, builder: ProfileBuilder) -> Self {
1210 self.profile_builder = Some(builder);
1211 self
1212 }
1213
1214 pub fn with_tmpdir(mut self, tmpdir: Option<PathBuf>) -> Self {
1215 if let Launcher::Local {
1216 tmpdir: ref mut slot,
1217 ..
1218 } = self.launcher
1219 {
1220 *slot = tmpdir;
1221 self.fallback = self.launcher.fallback();
1222 }
1223 self
1224 }
1225
1226 pub fn local(root: PathBuf) -> Self {
1227 Self::new(Launcher::Local {
1228 root,
1229 profile: None,
1230 tmpdir: None,
1231 })
1232 }
1233
1234 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1235 Self::new(Launcher::Local {
1236 root,
1237 profile: Some(profile.into()),
1238 tmpdir: None,
1239 })
1240 }
1241
1242 pub fn container(container_id: String, workdir: PathBuf) -> Self {
1243 Self::new(Launcher::Container {
1244 container_id,
1245 workdir,
1246 })
1247 }
1248
1249 pub fn is_persistent(&self) -> bool {
1251 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1252 if g.is_none() {
1253 *g = Session::start(&self.launcher).ok();
1254 }
1255 g.is_some()
1256 }
1257
1258 fn collect_aborted_output(
1259 &self,
1260 fallback: &dyn Shell,
1261 out: &str,
1262 err: &str,
1263 note: String,
1264 code: i32,
1265 ) -> Output {
1266 let cat = |p: &str| {
1267 fallback
1268 .exec(
1269 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1270 Path::new("/"),
1271 Duration::from_secs(30),
1272 )
1273 .map(|o| o.stdout)
1274 .unwrap_or_default()
1275 };
1276 let (stdout, stderr) = (cat(out), cat(err));
1277 Output {
1278 stdout,
1279 stderr: format!("{stderr}{note}"),
1280 exit_code: code,
1281 }
1282 }
1283
1284 fn run_harness(
1286 &self,
1287 command: &str,
1288 cwd: &Path,
1289 timeout: Duration,
1290 ) -> Option<Result<Output, String>> {
1291 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1292 if g.is_none() {
1293 *g = Session::start_with_marker(&self.launcher, false).ok();
1294 }
1295 let session = g.as_mut()?;
1296 let (out, err, note, code) = match session.run(command, Some(cwd), timeout) {
1297 RunResult::Done(o) => return Some(Ok(o)),
1298 RunResult::Failed(msg) => {
1299 session.kill();
1300 *g = None;
1301 return Some(Err(msg));
1302 }
1303 RunResult::TimedOut { out, err } => (
1304 out,
1305 err,
1306 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1307 124,
1308 ),
1309 RunResult::Died { out, err } => (
1310 out,
1311 err,
1312 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1313 .to_string(),
1314 1,
1315 ),
1316 };
1317 session.kill();
1318 *g = None;
1319 drop(g);
1320 Some(Ok(self.collect_aborted_output(
1321 self.fallback.as_ref(),
1322 &out,
1323 &err,
1324 note,
1325 code,
1326 )))
1327 }
1328
1329 fn run_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1330 let desired_profile = match &self.profile_builder {
1331 Some(builder) => Some(builder()?),
1332 None => None,
1333 };
1334 let launcher = match &desired_profile {
1335 Some(profile) => self.launcher.with_profile(profile.clone()),
1336 None => self.launcher.clone(),
1337 };
1338
1339 let mut restarted = false;
1340 let mut g = self.user.lock().unwrap_or_else(|e| e.into_inner());
1341
1342 let mut saved_cwd = None;
1343 if let (Some(desired), Some(existing)) = (&desired_profile, g.as_mut()) {
1344 if existing.profile.as_ref() != Some(desired) {
1345 if let RunResult::Done(o) =
1346 existing.session.run("pwd", None, Duration::from_secs(5))
1347 {
1348 if o.exit_code == 0 {
1349 let dir = o.stdout.trim_end_matches(&['\n', '\r'][..]);
1350 if !dir.is_empty() {
1351 saved_cwd = Some(PathBuf::from(dir));
1352 }
1353 }
1354 }
1355 existing.session.close();
1356 *g = None;
1357 restarted = true;
1358 }
1359 }
1360
1361 if g.is_none() {
1362 match Session::start_with_marker(&launcher, true) {
1363 Ok(mut session) => {
1364 if let Some(dir) = saved_cwd {
1365 let _ = session.run(
1366 &format!("cd -- {}", quote(&dir.to_string_lossy())),
1367 None,
1368 Duration::from_secs(5),
1369 );
1370 }
1371 *g = Some(UserSession {
1372 session,
1373 profile: desired_profile,
1374 });
1375 }
1376 Err(_) => {
1377 drop(g);
1378 let mut out = if self.profile_builder.is_some() {
1379 launcher.fallback().exec_user(command, cwd, timeout)?
1380 } else {
1381 self.fallback.exec_user(command, cwd, timeout)?
1382 };
1383 if restarted {
1384 out.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", out.stdout);
1385 }
1386 return Ok(out);
1387 }
1388 }
1389 }
1390
1391 let user = g.as_mut().unwrap();
1392 let mut output = match user.session.run(command, None, timeout) {
1393 RunResult::Done(o) => o,
1394 RunResult::Failed(msg) => {
1395 user.session.kill();
1396 *g = None;
1397 return Err(msg);
1398 }
1399 RunResult::TimedOut { out, err } => {
1400 user.session.kill();
1401 *g = None;
1402 drop(g);
1403 let fallback = if self.profile_builder.is_some() {
1404 launcher.fallback()
1405 } else {
1406 self.launcher.fallback()
1407 };
1408 self.collect_aborted_output(
1409 fallback.as_ref(),
1410 &out,
1411 &err,
1412 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1413 124,
1414 )
1415 }
1416 RunResult::Died { out, err } => {
1417 user.session.kill();
1418 *g = None;
1419 drop(g);
1420 let fallback = if self.profile_builder.is_some() {
1421 launcher.fallback()
1422 } else {
1423 self.launcher.fallback()
1424 };
1425 self.collect_aborted_output(
1426 fallback.as_ref(),
1427 &out,
1428 &err,
1429 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1430 .to_string(),
1431 1,
1432 )
1433 }
1434 };
1435 if restarted {
1436 output.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", output.stdout);
1437 }
1438 Ok(output)
1439 }
1440}
1441
1442impl Shell for PersistentShell {
1443 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1444 self.run_harness(command, cwd, timeout)
1445 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1446 }
1447
1448 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1449 self.run_user(command, cwd, timeout)
1450 }
1451
1452 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1453 self.fallback.exec_host(command, cwd, timeout)
1454 }
1455
1456 fn describe(&self) -> String {
1457 format!(
1458 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1459 later commands. File tools always resolve paths from the workspace root.",
1460 self.fallback.describe()
1461 )
1462 }
1463}
1464
1465impl Drop for PersistentShell {
1466 fn drop(&mut self) {
1467 if let Some(mut s) = self
1468 .harness
1469 .lock()
1470 .unwrap_or_else(|e| e.into_inner())
1471 .take()
1472 {
1473 s.close();
1474 }
1475 if let Some(mut u) = self.user.lock().unwrap_or_else(|e| e.into_inner()).take() {
1476 u.session.close();
1477 }
1478 }
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483 use super::*;
1484
1485 #[test]
1486 fn persistent_shell_profile_builder_error_fails_command() {
1487 let tmp = tempfile::tempdir().unwrap();
1488 let shell =
1489 PersistentShell::local(tmp.path().to_path_buf()).with_profile_builder(Arc::new(|| {
1490 Err("cannot read .wt: permission denied".into())
1491 }));
1492 let err = shell
1493 .exec_user("echo hi", tmp.path(), Duration::from_secs(5))
1494 .unwrap_err();
1495 assert_eq!(err, "cannot read .wt: permission denied");
1496 }
1497
1498 #[test]
1499 fn parse_header_accepts_valid_and_rejects_malformed() {
1500 assert_eq!(parse_header("0 3 4"), Ok((0, 3, 4)));
1501 assert_eq!(parse_header("127 0 12"), Ok((127, 0, 12)));
1502 assert_eq!(parse_header("-1 0 0"), Ok((-1, 0, 0)));
1503
1504 for bad in ["", "x 1 2", "0 1", "0 -1 2", "0 1 2 3"] {
1505 let err = parse_header(bad).unwrap_err();
1506 assert_eq!(
1507 err,
1508 format!("shell returned a malformed result header: {bad}")
1509 );
1510 }
1511 }
1512
1513 #[cfg(unix)]
1514 #[test]
1515 fn persistent_shell_rejects_malformed_result_header_and_recovers() {
1516 let tmp = tempfile::tempdir().unwrap();
1517 let root = tmp.path().canonicalize().unwrap();
1518 let shell = PersistentShell::local(root.clone());
1519 let err = shell
1520 .exec_user(
1521 "printf() { builtin printf '__BLYTE_0__ x 1 2\\n'; }",
1522 &root,
1523 Duration::from_secs(10),
1524 )
1525 .unwrap_err();
1526 assert_eq!(err, "shell returned a malformed result header: x 1 2");
1527
1528 let recovered = shell
1529 .exec_user("echo ok", &root, Duration::from_secs(10))
1530 .unwrap();
1531 assert_eq!(recovered.exit_code, 0);
1532 assert_eq!(recovered.stdout, "ok\n");
1533 }
1534
1535 struct FailingExecShell {
1536 outcome: Result<Output, String>,
1537 }
1538
1539 impl Shell for FailingExecShell {
1540 fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
1541 self.outcome.clone()
1542 }
1543
1544 fn describe(&self) -> String {
1545 "failing".into()
1546 }
1547 }
1548
1549 struct UnspawnableShell;
1550
1551 impl Shell for UnspawnableShell {
1552 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1553 let mut cmd = Command::new("/nonexistent-blyte-probe-binary");
1554 cmd.arg("-c").arg(command).current_dir(cwd);
1555 exec_command(cmd, timeout)
1556 }
1557
1558 fn describe(&self) -> String {
1559 "unspawnable".into()
1560 }
1561 }
1562
1563 #[test]
1564 fn available_binaries_returns_err_when_probe_cannot_be_spawned() {
1565 let tmp = tempfile::tempdir().unwrap();
1566 let err = UnspawnableShell
1567 .available_binaries(tmp.path(), &["git", "cargo"])
1568 .unwrap_err();
1569 assert!(err.contains("command -v git"), "got: {err}");
1570 assert!(
1571 err.contains("/nonexistent-blyte-probe-binary"),
1572 "got: {err}"
1573 );
1574 }
1575
1576 #[test]
1577 fn available_binaries_returns_err_when_probe_exits_nonzero() {
1578 let shell = FailingExecShell {
1579 outcome: Ok(Output {
1580 stdout: String::new(),
1581 stderr: "Error response from daemon: container is not running\n".into(),
1582 exit_code: 125,
1583 }),
1584 };
1585 let err = shell
1586 .available_binaries(Path::new("."), &["git", "cargo"])
1587 .unwrap_err();
1588 assert!(err.contains("command -v git"), "got: {err}");
1589 assert!(err.contains("125"), "got: {err}");
1590 assert!(err.contains("container is not running"), "got: {err}");
1591 }
1592
1593 #[test]
1594 fn available_binaries_succeeds_when_all_candidates_are_absent() {
1595 let tmp = tempfile::tempdir().unwrap();
1596 let bins = LocalShell
1597 .available_binaries(
1598 tmp.path(),
1599 &[
1600 "blyte_nonexistent_probe_binary_a",
1601 "blyte_nonexistent_probe_binary_b",
1602 ],
1603 )
1604 .expect("missing candidates must not fail the probe");
1605 assert!(bins.is_empty(), "got: {bins:?}");
1606 }
1607}