@@ -1,7 +1,7 @@
1−use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2−use anyhow::{Context, Error, Result, bail};
31use std::{
4− env, fs,
2+ env,
3+ ffi::OsString,
4+ fs,
55 io::{self, Write},
66 os::{
77 fd::RawFd,
@@ -15,7 +15,6 @@ use std::{
1515 process::{Command, Stdio},
1616 sync::{
1717 Arc, Condvar, Mutex,
18− atomic::{AtomicBool, Ordering},
1918 mpsc::{self, Receiver, Sender},
2019 },
2120 thread,
@@ -23,8 +22,8 @@ use std::{
2322};
2423
2524use block2::RcBlock;
26−use bytesize::ByteSize;
2725use dispatch2::DispatchQueue;
26+use lexopt::prelude::*;
2827use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
2928use objc2_foundation::*;
3029use objc2_virtualization::*;
@@ -33,46 +32,39 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3332const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3433const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3534const SHARED_DIRECTORIES_TAG: &str = "shared";
36−pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3735
36+const BYTES_PER_MB: u64 = 1024 * 1024;
37+const DEFAULT_CPU_COUNT: usize = 2;
38+const DEFAULT_RAM_MB: u64 = 2048;
39+const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
3840const START_TIMEOUT: Duration = Duration::from_secs(60);
41+const DEFAULT_EXPECT_TIMEOUT: Duration = Duration::from_secs(30);
3942const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40−const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
41−
42−const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
4343const PROVISION_SCRIPT: &str = include_str!("provision.sh");
44−const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
45−const DEFAULT_RAW_NAME: &str = "default.raw";
46−const INSTANCE_RAW_NAME: &str = "instance.raw";
47−const BASE_DISK_RAW_NAME: &str = "disk.raw";
4844
4945#[derive(Clone)]
50−pub enum LoginAction {
51− Expect {
52− text: String,
53− timeout: Duration,
54− },
55− ExpectEither {
56− success: String,
57− failure: String,
58− timeout: Duration,
59− },
46+enum LoginAction {
47+ Expect { text: String, timeout: Duration },
6048 Send(String),
49+ Script { path: PathBuf, index: usize },
6150}
62−use crate::config::BoxConfig;
6351use LoginAction::*;
6452
6553#[derive(Clone)]
66−pub struct DirectoryShare {
54+struct DirectoryShare {
6755 host: PathBuf,
6856 guest: PathBuf,
6957 read_only: bool,
7058}
7159
7260impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
61+ fn new(
62+ host: PathBuf,
63+ mut guest: PathBuf,
64+ read_only: bool,
65+ ) -> Result<Self, Box<dyn std::error::Error>> {
7466 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
67+ return Err(format!("Host path does not exist: {}", host.display()).into());
7668 }
7769 if !guest.is_absolute() {
7870 guest = PathBuf::from("/root").join(guest);
@@ -84,22 +76,23 @@ impl DirectoryShare {
8476 })
8577 }
8678
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
79+ fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
8880 let parts: Vec<&str> = spec.split(':').collect();
8981 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
82+ return Err(format!("Invalid mount spec: {spec}").into());
9183 }
92− let host = expand_tilde_path(parts[0]);
84+ let host = PathBuf::from(parts[0]);
9385 let guest = PathBuf::from(parts[1]);
9486 let read_only = if parts.len() == 3 {
9587 match parts[2] {
9688 "read-only" => true,
9789 "read-write" => false,
9890 _ => {
99− bail!(format!(
91+ return Err(format!(
10092 "Invalid mount mode '{}'; expected read-only or read-write",
10193 parts[2]
102− ));
94+ )
95+ .into());
10396 }
10497 }
10598 } else {
@@ -122,58 +115,47 @@ impl DirectoryShare {
122115 }
123116}
124117
125−fn expand_tilde_path(value: &str) -> PathBuf {
126− if let Some(stripped) = value.strip_prefix("~/") {
127− if let Ok(home) = env::var("HOME") {
128− return PathBuf::from(home).join(stripped);
129− }
130− } else if value == "~"
131− && let Ok(home) = env::var("HOME")
132− {
133− return PathBuf::from(home);
134− }
135− PathBuf::from(value)
136−}
118+fn main() -> Result<(), Box<dyn std::error::Error>> {
119+ let args = parse_cli()?;
137120
138−pub struct VmArg {
139− pub cpu_count: usize,
140− pub ram_bytes: u64,
141− pub disk_bytes: u64,
142− pub no_default_mounts: bool,
143− pub mounts: Vec<String>,
144−}
145−
146−type StatusEmitter<'a> = dyn Fn(&str) + std::marker::Send + Sync + 'a;
147−
148−fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149− if let Some(status) = status {
150− status(message);
121+ if args.version {
122+ println!("Vibe");
123+ println!("https://github.com/lynaghk/vibe/");
124+ println!("Git SHA: {}", env!("GIT_SHA"));
125+ std::process::exit(0);
151126 }
152−}
153127
154−pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
155−where
156− F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
157−{
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
159−}
128+ if args.help {
129+ println!(
130+ "Vibe is a quick way to spin up a Linux virtual machine on Mac to sandbox LLM agents.
131+
132+vibe [OPTIONS] [disk-image.raw]
133+
134+Options
135+
136+ --help Print this help message.
137+ --version Print the version (commit SHA).
138+ --no-default-mounts Disable all default mounts.
139+ --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
140+ Defaults to read-write.
141+ Errors if host-path does not exist.
142+ --cpus <count> Number of virtual CPUs (default {DEFAULT_CPU_COUNT}).
143+ --ram <megabytes> RAM size in megabytes (default {DEFAULT_RAM_MB}).
144+ --script <path/to/script.sh> Run script in VM.
145+ --send <some-command> Type `some-command` followed by newline into the VM.
146+ --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
147+ If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
148+"
149+ );
150+ std::process::exit(0);
151+ }
160152
161−pub fn run_with_args_and_extras<F>(
162− args: VmArg,
163− io_handler: F,
164− extra_login_actions: Vec<LoginAction>,
165− extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
167−) -> Result<()>
168−where
169− F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
170−{
171153 ensure_signed();
172154
173155 let project_root = env::current_dir()?;
174156 let project_name = project_root
175157 .file_name()
176− .with_context(|| "Project directory has no name")?
158+ .ok_or("Project directory has no name")?
177159 .to_string_lossy()
178160 .into_owned();
179161
@@ -181,14 +163,10 @@ where
181163 let cache_home = env::var("XDG_CACHE_HOME")
182164 .map(PathBuf::from)
183165 .unwrap_or_else(|_| home.join(".cache"));
184− let cache_dir = cache_home.join(GLOBAL_CACHE_DIR_NAME);
166+ let cache_dir = cache_home.join("vibe");
185167 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
186168
187− let instance_dir = project_root.join(INSTANCE_DIR_NAME);
188− fs::create_dir_all(&instance_dir)?;
189− emit_status(status, "preparing VM image...");
190− tracing::info!("preparing VM image...");
191− let provision_log = instance_dir.join("provision.log");
169+ let instance_dir = project_root.join(".vibe");
192170
193171 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194172 let base_compressed = cache_dir.join(basename_compressed);
@@ -197,8 +175,8 @@ where
197175 basename_compressed.trim_end_matches(".tar.xz")
198176 ));
199177
200− let default_raw = cache_dir.join(DEFAULT_RAW_NAME);
201− let instance_raw = instance_dir.join(INSTANCE_RAW_NAME);
178+ let default_raw = cache_dir.join("default.raw");
179+ let instance_raw = instance_dir.join("instance.raw");
202180
203181 // Prepare system-wide directories
204182 fs::create_dir_all(&cache_dir)?;
@@ -207,31 +185,28 @@ where
207185 let mise_directory_share =
208186 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
209187
210− ensure_default_image(
211− &base_raw,
212− &base_compressed,
213− &default_raw,
214− std::slice::from_ref(&mise_directory_share),
215− Some(&provision_log),
216− status,
217− )?;
218− let _ = ensure_instance_disk(
219− &instance_raw,
220− &default_raw,
221− ByteSize(args.disk_bytes),
222− status,
223− )?;
224− let base_size = fs::metadata(&default_raw)?.len();
225− let instance_size = fs::metadata(&instance_raw)?.len();
226− let needs_resize = instance_size > base_size;
227− let disk_path = instance_raw;
188+ let disk_path = if let Some(path) = args.disk {
189+ if !path.exists() {
190+ return Err(format!("Disk image does not exist: {}", path.display()).into());
191+ }
192+ path
193+ } else {
194+ ensure_default_image(
195+ &base_raw,
196+ &base_compressed,
197+ &default_raw,
198+ std::slice::from_ref(&mise_directory_share),
199+ )?;
200+ ensure_instance_disk(&instance_raw, &default_raw)?;
201+
202+ instance_raw
203+ };
228204
229205 let mut login_actions = Vec::new();
230206 let mut directory_shares = Vec::new();
231207
232208 if !args.no_default_mounts {
233− let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234− login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
209+ login_actions.push(Send(format!("cd {project_name}")));
235210
236211 // discourage read/write of .git folder from within the VM. note that this isn't secure, since the VM runs as root and could unmount this.
237212 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -239,55 +214,170 @@ where
239214 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
240215 }
241216
217+ directory_shares.push(
218+ DirectoryShare::new(
219+ project_root,
220+ PathBuf::from("/root/").join(project_name),
221+ false,
222+ )
223+ .expect("Project directory must exist"),
224+ );
225+
242226 directory_shares.push(mise_directory_share);
243− }
244227
245− directory_shares.extend(extra_directory_shares);
228+ // Add default shares, if they exist
229+ for share in [
230+ DirectoryShare::new(home.join(".m2"), "/root/.m2".into(), false),
231+ DirectoryShare::new(
232+ home.join(".cargo/registry"),
233+ "/root/.cargo/registry".into(),
234+ false,
235+ ),
236+ DirectoryShare::new(home.join(".codex"), "/root/.codex".into(), false),
237+ DirectoryShare::new(home.join(".claude"), "/root/.claude".into(), false),
238+ ]
239+ .into_iter()
240+ .flatten()
241+ {
242+ directory_shares.push(share)
243+ }
244+ }
246245
247246 for spec in &args.mounts {
248247 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
249248 }
250249
251− if needs_resize {
252− let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
253− login_actions.push(Send(resize_cmd));
254− }
255−
256250 if let Some(motd_action) = motd_login_action(&directory_shares) {
257251 login_actions.push(motd_action);
258252 }
259253
260− login_actions.extend(extra_login_actions);
254+ // Any user-provided login actions must come after our system ones
255+ login_actions.extend(args.login_actions);
261256
262− run_vm_with_io(
257+ run_vm(
263258 &disk_path,
264259 &login_actions,
265260 &directory_shares[..],
266261 args.cpu_count,
267262 args.ram_bytes,
268− status,
269− io_handler,
270263 )
271264}
272265
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
266+struct CliArgs {
267+ disk: Option<PathBuf>,
268+ version: bool,
269+ help: bool,
270+ no_default_mounts: bool,
271+ mounts: Vec<String>,
272+ login_actions: Vec<LoginAction>,
273+ cpu_count: usize,
274+ ram_bytes: u64,
275+}
276+
277+fn parse_cli() -> Result<CliArgs, Box<dyn std::error::Error>> {
278+ fn os_to_string(value: OsString, flag: &str) -> Result<String, Box<dyn std::error::Error>> {
279+ value
280+ .into_string()
281+ .map_err(|_| format!("{flag} expects valid UTF-8").into())
282+ }
283+
284+ let mut parser = lexopt::Parser::from_env();
285+ let mut disk = None;
286+ let mut version = false;
287+ let mut help = false;
288+ let mut no_default_mounts = false;
289+ let mut mounts = Vec::new();
290+ let mut login_actions = Vec::new();
291+ let mut script_index = 0;
292+ let mut cpu_count = DEFAULT_CPU_COUNT;
293+ let mut ram_bytes = DEFAULT_RAM_BYTES;
294+
295+ while let Some(arg) = parser.next()? {
296+ match arg {
297+ Long("version") => version = true,
298+ Long("help") | Short('h') => help = true,
299+ Long("no-default-mounts") => no_default_mounts = true,
300+ Long("cpus") => {
301+ let value = os_to_string(parser.value()?, "--cpus")?.parse()?;
302+ if value == 0 {
303+ return Err("--cpus must be >= 1".into());
304+ }
305+ cpu_count = value;
306+ }
307+ Long("ram") => {
308+ let value: u64 = os_to_string(parser.value()?, "--ram")?.parse()?;
309+ if value == 0 {
310+ return Err("--ram must be >= 1".into());
311+ }
312+ ram_bytes = value * BYTES_PER_MB;
313+ }
314+ Long("mount") => {
315+ mounts.push(os_to_string(parser.value()?, "--mount")?);
316+ }
317+ Long("script") => {
318+ login_actions.push(Script {
319+ path: os_to_string(parser.value()?, "--script")?.into(),
320+ index: script_index,
321+ });
322+ script_index += 1;
323+ }
324+ Long("send") => {
325+ login_actions.push(Send(os_to_string(parser.value()?, "--send")?));
326+ }
327+ Long("expect") => {
328+ let text = os_to_string(parser.value()?, "--expect")?;
329+ let timeout = match parser.optional_value() {
330+ Some(value) => Duration::from_secs(os_to_string(value, "--expect")?.parse()?),
331+ None => DEFAULT_EXPECT_TIMEOUT,
332+ };
333+ login_actions.push(Expect { text, timeout });
334+ }
335+ Value(value) => {
336+ if disk.is_some() {
337+ return Err("Only one disk path may be provided".into());
338+ }
339+ disk = Some(PathBuf::from(value));
340+ }
341+ _ => return Err(arg.unexpected().into()),
342+ }
343+ }
344+
345+ Ok(CliArgs {
346+ disk,
347+ version,
348+ help,
349+ no_default_mounts,
350+ mounts,
351+ login_actions,
352+ cpu_count,
353+ ram_bytes,
354+ })
355+}
356+
357+fn script_command_from_path(
358+ path: &Path,
359+ index: usize,
360+) -> Result<String, Box<dyn std::error::Error>> {
361+ let script = fs::read_to_string(path)
362+ .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
363+ let label = format!("{}_{}", index, path.file_name().unwrap().display());
364+ script_command_from_content(&label, &script)
365+}
366+
367+fn script_command_from_content(
368+ label: &str,
369+ script: &str,
370+) -> Result<String, Box<dyn std::error::Error>> {
274371 let marker = "VIBE_SCRIPT_EOF";
275372 let guest_dir = "/tmp/vibe-scripts";
276373 let guest_path = format!("{guest_dir}/{label}.sh");
277− let script_body = match script.split_once('\n') {
278− Some((first, rest)) if first.starts_with("#!") => rest,
279− _ => script,
280− };
281− let wrapped_script = ERROR_REPORT_SCRIPT
282− .replace("__LABEL__", label)
283− .replace("__SCRIPT_BODY__", script_body);
284374 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
375+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
286376 );
287377 if script.contains(marker) {
288− bail!(format!(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
290− ));
378+ return Err(
379+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
380+ );
291381 }
292382 Ok(command)
293383}
@@ -321,6 +411,18 @@ fn motd_login_action(directory_shares: &[DirectoryShare]) -> Option<LoginAction>
321411 }
322412
323413 let mut output = String::new();
414+ output.push_str(
415+ "
416+░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
417+░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
418+ ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
419+ ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░░▒▓██████▓▒░
420+ ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
421+ ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
422+ ░▒▓██▓▒░ ░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
423+
424+",
425+ );
324426 output.push_str(&format!(
325427 "{host_header:<host_width$} {guest_header:<guest_width$} {mode_header}\n",
326428 host_width = host_width
@@ -351,12 +453,6 @@ enum WaitResult {
351453 Found,
352454}
353455
354−#[derive(PartialEq, Eq)]
355−enum WaitAnyResult {
356− Timeout,
357− Found(usize),
358−}
359−
360456pub enum VmInput {
361457 Bytes(Vec<u8>),
362458 Shutdown,
@@ -364,7 +460,6 @@ pub enum VmInput {
364460
365461enum VmOutput {
366462 LoginActionTimeout { action: String, timeout: Duration },
367− LoginActionFailed { action: String, reason: String },
368463}
369464
370465#[derive(Default)]
@@ -401,100 +496,20 @@ impl OutputMonitor {
401496 WaitResult::Found
402497 }
403498 }
404−
405− fn wait_for_any(&self, needles: &[&str], timeout: Duration) -> WaitAnyResult {
406− let mut found: Option<usize> = None;
407− let (_unused, timeout_result) = self
408− .condvar
409− .wait_timeout_while(self.buffer.lock().unwrap(), timeout, |buf| {
410− if let Some((pos, idx, len)) = find_any(buf, needles) {
411− *buf = buf[(pos + len)..].to_string();
412− found = Some(idx);
413− false
414− } else {
415− true
416− }
417− })
418− .unwrap();
419−
420− if timeout_result.timed_out() {
421− WaitAnyResult::Timeout
422− } else {
423− WaitAnyResult::Found(found.unwrap_or(0))
424− }
425− }
426−}
427−
428−fn find_any(buf: &str, needles: &[&str]) -> Option<(usize, usize, usize)> {
429− let mut best: Option<(usize, usize, usize)> = None; // (pos, idx, len)
430− for (idx, needle) in needles.iter().enumerate() {
431− if let Some(pos) = buf.find(needle) {
432− let candidate = (pos, idx, needle.len());
433− if best.is_none_or(|b| candidate.0 < b.0) {
434− best = Some(candidate);
435− }
436− }
437− }
438− best
439−}
440−
441−#[derive(Debug)]
442−pub struct IoControl {
443− forward_input: AtomicBool,
444− forward_output: AtomicBool,
445− restore_terminal: AtomicBool,
446−}
447−
448−impl IoControl {
449− pub fn new() -> Arc<Self> {
450− Arc::new(Self {
451− forward_input: AtomicBool::new(true),
452− forward_output: AtomicBool::new(true),
453− restore_terminal: AtomicBool::new(false),
454− })
455− }
456−
457− pub fn set_forward_input(&self, enabled: bool) {
458− self.forward_input.store(enabled, Ordering::SeqCst);
459− }
460−
461− pub fn set_forward_output(&self, enabled: bool) {
462− self.forward_output.store(enabled, Ordering::SeqCst);
463− }
464−
465− pub fn request_terminal_restore(&self) {
466− self.restore_terminal.store(true, Ordering::SeqCst);
467− }
468−
469− fn forward_input(&self) -> bool {
470− self.forward_input.load(Ordering::SeqCst)
471− }
472−
473− fn forward_output(&self) -> bool {
474− self.forward_output.load(Ordering::SeqCst)
475− }
476−
477− fn take_restore_terminal(&self) -> bool {
478− self.restore_terminal
479− .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
480− .is_ok()
481− }
482499}
483500
484501fn ensure_base_image(
485502 base_raw: &Path,
486503 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
488−) -> Result<()> {
504+) -> Result<(), Box<dyn std::error::Error>> {
489505 if base_raw.exists() {
490506 return Ok(());
491507 }
492508
493509 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
510+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
495511 {
496− emit_status(status, "downloading base image...");
497− tracing::info!("downloading base image");
512+ println!("Downloading base image...");
498513 let status = Command::new("curl")
499514 .args([
500515 "--continue-at",
@@ -508,14 +523,12 @@ fn ensure_base_image(
508523 ])
509524 .status()?;
510525 if !status.success() {
511− bail!("failed to download base image");
526+ return Err("Failed to download base image".into());
512527 }
513528 }
514529
515530 // Check SHA
516531 {
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
519532 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
520533
521534 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +546,18 @@ fn ensure_base_image(
533546
534547 let status = child.wait().expect("failed to wait on child");
535548 if !status.success() {
536− bail!(format!(
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538− ));
549+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
539550 }
540551 }
541552
542− emit_status(status, "decompressing base image...");
543− tracing::info!("decompressing base image...");
553+ println!("Decompressing base image...");
544554 let status = Command::new("tar")
545− .args([
546− "-xOf",
547− &base_compressed.to_string_lossy(),
548− BASE_DISK_RAW_NAME,
549− ])
550− .stdout(fs::File::create(base_raw)?)
555+ .args(["-xOf", &base_compressed.to_string_lossy(), "disk.raw"])
556+ .stdout(std::fs::File::create(base_raw)?)
551557 .status()?;
552558
553559 if !status.success() {
554− bail!("Failed to decompress base image");
560+ return Err("Failed to decompress base image".into());
555561 }
556562
557563 Ok(())
@@ -562,56 +568,24 @@ fn ensure_default_image(
562568 base_compressed: &Path,
563569 default_raw: &Path,
564570 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
566− status: Option<&StatusEmitter<'_>>,
567−) -> Result<()> {
571+) -> Result<(), Box<dyn std::error::Error>> {
568572 if default_raw.exists() {
569573 return Ok(());
570574 }
571575
572− ensure_base_image(base_raw, base_compressed, status)?;
576+ ensure_base_image(base_raw, base_compressed)?;
573577
574− emit_status(status, "configuring base image...");
575− tracing::info!("configuring base image...");
578+ println!("Configuring base image...");
576579 fs::copy(base_raw, default_raw)?;
577580
578581 let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
579− let provision_actions = [
580− Send(provision_command),
581− ExpectEither {
582− success: "VIBEBOX_PROVISION_OK".to_string(),
583− failure: "VIBEBOX_PROVISION_FAILED".to_string(),
584− timeout: PROVISION_EXPECT_TIMEOUT,
585− },
586− ];
587− let provision_result = if let Some(log_path) = provision_log {
588− let log_path = log_path.to_path_buf();
589− run_vm_with_io(
590− default_raw,
591− &provision_actions,
592− directory_shares,
593− BoxConfig::default().cpu_count,
594− BoxConfig::default().ram_size.as_u64(),
595− status,
596− move |output_monitor, vm_output_fd, vm_input_fd| {
597− spawn_vm_io_with_log(output_monitor, vm_output_fd, vm_input_fd, log_path)
598− },
599− )
600− } else {
601− run_vm(
602− default_raw,
603− &provision_actions,
604− directory_shares,
605− BoxConfig::default().cpu_count,
606− BoxConfig::default().ram_size.as_u64(),
607− status,
608− )
609− };
610−
611− if let Err(err) = provision_result {
612− let _ = fs::remove_file(default_raw);
613− return Err(err);
614− }
582+ run_vm(
583+ default_raw,
584+ &[Send(provision_command)],
585+ directory_shares,
586+ DEFAULT_CPU_COUNT,
587+ DEFAULT_RAM_BYTES,
588+ )?;
615589
616590 Ok(())
617591}
@@ -619,47 +593,15 @@ fn ensure_default_image(
619593fn ensure_instance_disk(
620594 instance_raw: &Path,
621595 template_raw: &Path,
622− target_bytes: ByteSize,
623− status: Option<&StatusEmitter<'_>>,
624−) -> Result<bool> {
596+) -> Result<(), Box<dyn std::error::Error>> {
625597 if instance_raw.exists() {
626− let current_size = ByteSize(fs::metadata(instance_raw)?.len());
627− if current_size != target_bytes {
628− let current_gb = current_size;
629− let target_gb = target_bytes;
630− tracing::warn!(
631− "instance disk size does not match config (current {}, config {}); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
632− current_gb,
633− target_gb
634− );
635− }
636− return Ok(false);
637− }
638−
639− let template_size = ByteSize(fs::metadata(template_raw)?.len());
640− if target_bytes < template_size {
641− bail!(format!(
642− "Requested disk size {} is smaller than base image size {}",
643− target_bytes, template_size
644− ));
645− }
646− let target_size = target_bytes;
647− let needs_resize = target_size > template_size;
648−
649− emit_status(status, "creating instance disk...");
650− tracing::info!("creating instance disk...");
651− tracing::info!(path = %template_raw.display(), "creating instance disk");
652− fs::create_dir_all(instance_raw.parent().unwrap())?;
653− if target_size == template_size {
654− fs::copy(template_raw, instance_raw)?;
655− return Ok(needs_resize);
598+ return Ok(());
656599 }
657600
658− let mut dst = fs::File::create(instance_raw)?;
659− dst.set_len(target_size.as_u64())?;
660− let mut src = fs::File::open(template_raw)?;
661− std::io::copy(&mut src, &mut dst)?;
662− Ok(needs_resize)
601+ println!("Creating instance disk from {}...", template_raw.display());
602+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
603+ fs::copy(template_raw, instance_raw)?;
604+ Ok(())
663605}
664606
665607pub struct IoContext {
@@ -675,16 +617,10 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675617 (read_stream.into(), write_stream.into())
676618}
677619
678−pub fn spawn_vm_io_with_hooks<
679− F: FnMut(&str) -> bool + std::marker::Send + 'static,
680− G: FnMut(&[u8]) + std::marker::Send + 'static,
681−>(
620+pub fn spawn_vm_io(
682621 output_monitor: Arc<OutputMonitor>,
683622 vm_output_fd: OwnedFd,
684623 vm_input_fd: OwnedFd,
685− io_control: Arc<IoControl>,
686− mut on_line: F,
687− mut on_output: G,
688624) -> IoContext {
689625 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
690626
@@ -700,12 +636,7 @@ pub fn spawn_vm_io_with_hooks<
700636 Error,
701637 }
702638
703− fn poll_with_wakeup<'a>(
704− main_fd: RawFd,
705− wakeup_fd: RawFd,
706− buf: &'a mut [u8],
707− timeout_ms: i32,
708− ) -> PollResult<'a> {
639+ fn poll_with_wakeup<'a>(main_fd: RawFd, wakeup_fd: RawFd, buf: &'a mut [u8]) -> PollResult<'a> {
709640 let mut fds = [
710641 libc::pollfd {
711642 fd: main_fd,
@@ -719,12 +650,8 @@ pub fn spawn_vm_io_with_hooks<
719650 },
720651 ];
721652
722− let ret = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout_ms) };
723− if ret == 0 {
724− PollResult::Spurious
725− } else if ret < 0 {
726− PollResult::Error
727− } else if fds[1].revents & libc::POLLIN != 0 {
653+ let ret = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
654+ if ret <= 0 || fds[1].revents & libc::POLLIN != 0 {
728655 PollResult::Shutdown
729656 } else if fds[0].revents & libc::POLLIN != 0 {
730657 let n = unsafe { libc::read(main_fd, buf.as_mut_ptr() as *mut _, buf.len()) };
@@ -740,68 +667,23 @@ pub fn spawn_vm_io_with_hooks<
740667 }
741668 }
742669
743− fn poll_wakeup_only(wakeup_fd: RawFd, timeout_ms: i32) -> bool {
744− let mut fds = [libc::pollfd {
745− fd: wakeup_fd,
746− events: libc::POLLIN,
747− revents: 0,
748− }];
749−
750− let ret = unsafe { libc::poll(fds.as_mut_ptr(), 1, timeout_ms) };
751− ret > 0 && fds[0].revents & libc::POLLIN != 0
752− }
753−
754670 // Copies from stdin to the VM; also polls wakeup_read to exit the thread when it's time to shutdown.
755671 let stdin_thread = thread::spawn({
756672 let input_tx = input_tx.clone();
757673 let raw_guard = raw_guard.clone();
758674 let wakeup_read = wakeup_read.try_clone().unwrap();
759− let io_control = io_control.clone();
760675
761676 move || {
762677 let mut buf = [0u8; 1024];
763− let mut pending_command: Vec<u8> = Vec::new();
764− let mut command_mode = false;
765678 loop {
766− if !io_control.forward_input() {
767− if poll_wakeup_only(wakeup_read.as_raw_fd(), 100) {
768− break;
769− }
770− continue;
771− }
772−
773− match poll_with_wakeup(libc::STDIN_FILENO, wakeup_read.as_raw_fd(), &mut buf, -1) {
679+ match poll_with_wakeup(libc::STDIN_FILENO, wakeup_read.as_raw_fd(), &mut buf) {
774680 PollResult::Shutdown | PollResult::Error => break,
775681 PollResult::Spurious => continue,
776682 PollResult::Ready(bytes) => {
777− let mut send_buf: Vec<u8> = Vec::new();
778− for &b in bytes {
779− if pending_command.is_empty() && !command_mode && b == b':' {
780− command_mode = true;
781− }
782−
783− if command_mode {
784− pending_command.push(b);
785− } else {
786− send_buf.push(b);
787− }
788−
789− if b == b'\n' && command_mode {
790− let line = String::from_utf8_lossy(&pending_command);
791− let trimmed = line.trim_end_matches(&['\r', '\n'][..]);
792− let consumed = on_line(trimmed);
793− if !consumed {
794− send_buf.extend_from_slice(&pending_command);
795− }
796− pending_command.clear();
797− command_mode = false;
798− }
799− }
800683 if raw_guard.lock().unwrap().is_none() {
801684 continue;
802685 }
803− if !send_buf.is_empty() && input_tx.send(VmInput::Bytes(send_buf)).is_err()
804− {
686+ if input_tx.send(VmInput::Bytes(bytes.to_vec())).is_err() {
805687 break;
806688 }
807689 }
@@ -814,40 +696,28 @@ pub fn spawn_vm_io_with_hooks<
814696 let stdout_thread = thread::spawn({
815697 let raw_guard = raw_guard.clone();
816698 let wakeup_read = wakeup_read.try_clone().unwrap();
817− let io_control = io_control.clone();
818699
819700 move || {
701+ let mut stdout = std::io::stdout().lock();
820702 let mut buf = [0u8; 1024];
821703 loop {
822− if io_control.take_restore_terminal() {
823− let mut guard = raw_guard.lock().unwrap();
824− *guard = None;
825− }
826− match poll_with_wakeup(
827− vm_output_fd.as_raw_fd(),
828− wakeup_read.as_raw_fd(),
829− &mut buf,
830− 100,
831− ) {
704+ match poll_with_wakeup(vm_output_fd.as_raw_fd(), wakeup_read.as_raw_fd(), &mut buf)
705+ {
832706 PollResult::Shutdown | PollResult::Error => break,
833707 PollResult::Spurious => continue,
834708 PollResult::Ready(bytes) => {
835− if io_control.forward_output() {
836− // enable raw mode if we haven't already
837− if raw_guard.lock().unwrap().is_none()
838− && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
839− {
840− *raw_guard.lock().unwrap() = Some(guard);
841− }
842−
843− let mut stdout = io::stdout().lock();
844− if stdout.write_all(bytes).is_err() {
845− break;
846− }
847− let _ = stdout.flush();
709+ // enable raw mode, if we haven't already
710+ if raw_guard.lock().unwrap().is_none()
711+ && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
712+ {
713+ *raw_guard.lock().unwrap() = Some(guard);
714+ }
715+
716+ if stdout.write_all(bytes).is_err() {
717+ break;
848718 }
719+ let _ = stdout.flush();
849720 output_monitor.push(bytes);
850− on_output(bytes);
851721 }
852722 }
853723 }
@@ -856,7 +726,7 @@ pub fn spawn_vm_io_with_hooks<
856726
857727 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858728 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
729+ let mut vm_writer = std::fs::File::from(vm_input_fd);
860730 loop {
861731 match input_rx.recv() {
862732 Ok(VmInput::Bytes(data)) => {
@@ -879,63 +749,6 @@ pub fn spawn_vm_io_with_hooks<
879749 }
880750}
881751
882−pub fn spawn_vm_io_with_line_handler<F>(
883− output_monitor: Arc<OutputMonitor>,
884− vm_output_fd: OwnedFd,
885− vm_input_fd: OwnedFd,
886− on_line: F,
887−) -> IoContext
888−where
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
890−{
891− spawn_vm_io_with_hooks(
892− output_monitor,
893− vm_output_fd,
894− vm_input_fd,
895− IoControl::new(),
896− on_line,
897− |_| {},
898− )
899−}
900−
901−pub fn spawn_vm_io(
902− output_monitor: Arc<OutputMonitor>,
903− vm_output_fd: OwnedFd,
904− vm_input_fd: OwnedFd,
905−) -> IoContext {
906− spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
907−}
908−
909−fn spawn_vm_io_with_log(
910− output_monitor: Arc<OutputMonitor>,
911− vm_output_fd: OwnedFd,
912− vm_input_fd: OwnedFd,
913− log_path: PathBuf,
914−) -> IoContext {
915− let log_file = fs::OpenOptions::new()
916− .create(true)
917− .write(true)
918− .truncate(true)
919− .open(&log_path)
920− .ok()
921− .map(|file| Arc::new(Mutex::new(file)));
922−
923− spawn_vm_io_with_hooks(
924− output_monitor,
925− vm_output_fd,
926− vm_input_fd,
927− IoControl::new(),
928− |_| false,
929− move |bytes| {
930− if let Some(log) = &log_file
931− && let Ok(mut file) = log.lock()
932− {
933− let _ = file.write_all(bytes);
934− }
935− },
936− )
937−}
938−
939752impl IoContext {
940753 pub fn shutdown(self) {
941754 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +766,7 @@ fn create_vm_configuration(
953766 vm_writes_to_fd: OwnedFd,
954767 cpu_count: usize,
955768 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
769+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
957770 unsafe {
958771 let platform =
959772 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +800,7 @@ fn create_vm_configuration(
987800 false,
988801 VZDiskImageCachingMode::Automatic,
989802 VZDiskImageSynchronizationMode::Full,
990− )?;
803+ ).unwrap();
991804
992805 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993806 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +887,7 @@ fn create_vm_configuration(
1074887 // Validate
1075888 config.validateWithError().map_err(|e| {
1076889 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
890+ "Invalid VM configuration: {:?}",
1078891 e.localizedDescription()
1079892 ))
1080893 })?;
@@ -1083,9 +896,9 @@ fn create_vm_configuration(
1083896 }
1084897}
1085898
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
899+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1087900 unsafe {
1088− let temp_dir = env::temp_dir();
901+ let temp_dir = std::env::temp_dir();
1089902 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1090903 let url = nsurl_from_path(&temp_path)?;
1091904 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +914,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1101914fn spawn_login_actions_thread(
1102915 login_actions: Vec<LoginAction>,
1103916 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
917+ input_tx: mpsc::Sender<VmInput>,
918+ vm_output_tx: mpsc::Sender<VmOutput>,
1106919) -> thread::JoinHandle<()> {
1107920 thread::spawn(move || {
1108921 for a in login_actions {
@@ -1116,48 +929,34 @@ fn spawn_login_actions_thread(
1116929 return;
1117930 }
1118931 }
1119− ExpectEither {
1120− success,
1121− failure,
1122− timeout,
1123− } => match output_monitor.wait_for_any(&[&success, &failure], timeout) {
1124− WaitAnyResult::Found(0) => {}
1125− WaitAnyResult::Found(_) => {
1126− let _ = vm_output_tx.send(VmOutput::LoginActionFailed {
1127− action: format!("expect '{}'", success),
1128− reason: format!("saw failure marker '{}'", failure),
1129− });
1130− return;
1131− }
1132− WaitAnyResult::Timeout => {
1133− let _ = vm_output_tx.send(VmOutput::LoginActionTimeout {
1134− action: format!("expect '{}'", success),
1135− timeout,
1136− });
1137− return;
1138− }
1139− },
1140932 Send(mut text) => {
1141933 text.push('\n'); // Type the newline so the command is actually submitted.
1142934 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
1143935 }
936+ Script { path, index } => {
937+ let command = match script_command_from_path(&path, index) {
938+ Ok(command) => command,
939+ Err(err) => {
940+ eprintln!("{err}");
941+ return;
942+ }
943+ };
944+ let mut text = command;
945+ text.push('\n');
946+ input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
947+ }
1144948 }
1145949 }
1146950 })
1147951}
1148952
1149−fn run_vm_with_io<F>(
953+fn run_vm(
1150954 disk_path: &Path,
1151955 login_actions: &[LoginAction],
1152956 directory_shares: &[DirectoryShare],
1153957 cpu_count: usize,
1154958 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
1156− io_handler: F,
1157−) -> Result<()>
1158−where
1159− F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
1160−{
959+) -> Result<(), Box<dyn std::error::Error>> {
1161960 let (vm_reads_from, we_write_to) = create_pipe();
1162961 let (we_read_from, vm_writes_to) = create_pipe();
1163962
@@ -1201,26 +1000,24 @@ where
12011000
12021001 match rx.try_recv() {
12031002 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1003+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
12051004 break;
12061005 }
12071006 Err(mpsc::TryRecvError::Empty) => continue,
12081007 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1008+ return Err("VM start channel disconnected".into());
12101009 }
12111010 }
12121011 }
12131012
12141013 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1014+ return Err("Timed out waiting for VM to start".into());
12161015 }
12171016
1218− emit_status(status, "vm booting... go vibecoder!");
1219− tracing::info!("vm booting... go vibecoder!");
1220− tracing::info!("vm booting");
1017+ println!("VM booting...");
12211018
12221019 let output_monitor = Arc::new(OutputMonitor::default());
1223− let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
1020+ let io_ctx = spawn_vm_io(output_monitor.clone(), we_read_from, we_write_to);
12241021
12251022 let mut all_login_actions = vec![
12261023 Expect {
@@ -1262,7 +1059,7 @@ where
12621059 );
12631060
12641061 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1062+ let mut exit_result = Ok(());
12661063 loop {
12671064 unsafe {
12681065 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,28 +1078,12 @@ where
12811078 exit_result = Err(format!(
12821079 "Login action ({}) timed out after {:?}; shutting down.",
12831080 action, timeout
1284− ));
1285− unsafe {
1286− if vm.canRequestStop() {
1287− if let Err(err) = vm.requestStopWithError() {
1288− tracing::error!(error = ?err, "failed to request VM stop");
1289− }
1290− } else if vm.canStop() {
1291− let handler = RcBlock::new(|_error: *mut NSError| {});
1292− vm.stopWithCompletionHandler(&handler);
1293− }
1294− }
1295− break;
1296− }
1297− Ok(VmOutput::LoginActionFailed { action, reason }) => {
1298− exit_result = Err(format!(
1299− "Login action ({}) failed: {}; shutting down.",
1300− action, reason
1301− ));
1081+ )
1082+ .into());
13021083 unsafe {
13031084 if vm.canRequestStop() {
13041085 if let Err(err) = vm.requestStopWithError() {
1305− tracing::error!(error = ?err, "failed to request VM stop");
1086+ eprintln!("Failed to request VM stop: {:?}", err);
13061087 }
13071088 } else if vm.canStop() {
13081089 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1314,7 +1095,7 @@ where
13141095 Err(mpsc::TryRecvError::Empty) => {}
13151096 Err(mpsc::TryRecvError::Disconnected) => {}
13161097 }
1317− if state != VZVirtualMachineState::Running {
1098+ if state != objc2_virtualization::VZVirtualMachineState::Running {
13181099 //eprintln!("VM stopped with state: {:?}", state);
13191100 break;
13201101 }
@@ -1324,29 +1105,10 @@ where
13241105
13251106 io_ctx.shutdown();
13261107
1327− exit_result.map_err(Error::msg)
1108+ exit_result
13281109}
13291110
1330−fn run_vm(
1331− disk_path: &Path,
1332− login_actions: &[LoginAction],
1333− directory_shares: &[DirectoryShare],
1334− cpu_count: usize,
1335− ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1337−) -> Result<()> {
1338− run_vm_with_io(
1339− disk_path,
1340− login_actions,
1341− directory_shares,
1342− cpu_count,
1343− ram_bytes,
1344− status,
1345− spawn_vm_io,
1346− )
1347−}
1348−
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1111+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
13501112 let abs_path = if path.is_absolute() {
13511113 path.to_path_buf()
13521114 } else {
@@ -1355,7 +1117,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13551117 let ns_path = NSString::from_str(
13561118 abs_path
13571119 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1120+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
13591121 );
13601122 Ok(NSURL::fileURLWithPath(&ns_path))
13611123}
@@ -1370,7 +1132,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13701132 let original = attributes;
13711133
13721134 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1135+ attributes.c_iflag &= !(libc::ICRNL);
13741136 // Disable canonical mode (line buffering), echo, and signal generation
13751137 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13761138 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1160,7 @@ impl Drop for RawModeGuard {
13981160
13991161// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
14001162pub fn ensure_signed() {
1401− if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1402− return;
1403− }
1404− let exe = env::current_exe().expect("failed to get current exe path");
1163+ let exe = std::env::current_exe().expect("failed to get current exe path");
14051164 let exe_str = exe.to_str().expect("exe path not valid utf-8");
14061165
14071166 let has_required_entitlements = {
@@ -1423,10 +1182,10 @@ pub fn ensure_signed() {
14231182 }
14241183
14251184 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1426− let entitlements_path = env::temp_dir().join("entitlements.plist");
1427− fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1185+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1186+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
14281187
1429− let output = Command::new("codesign")
1188+ let status = Command::new("codesign")
14301189 .args([
14311190 "--sign",
14321191 "-",
@@ -1435,27 +1194,22 @@ pub fn ensure_signed() {
14351194 entitlements_path.to_str().unwrap(),
14361195 exe_str,
14371196 ])
1438− .output();
1197+ .status();
14391198
1440− let _ = fs::remove_file(&entitlements_path);
1199+ let _ = std::fs::remove_file(&entitlements_path);
14411200
1442− match output {
1443− Ok(o) if o.status.success() => {
1444− let stderr = String::from_utf8_lossy(&o.stderr);
1445− if !stderr.trim().is_empty() {
1446− tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
1447− }
1448− let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1449− tracing::error!(error = %err, "failed to re-exec after signing");
1201+ match status {
1202+ Ok(s) if s.success() => {
1203+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1204+ eprintln!("failed to re-exec after signing: {err}");
14501205 std::process::exit(1);
14511206 }
1452− Ok(o) => {
1453− let stderr = String::from_utf8_lossy(&o.stderr);
1454− tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
1207+ Ok(s) => {
1208+ eprintln!("codesign failed with status: {s}");
14551209 std::process::exit(1);
14561210 }
14571211 Err(e) => {
1458− tracing::error!(error = %e, "failed to run codesign");
1212+ eprintln!("failed to run codesign: {e}");
14591213 std::process::exit(1);
14601214 }
14611215 }