use super::{AdvanceOutcome, run};
use crate::harness_root;
use crate::prompt::inbox::{self, AdvanceLauncher, baton};
use crate::prompt::resolve::{ConfigSource, resolve_worker};
use crate::prompt::{Deps, Error, RealSleeper, SpawnAdapter, SystemClock};
use crate::prompt::{NanoIdGen, tool::SpawnTool};
use std::ffi::OsStr;
use std::path::Path;
use std::process::Command;
use std::sync::atomic::AtomicBool;
#[derive(Debug)]
pub enum AdvanceHandoff {
Done,
Exec(Command),
}
pub fn cli_run(
workspace: &Path,
agent_id: &str,
driver_target: &Path,
adapter_target: Option<&Path>,
stop: &AtomicBool,
) -> Result<AdvanceHandoff, Error> {
cli_run_with(
workspace,
agent_id,
std::env::var_os(baton::LOCK_FD_ENV).as_deref(),
driver_target,
adapter_target,
stop,
)
}
fn cli_run_with(
workspace: &Path,
agent_id: &str,
lease_env: Option<&OsStr>,
driver_target: &Path,
adapter_target: Option<&Path>,
stop: &AtomicBool,
) -> Result<AdvanceHandoff, Error> {
crate::workspace::require(workspace)?;
crate::workspace::require_agent(
workspace,
agent_id,
"a hop drives an existing agent (ARCH §2.3: the `agents/*` refs are the registry)",
&crate::template::RealGit::new(),
)?;
let inbox_dir = inbox::inbox_dir(workspace, agent_id);
let lease = match baton::take_lease(lease_env, &inbox_dir) {
Ok(Some(lease)) => lease,
Ok(None) => return Ok(AdvanceHandoff::Done),
Err(baton::LeaseError::Acquire(source)) => {
return Err(Error::ExecutorLock {
path: inbox_dir,
source,
});
}
Err(baton::LeaseError::Adopt(e)) => {
return Err(Error::LeaseAdopt {
agent: agent_id.to_string(),
detail: e.to_string(),
});
}
};
let roots = harness_root::resolve()?;
let tool_executor = SpawnTool::new(&roots.data, &SystemClock, driver_target);
let launcher = AdvanceLauncher::with_exe(driver_target.to_path_buf());
let deps = Deps {
adapter: &SpawnAdapter,
sleeper: &RealSleeper,
git: &crate::template::RealGit::new(),
clock: &SystemClock,
id_gen: &NanoIdGen,
tool_executor: &tool_executor,
config_root: &roots.config,
adapter_target,
stop,
launcher: &launcher,
};
let outcome = run(workspace, agent_id, Some(lease), &deps, &mut || {
resolve_worker(workspace, ConfigSource::Agent(agent_id), &deps)
})?;
handoff(driver_target, workspace, agent_id, outcome)
}
fn handoff(
exe: &Path,
workspace: &Path,
agent_id: &str,
outcome: AdvanceOutcome,
) -> Result<AdvanceHandoff, Error> {
match outcome {
AdvanceOutcome::ToolsPending(lease) => Ok(AdvanceHandoff::Exec(baton::successor_command(
exe, workspace, agent_id, lease,
)?)),
_ => Ok(AdvanceHandoff::Done),
}
}
#[cfg(test)]
mod tests;