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";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lease {
pub pid: u32,
pub started_at: String,
pub root: PathBuf,
}
#[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| pid_is_live(lease.pid))
}
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());
}
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 Ok(cwd) = std::env::current_dir() {
roots.push(cwd);
}
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,
}
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();
if cfg!(target_os = "macos") {
let path = root.join(SERVICE_DIR).join(format!("{SERVICE_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>{SERVICE_NAME}</string>
<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,
}
} else {
let path = root
.join(SERVICE_DIR)
.join(format!("{SERVICE_NAME}.service"));
let text = format!(
"[Unit]\n\
Description=supercode orchestrator ({root_display})\n\
After=network.target\n\
\n\
[Service]\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 {SERVICE_NAME}",
path.display()
);
ServiceUnit {
kind: "systemd",
path,
text,
install_command: install,
}
}
}
#[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 {
if program.contains('/') {
return program.to_string();
}
if let Some(path) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path) {
let candidate = dir.join(program);
if candidate.is_file() {
return candidate.display().to_string();
}
}
}
program.to_string()
}
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.to_string();
let target = format!("{}/{SERVICE_NAME}", 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.to_string();
match run_tool("systemctl", &["--user", "is-active", SERVICE_NAME]) {
Ok((active, text)) => {
let known = run_tool("systemctl", &["--user", "is-enabled", SERVICE_NAME])
.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.to_string(),
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", SERVICE_NAME],
] {
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()?;
let unit_path = root.join(SERVICE_DIR).join(unit_file_name());
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() -> Result<(), OrchestratorError> {
let target = format!("{}/{SERVICE_NAME}", gui_domain());
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() -> Result<(), OrchestratorError> {
let _ = run_tool("systemctl", &["--user", "disable", "--now", SERVICE_NAME]);
Ok(())
}
#[cfg(not(unix))]
fn platform_uninstall() -> Result<(), OrchestratorError> {
Ok(())
}
fn unit_file_name() -> String {
if cfg!(target_os = "macos") {
format!("{SERVICE_NAME}.plist")
} else {
format!("{SERVICE_NAME}.service")
}
}
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,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch(label: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"supercode-orchestrator-{label}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&root).unwrap();
root
}
#[test]
fn a_lease_round_trips_and_a_missing_one_is_not_running() {
let root = &scratch("lease");
let root = root.as_path();
assert!(read_lease(root).is_none());
assert!(live_lease(root).is_none());
let lease = Lease {
pid: std::process::id(),
started_at: "2026-09-04T00:00:00Z".into(),
root: root.to_path_buf(),
};
write_lease(root, &lease).unwrap();
assert_eq!(read_lease(root).as_ref(), Some(&lease));
assert!(live_lease(root).is_some());
clear_lease(root).unwrap();
assert!(read_lease(root).is_none());
assert!(matches!(
stop(root),
Err(OrchestratorError::NotRunning { .. })
));
std::fs::remove_dir_all(root).ok();
}
#[test]
fn a_stale_lease_is_not_live() {
let root = &scratch("stale");
let root = root.as_path();
write_lease(
root,
&Lease {
pid: 0x7FFF_FFFF,
started_at: "2026-09-04T00:00:00Z".into(),
root: root.to_path_buf(),
},
)
.unwrap();
assert!(read_lease(root).is_some(), "the file is still there");
assert!(live_lease(root).is_none(), "but nothing is serving it");
std::fs::remove_dir_all(root).ok();
}
#[test]
fn the_service_unit_names_the_home_the_entry_and_its_install_command() {
let root = &scratch("unit");
let root = root.as_path();
let entry = PathBuf::from("/opt/supercode/sdk/orchestrator/bin/orchestrator.mjs");
let unit = service_unit(root, &entry, "/usr/bin/node");
assert!(unit.text.contains(&root.display().to_string()));
assert!(unit.text.contains("orchestrator.mjs"));
assert!(unit.text.contains(SERVICE_NAME));
assert!(unit
.install_command
.contains(&unit.path.display().to_string()));
assert!(unit.path.starts_with(root.join(SERVICE_DIR)));
assert_eq!(
unit.kind,
if cfg!(target_os = "macos") {
"launchd"
} else {
"systemd"
}
);
std::fs::remove_dir_all(root).ok();
}
#[test]
fn service_status_reports_the_label_and_installs_nothing() {
let root = &scratch("service-status");
let root = root.as_path();
let state = service_status(root);
assert_eq!(state.label, SERVICE_NAME);
assert!(
matches!(state.kind, "launchd" | "systemd" | "none"),
"{state:?}"
);
assert!(
!root.join(SERVICE_DIR).exists(),
"asking never writes a unit"
);
std::fs::remove_dir_all(root).ok();
}
#[test]
fn a_program_is_resolved_absolutely_for_the_service_manager() {
assert_eq!(absolute_program("/usr/bin/env"), "/usr/bin/env");
let resolved = absolute_program("sh");
assert!(resolved.starts_with('/'), "{resolved}");
assert_eq!(
absolute_program("definitely-not-a-program"),
"definitely-not-a-program"
);
}
#[test]
fn the_daemon_entry_resolves_in_this_checkout() {
let entry = daemon_entry().expect("sdk/orchestrator/bin/orchestrator.mjs");
assert!(entry.ends_with(DAEMON_ENTRY));
}
}