@@ -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,
@@ -23,8 +23,8 @@ use std::{
2323};
2424
2525use block2::RcBlock;
26−use bytesize::ByteSize;
2726use dispatch2::DispatchQueue;
27+use lexopt::prelude::*;
2828use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
2929use objc2_foundation::*;
3030use objc2_virtualization::*;
@@ -33,46 +33,39 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3333const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3434const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3535const SHARED_DIRECTORIES_TAG: &str = "shared";
36−pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3736
37+const BYTES_PER_MB: u64 = 1024 * 1024;
38+const DEFAULT_CPU_COUNT: usize = 2;
39+const DEFAULT_RAM_MB: u64 = 2048;
40+const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
3841const START_TIMEOUT: Duration = Duration::from_secs(60);
42+const DEFAULT_EXPECT_TIMEOUT: Duration = Duration::from_secs(30);
3943const 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");
4344const 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";
4845
4946#[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− },
47+pub(crate) enum LoginAction {
48+ Expect { text: String, timeout: Duration },
6049 Send(String),
50+ Script { path: PathBuf, index: usize },
6151}
62−use crate::config::BoxConfig;
6352use LoginAction::*;
6453
6554#[derive(Clone)]
66−pub struct DirectoryShare {
55+pub(crate) struct DirectoryShare {
6756 host: PathBuf,
6857 guest: PathBuf,
6958 read_only: bool,
7059}
7160
7261impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
62+ pub(crate) fn new(
63+ host: PathBuf,
64+ mut guest: PathBuf,
65+ read_only: bool,
66+ ) -> Result<Self, Box<dyn std::error::Error>> {
7467 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
68+ return Err(format!("Host path does not exist: {}", host.display()).into());
7669 }
7770 if !guest.is_absolute() {
7871 guest = PathBuf::from("/root").join(guest);
@@ -84,22 +77,23 @@ impl DirectoryShare {
8477 })
8578 }
8679
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
80+ pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
8881 let parts: Vec<&str> = spec.split(':').collect();
8982 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
83+ return Err(format!("Invalid mount spec: {spec}").into());
9184 }
92− let host = expand_tilde_path(parts[0]);
85+ let host = PathBuf::from(parts[0]);
9386 let guest = PathBuf::from(parts[1]);
9487 let read_only = if parts.len() == 3 {
9588 match parts[2] {
9689 "read-only" => true,
9790 "read-write" => false,
9891 _ => {
99− bail!(format!(
92+ return Err(format!(
10093 "Invalid mount mode '{}'; expected read-only or read-write",
10194 parts[2]
102− ));
95+ )
96+ .into());
10397 }
10498 }
10599 } else {
@@ -122,49 +116,19 @@ impl DirectoryShare {
122116 }
123117}
124118
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−}
137−
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);
151− }
152−}
153−
154−pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
119+pub fn run_with_args<F>(args: CliArgs, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
155120where
156121 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
157122{
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
123+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
159124}
160125
161−pub fn run_with_args_and_extras<F>(
162− args: VmArg,
126+pub(crate) fn run_with_args_and_extras<F>(
127+ args: CliArgs,
163128 io_handler: F,
164129 extra_login_actions: Vec<LoginAction>,
165130 extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
167−) -> Result<()>
131+) -> Result<(), Box<dyn std::error::Error>>
168132where
169133 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
170134{
@@ -173,7 +137,7 @@ where
173137 let project_root = env::current_dir()?;
174138 let project_name = project_root
175139 .file_name()
176− .with_context(|| "Project directory has no name")?
140+ .ok_or("Project directory has no name")?
177141 .to_string_lossy()
178142 .into_owned();
179143
@@ -181,14 +145,10 @@ where
181145 let cache_home = env::var("XDG_CACHE_HOME")
182146 .map(PathBuf::from)
183147 .unwrap_or_else(|_| home.join(".cache"));
184− let cache_dir = cache_home.join(GLOBAL_CACHE_DIR_NAME);
148+ let cache_dir = cache_home.join("vibe");
185149 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
186150
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");
151+ let instance_dir = project_root.join(".vibe");
192152
193153 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194154 let base_compressed = cache_dir.join(basename_compressed);
@@ -197,8 +157,8 @@ where
197157 basename_compressed.trim_end_matches(".tar.xz")
198158 ));
199159
200− let default_raw = cache_dir.join(DEFAULT_RAW_NAME);
201− let instance_raw = instance_dir.join(INSTANCE_RAW_NAME);
160+ let default_raw = cache_dir.join("default.raw");
161+ let instance_raw = instance_dir.join("instance.raw");
202162
203163 // Prepare system-wide directories
204164 fs::create_dir_all(&cache_dir)?;
@@ -207,31 +167,28 @@ where
207167 let mise_directory_share =
208168 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
209169
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;
170+ let disk_path = if let Some(path) = args.disk {
171+ if !path.exists() {
172+ return Err(format!("Disk image does not exist: {}", path.display()).into());
173+ }
174+ path
175+ } else {
176+ ensure_default_image(
177+ &base_raw,
178+ &base_compressed,
179+ &default_raw,
180+ std::slice::from_ref(&mise_directory_share),
181+ )?;
182+ ensure_instance_disk(&instance_raw, &default_raw)?;
183+
184+ instance_raw
185+ };
228186
229187 let mut login_actions = Vec::new();
230188 let mut directory_shares = Vec::new();
231189
232190 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())));
191+ login_actions.push(Send(format!("cd {project_name}")));
235192
236193 // 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.
237194 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -239,7 +196,38 @@ where
239196 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
240197 }
241198
199+ directory_shares.push(
200+ DirectoryShare::new(
201+ project_root,
202+ PathBuf::from("/root/").join(project_name),
203+ false,
204+ )
205+ .expect("Project directory must exist"),
206+ );
207+
242208 directory_shares.push(mise_directory_share);
209+
210+ // Add default shares, if they exist
211+ for share in [
212+ DirectoryShare::new(home.join(".m2"), "/root/.m2".into(), false),
213+ DirectoryShare::new(
214+ home.join(".cargo/registry"),
215+ "/root/.cargo/registry".into(),
216+ false,
217+ ),
218+ DirectoryShare::new(home.join(".codex"), "/root/.codex".into(), false),
219+ DirectoryShare::new(home.join(".claude"), "/root/.claude".into(), false),
220+ DirectoryShare::new(
221+ "/Users/zhangjie/Documents/Code/CompletePrograms/vibebox/.ssh".into(),
222+ "/root/.ssh".into(),
223+ true,
224+ ),
225+ ]
226+ .into_iter()
227+ .flatten()
228+ {
229+ directory_shares.push(share)
230+ }
243231 }
244232
245233 directory_shares.extend(extra_directory_shares);
@@ -248,46 +236,199 @@ where
248236 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
249237 }
250238
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−
256239 if let Some(motd_action) = motd_login_action(&directory_shares) {
257240 login_actions.push(motd_action);
258241 }
259242
260243 login_actions.extend(extra_login_actions);
261244
245+ // Any user-provided login actions must come after our system ones
246+ login_actions.extend(args.login_actions);
247+
262248 run_vm_with_io(
263249 &disk_path,
264250 &login_actions,
265251 &directory_shares[..],
266252 args.cpu_count,
267253 args.ram_bytes,
268− status,
269254 io_handler,
270255 )
271256}
272257
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
258+pub fn print_help() {
259+ println!(
260+ "Vibe is a quick way to spin up a Linux virtual machine on Mac to sandbox LLM agents.
261+
262+vibe [OPTIONS] [disk-image.raw]
263+
264+Options
265+
266+ --help Print this help message.
267+ --version Print the version (commit SHA).
268+ --no-default-mounts Disable all default mounts.
269+ --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
270+ Defaults to read-write.
271+ Errors if host-path does not exist.
272+ --cpus <count> Number of virtual CPUs (default {DEFAULT_CPU_COUNT}).
273+ --ram <megabytes> RAM size in megabytes (default {DEFAULT_RAM_MB}).
274+ --script <path/to/script.sh> Run script in VM.
275+ --send <some-command> Type `some-command` followed by newline into the VM.
276+ --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
277+ If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
278+"
279+ );
280+}
281+
282+pub fn print_version() {
283+ println!("Vibe");
284+ println!("https://github.com/lynaghk/vibe/");
285+ println!("Git SHA: {}", env!("GIT_SHA"));
286+}
287+
288+pub struct CliArgs {
289+ disk: Option<PathBuf>,
290+ version: bool,
291+ help: bool,
292+ no_default_mounts: bool,
293+ mounts: Vec<String>,
294+ login_actions: Vec<LoginAction>,
295+ cpu_count: usize,
296+ ram_bytes: u64,
297+}
298+
299+impl CliArgs {
300+ pub fn version(&self) -> bool {
301+ self.version
302+ }
303+
304+ pub fn help(&self) -> bool {
305+ self.help
306+ }
307+
308+ pub fn cpu_count(&self) -> usize {
309+ self.cpu_count
310+ }
311+
312+ pub fn ram_bytes(&self) -> u64 {
313+ self.ram_bytes
314+ }
315+
316+ pub fn ram_mb(&self) -> u64 {
317+ self.ram_bytes / BYTES_PER_MB
318+ }
319+}
320+
321+pub fn parse_cli() -> Result<CliArgs, Box<dyn std::error::Error>> {
322+ parse_cli_from(env::args_os())
323+}
324+
325+pub fn parse_cli_from<I>(args: I) -> Result<CliArgs, Box<dyn std::error::Error>>
326+where
327+ I: IntoIterator<Item = OsString>,
328+{
329+ fn os_to_string(value: OsString, flag: &str) -> Result<String, Box<dyn std::error::Error>> {
330+ value
331+ .into_string()
332+ .map_err(|_| format!("{flag} expects valid UTF-8").into())
333+ }
334+
335+ let mut parser = lexopt::Parser::from_iter(args);
336+ let mut disk = None;
337+ let mut version = false;
338+ let mut help = false;
339+ let mut no_default_mounts = false;
340+ let mut mounts = Vec::new();
341+ let mut login_actions = Vec::new();
342+ let mut script_index = 0;
343+ let mut cpu_count = DEFAULT_CPU_COUNT;
344+ let mut ram_bytes = DEFAULT_RAM_BYTES;
345+
346+ while let Some(arg) = parser.next()? {
347+ match arg {
348+ Long("version") => version = true,
349+ Long("help") | Short('h') => help = true,
350+ Long("no-default-mounts") => no_default_mounts = true,
351+ Long("cpus") => {
352+ let value = os_to_string(parser.value()?, "--cpus")?.parse()?;
353+ if value == 0 {
354+ return Err("--cpus must be >= 1".into());
355+ }
356+ cpu_count = value;
357+ }
358+ Long("ram") => {
359+ let value: u64 = os_to_string(parser.value()?, "--ram")?.parse()?;
360+ if value == 0 {
361+ return Err("--ram must be >= 1".into());
362+ }
363+ ram_bytes = value * BYTES_PER_MB;
364+ }
365+ Long("mount") => {
366+ mounts.push(os_to_string(parser.value()?, "--mount")?);
367+ }
368+ Long("script") => {
369+ login_actions.push(Script {
370+ path: os_to_string(parser.value()?, "--script")?.into(),
371+ index: script_index,
372+ });
373+ script_index += 1;
374+ }
375+ Long("send") => {
376+ login_actions.push(Send(os_to_string(parser.value()?, "--send")?));
377+ }
378+ Long("expect") => {
379+ let text = os_to_string(parser.value()?, "--expect")?;
380+ let timeout = match parser.optional_value() {
381+ Some(value) => Duration::from_secs(os_to_string(value, "--expect")?.parse()?),
382+ None => DEFAULT_EXPECT_TIMEOUT,
383+ };
384+ login_actions.push(Expect { text, timeout });
385+ }
386+ Value(value) => {
387+ if disk.is_some() {
388+ return Err("Only one disk path may be provided".into());
389+ }
390+ disk = Some(PathBuf::from(value));
391+ }
392+ _ => return Err(arg.unexpected().into()),
393+ }
394+ }
395+
396+ Ok(CliArgs {
397+ disk,
398+ version,
399+ help,
400+ no_default_mounts,
401+ mounts,
402+ login_actions,
403+ cpu_count,
404+ ram_bytes,
405+ })
406+}
407+
408+fn script_command_from_path(
409+ path: &Path,
410+ index: usize,
411+) -> Result<String, Box<dyn std::error::Error>> {
412+ let script = fs::read_to_string(path)
413+ .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
414+ let label = format!("{}_{}", index, path.file_name().unwrap().display());
415+ script_command_from_content(&label, &script)
416+}
417+
418+pub(crate) fn script_command_from_content(
419+ label: &str,
420+ script: &str,
421+) -> Result<String, Box<dyn std::error::Error>> {
274422 let marker = "VIBE_SCRIPT_EOF";
275423 let guest_dir = "/tmp/vibe-scripts";
276424 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);
284425 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
426+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
286427 );
287428 if script.contains(marker) {
288− bail!(format!(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
290− ));
429+ return Err(
430+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
431+ );
291432 }
292433 Ok(command)
293434}
@@ -351,12 +492,6 @@ enum WaitResult {
351492 Found,
352493}
353494
354−#[derive(PartialEq, Eq)]
355−enum WaitAnyResult {
356− Timeout,
357− Found(usize),
358−}
359−
360495pub enum VmInput {
361496 Bytes(Vec<u8>),
362497 Shutdown,
@@ -364,7 +499,6 @@ pub enum VmInput {
364499
365500enum VmOutput {
366501 LoginActionTimeout { action: String, timeout: Duration },
367− LoginActionFailed { action: String, reason: String },
368502}
369503
370504#[derive(Default)]
@@ -401,41 +535,6 @@ impl OutputMonitor {
401535 WaitResult::Found
402536 }
403537 }
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
439538}
440539
441540#[derive(Debug)]
@@ -484,17 +583,15 @@ impl IoControl {
484583fn ensure_base_image(
485584 base_raw: &Path,
486585 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
488−) -> Result<()> {
586+) -> Result<(), Box<dyn std::error::Error>> {
489587 if base_raw.exists() {
490588 return Ok(());
491589 }
492590
493591 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
592+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
495593 {
496− emit_status(status, "downloading base image...");
497− tracing::info!("downloading base image");
594+ println!("Downloading base image...");
498595 let status = Command::new("curl")
499596 .args([
500597 "--continue-at",
@@ -508,14 +605,12 @@ fn ensure_base_image(
508605 ])
509606 .status()?;
510607 if !status.success() {
511− bail!("failed to download base image");
608+ return Err("Failed to download base image".into());
512609 }
513610 }
514611
515612 // Check SHA
516613 {
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
519614 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
520615
521616 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +628,18 @@ fn ensure_base_image(
533628
534629 let status = child.wait().expect("failed to wait on child");
535630 if !status.success() {
536− bail!(format!(
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538− ));
631+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
539632 }
540633 }
541634
542− emit_status(status, "decompressing base image...");
543− tracing::info!("decompressing base image...");
635+ println!("Decompressing base image...");
544636 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)?)
637+ .args(["-xOf", &base_compressed.to_string_lossy(), "disk.raw"])
638+ .stdout(std::fs::File::create(base_raw)?)
551639 .status()?;
552640
553641 if !status.success() {
554− bail!("Failed to decompress base image");
642+ return Err("Failed to decompress base image".into());
555643 }
556644
557645 Ok(())
@@ -562,56 +650,24 @@ fn ensure_default_image(
562650 base_compressed: &Path,
563651 default_raw: &Path,
564652 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
566− status: Option<&StatusEmitter<'_>>,
567−) -> Result<()> {
653+) -> Result<(), Box<dyn std::error::Error>> {
568654 if default_raw.exists() {
569655 return Ok(());
570656 }
571657
572− ensure_base_image(base_raw, base_compressed, status)?;
658+ ensure_base_image(base_raw, base_compressed)?;
573659
574− emit_status(status, "configuring base image...");
575− tracing::info!("configuring base image...");
660+ println!("Configuring base image...");
576661 fs::copy(base_raw, default_raw)?;
577662
578663 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− }
664+ run_vm(
665+ default_raw,
666+ &[Send(provision_command)],
667+ directory_shares,
668+ DEFAULT_CPU_COUNT,
669+ DEFAULT_RAM_BYTES,
670+ )?;
615671
616672 Ok(())
617673}
@@ -619,47 +675,15 @@ fn ensure_default_image(
619675fn ensure_instance_disk(
620676 instance_raw: &Path,
621677 template_raw: &Path,
622− target_bytes: ByteSize,
623− status: Option<&StatusEmitter<'_>>,
624−) -> Result<bool> {
678+) -> Result<(), Box<dyn std::error::Error>> {
625679 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);
680+ return Ok(());
656681 }
657682
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)
683+ println!("Creating instance disk from {}...", template_raw.display());
684+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
685+ fs::copy(template_raw, instance_raw)?;
686+ Ok(())
663687}
664688
665689pub struct IoContext {
@@ -675,17 +699,18 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675699 (read_stream.into(), write_stream.into())
676700}
677701
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−>(
702+pub fn spawn_vm_io_with_hooks<F, G>(
682703 output_monitor: Arc<OutputMonitor>,
683704 vm_output_fd: OwnedFd,
684705 vm_input_fd: OwnedFd,
685706 io_control: Arc<IoControl>,
686707 mut on_line: F,
687708 mut on_output: G,
688−) -> IoContext {
709+) -> IoContext
710+where
711+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
712+ G: FnMut(&[u8]) + ::std::marker::Send + 'static,
713+{
689714 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
690715
691716 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -833,14 +858,14 @@ pub fn spawn_vm_io_with_hooks<
833858 PollResult::Spurious => continue,
834859 PollResult::Ready(bytes) => {
835860 if io_control.forward_output() {
836− // enable raw mode if we haven't already
861+ // enable raw mode, if we haven't already
837862 if raw_guard.lock().unwrap().is_none()
838863 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
839864 {
840865 *raw_guard.lock().unwrap() = Some(guard);
841866 }
842867
843− let mut stdout = io::stdout().lock();
868+ let mut stdout = std::io::stdout().lock();
844869 if stdout.write_all(bytes).is_err() {
845870 break;
846871 }
@@ -856,7 +881,7 @@ pub fn spawn_vm_io_with_hooks<
856881
857882 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858883 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
884+ let mut vm_writer = std::fs::File::from(vm_input_fd);
860885 loop {
861886 match input_rx.recv() {
862887 Ok(VmInput::Bytes(data)) => {
@@ -886,7 +911,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
886911 on_line: F,
887912) -> IoContext
888913where
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
914+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
890915{
891916 spawn_vm_io_with_hooks(
892917 output_monitor,
@@ -906,36 +931,6 @@ pub fn spawn_vm_io(
906931 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
907932}
908933
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−
939934impl IoContext {
940935 pub fn shutdown(self) {
941936 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +948,7 @@ fn create_vm_configuration(
953948 vm_writes_to_fd: OwnedFd,
954949 cpu_count: usize,
955950 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
951+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
957952 unsafe {
958953 let platform =
959954 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +982,7 @@ fn create_vm_configuration(
987982 false,
988983 VZDiskImageCachingMode::Automatic,
989984 VZDiskImageSynchronizationMode::Full,
990− )?;
985+ ).unwrap();
991986
992987 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993988 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +1069,7 @@ fn create_vm_configuration(
10741069 // Validate
10751070 config.validateWithError().map_err(|e| {
10761071 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
1072+ "Invalid VM configuration: {:?}",
10781073 e.localizedDescription()
10791074 ))
10801075 })?;
@@ -1083,9 +1078,9 @@ fn create_vm_configuration(
10831078 }
10841079}
10851080
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1081+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
10871082 unsafe {
1088− let temp_dir = env::temp_dir();
1083+ let temp_dir = std::env::temp_dir();
10891084 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10901085 let url = nsurl_from_path(&temp_path)?;
10911086 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +1096,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
11011096fn spawn_login_actions_thread(
11021097 login_actions: Vec<LoginAction>,
11031098 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
1099+ input_tx: mpsc::Sender<VmInput>,
1100+ vm_output_tx: mpsc::Sender<VmOutput>,
11061101) -> thread::JoinHandle<()> {
11071102 thread::spawn(move || {
11081103 for a in login_actions {
@@ -1116,31 +1111,22 @@ fn spawn_login_actions_thread(
11161111 return;
11171112 }
11181113 }
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− },
11401114 Send(mut text) => {
11411115 text.push('\n'); // Type the newline so the command is actually submitted.
11421116 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
11431117 }
1118+ Script { path, index } => {
1119+ let command = match script_command_from_path(&path, index) {
1120+ Ok(command) => command,
1121+ Err(err) => {
1122+ eprintln!("{err}");
1123+ return;
1124+ }
1125+ };
1126+ let mut text = command;
1127+ text.push('\n');
1128+ input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
1129+ }
11441130 }
11451131 }
11461132 })
@@ -1152,9 +1138,8 @@ fn run_vm_with_io<F>(
11521138 directory_shares: &[DirectoryShare],
11531139 cpu_count: usize,
11541140 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
11561141 io_handler: F,
1157−) -> Result<()>
1142+) -> Result<(), Box<dyn std::error::Error>>
11581143where
11591144 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11601145{
@@ -1201,23 +1186,21 @@ where
12011186
12021187 match rx.try_recv() {
12031188 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1189+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
12051190 break;
12061191 }
12071192 Err(mpsc::TryRecvError::Empty) => continue,
12081193 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1194+ return Err("VM start channel disconnected".into());
12101195 }
12111196 }
12121197 }
12131198
12141199 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1200+ return Err("Timed out waiting for VM to start".into());
12161201 }
12171202
1218− emit_status(status, "vm booting... go vibecoder!");
1219− tracing::info!("vm booting... go vibecoder!");
1220− tracing::info!("vm booting");
1203+ println!("VM booting...");
12211204
12221205 let output_monitor = Arc::new(OutputMonitor::default());
12231206 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
@@ -1262,7 +1245,7 @@ where
12621245 );
12631246
12641247 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1248+ let mut exit_result = Ok(());
12661249 loop {
12671250 unsafe {
12681251 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,28 +1264,12 @@ where
12811264 exit_result = Err(format!(
12821265 "Login action ({}) timed out after {:?}; shutting down.",
12831266 action, timeout
1284− ));
1267+ )
1268+ .into());
12851269 unsafe {
12861270 if vm.canRequestStop() {
12871271 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− ));
1302− unsafe {
1303− if vm.canRequestStop() {
1304− if let Err(err) = vm.requestStopWithError() {
1305− tracing::error!(error = ?err, "failed to request VM stop");
1272+ eprintln!("Failed to request VM stop: {:?}", err);
13061273 }
13071274 } else if vm.canStop() {
13081275 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1314,7 +1281,7 @@ where
13141281 Err(mpsc::TryRecvError::Empty) => {}
13151282 Err(mpsc::TryRecvError::Disconnected) => {}
13161283 }
1317− if state != VZVirtualMachineState::Running {
1284+ if state != objc2_virtualization::VZVirtualMachineState::Running {
13181285 //eprintln!("VM stopped with state: {:?}", state);
13191286 break;
13201287 }
@@ -1324,7 +1291,7 @@ where
13241291
13251292 io_ctx.shutdown();
13261293
1327− exit_result.map_err(Error::msg)
1294+ exit_result
13281295}
13291296
13301297fn run_vm(
@@ -1333,20 +1300,18 @@ fn run_vm(
13331300 directory_shares: &[DirectoryShare],
13341301 cpu_count: usize,
13351302 ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1337−) -> Result<()> {
1303+) -> Result<(), Box<dyn std::error::Error>> {
13381304 run_vm_with_io(
13391305 disk_path,
13401306 login_actions,
13411307 directory_shares,
13421308 cpu_count,
13431309 ram_bytes,
1344− status,
13451310 spawn_vm_io,
13461311 )
13471312}
13481313
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1314+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
13501315 let abs_path = if path.is_absolute() {
13511316 path.to_path_buf()
13521317 } else {
@@ -1355,7 +1320,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13551320 let ns_path = NSString::from_str(
13561321 abs_path
13571322 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1323+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
13591324 );
13601325 Ok(NSURL::fileURLWithPath(&ns_path))
13611326}
@@ -1370,7 +1335,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13701335 let original = attributes;
13711336
13721337 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1338+ attributes.c_iflag &= !(libc::ICRNL);
13741339 // Disable canonical mode (line buffering), echo, and signal generation
13751340 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13761341 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1363,7 @@ impl Drop for RawModeGuard {
13981363
13991364// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
14001365pub 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");
1366+ let exe = std::env::current_exe().expect("failed to get current exe path");
14051367 let exe_str = exe.to_str().expect("exe path not valid utf-8");
14061368
14071369 let has_required_entitlements = {
@@ -1423,10 +1385,10 @@ pub fn ensure_signed() {
14231385 }
14241386
14251387 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");
1388+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1389+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
14281390
1429− let output = Command::new("codesign")
1391+ let status = Command::new("codesign")
14301392 .args([
14311393 "--sign",
14321394 "-",
@@ -1435,27 +1397,22 @@ pub fn ensure_signed() {
14351397 entitlements_path.to_str().unwrap(),
14361398 exe_str,
14371399 ])
1438− .output();
1400+ .status();
14391401
1440− let _ = fs::remove_file(&entitlements_path);
1402+ let _ = std::fs::remove_file(&entitlements_path);
14411403
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");
1404+ match status {
1405+ Ok(s) if s.success() => {
1406+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1407+ eprintln!("failed to re-exec after signing: {err}");
14501408 std::process::exit(1);
14511409 }
1452− Ok(o) => {
1453− let stderr = String::from_utf8_lossy(&o.stderr);
1454− tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
1410+ Ok(s) => {
1411+ eprintln!("codesign failed with status: {s}");
14551412 std::process::exit(1);
14561413 }
14571414 Err(e) => {
1458− tracing::error!(error = %e, "failed to run codesign");
1415+ eprintln!("failed to run codesign: {e}");
14591416 std::process::exit(1);
14601417 }
14611418 }