use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
pub const LOCK_FILE: &str = "orchestrator.lock";
pub const SERVICE_DIR: &str = "service";
pub const DAEMON_ENTRY: &str = "bin/orchestrator.mjs";
pub const SERVICE_NAME: &str = "ai.volter.supercode.orchestrator";
pub fn service_name(root: &Path) -> String {
let mut hash = 0xcbf29ce484222325_u64;
for byte in root.to_string_lossy().bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
format!("{SERVICE_NAME}-{hash:016x}")
}
fn unit_environment() -> (String, String) {
let path = std::env::var("PATH")
.ok()
.filter(|path| !path.trim().is_empty())
.unwrap_or_else(|| "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin".into());
(path, std::env::var("HOME").unwrap_or_default())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lease {
pub pid: u32,
pub started_at: String,
pub root: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boot: Option<String>,
}
impl Lease {
pub fn is_live(&self) -> bool {
let here = this_host();
if self
.host
.as_deref()
.is_some_and(|host| Some(host) != here.0.as_deref())
{
return false;
}
if let (Some(boot), Some(now)) = (self.boot.as_deref(), here.1.as_deref()) {
if boot != now {
return false;
}
}
pid_is_live(self.pid)
}
}
pub fn this_host() -> (Option<String>, Option<String>) {
let boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty());
(hostname(), boot)
}
fn hostname() -> Option<String> {
#[cfg(unix)]
{
let mut buffer = [0u8; 256];
let status = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
if status != 0 {
return None;
}
let end = buffer
.iter()
.position(|byte| *byte == 0)
.unwrap_or(buffer.len());
String::from_utf8(buffer[..end].to_vec())
.ok()
.filter(|name| !name.is_empty())
}
#[cfg(not(unix))]
{
std::env::var("COMPUTERNAME").ok()
}
}
#[derive(Debug, thiserror::Error)]
pub enum OrchestratorError {
#[error("the orchestrator is not running for `{0}` (no live lease at `{1}`)", root.display(), lock.display())]
NotRunning {
root: PathBuf,
lock: PathBuf,
},
#[error("the orchestrator is already running for `{}` (pid {pid})", root.display())]
AlreadyRunning {
root: PathBuf,
pid: u32,
},
#[error("no orchestrator daemon entry found (looked for `{DAEMON_ENTRY}` under: {searched})")]
NoDaemonEntry {
searched: String,
},
#[error("orchestrator lease `{}`: {source}", path.display())]
Lease {
path: PathBuf,
source: std::io::Error,
},
#[error("orchestrator service: {action} failed: {detail}")]
Service {
action: &'static str,
detail: String,
},
}
pub fn lock_path(root: &Path) -> PathBuf {
root.join(LOCK_FILE)
}
pub fn read_lease(root: &Path) -> Option<Lease> {
let text = std::fs::read_to_string(lock_path(root)).ok()?;
serde_json::from_str(&text).ok()
}
pub fn write_lease(root: &Path, lease: &Lease) -> Result<(), OrchestratorError> {
let path = lock_path(root);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|source| OrchestratorError::Lease {
path: path.clone(),
source,
})?;
}
let text = serde_json::to_string_pretty(lease).unwrap_or_default();
std::fs::write(&path, format!("{text}\n")).map_err(|source| OrchestratorError::Lease {
path: path.clone(),
source,
})
}
pub fn clear_lease(root: &Path) -> Result<(), OrchestratorError> {
let path = lock_path(root);
match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(source) => Err(OrchestratorError::Lease { path, source }),
}
}
pub fn pid_is_live(pid: u32) -> bool {
#[cfg(unix)]
{
if pid == 0 {
return false;
}
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}
#[cfg(not(unix))]
{
let _ = pid;
true
}
}
pub fn live_lease(root: &Path) -> Option<Lease> {
read_lease(root).filter(Lease::is_live)
}
pub fn stop(root: &Path) -> Result<Lease, OrchestratorError> {
let Some(lease) = live_lease(root) else {
return Err(OrchestratorError::NotRunning {
root: root.to_path_buf(),
lock: lock_path(root),
});
};
#[cfg(unix)]
unsafe {
libc::kill(lease.pid as libc::pid_t, libc::SIGTERM);
}
clear_lease(root)?;
Ok(lease)
}
pub fn daemon_entry() -> Result<PathBuf, OrchestratorError> {
let mut searched = Vec::new();
if let Some(explicit) = std::env::var_os("SUPERCODE_ORCHESTRATOR_ENTRY") {
let path = PathBuf::from(explicit);
if path.is_file() {
return Ok(path);
}
searched.push(path.display().to_string());
}
for dir in std::env::var_os("PATH")
.iter()
.flat_map(std::env::split_paths)
{
let command = dir.join("supercode-orchestrator");
if let Ok(entry) = std::fs::canonicalize(&command) {
if entry.is_file() && entry.ends_with(DAEMON_ENTRY) {
return Ok(entry);
}
}
}
searched.push("supercode-orchestrator on PATH".to_string());
let mut roots: Vec<PathBuf> = Vec::new();
if let Ok(exe) = std::env::current_exe() {
roots.extend(exe.ancestors().skip(1).take(4).map(Path::to_path_buf));
}
if let Some(workspace) = Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2) {
roots.push(workspace.to_path_buf());
}
for root in roots {
let candidate = root.join("sdk/orchestrator").join(DAEMON_ENTRY);
if candidate.is_file() {
return Ok(candidate);
}
searched.push(candidate.display().to_string());
}
Err(OrchestratorError::NoDaemonEntry {
searched: searched.join(", "),
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ServiceUnit {
pub kind: &'static str,
pub path: PathBuf,
pub text: String,
pub install_command: String,
#[serde(skip)]
pub files: Vec<(PathBuf, String)>,
}
pub fn service_unit(root: &Path, entry: &Path, node: &str) -> ServiceUnit {
let root_display = root.display().to_string();
let entry_display = entry.display().to_string();
let name = service_name(root);
let (env_path, env_home) = unit_environment();
if cfg!(target_os = "macos") {
let path = root.join(SERVICE_DIR).join(format!("{name}.plist"));
let text = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>{name}</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key><string>{env_path}</string>
<key>HOME</key><string>{env_home}</string>
</dict>
<key>ProgramArguments</key>
<array>
<string>{node}</string>
<string>{entry_display}</string>
<string>--root</string>
<string>{root_display}</string>
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>{root_display}/service/orchestrator.out.log</string>
<key>StandardErrorPath</key><string>{root_display}/service/orchestrator.err.log</string>
</dict>
</plist>
"#
);
let install = format!("launchctl bootstrap gui/$(id -u) {}", path.display());
ServiceUnit {
kind: "launchd",
path,
text,
install_command: install,
files: Vec::new(),
}
} else {
let path = root.join(SERVICE_DIR).join(format!("{name}.service"));
let text = format!(
"[Unit]\n\
Description=supercode orchestrator ({root_display})\n\
After=network.target\n\
\n\
[Service]\n\
Environment=PATH={env_path}\n\
Environment=HOME={env_home}\n\
ExecStart={node} {entry_display} --root {root_display}\n\
Restart=on-failure\n\
KillSignal=SIGTERM\n\
\n\
[Install]\n\
WantedBy=default.target\n"
);
let install = format!(
"systemctl --user link {} && systemctl --user enable --now {name}",
path.display()
);
ServiceUnit {
kind: "systemd",
path,
text,
install_command: install,
files: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ServiceState {
pub kind: &'static str,
pub label: String,
pub installed: bool,
pub pid: Option<u32>,
pub detail: String,
}
pub fn absolute_program(program: &str) -> String {
resolve_program(program).display().to_string()
}
pub fn resolve_program(program: &str) -> PathBuf {
resolve_program_in(
program,
std::env::var_os("PATH").as_deref(),
std::env::var("PATHEXT").ok().as_deref(),
cfg!(windows),
)
}
fn resolve_program_in(
program: &str,
path: Option<&std::ffi::OsStr>,
pathext: Option<&str>,
windows: bool,
) -> PathBuf {
if program.contains('/') || (windows && program.contains('\\')) {
return PathBuf::from(program);
}
let extensions: Vec<String> = if windows && Path::new(program).extension().is_none() {
pathext
.unwrap_or(".COM;.EXE;.BAT;.CMD")
.split(';')
.filter(|extension| !extension.is_empty())
.map(str::to_ascii_lowercase)
.collect()
} else {
vec![String::new()]
};
for dir in path.map(std::env::split_paths).into_iter().flatten() {
for extension in &extensions {
let candidate = dir.join(format!("{program}{extension}"));
if candidate.is_file() {
return candidate;
}
}
}
PathBuf::from(program)
}
#[allow(dead_code)]
fn unit_label(unit: &ServiceUnit) -> String {
unit.path
.file_stem()
.map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn run_tool(program: &str, args: &[&str]) -> Result<(bool, String), std::io::Error> {
let output = std::process::Command::new(program).args(args).output()?;
let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
text.push_str(&String::from_utf8_lossy(&output.stderr));
Ok((output.status.success(), text.trim().to_string()))
}
#[cfg(target_os = "macos")]
fn gui_domain() -> String {
format!("gui/{}", unsafe { libc::getuid() })
}
pub fn service_status(root: &Path) -> ServiceState {
platform_status(root)
}
#[cfg(target_os = "macos")]
fn platform_status(root: &Path) -> ServiceState {
let label = service_name(root);
let target = format!("{}/{label}", gui_domain());
match run_tool("launchctl", &["print", &target]) {
Ok((true, text)) => ServiceState {
kind: "launchd",
label,
installed: true,
pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
},
Ok((false, _)) => ServiceState {
kind: "launchd",
label,
installed: false,
pid: None,
detail: format!("not bootstrapped in {}", gui_domain()),
},
Err(error) => ServiceState {
kind: "launchd",
label,
installed: false,
pid: None,
detail: format!("launchctl unavailable: {error}"),
},
}
}
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_status(root: &Path) -> ServiceState {
let label = service_name(root);
match run_tool("systemctl", &["--user", "is-active", &label]) {
Ok((active, text)) => {
let known = run_tool("systemctl", &["--user", "is-enabled", &label])
.map(|(ok, _)| ok)
.unwrap_or(false);
ServiceState {
kind: "systemd",
label,
installed: active || known,
pid: None,
detail: if text.is_empty() {
"unknown".into()
} else {
text
},
}
}
Err(error) => ServiceState {
kind: "systemd",
label,
installed: false,
pid: None,
detail: format!("systemctl unavailable: {error}"),
},
}
}
#[cfg(not(unix))]
fn platform_status(root: &Path) -> ServiceState {
ServiceState {
kind: "none",
label: service_name(root),
installed: false,
pid: None,
detail: "no service manager on this platform".into(),
}
}
#[cfg(target_os = "macos")]
fn field_of(text: &str, key: &str) -> Option<String> {
text.lines()
.find_map(|line| line.trim().strip_prefix(key))
.map(|value| value.trim().to_string())
}
pub fn install_service(
root: &Path,
entry: &Path,
node: &str,
) -> Result<(ServiceUnit, ServiceState), OrchestratorError> {
let existing = service_status(root);
if existing.installed {
return Err(OrchestratorError::Service {
action: "install",
detail: format!(
"`{}` is already installed ({}); `supercode orchestrator setup --uninstall` first",
existing.label, existing.detail
),
});
}
let unit = service_unit(root, entry, &absolute_program(node));
write_unit(&unit)?;
platform_install(&unit)?;
Ok((unit, service_status(root)))
}
#[cfg(target_os = "macos")]
fn platform_install(unit: &ServiceUnit) -> Result<(), OrchestratorError> {
let path = unit.path.display().to_string();
let (ok, text) =
run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
OrchestratorError::Service {
action: "install",
detail: format!("launchctl: {error}"),
}
})?;
if !ok {
return Err(OrchestratorError::Service {
action: "install",
detail: format!("launchctl bootstrap {}: {text}", gui_domain()),
});
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_install(unit: &ServiceUnit) -> Result<(), OrchestratorError> {
let path = unit.path.display().to_string();
for args in [
vec!["--user", "link", path.as_str()],
vec!["--user", "enable", "--now", unit_label(unit).as_str()],
] {
let (ok, text) =
run_tool("systemctl", &args).map_err(|error| OrchestratorError::Service {
action: "install",
detail: format!("systemctl: {error}"),
})?;
if !ok {
return Err(OrchestratorError::Service {
action: "install",
detail: format!("systemctl {}: {text}", args.join(" ")),
});
}
}
Ok(())
}
#[cfg(not(unix))]
fn platform_install(_unit: &ServiceUnit) -> Result<(), OrchestratorError> {
Err(OrchestratorError::Service {
action: "install",
detail: "no service manager on this platform".into(),
})
}
pub fn uninstall_service(root: &Path) -> Result<ServiceState, OrchestratorError> {
platform_uninstall(root)?;
let unit_path = root.join(SERVICE_DIR).join(unit_file_name(root));
match std::fs::remove_file(&unit_path) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(source) => {
return Err(OrchestratorError::Lease {
path: unit_path,
source,
})
}
}
let mut state = service_status(root);
for _ in 0..40 {
if !state.installed {
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
state = service_status(root);
}
Ok(state)
}
#[cfg(target_os = "macos")]
fn platform_uninstall(root: &Path) -> Result<(), OrchestratorError> {
let target = format!("{}/{}", gui_domain(), service_name(root));
let (ok, text) = run_tool("launchctl", &["bootout", &target]).map_err(|error| {
OrchestratorError::Service {
action: "uninstall",
detail: format!("launchctl: {error}"),
}
})?;
if !ok && !text.contains("No such process") && !text.contains("not find") {
return Err(OrchestratorError::Service {
action: "uninstall",
detail: format!("launchctl bootout {target}: {text}"),
});
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_uninstall(root: &Path) -> Result<(), OrchestratorError> {
let _ = run_tool(
"systemctl",
&["--user", "disable", "--now", &service_name(root)],
);
Ok(())
}
#[cfg(not(unix))]
fn platform_uninstall(_root: &Path) -> Result<(), OrchestratorError> {
Ok(())
}
fn unit_file_name(root: &Path) -> String {
if cfg!(target_os = "macos") {
format!("{}.plist", service_name(root))
} else {
format!("{}.service", service_name(root))
}
}
pub fn write_unit(unit: &ServiceUnit) -> Result<(), OrchestratorError> {
if let Some(parent) = unit.path.parent() {
std::fs::create_dir_all(parent).map_err(|source| OrchestratorError::Lease {
path: unit.path.clone(),
source,
})?;
}
std::fs::write(&unit.path, &unit.text).map_err(|source| OrchestratorError::Lease {
path: unit.path.clone(),
source,
})
}