@@ -1,11 +1,7 @@
1−mod session_manager;
2−
3−pub use session_manager::{SessionError, SessionManager, SessionRecord};
4−
1+use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2+use anyhow::{Context, Error, Result, bail};
53use std::{
6− env,
7− ffi::OsString,
8− fs,
4+ env, fs,
95 io::{self, Write},
106 os::{
117 fd::RawFd,
@@ -19,6 +15,7 @@ use std::{
1915 process::{Command, Stdio},
2016 sync::{
2117 Arc, Condvar, Mutex,
18+ atomic::{AtomicBool, Ordering},
2219 mpsc::{self, Receiver, Sender},
2320 },
2421 thread,
@@ -26,8 +23,8 @@ use std::{
2623};
2724
2825use block2::RcBlock;
26+use bytesize::ByteSize;
2927use dispatch2::DispatchQueue;
30−use lexopt::prelude::*;
3128use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
3229use objc2_foundation::*;
3330use objc2_virtualization::*;
@@ -36,39 +33,46 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3633const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3734const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3835const SHARED_DIRECTORIES_TAG: &str = "shared";
36+pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3937
40−const BYTES_PER_MB: u64 = 1024 * 1024;
41−const DEFAULT_CPU_COUNT: usize = 2;
42−const DEFAULT_RAM_MB: u64 = 2048;
43−const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
4438const START_TIMEOUT: Duration = Duration::from_secs(60);
45−const DEFAULT_EXPECT_TIMEOUT: Duration = Duration::from_secs(30);
4639const 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");
4743const 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";
4848
4949#[derive(Clone)]
50−enum LoginAction {
51− Expect { text: String, timeout: Duration },
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+ },
5260 Send(String),
53− Script { path: PathBuf, index: usize },
5461}
62+use crate::config::BoxConfig;
5563use LoginAction::*;
5664
5765#[derive(Clone)]
58−struct DirectoryShare {
66+pub struct DirectoryShare {
5967 host: PathBuf,
6068 guest: PathBuf,
6169 read_only: bool,
6270}
6371
6472impl DirectoryShare {
65− fn new(
66− host: PathBuf,
67− mut guest: PathBuf,
68− read_only: bool,
69− ) -> Result<Self, Box<dyn std::error::Error>> {
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
7074 if !host.exists() {
71− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
7276 }
7377 if !guest.is_absolute() {
7478 guest = PathBuf::from("/root").join(guest);
@@ -80,23 +84,22 @@ impl DirectoryShare {
8084 })
8185 }
8286
83− fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
87+ pub fn from_mount_spec(spec: &str) -> Result<Self> {
8488 let parts: Vec<&str> = spec.split(':').collect();
8589 if parts.len() < 2 || parts.len() > 3 {
86− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
8791 }
88− let host = PathBuf::from(parts[0]);
92+ let host = expand_tilde_path(parts[0]);
8993 let guest = PathBuf::from(parts[1]);
9094 let read_only = if parts.len() == 3 {
9195 match parts[2] {
9296 "read-only" => true,
9397 "read-write" => false,
9498 _ => {
95− return Err(format!(
99+ bail!(format!(
96100 "Invalid mount mode '{}'; expected read-only or read-write",
97101 parts[2]
98− )
99− .into());
102+ ));
100103 }
101104 }
102105 } else {
@@ -119,47 +122,58 @@ impl DirectoryShare {
119122 }
120123}
121124
122−fn main() -> Result<(), Box<dyn std::error::Error>> {
123− let args = parse_cli()?;
124−
125− if args.version {
126− println!("Vibe");
127− println!("https://github.com/lynaghk/vibe/");
128− println!("Git SHA: {}", env!("GIT_SHA"));
129− std::process::exit(0);
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);
130134 }
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;
131147
132− if args.help {
133− println!(
134− "Vibe is a quick way to spin up a Linux virtual machine on Mac to sandbox LLM agents.
135−
136−vibe [OPTIONS] [disk-image.raw]
137−
138−Options
139−
140− --help Print this help message.
141− --version Print the version (commit SHA).
142− --no-default-mounts Disable all default mounts.
143− --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
144− Defaults to read-write.
145− Errors if host-path does not exist.
146− --cpus <count> Number of virtual CPUs (default {DEFAULT_CPU_COUNT}).
147− --ram <megabytes> RAM size in megabytes (default {DEFAULT_RAM_MB}).
148− --script <path/to/script.sh> Run script in VM.
149− --send <some-command> Type `some-command` followed by newline into the VM.
150− --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
151− If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
152−"
153− );
154− std::process::exit(0);
148+fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149+ if let Some(status) = status {
150+ status(message);
155151 }
152+}
156153
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+}
160+
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+{
157171 ensure_signed();
158172
159173 let project_root = env::current_dir()?;
160174 let project_name = project_root
161175 .file_name()
162− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
163177 .to_string_lossy()
164178 .into_owned();
165179
@@ -167,10 +181,14 @@ Options
167181 let cache_home = env::var("XDG_CACHE_HOME")
168182 .map(PathBuf::from)
169183 .unwrap_or_else(|_| home.join(".cache"));
170− let cache_dir = cache_home.join("vibe");
184+ let cache_dir = cache_home.join(GLOBAL_CACHE_DIR_NAME);
171185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
172186
173− let instance_dir = project_root.join(".vibe");
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");
174192
175193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
176194 let base_compressed = cache_dir.join(basename_compressed);
@@ -179,8 +197,8 @@ Options
179197 basename_compressed.trim_end_matches(".tar.xz")
180198 ));
181199
182− let default_raw = cache_dir.join("default.raw");
183− let instance_raw = instance_dir.join("instance.raw");
200+ let default_raw = cache_dir.join(DEFAULT_RAW_NAME);
201+ let instance_raw = instance_dir.join(INSTANCE_RAW_NAME);
184202
185203 // Prepare system-wide directories
186204 fs::create_dir_all(&cache_dir)?;
@@ -189,28 +207,31 @@ Options
189207 let mise_directory_share =
190208 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
191209
192− let disk_path = if let Some(path) = args.disk {
193− if !path.exists() {
194− return Err(format!("Disk image does not exist: {}", path.display()).into());
195− }
196− path
197− } else {
198− ensure_default_image(
199− &base_raw,
200− &base_compressed,
201− &default_raw,
202− std::slice::from_ref(&mise_directory_share),
203− )?;
204− ensure_instance_disk(&instance_raw, &default_raw)?;
205−
206− instance_raw
207− };
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;
208228
209229 let mut login_actions = Vec::new();
210230 let mut directory_shares = Vec::new();
211231
212232 if !args.no_default_mounts {
213− login_actions.push(Send(format!("cd {project_name}")));
233+ let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234+ login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
214235
215236 // 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.
216237 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -218,170 +239,55 @@ Options
218239 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
219240 }
220241
221− directory_shares.push(
222− DirectoryShare::new(
223− project_root,
224− PathBuf::from("/root/").join(project_name),
225− false,
226− )
227− .expect("Project directory must exist"),
228− );
229−
230242 directory_shares.push(mise_directory_share);
231−
232− // Add default shares, if they exist
233− for share in [
234− DirectoryShare::new(home.join(".m2"), "/root/.m2".into(), false),
235− DirectoryShare::new(
236− home.join(".cargo/registry"),
237− "/root/.cargo/registry".into(),
238− false,
239− ),
240− DirectoryShare::new(home.join(".codex"), "/root/.codex".into(), false),
241− DirectoryShare::new(home.join(".claude"), "/root/.claude".into(), false),
242− ]
243− .into_iter()
244− .flatten()
245− {
246− directory_shares.push(share)
247− }
248243 }
249244
245+ directory_shares.extend(extra_directory_shares);
246+
250247 for spec in &args.mounts {
251248 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
252249 }
253250
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+
254256 if let Some(motd_action) = motd_login_action(&directory_shares) {
255257 login_actions.push(motd_action);
256258 }
257259
258− // Any user-provided login actions must come after our system ones
259− login_actions.extend(args.login_actions);
260+ login_actions.extend(extra_login_actions);
260261
261− run_vm(
262+ run_vm_with_io(
262263 &disk_path,
263264 &login_actions,
264265 &directory_shares[..],
265266 args.cpu_count,
266267 args.ram_bytes,
268+ status,
269+ io_handler,
267270 )
268271}
269272
270−struct CliArgs {
271− disk: Option<PathBuf>,
272− version: bool,
273− help: bool,
274− no_default_mounts: bool,
275− mounts: Vec<String>,
276− login_actions: Vec<LoginAction>,
277− cpu_count: usize,
278− ram_bytes: u64,
279−}
280−
281−fn parse_cli() -> Result<CliArgs, Box<dyn std::error::Error>> {
282− fn os_to_string(value: OsString, flag: &str) -> Result<String, Box<dyn std::error::Error>> {
283− value
284− .into_string()
285− .map_err(|_| format!("{flag} expects valid UTF-8").into())
286− }
287−
288− let mut parser = lexopt::Parser::from_env();
289− let mut disk = None;
290− let mut version = false;
291− let mut help = false;
292− let mut no_default_mounts = false;
293− let mut mounts = Vec::new();
294− let mut login_actions = Vec::new();
295− let mut script_index = 0;
296− let mut cpu_count = DEFAULT_CPU_COUNT;
297− let mut ram_bytes = DEFAULT_RAM_BYTES;
298−
299− while let Some(arg) = parser.next()? {
300− match arg {
301− Long("version") => version = true,
302− Long("help") | Short('h') => help = true,
303− Long("no-default-mounts") => no_default_mounts = true,
304− Long("cpus") => {
305− let value = os_to_string(parser.value()?, "--cpus")?.parse()?;
306− if value == 0 {
307− return Err("--cpus must be >= 1".into());
308− }
309− cpu_count = value;
310− }
311− Long("ram") => {
312− let value: u64 = os_to_string(parser.value()?, "--ram")?.parse()?;
313− if value == 0 {
314− return Err("--ram must be >= 1".into());
315− }
316− ram_bytes = value * BYTES_PER_MB;
317− }
318− Long("mount") => {
319− mounts.push(os_to_string(parser.value()?, "--mount")?);
320− }
321− Long("script") => {
322− login_actions.push(Script {
323− path: os_to_string(parser.value()?, "--script")?.into(),
324− index: script_index,
325− });
326− script_index += 1;
327− }
328− Long("send") => {
329− login_actions.push(Send(os_to_string(parser.value()?, "--send")?));
330− }
331− Long("expect") => {
332− let text = os_to_string(parser.value()?, "--expect")?;
333− let timeout = match parser.optional_value() {
334− Some(value) => Duration::from_secs(os_to_string(value, "--expect")?.parse()?),
335− None => DEFAULT_EXPECT_TIMEOUT,
336− };
337− login_actions.push(Expect { text, timeout });
338− }
339− Value(value) => {
340− if disk.is_some() {
341− return Err("Only one disk path may be provided".into());
342− }
343− disk = Some(PathBuf::from(value));
344− }
345− _ => return Err(arg.unexpected().into()),
346− }
347− }
348−
349− Ok(CliArgs {
350− disk,
351− version,
352− help,
353− no_default_mounts,
354− mounts,
355− login_actions,
356− cpu_count,
357− ram_bytes,
358− })
359−}
360−
361−fn script_command_from_path(
362− path: &Path,
363− index: usize,
364−) -> Result<String, Box<dyn std::error::Error>> {
365− let script = fs::read_to_string(path)
366− .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
367− let label = format!("{}_{}", index, path.file_name().unwrap().display());
368− script_command_from_content(&label, &script)
369−}
370−
371−fn script_command_from_content(
372− label: &str,
373− script: &str,
374−) -> Result<String, Box<dyn std::error::Error>> {
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
375274 let marker = "VIBE_SCRIPT_EOF";
376275 let guest_dir = "/tmp/vibe-scripts";
377276 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);
378284 let command = format!(
379− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
285+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
380286 );
381287 if script.contains(marker) {
382− return Err(
383− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
384− );
288+ bail!(format!(
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
290+ ));
385291 }
386292 Ok(command)
387293}
@@ -415,18 +321,6 @@ fn motd_login_action(directory_shares: &[DirectoryShare]) -> Option<LoginAction>
415321 }
416322
417323 let mut output = String::new();
418− output.push_str(
419− "
420−░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
421−░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
422− ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
423− ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░░▒▓██████▓▒░
424− ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
425− ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
426− ░▒▓██▓▒░ ░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
427−
428−",
429− );
430324 output.push_str(&format!(
431325 "{host_header:<host_width$} {guest_header:<guest_width$} {mode_header}\n",
432326 host_width = host_width
@@ -457,6 +351,12 @@ enum WaitResult {
457351 Found,
458352}
459353
354+#[derive(PartialEq, Eq)]
355+enum WaitAnyResult {
356+ Timeout,
357+ Found(usize),
358+}
359+
460360pub enum VmInput {
461361 Bytes(Vec<u8>),
462362 Shutdown,
@@ -464,6 +364,7 @@ pub enum VmInput {
464364
465365enum VmOutput {
466366 LoginActionTimeout { action: String, timeout: Duration },
367+ LoginActionFailed { action: String, reason: String },
467368}
468369
469370#[derive(Default)]
@@ -500,20 +401,100 @@ impl OutputMonitor {
500401 WaitResult::Found
501402 }
502403 }
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+ }
503482}
504483
505484fn ensure_base_image(
506485 base_raw: &Path,
507486 base_compressed: &Path,
508−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
488+) -> Result<()> {
509489 if base_raw.exists() {
510490 return Ok(());
511491 }
512492
513493 if !base_compressed.exists()
514− || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
494+ || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
515495 {
516− println!("Downloading base image...");
496+ emit_status(status, "downloading base image...");
497+ tracing::info!("downloading base image");
517498 let status = Command::new("curl")
518499 .args([
519500 "--continue-at",
@@ -527,12 +508,14 @@ fn ensure_base_image(
527508 ])
528509 .status()?;
529510 if !status.success() {
530− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
531512 }
532513 }
533514
534515 // Check SHA
535516 {
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
536519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
537520
538521 let mut child = Command::new("/usr/bin/shasum")
@@ -550,18 +533,25 @@ fn ensure_base_image(
550533
551534 let status = child.wait().expect("failed to wait on child");
552535 if !status.success() {
553− return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
536+ bail!(format!(
537+ "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538+ ));
554539 }
555540 }
556541
557− println!("Decompressing base image...");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
558544 let status = Command::new("tar")
559− .args(["-xOf", &base_compressed.to_string_lossy(), "disk.raw"])
560− .stdout(std::fs::File::create(base_raw)?)
545+ .args([
546+ "-xOf",
547+ &base_compressed.to_string_lossy(),
548+ BASE_DISK_RAW_NAME,
549+ ])
550+ .stdout(fs::File::create(base_raw)?)
561551 .status()?;
562552
563553 if !status.success() {
564− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
565555 }
566556
567557 Ok(())
@@ -572,24 +562,56 @@ fn ensure_default_image(
572562 base_compressed: &Path,
573563 default_raw: &Path,
574564 directory_shares: &[DirectoryShare],
575−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
567+) -> Result<()> {
576568 if default_raw.exists() {
577569 return Ok(());
578570 }
579571
580− ensure_base_image(base_raw, base_compressed)?;
572+ ensure_base_image(base_raw, base_compressed, status)?;
581573
582− println!("Configuring base image...");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
583576 fs::copy(base_raw, default_raw)?;
584577
585578 let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
586− run_vm(
587− default_raw,
588− &[Send(provision_command)],
589− directory_shares,
590− DEFAULT_CPU_COUNT,
591− DEFAULT_RAM_BYTES,
592− )?;
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+ }
593615
594616 Ok(())
595617}
@@ -597,15 +619,47 @@ fn ensure_default_image(
597619fn ensure_instance_disk(
598620 instance_raw: &Path,
599621 template_raw: &Path,
600−) -> Result<(), Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
624+) -> Result<bool> {
601625 if instance_raw.exists() {
602− return Ok(());
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);
603637 }
604638
605− println!("Creating instance disk from {}...", template_raw.display());
606− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
607− fs::copy(template_raw, instance_raw)?;
608− Ok(())
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);
656+ }
657+
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)
609663}
610664
611665pub struct IoContext {
@@ -621,10 +675,16 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
621675 (read_stream.into(), write_stream.into())
622676}
623677
624−pub fn spawn_vm_io(
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+>(
625682 output_monitor: Arc<OutputMonitor>,
626683 vm_output_fd: OwnedFd,
627684 vm_input_fd: OwnedFd,
685+ io_control: Arc<IoControl>,
686+ mut on_line: F,
687+ mut on_output: G,
628688) -> IoContext {
629689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
630690
@@ -640,7 +700,12 @@ pub fn spawn_vm_io(
640700 Error,
641701 }
642702
643− fn poll_with_wakeup<'a>(main_fd: RawFd, wakeup_fd: RawFd, buf: &'a mut [u8]) -> PollResult<'a> {
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> {
644709 let mut fds = [
645710 libc::pollfd {
646711 fd: main_fd,
@@ -654,8 +719,12 @@ pub fn spawn_vm_io(
654719 },
655720 ];
656721
657− let ret = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
658− if ret <= 0 || fds[1].revents & libc::POLLIN != 0 {
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 {
659728 PollResult::Shutdown
660729 } else if fds[0].revents & libc::POLLIN != 0 {
661730 let n = unsafe { libc::read(main_fd, buf.as_mut_ptr() as *mut _, buf.len()) };
@@ -671,23 +740,68 @@ pub fn spawn_vm_io(
671740 }
672741 }
673742
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+
674754 // Copies from stdin to the VM; also polls wakeup_read to exit the thread when it's time to shutdown.
675755 let stdin_thread = thread::spawn({
676756 let input_tx = input_tx.clone();
677757 let raw_guard = raw_guard.clone();
678758 let wakeup_read = wakeup_read.try_clone().unwrap();
759+ let io_control = io_control.clone();
679760
680761 move || {
681762 let mut buf = [0u8; 1024];
763+ let mut pending_command: Vec<u8> = Vec::new();
764+ let mut command_mode = false;
682765 loop {
683− match poll_with_wakeup(libc::STDIN_FILENO, wakeup_read.as_raw_fd(), &mut buf) {
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) {
684774 PollResult::Shutdown | PollResult::Error => break,
685775 PollResult::Spurious => continue,
686776 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+ }
687800 if raw_guard.lock().unwrap().is_none() {
688801 continue;
689802 }
690− if input_tx.send(VmInput::Bytes(bytes.to_vec())).is_err() {
803+ if !send_buf.is_empty() && input_tx.send(VmInput::Bytes(send_buf)).is_err()
804+ {
691805 break;
692806 }
693807 }
@@ -700,28 +814,40 @@ pub fn spawn_vm_io(
700814 let stdout_thread = thread::spawn({
701815 let raw_guard = raw_guard.clone();
702816 let wakeup_read = wakeup_read.try_clone().unwrap();
817+ let io_control = io_control.clone();
703818
704819 move || {
705− let mut stdout = std::io::stdout().lock();
706820 let mut buf = [0u8; 1024];
707821 loop {
708− match poll_with_wakeup(vm_output_fd.as_raw_fd(), wakeup_read.as_raw_fd(), &mut buf)
709− {
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+ ) {
710832 PollResult::Shutdown | PollResult::Error => break,
711833 PollResult::Spurious => continue,
712834 PollResult::Ready(bytes) => {
713− // enable raw mode, if we haven't already
714− if raw_guard.lock().unwrap().is_none()
715− && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
716− {
717− *raw_guard.lock().unwrap() = Some(guard);
718− }
719−
720− if stdout.write_all(bytes).is_err() {
721− break;
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();
722848 }
723− let _ = stdout.flush();
724849 output_monitor.push(bytes);
850+ on_output(bytes);
725851 }
726852 }
727853 }
@@ -730,7 +856,7 @@ pub fn spawn_vm_io(
730856
731857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
732858 let mux_thread = thread::spawn(move || {
733− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
734860 loop {
735861 match input_rx.recv() {
736862 Ok(VmInput::Bytes(data)) => {
@@ -753,6 +879,63 @@ pub fn spawn_vm_io(
753879 }
754880}
755881
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+
756939impl IoContext {
757940 pub fn shutdown(self) {
758941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -770,7 +953,7 @@ fn create_vm_configuration(
770953 vm_writes_to_fd: OwnedFd,
771954 cpu_count: usize,
772955 ram_bytes: u64,
773−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
774957 unsafe {
775958 let platform =
776959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -804,7 +987,7 @@ fn create_vm_configuration(
804987 false,
805988 VZDiskImageCachingMode::Automatic,
806989 VZDiskImageSynchronizationMode::Full,
807− ).unwrap();
990+ )?;
808991
809992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
810993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -891,7 +1074,7 @@ fn create_vm_configuration(
8911074 // Validate
8921075 config.validateWithError().map_err(|e| {
8931076 io::Error::other(format!(
894− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
8951078 e.localizedDescription()
8961079 ))
8971080 })?;
@@ -900,9 +1083,9 @@ fn create_vm_configuration(
9001083 }
9011084}
9021085
903−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
9041087 unsafe {
905− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
9061089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
9071090 let url = nsurl_from_path(&temp_path)?;
9081091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -918,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
9181101fn spawn_login_actions_thread(
9191102 login_actions: Vec<LoginAction>,
9201103 output_monitor: Arc<OutputMonitor>,
921− input_tx: mpsc::Sender<VmInput>,
922− vm_output_tx: mpsc::Sender<VmOutput>,
1104+ input_tx: Sender<VmInput>,
1105+ vm_output_tx: Sender<VmOutput>,
9231106) -> thread::JoinHandle<()> {
9241107 thread::spawn(move || {
9251108 for a in login_actions {
@@ -933,34 +1116,48 @@ fn spawn_login_actions_thread(
9331116 return;
9341117 }
9351118 }
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+ },
9361140 Send(mut text) => {
9371141 text.push('\n'); // Type the newline so the command is actually submitted.
9381142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
9391143 }
940− Script { path, index } => {
941− let command = match script_command_from_path(&path, index) {
942− Ok(command) => command,
943− Err(err) => {
944− eprintln!("{err}");
945− return;
946− }
947− };
948− let mut text = command;
949− text.push('\n');
950− input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
951− }
9521144 }
9531145 }
9541146 })
9551147}
9561148
957−fn run_vm(
1149+fn run_vm_with_io<F>(
9581150 disk_path: &Path,
9591151 login_actions: &[LoginAction],
9601152 directory_shares: &[DirectoryShare],
9611153 cpu_count: usize,
9621154 ram_bytes: u64,
963−) -> Result<(), Box<dyn std::error::Error>> {
1155+ status: Option<&StatusEmitter<'_>>,
1156+ io_handler: F,
1157+) -> Result<()>
1158+where
1159+ F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
1160+{
9641161 let (vm_reads_from, we_write_to) = create_pipe();
9651162 let (we_read_from, vm_writes_to) = create_pipe();
9661163
@@ -1004,24 +1201,26 @@ fn run_vm(
10041201
10051202 match rx.try_recv() {
10061203 Ok(result) => {
1007− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
10081205 break;
10091206 }
10101207 Err(mpsc::TryRecvError::Empty) => continue,
10111208 Err(mpsc::TryRecvError::Disconnected) => {
1012− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
10131210 }
10141211 }
10151212 }
10161213
10171214 if Instant::now() >= start_deadline {
1018− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
10191216 }
10201217
1021− println!("VM booting...");
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
1220+ tracing::info!("vm booting");
10221221
10231222 let output_monitor = Arc::new(OutputMonitor::default());
1024− let io_ctx = spawn_vm_io(output_monitor.clone(), we_read_from, we_write_to);
1223+ let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
10251224
10261225 let mut all_login_actions = vec![
10271226 Expect {
@@ -1063,7 +1262,7 @@ fn run_vm(
10631262 );
10641263
10651264 let mut last_state = None;
1066− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
10671266 loop {
10681267 unsafe {
10691268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1082,12 +1281,28 @@ fn run_vm(
10821281 exit_result = Err(format!(
10831282 "Login action ({}) timed out after {:?}; shutting down.",
10841283 action, timeout
1085− )
1086− .into());
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+ ));
10871302 unsafe {
10881303 if vm.canRequestStop() {
10891304 if let Err(err) = vm.requestStopWithError() {
1090− eprintln!("Failed to request VM stop: {:?}", err);
1305+ tracing::error!(error = ?err, "failed to request VM stop");
10911306 }
10921307 } else if vm.canStop() {
10931308 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1099,7 +1314,7 @@ fn run_vm(
10991314 Err(mpsc::TryRecvError::Empty) => {}
11001315 Err(mpsc::TryRecvError::Disconnected) => {}
11011316 }
1102− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
11031318 //eprintln!("VM stopped with state: {:?}", state);
11041319 break;
11051320 }
@@ -1109,10 +1324,29 @@ fn run_vm(
11091324
11101325 io_ctx.shutdown();
11111326
1112− exit_result
1327+ exit_result.map_err(Error::msg)
11131328}
11141329
1115−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
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>> {
11161350 let abs_path = if path.is_absolute() {
11171351 path.to_path_buf()
11181352 } else {
@@ -1121,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
11211355 let ns_path = NSString::from_str(
11221356 abs_path
11231357 .to_str()
1124− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
11251359 );
11261360 Ok(NSURL::fileURLWithPath(&ns_path))
11271361}
@@ -1136,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
11361370 let original = attributes;
11371371
11381372 // Disable translation of carriage return to newline on input
1139− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
11401374 // Disable canonical mode (line buffering), echo, and signal generation
11411375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
11421376 attributes.c_cc[libc::VMIN] = 0;
@@ -1164,7 +1398,10 @@ impl Drop for RawModeGuard {
11641398
11651399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
11661400pub fn ensure_signed() {
1167− let exe = std::env::current_exe().expect("failed to get current exe path");
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");
11681405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
11691406
11701407 let has_required_entitlements = {
@@ -1186,10 +1423,10 @@ pub fn ensure_signed() {
11861423 }
11871424
11881425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1189− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1190− std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1426+ let entitlements_path = env::temp_dir().join("entitlements.plist");
1427+ fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
11911428
1192− let status = Command::new("codesign")
1429+ let output = Command::new("codesign")
11931430 .args([
11941431 "--sign",
11951432 "-",
@@ -1198,22 +1435,27 @@ pub fn ensure_signed() {
11981435 entitlements_path.to_str().unwrap(),
11991436 exe_str,
12001437 ])
1201− .status();
1438+ .output();
12021439
1203− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
12041441
1205− match status {
1206− Ok(s) if s.success() => {
1207− let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1208− eprintln!("failed to re-exec after signing: {err}");
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");
12091450 std::process::exit(1);
12101451 }
1211− Ok(s) => {
1212− eprintln!("codesign failed with status: {s}");
1452+ Ok(o) => {
1453+ let stderr = String::from_utf8_lossy(&o.stderr);
1454+ tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
12131455 std::process::exit(1);
12141456 }
12151457 Err(e) => {
1216− eprintln!("failed to run codesign: {e}");
1458+ tracing::error!(error = %e, "failed to run codesign");
12171459 std::process::exit(1);
12181460 }
12191461 }