use std::path::{Path, PathBuf};
use crate::orchestrator::{absolute_program, ServiceState, ServiceUnit};
pub const TEAMS_ENTRY: &str = "bin/teams.mjs";
pub const TEAMS_PACKAGE: &str = "@volter-ai-dev/supercode-teams";
pub const SERVICE_DIR: &str = "service";
pub const SERVICE_NAME: &str = "dev.volter.supercode-teams-machine";
pub fn connector_service_name(server_id: &str, team_id: &str, context: &str) -> String {
let mut hash = 0xcbf29ce484222325_u64;
for byte in [server_id, team_id, context].join("\0").bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
format!("dev.volter.supercode-teams-connector-{hash:016x}")
}
fn plist_text(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
fn service_text(value: &str) -> Result<&str, TeamsError> {
if value.chars().any(char::is_control) {
return Err(TeamsError::Service {
action: "render",
detail: "service parameters cannot contain control characters".into(),
});
}
Ok(value)
}
fn systemd_arg(value: &str) -> String {
format!(
"\"{}\"",
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
.replace('$', "$$")
)
}
pub fn connector_service_unit(
teams_home: &Path,
supercode_home: &Path,
entry: &Path,
node: &str,
supercode: &Path,
context: &str,
cwd: &Path,
server_id: &str,
team_id: &str,
) -> Result<ServiceUnit, TeamsError> {
let teams_home_text = teams_home.display().to_string();
let supercode_home_text = supercode_home.display().to_string();
let entry_text = entry.display().to_string();
let supercode_text = supercode.display().to_string();
let workspace_text = cwd.display().to_string();
for value in [
teams_home_text.as_str(),
supercode_home_text.as_str(),
entry_text.as_str(),
node,
supercode_text.as_str(),
context,
workspace_text.as_str(),
server_id,
team_id,
] {
service_text(value)?;
}
let label = connector_service_name(server_id, team_id, context);
let suffix = if cfg!(target_os = "macos") {
"plist"
} else {
"service"
};
let path = teams_home
.join(SERVICE_DIR)
.join(format!("{label}.{suffix}"));
let node = absolute_program(node);
let entry = entry_text;
let workspace = workspace_text;
let home = supercode_home_text;
let supercode = supercode_text;
if cfg!(target_os = "macos") {
let node = plist_text(&node);
let entry = plist_text(&entry);
let workspace = plist_text(&workspace);
let home = plist_text(&home);
let supercode = plist_text(&supercode);
let context = plist_text(context);
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>{label}</string>
<key>ProgramArguments</key><array><string>{node}</string><string>{entry}</string><string>teams</string><string>connect</string><string>--context</string><string>{context}</string><string>--cwd</string><string>{workspace}</string></array>
<key>EnvironmentVariables</key><dict><key>SUPERCODE_HOME</key><string>{home}</string><key>SUPERCODE_BIN</key><string>{supercode}</string></dict>
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>{}/service/{label}.out.log</string>
<key>StandardErrorPath</key><string>{}/service/{label}.err.log</string>
</dict></plist>
"#,
plist_text(&teams_home_text),
plist_text(&teams_home_text)
);
Ok(ServiceUnit {
kind: "launchd",
path: path.clone(),
text,
install_command: format!("launchctl bootstrap gui/$(id -u) {}", path.display()),
})
} else {
let environment_home = systemd_arg(&format!("SUPERCODE_HOME={home}"));
let environment_bin = systemd_arg(&format!("SUPERCODE_BIN={supercode}"));
let node = systemd_arg(&node);
let entry = systemd_arg(&entry);
let workspace = systemd_arg(&workspace);
let context_description = context.replace('%', "%%").replace('$', "$$");
let context = systemd_arg(context);
let text = format!("[Unit]\nDescription=supercode Teams connector ({context_description})\nAfter=network.target\n\n[Service]\nEnvironment={environment_home}\nEnvironment={environment_bin}\nExecStart={node} {entry} teams connect --context {context} --cwd {workspace}\nRestart=on-failure\nKillSignal=SIGTERM\n\n[Install]\nWantedBy=default.target\n");
Ok(ServiceUnit {
kind: "systemd",
path: path.clone(),
text,
install_command: format!(
"systemctl --user link {} && systemctl --user enable --now {label}",
path.display()
),
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum TeamsError {
#[error("no teams entry found (looked for `sdk/teams/{TEAMS_ENTRY}` under: {searched}); install it with `npm install -g {TEAMS_PACKAGE}`")]
NoEntry {
searched: String,
},
#[error("teams service: {action} failed: {detail}")]
Service {
action: &'static str,
detail: String,
},
#[error("teams file `{}`: {source}", path.display())]
File {
path: PathBuf,
source: std::io::Error,
},
}
pub fn teams_home() -> PathBuf {
if let Ok(home) = std::env::var("SUPERCODE_TEAMS_HOME") {
if !home.is_empty() {
return PathBuf::from(home);
}
}
crate::agent::global_instructions_dir().join("teams")
}
pub fn teams_entry() -> Result<PathBuf, TeamsError> {
let mut searched = Vec::new();
if let Some(explicit) = std::env::var_os("SUPERCODE_TEAMS_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/teams").join(TEAMS_ENTRY);
if candidate.is_file() {
return Ok(candidate);
}
searched.push(candidate.display().to_string());
}
if let Some(global) = global_npm_root() {
let candidate = global.join(TEAMS_PACKAGE).join(TEAMS_ENTRY);
if candidate.is_file() {
return Ok(candidate);
}
searched.push(candidate.display().to_string());
}
Err(TeamsError::NoEntry {
searched: searched.join(", "),
})
}
fn global_npm_root() -> Option<PathBuf> {
let output = std::process::Command::new("npm")
.args(["root", "-g"])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout);
let root = text.trim();
if root.is_empty() {
return None;
}
Some(PathBuf::from(root))
}
pub fn service_unit(home: &Path, entry: &Path, node: &str) -> ServiceUnit {
let home_display = home.display().to_string();
let entry_display = entry.display().to_string();
if cfg!(target_os = "macos") {
let path = home.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>machine</string>
<string>start</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>SUPERCODE_TEAMS_HOME</key><string>{home_display}</string>
</dict>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>{home_display}/service/teams-machine.out.log</string>
<key>StandardErrorPath</key><string>{home_display}/service/teams-machine.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 = home
.join(SERVICE_DIR)
.join(format!("{SERVICE_NAME}.service"));
let text = format!(
"[Unit]\n\
Description=supercode teams machine daemon ({home_display})\n\
After=network.target\n\
\n\
[Service]\n\
Environment=SUPERCODE_TEAMS_HOME={home_display}\n\
ExecStart={node} {entry_display} machine start\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,
}
}
}
pub fn write_unit(unit: &ServiceUnit) -> Result<(), TeamsError> {
if let Some(parent) = unit.path.parent() {
std::fs::create_dir_all(parent).map_err(|source| TeamsError::File {
path: unit.path.clone(),
source,
})?;
}
std::fs::write(&unit.path, &unit.text).map_err(|source| TeamsError::File {
path: unit.path.clone(),
source,
})
}
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() -> ServiceState {
platform_status()
}
#[cfg(target_os = "macos")]
fn platform_status() -> 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() -> 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() -> 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())
}
fn unit_file_name() -> String {
if cfg!(target_os = "macos") {
format!("{SERVICE_NAME}.plist")
} else {
format!("{SERVICE_NAME}.service")
}
}
pub fn install_service(
home: &Path,
entry: &Path,
node: &str,
) -> Result<(ServiceUnit, ServiceState), TeamsError> {
let existing = service_status();
if existing.installed {
return Err(TeamsError::Service {
action: "install",
detail: format!(
"`{}` is already installed ({}); `supercode teams machine uninstall` first",
existing.label, existing.detail
),
});
}
let unit = service_unit(home, entry, &absolute_program(node));
write_unit(&unit)?;
platform_install(&unit)?;
Ok((unit, service_status()))
}
pub fn install_connector_service(
unit: &ServiceUnit,
label: &str,
) -> Result<ServiceState, TeamsError> {
let existing = named_service_status(label);
if unit.path.exists() {
let old = std::fs::read_to_string(&unit.path).map_err(|source| TeamsError::File {
path: unit.path.clone(),
source,
})?;
if old != unit.text {
return Err(TeamsError::Service { action: "install", detail: format!("`{label}` exists with different context or service parameters; disconnect it first") });
}
if existing.installed {
return Ok(existing);
}
} else if existing.installed {
return Err(TeamsError::Service {
action: "install",
detail: format!(
"service manager already owns `{label}` without its expected unit file"
),
});
}
write_unit(unit)?;
named_platform_install(unit, label)?;
Ok(named_service_status(label))
}
pub fn uninstall_connector_service(
teams_home: &Path,
label: &str,
) -> Result<ServiceState, TeamsError> {
named_platform_uninstall(label)?;
let suffix = if cfg!(target_os = "macos") {
"plist"
} else {
"service"
};
let path = teams_home
.join(SERVICE_DIR)
.join(format!("{label}.{suffix}"));
match std::fs::remove_file(&path) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(source) => return Err(TeamsError::File { path, source }),
}
Ok(named_service_status(label))
}
pub fn connector_service_status(label: &str) -> ServiceState {
named_service_status(label)
}
#[cfg(target_os = "macos")]
fn named_service_status(label: &str) -> ServiceState {
let target = format!("{}/{label}", gui_domain());
match run_tool("launchctl", &["print", &target]) {
Ok((true, text)) => ServiceState {
kind: "launchd",
label: label.into(),
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: label.into(),
installed: false,
pid: None,
detail: format!("not bootstrapped in {}", gui_domain()),
},
Err(error) => ServiceState {
kind: "launchd",
label: label.into(),
installed: false,
pid: None,
detail: format!("launchctl unavailable: {error}"),
},
}
}
#[cfg(all(unix, not(target_os = "macos")))]
fn named_service_status(label: &str) -> ServiceState {
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: label.into(),
installed: active || known,
pid: None,
detail: if text.is_empty() {
"unknown".into()
} else {
text
},
}
}
Err(error) => ServiceState {
kind: "systemd",
label: label.into(),
installed: false,
pid: None,
detail: format!("systemctl unavailable: {error}"),
},
}
}
#[cfg(not(unix))]
fn named_service_status(label: &str) -> ServiceState {
ServiceState {
kind: "none",
label: label.into(),
installed: false,
pid: None,
detail: "no service manager on this platform".into(),
}
}
#[cfg(target_os = "macos")]
fn named_platform_install(unit: &ServiceUnit, _label: &str) -> Result<(), TeamsError> {
platform_install(unit)
}
#[cfg(all(unix, not(target_os = "macos")))]
fn named_platform_install(unit: &ServiceUnit, label: &str) -> Result<(), TeamsError> {
let path = unit.path.display().to_string();
for args in [
vec!["--user", "link", path.as_str()],
vec!["--user", "enable", "--now", label],
] {
let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
action: "install",
detail: format!("systemctl: {error}"),
})?;
if !ok {
return Err(TeamsError::Service {
action: "install",
detail: format!("systemctl {}: {text}", args.join(" ")),
});
}
}
Ok(())
}
#[cfg(not(unix))]
fn named_platform_install(_unit: &ServiceUnit, _label: &str) -> Result<(), TeamsError> {
Err(TeamsError::Service {
action: "install",
detail: "no service manager on this platform".into(),
})
}
#[cfg(target_os = "macos")]
fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
let target = format!("{}/{label}", gui_domain());
let (ok, text) =
run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
action: "uninstall",
detail: format!("launchctl: {error}"),
})?;
if !ok && !text.contains("No such process") && !text.contains("not find") {
return Err(TeamsError::Service {
action: "uninstall",
detail: format!("launchctl bootout {target}: {text}"),
});
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
let _ = run_tool("systemctl", &["--user", "disable", "--now", label]);
Ok(())
}
#[cfg(not(unix))]
fn named_platform_uninstall(_label: &str) -> Result<(), TeamsError> {
Ok(())
}
#[cfg(target_os = "macos")]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
let path = unit.path.display().to_string();
let (ok, text) =
run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
TeamsError::Service {
action: "install",
detail: format!("launchctl: {error}"),
}
})?;
if !ok {
return Err(TeamsError::Service {
action: "install",
detail: format!("launchctl bootstrap {}: {text}", gui_domain()),
});
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
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| TeamsError::Service {
action: "install",
detail: format!("systemctl: {error}"),
})?;
if !ok {
return Err(TeamsError::Service {
action: "install",
detail: format!("systemctl {}: {text}", args.join(" ")),
});
}
}
Ok(())
}
#[cfg(not(unix))]
fn platform_install(_unit: &ServiceUnit) -> Result<(), TeamsError> {
Err(TeamsError::Service {
action: "install",
detail: "no service manager on this platform".into(),
})
}
pub fn uninstall_service(home: &Path) -> Result<ServiceState, TeamsError> {
platform_uninstall()?;
let unit_path = home.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(TeamsError::File {
path: unit_path,
source,
})
}
}
let mut state = service_status();
for _ in 0..40 {
if !state.installed {
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
state = service_status();
}
Ok(state)
}
#[cfg(target_os = "macos")]
fn platform_uninstall() -> Result<(), TeamsError> {
let target = format!("{}/{SERVICE_NAME}", gui_domain());
let (ok, text) =
run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
action: "uninstall",
detail: format!("launchctl: {error}"),
})?;
if !ok && !text.contains("No such process") && !text.contains("not find") {
return Err(TeamsError::Service {
action: "uninstall",
detail: format!("launchctl bootout {target}: {text}"),
});
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_uninstall() -> Result<(), TeamsError> {
let _ = run_tool("systemctl", &["--user", "disable", "--now", SERVICE_NAME]);
Ok(())
}
#[cfg(not(unix))]
fn platform_uninstall() -> Result<(), TeamsError> {
Ok(())
}
#[cfg(test)]
mod connector_service_tests {
use super::*;
#[test]
fn connector_unit_is_context_scoped_and_contains_no_credential() {
let unit = connector_service_unit(
Path::new("/tmp/teams home"),
Path::new("/tmp/supercode home"),
Path::new("/tmp/sdk/teams/bin/teams.mjs"),
"/usr/bin/node",
Path::new("/tmp/bin/supercode"),
"work",
Path::new("/tmp/project with spaces"),
"srv_1",
"team_1",
)
.unwrap();
assert!(unit.text.contains("teams"));
assert!(unit.text.contains("connect"));
assert!(unit.text.contains("work"));
assert!(!unit.text.contains("credential"));
assert!(unit
.path
.file_name()
.unwrap()
.to_string_lossy()
.contains(&connector_service_name("srv_1", "team_1", "work")));
}
#[test]
fn connector_labels_separate_context_and_team() {
assert_ne!(
connector_service_name("srv", "team-a", "work"),
connector_service_name("srv", "team-b", "work")
);
assert_ne!(
connector_service_name("srv", "team-a", "work"),
connector_service_name("srv", "team-a", "personal")
);
}
#[test]
fn connector_unit_rejects_newlines_and_escapes_service_syntax() {
let unsafe_unit = connector_service_unit(
Path::new("/tmp/teams"),
Path::new("/tmp/home"),
Path::new("/tmp/entry"),
"/usr/bin/node",
Path::new("/tmp/supercode"),
"bad\ncontext",
Path::new("/tmp/work"),
"srv",
"team",
);
assert!(unsafe_unit.is_err());
let unit = connector_service_unit(
Path::new("/tmp/teams & logs"),
Path::new("/tmp/home $x"),
Path::new("/tmp/entry %i"),
"/usr/bin/node",
Path::new("/tmp/super\"code"),
"work",
Path::new("/tmp/a & b % $"),
"srv",
"team",
)
.unwrap();
if cfg!(target_os = "macos") {
assert!(unit.text.contains("&"));
} else {
assert!(unit.text.contains("%%"));
assert!(unit.text.contains("$$"));
assert!(unit.text.contains("\\\""));
}
}
}