1use std::path::{Path, PathBuf};
23
24use crate::orchestrator::{absolute_program, resolve_program, ServiceState, ServiceUnit};
25
26pub const TEAMS_ENTRY: &str = "bin/teams.mjs";
28
29pub const TEAMS_PACKAGE: &str = "@volter/supercode-teams";
31
32pub const SERVICE_DIR: &str = "service";
34
35pub const SERVICE_NAME: &str = "dev.volter.supercode-teams-machine";
37
38pub fn connector_service_name(server_id: &str, team_id: &str, context: &str) -> String {
40 let mut hash = 0xcbf29ce484222325_u64;
43 for byte in [server_id, team_id, context].join("\0").bytes() {
44 hash ^= u64::from(byte);
45 hash = hash.wrapping_mul(0x100000001b3);
46 }
47 format!("dev.volter.supercode-teams-connector-{hash:016x}")
48}
49
50fn plist_text(value: &str) -> String {
51 value
52 .replace('&', "&")
53 .replace('<', "<")
54 .replace('>', ">")
55}
56
57fn service_text(value: &str) -> Result<&str, TeamsError> {
58 if value.chars().any(char::is_control) {
59 return Err(TeamsError::Service {
60 action: "render",
61 detail: "service parameters cannot contain control characters".into(),
62 });
63 }
64 Ok(value)
65}
66
67fn systemd_arg(value: &str) -> String {
68 format!(
69 "\"{}\"",
70 value
71 .replace('\\', "\\\\")
72 .replace('"', "\\\"")
73 .replace('%', "%%")
74 .replace('$', "$$")
75 )
76}
77
78pub fn connector_service_unit(
80 teams_home: &Path,
81 supercode_home: &Path,
82 entry: &Path,
83 node: &str,
84 supercode: &Path,
85 context: &str,
86 cwd: &Path,
87 server_id: &str,
88 team_id: &str,
89) -> Result<ServiceUnit, TeamsError> {
90 let teams_home_text = teams_home.display().to_string();
91 let supercode_home_text = supercode_home.display().to_string();
92 let entry_text = entry.display().to_string();
93 let supercode_text = supercode.display().to_string();
94 let workspace_text = cwd.display().to_string();
95 for value in [
96 teams_home_text.as_str(),
97 supercode_home_text.as_str(),
98 entry_text.as_str(),
99 node,
100 supercode_text.as_str(),
101 context,
102 workspace_text.as_str(),
103 server_id,
104 team_id,
105 ] {
106 service_text(value)?;
107 }
108 let label = connector_service_name(server_id, team_id, context);
109 let path = teams_home
110 .join(SERVICE_DIR)
111 .join(format!("{label}.{}", connector_unit_suffix()));
112 let node = absolute_program(node);
113 let entry = entry_text;
114 let workspace = workspace_text;
115 let home = supercode_home_text;
116 let supercode = supercode_text;
117 if cfg!(windows) {
118 let log_path = teams_home.join(SERVICE_DIR).join(format!("{label}.log"));
119 return windows_task(
120 &path,
121 &label,
122 &format!("supercode Teams connector ({context})"),
123 &service_env_path(teams_home, &label),
124 &[
125 ("SUPERCODE_HOME", home.as_str()),
126 ("SUPERCODE_BIN", supercode.as_str()),
127 ("SUPERCODE_TEAMS_LOG", &log_path.display().to_string()),
128 ],
129 &node,
130 &[
131 entry.as_str(),
132 "teams",
133 "connect",
134 "--foreground",
135 "--context",
136 context,
137 "--cwd",
138 workspace.as_str(),
139 ],
140 &workspace,
141 );
142 }
143 if cfg!(target_os = "macos") {
144 let node = plist_text(&node);
145 let entry = plist_text(&entry);
146 let workspace = plist_text(&workspace);
147 let home = plist_text(&home);
148 let supercode = plist_text(&supercode);
149 let context = plist_text(context);
150 let search_path = plist_text(&service_path());
151 let text = format!(
156 r#"<?xml version="1.0" encoding="UTF-8"?>
157<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
158<plist version="1.0"><dict>
159 <key>Label</key><string>{label}</string>
160 <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>
161 <key>EnvironmentVariables</key><dict><key>SUPERCODE_HOME</key><string>{home}</string><key>SUPERCODE_BIN</key><string>{supercode}</string><key>PATH</key><string>{search_path}</string></dict>
162 <key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ProcessType</key><string>Interactive</string>
163 <key>StandardOutPath</key><string>{}/service/{label}.out.log</string>
164 <key>StandardErrorPath</key><string>{}/service/{label}.err.log</string>
165</dict></plist>
166"#,
167 plist_text(&teams_home_text),
168 plist_text(&teams_home_text)
169 );
170 Ok(ServiceUnit {
171 kind: "launchd",
172 path: path.clone(),
173 text,
174 install_command: format!("launchctl bootstrap gui/$(id -u) {}", path.display()),
175 files: Vec::new(),
176 })
177 } else {
178 let environment_home = systemd_arg(&format!("SUPERCODE_HOME={home}"));
179 let environment_bin = systemd_arg(&format!("SUPERCODE_BIN={supercode}"));
180 let environment_path = systemd_arg(&format!("PATH={}", service_path()));
181 let node = systemd_arg(&node);
182 let entry = systemd_arg(&entry);
183 let workspace = systemd_arg(&workspace);
184 let context_description = context.replace('%', "%%").replace('$', "$$");
185 let context = systemd_arg(context);
186 let text = format!("[Unit]\nDescription=supercode Teams connector ({context_description})\nAfter=network.target\n\n[Service]\nEnvironment={environment_home}\nEnvironment={environment_bin}\nEnvironment={environment_path}\nExecStart={node} {entry} teams connect --context {context} --cwd {workspace}\nRestart=on-failure\nKillSignal=SIGTERM\nKillMode=process\n\n[Install]\nWantedBy=default.target\n");
189 Ok(ServiceUnit {
190 kind: "systemd",
191 path: path.clone(),
192 text,
193 install_command: format!(
194 "systemctl --user link {} && systemctl --user enable --now {label}",
195 path.display()
196 ),
197 files: Vec::new(),
198 })
199 }
200}
201
202fn connector_unit_suffix() -> &'static str {
204 if cfg!(windows) {
205 "xml"
206 } else if cfg!(target_os = "macos") {
207 "plist"
208 } else {
209 "service"
210 }
211}
212
213fn service_env_path(teams_home: &Path, label: &str) -> PathBuf {
215 teams_home.join(SERVICE_DIR).join(format!("{label}.env"))
216}
217
218#[allow(clippy::too_many_arguments)]
221fn windows_task(
222 path: &Path,
223 label: &str,
224 description: &str,
225 env_path: &Path,
226 env: &[(&str, &str)],
227 node: &str,
228 node_args: &[&str],
229 working_directory: &str,
230) -> Result<ServiceUnit, TeamsError> {
231 let env_text = env
237 .iter()
238 .map(|(key, value)| env_file_value(value).map(|value| format!("{key}={value}\n")))
239 .collect::<Result<String, _>>()?;
240 let env_flag = format!("--env-file={}", env_path.display());
241 let mut arguments = vec![node, env_flag.as_str()];
242 arguments.extend_from_slice(node_args);
243 for value in arguments.iter().chain([&working_directory]) {
245 if value.contains('%') {
246 return Err(TeamsError::Service {
247 action: "render",
248 detail: format!("a Windows task cannot carry a path containing `%`: {value}"),
249 });
250 }
251 }
252 let arguments = arguments
253 .iter()
254 .map(|argument| windows_arg(argument))
255 .collect::<Vec<_>>()
256 .join(" ");
257 let user = windows_user();
258 let conhost = Path::new(&std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()))
259 .join(r"System32\conhost.exe")
260 .display()
261 .to_string();
262 let text = format!(
265 r#"<?xml version="1.0" encoding="UTF-16"?>
266<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
267 <RegistrationInfo><Description>{}</Description></RegistrationInfo>
268 <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>{}</UserId></LogonTrigger><TimeTrigger><StartBoundary>2000-01-01T00:00:00</StartBoundary><Enabled>true</Enabled><Repetition><Interval>PT1M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger></Triggers>
269 <Principals><Principal id="Author"><UserId>{}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
270 <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority><RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure><StartWhenAvailable>true</StartWhenAvailable></Settings>
271 <Actions Context="Author"><Exec><Command>{}</Command><Arguments>--headless {}</Arguments><WorkingDirectory>{}</WorkingDirectory></Exec></Actions>
272</Task>
273"#,
274 xml_text(description),
275 xml_text(&user),
276 xml_text(&user),
277 xml_text(&conhost),
278 xml_text(&arguments),
279 xml_text(working_directory),
280 );
281 Ok(ServiceUnit {
282 kind: "schtasks",
283 path: path.to_path_buf(),
284 text,
285 install_command: format!("schtasks /Create /TN {label} /XML {} /F", path.display()),
286 files: vec![(env_path.to_path_buf(), env_text)],
287 })
288}
289
290fn xml_text(value: &str) -> String {
292 plist_text(value).replace('"', """)
293}
294
295fn windows_arg(value: &str) -> String {
298 if !value.is_empty() && !value.contains([' ', '\t', '"']) {
299 return value.to_string();
300 }
301 let mut quoted = String::from("\"");
302 let mut backslashes = 0;
303 for character in value.chars() {
304 match character {
305 '\\' => backslashes += 1,
306 '"' => {
307 quoted.push_str(&"\\".repeat(backslashes * 2 + 1));
308 quoted.push('"');
309 backslashes = 0;
310 }
311 other => {
312 quoted.push_str(&"\\".repeat(backslashes));
313 quoted.push(other);
314 backslashes = 0;
315 }
316 }
317 }
318 quoted.push_str(&"\\".repeat(backslashes * 2));
319 quoted.push('"');
320 quoted
321}
322
323fn env_file_value(value: &str) -> Result<String, TeamsError> {
326 ['\'', '`']
327 .into_iter()
328 .find(|quote| !value.contains(*quote))
329 .map(|quote| format!("{quote}{value}{quote}"))
330 .or_else(|| (!value.contains(['"', '\\'])).then(|| format!("\"{value}\"")))
331 .ok_or_else(|| TeamsError::Service {
332 action: "render",
333 detail: format!("cannot write `{value}` into a service's environment file"),
334 })
335}
336
337fn windows_user() -> String {
339 let user = std::env::var("USERNAME").unwrap_or_default();
340 match std::env::var("USERDOMAIN") {
341 Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
342 _ => user,
343 }
344}
345
346pub fn connector_service_binary(
352 teams_home: &Path,
353 supercode: &Path,
354) -> Result<PathBuf, TeamsError> {
355 if !cfg!(windows) {
356 return Ok(supercode.to_path_buf());
357 }
358 let file = |path: &Path, source: std::io::Error| TeamsError::File {
359 path: path.to_path_buf(),
360 source,
361 };
362 let copies = teams_home.join(SERVICE_DIR).join("bin");
363 let version = env!("CARGO_PKG_VERSION");
364 let dir = copies.join(version);
365 let copy = dir.join(
366 supercode
367 .file_name()
368 .unwrap_or_else(|| "supercode.exe".as_ref()),
369 );
370 let size = |path: &Path| std::fs::metadata(path).map(|meta| meta.len()).ok();
371 if size(©).is_none() || size(©) != size(supercode) {
372 std::fs::create_dir_all(&dir).map_err(|source| file(&dir, source))?;
373 std::fs::copy(supercode, ©).map_err(|source| file(©, source))?;
374 }
375 if let Ok(entries) = std::fs::read_dir(&copies) {
376 for entry in entries.flatten() {
377 if entry.file_name() != version {
378 let _ = std::fs::remove_dir_all(entry.path());
379 }
380 }
381 }
382 Ok(copy)
383}
384
385#[derive(Debug, thiserror::Error)]
387pub enum TeamsError {
388 #[error("no teams entry found (looked for `sdk/teams/{TEAMS_ENTRY}` under: {searched}); install it with `npm install -g {TEAMS_PACKAGE}`")]
390 NoEntry {
391 searched: String,
393 },
394 #[error("teams service: {action} failed: {detail}")]
396 Service {
397 action: &'static str,
399 detail: String,
401 },
402 #[error("teams file `{}`: {source}", path.display())]
404 File {
405 path: PathBuf,
407 source: std::io::Error,
409 },
410}
411
412fn service_path() -> String {
416 std::env::var("PATH")
417 .ok()
418 .filter(|path| !path.trim().is_empty())
419 .unwrap_or_else(|| "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin".into())
420}
421
422pub fn teams_home() -> PathBuf {
427 if let Ok(home) = std::env::var("SUPERCODE_TEAMS_HOME") {
428 if !home.is_empty() {
429 return PathBuf::from(home);
430 }
431 }
432 crate::agent::global_instructions_dir().join("teams")
433}
434
435pub fn teams_entry() -> Result<PathBuf, TeamsError> {
445 let mut searched = Vec::new();
446 if let Some(explicit) = std::env::var_os("SUPERCODE_TEAMS_ENTRY") {
447 let path = PathBuf::from(explicit);
448 if path.is_file() {
449 return Ok(path);
450 }
451 searched.push(path.display().to_string());
452 }
453 let mut roots: Vec<PathBuf> = Vec::new();
454 if let Ok(exe) = std::env::current_exe() {
455 roots.extend(exe.ancestors().skip(1).take(4).map(Path::to_path_buf));
457 }
458 if let Some(workspace) = Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2) {
463 roots.push(workspace.to_path_buf());
464 }
465 for root in roots {
466 let candidate = root.join("sdk/teams").join(TEAMS_ENTRY);
467 if candidate.is_file() {
468 return Ok(candidate);
469 }
470 searched.push(candidate.display().to_string());
471 }
472 if let Ok(exe) = std::env::current_exe() {
477 for modules in exe
478 .ancestors()
479 .filter(|dir| dir.file_name().is_some_and(|name| name == "node_modules"))
480 {
481 let candidate = modules.join(TEAMS_PACKAGE).join(TEAMS_ENTRY);
482 if candidate.is_file() {
483 return Ok(candidate);
484 }
485 searched.push(candidate.display().to_string());
486 }
487 }
488 if let Some(global) = global_npm_root() {
489 let candidate = global.join(TEAMS_PACKAGE).join(TEAMS_ENTRY);
490 if candidate.is_file() {
491 return Ok(candidate);
492 }
493 searched.push(candidate.display().to_string());
494 }
495 Err(TeamsError::NoEntry {
496 searched: searched.join(", "),
497 })
498}
499
500fn global_npm_root() -> Option<PathBuf> {
502 let output = std::process::Command::new(resolve_program("npm"))
503 .args(["root", "-g"])
504 .stdin(std::process::Stdio::null())
505 .stderr(std::process::Stdio::null())
506 .output()
507 .ok()?;
508 if !output.status.success() {
509 return None;
510 }
511 let text = String::from_utf8_lossy(&output.stdout);
512 let root = text.trim();
513 if root.is_empty() {
514 return None;
515 }
516 Some(PathBuf::from(root))
517}
518
519pub fn service_unit(home: &Path, entry: &Path, node: &str) -> Result<ServiceUnit, TeamsError> {
528 let home_display = home.display().to_string();
529 let entry_display = entry.display().to_string();
530 for value in [home_display.as_str(), entry_display.as_str(), node] {
532 service_text(value)?;
533 }
534 if cfg!(windows) {
535 let log_path = home.join(SERVICE_DIR).join(format!("{SERVICE_NAME}.log"));
536 return windows_task(
537 &home.join(SERVICE_DIR).join(unit_file_name()),
538 SERVICE_NAME,
539 &format!("supercode teams machine daemon ({home_display})"),
540 &service_env_path(home, SERVICE_NAME),
541 &[
542 ("SUPERCODE_TEAMS_HOME", home_display.as_str()),
543 ("SUPERCODE_TEAMS_LOG", &log_path.display().to_string()),
544 ],
545 node,
546 &[entry_display.as_str(), "machine", "start"],
547 &home_display,
548 );
549 }
550 if cfg!(target_os = "macos") {
551 let path = home.join(SERVICE_DIR).join(format!("{SERVICE_NAME}.plist"));
552 let text = format!(
553 r#"<?xml version="1.0" encoding="UTF-8"?>
554<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
555<plist version="1.0">
556<dict>
557 <key>Label</key><string>{SERVICE_NAME}</string>
558 <key>ProgramArguments</key>
559 <array>
560 <string>{node}</string>
561 <string>{entry_display}</string>
562 <string>machine</string>
563 <string>start</string>
564 </array>
565 <key>EnvironmentVariables</key>
566 <dict>
567 <key>SUPERCODE_TEAMS_HOME</key><string>{home_display}</string>
568 </dict>
569 <key>RunAtLoad</key><true/>
570 <key>KeepAlive</key><true/>
571 <key>ProcessType</key><string>Interactive</string>
572 <key>StandardOutPath</key><string>{home_display}/service/teams-machine.out.log</string>
573 <key>StandardErrorPath</key><string>{home_display}/service/teams-machine.err.log</string>
574</dict>
575</plist>
576"#
577 );
578 let install = format!("launchctl bootstrap gui/$(id -u) {}", path.display());
579 Ok(ServiceUnit {
580 kind: "launchd",
581 path,
582 text,
583 install_command: install,
584 files: Vec::new(),
585 })
586 } else {
587 let path = home
588 .join(SERVICE_DIR)
589 .join(format!("{SERVICE_NAME}.service"));
590 let text = format!(
591 "[Unit]\n\
592 Description=supercode teams machine daemon ({home_display})\n\
593 After=network.target\n\
594 \n\
595 [Service]\n\
596 Environment=SUPERCODE_TEAMS_HOME={home_display}\n\
597 ExecStart={node} {entry_display} machine start\n\
598 Restart=on-failure\n\
599 KillSignal=SIGTERM\n\
600 KillMode=process\n\
601 \n\
602 [Install]\n\
603 WantedBy=default.target\n"
604 );
605 let install = format!(
606 "systemctl --user link {} && systemctl --user enable --now {SERVICE_NAME}",
607 path.display()
608 );
609 Ok(ServiceUnit {
610 kind: "systemd",
611 path,
612 text,
613 install_command: install,
614 files: Vec::new(),
615 })
616 }
617}
618
619pub fn write_unit(unit: &ServiceUnit) -> Result<(), TeamsError> {
621 if let Some(parent) = unit.path.parent() {
622 std::fs::create_dir_all(parent).map_err(|source| TeamsError::File {
623 path: unit.path.clone(),
624 source,
625 })?;
626 }
627 std::fs::write(&unit.path, &unit.text).map_err(|source| TeamsError::File {
628 path: unit.path.clone(),
629 source,
630 })?;
631 for (path, text) in &unit.files {
632 std::fs::write(path, text).map_err(|source| TeamsError::File {
633 path: path.clone(),
634 source,
635 })?;
636 }
637 Ok(())
638}
639
640fn run_tool(program: &str, args: &[&str]) -> Result<(bool, String), std::io::Error> {
642 let output = std::process::Command::new(program).args(args).output()?;
643 let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
644 text.push_str(&String::from_utf8_lossy(&output.stderr));
645 Ok((output.status.success(), text.trim().to_string()))
646}
647
648#[cfg(target_os = "macos")]
649fn gui_domain() -> String {
650 format!("gui/{}", unsafe { libc::getuid() })
652}
653
654pub fn service_status() -> ServiceState {
658 platform_status()
659}
660
661#[cfg(target_os = "macos")]
662fn platform_status() -> ServiceState {
663 let label = SERVICE_NAME.to_string();
664 let target = format!("{}/{SERVICE_NAME}", gui_domain());
665 match run_tool("launchctl", &["print", &target]) {
666 Ok((true, text)) => ServiceState {
667 kind: "launchd",
668 label,
669 installed: true,
670 pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
671 detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
672 },
673 Ok((false, _)) => ServiceState {
674 kind: "launchd",
675 label,
676 installed: false,
677 pid: None,
678 detail: format!("not bootstrapped in {}", gui_domain()),
679 },
680 Err(error) => ServiceState {
681 kind: "launchd",
682 label,
683 installed: false,
684 pid: None,
685 detail: format!("launchctl unavailable: {error}"),
686 },
687 }
688}
689
690#[cfg(all(unix, not(target_os = "macos")))]
691fn platform_status() -> ServiceState {
692 let label = SERVICE_NAME.to_string();
693 match run_tool("systemctl", &["--user", "is-active", SERVICE_NAME]) {
694 Ok((active, text)) => {
695 let known = run_tool("systemctl", &["--user", "is-enabled", SERVICE_NAME])
696 .map(|(ok, _)| ok)
697 .unwrap_or(false);
698 ServiceState {
699 kind: "systemd",
700 label,
701 installed: active || known,
702 pid: None,
703 detail: if text.is_empty() {
704 "unknown".into()
705 } else {
706 text
707 },
708 }
709 }
710 Err(error) => ServiceState {
711 kind: "systemd",
712 label,
713 installed: false,
714 pid: None,
715 detail: format!("systemctl unavailable: {error}"),
716 },
717 }
718}
719
720#[cfg(not(unix))]
721fn platform_status() -> ServiceState {
722 named_service_status(SERVICE_NAME)
723}
724
725#[cfg(target_os = "macos")]
727fn field_of(text: &str, key: &str) -> Option<String> {
728 text.lines()
729 .find_map(|line| line.trim().strip_prefix(key))
730 .map(|value| value.trim().to_string())
731}
732
733fn unit_file_name() -> String {
735 if cfg!(windows) {
736 format!("{SERVICE_NAME}.xml")
737 } else if cfg!(target_os = "macos") {
738 format!("{SERVICE_NAME}.plist")
739 } else {
740 format!("{SERVICE_NAME}.service")
741 }
742}
743
744pub fn install_service(
750 home: &Path,
751 entry: &Path,
752 node: &str,
753) -> Result<(ServiceUnit, ServiceState), TeamsError> {
754 let existing = service_status();
755 if existing.installed {
756 return Err(TeamsError::Service {
757 action: "install",
758 detail: format!(
759 "`{}` is already installed ({}); `supercode teams machine uninstall` first",
760 existing.label, existing.detail
761 ),
762 });
763 }
764 let unit = service_unit(home, entry, &absolute_program(node))?;
765 write_unit(&unit)?;
766 platform_install(&unit)?;
767 Ok((unit, service_status()))
768}
769
770pub fn install_connector_service(
776 unit: &ServiceUnit,
777 label: &str,
778) -> Result<ServiceState, TeamsError> {
779 let existing = named_service_status(label);
780 if unit.path.exists() {
781 let old = std::fs::read_to_string(&unit.path).map_err(|source| TeamsError::File {
782 path: unit.path.clone(),
783 source,
784 })?;
785 let same = old == unit.text
787 && unit
788 .files
789 .iter()
790 .all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|old| &old == text));
791 if same && existing.installed {
792 return Ok(existing);
793 }
794 if !same && existing.installed {
795 named_platform_uninstall(label)?;
796 }
797 } else if existing.installed {
798 return Err(TeamsError::Service {
799 action: "install",
800 detail: format!(
801 "service manager already owns `{label}` without its expected unit file"
802 ),
803 });
804 }
805 write_unit(unit)?;
806 named_platform_install(unit, label)?;
807 Ok(named_service_status(label))
808}
809
810pub fn register_message_tools(supercode: &Path) -> Vec<String> {
818 let program = supercode.display().to_string();
819 let mut report = Vec::new();
820 for (harness, get, remove, add) in [
821 (
822 "claude",
823 vec!["mcp", "get", "supercode"],
824 vec!["mcp", "remove", "--scope", "user", "supercode"],
825 vec![
826 "mcp",
827 "add",
828 "--scope",
829 "user",
830 "supercode",
831 "--",
832 &program,
833 "message",
834 "mcp",
835 ],
836 ),
837 (
838 "codex",
839 vec!["mcp", "get", "supercode"],
840 vec!["mcp", "remove", "supercode"],
841 vec!["mcp", "add", "supercode", "--", &program, "message", "mcp"],
842 ),
843 ] {
844 let run = |args: &[&str]| {
845 std::process::Command::new(resolve_program(harness))
846 .args(args)
847 .stdin(std::process::Stdio::null())
848 .output()
849 };
850 let names_program = |text: &str| {
852 if cfg!(windows) {
853 text.to_lowercase().contains(&program.to_lowercase())
854 } else {
855 text.contains(&program)
856 }
857 };
858 let replaced = match run(&get) {
859 Err(_) => {
860 report.push(format!("{harness}: not installed"));
861 continue;
862 }
863 Ok(found)
864 if found.status.success()
865 && names_program(&String::from_utf8_lossy(&found.stdout)) =>
866 {
867 report.push(format!("{harness}: already has supercode's tools"));
868 continue;
869 }
870 Ok(found) if found.status.success() => {
871 let _ = run(&remove);
872 true
873 }
874 Ok(_) => false,
875 };
876 match run(&add) {
877 Ok(added) if added.status.success() => report.push(if replaced {
878 format!("{harness}: supercode's tools now run {program} (new sessions load them)")
879 } else {
880 format!("{harness}: supercode's tools added (new sessions load them)")
881 }),
882 Ok(added) => report.push(format!(
883 "{harness}: could not add supercode's tools: {}",
884 String::from_utf8_lossy(&added.stderr).trim()
885 )),
886 Err(error) => report.push(format!(
887 "{harness}: could not add supercode's tools: {error}"
888 )),
889 }
890 }
891 report
892}
893
894pub fn uninstall_connector_service(
896 teams_home: &Path,
897 label: &str,
898) -> Result<ServiceState, TeamsError> {
899 named_platform_uninstall(label)?;
900 let unit = teams_home
901 .join(SERVICE_DIR)
902 .join(format!("{label}.{}", connector_unit_suffix()));
903 for path in [unit, service_env_path(teams_home, label)] {
904 match std::fs::remove_file(&path) {
905 Ok(()) => {}
906 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
907 Err(source) => return Err(TeamsError::File { path, source }),
908 }
909 }
910 Ok(named_service_status(label))
911}
912
913pub fn connector_service_status(label: &str) -> ServiceState {
915 named_service_status(label)
916}
917
918pub fn service_owns_daemon() -> bool {
923 if service_status().installed {
924 return true;
925 }
926 let Ok(entries) = std::fs::read_dir(teams_home().join(SERVICE_DIR)) else {
927 return false;
928 };
929 entries.flatten().any(|entry| {
930 let name = entry.file_name().to_string_lossy().into_owned();
931 let label = name
932 .strip_suffix(".plist")
933 .or_else(|| name.strip_suffix(".service"))
934 .unwrap_or(&name);
935 label.starts_with("dev.volter.supercode-teams-connector-")
936 && (name.ends_with(".plist") || name.ends_with(".service"))
937 && connector_service_status(label).installed
938 })
939}
940
941#[cfg(target_os = "macos")]
942fn named_service_status(label: &str) -> ServiceState {
943 let target = format!("{}/{label}", gui_domain());
944 match run_tool("launchctl", &["print", &target]) {
945 Ok((true, text)) => ServiceState {
946 kind: "launchd",
947 label: label.into(),
948 installed: true,
949 pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
950 detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
951 },
952 Ok((false, _)) => ServiceState {
953 kind: "launchd",
954 label: label.into(),
955 installed: false,
956 pid: None,
957 detail: format!("not bootstrapped in {}", gui_domain()),
958 },
959 Err(error) => ServiceState {
960 kind: "launchd",
961 label: label.into(),
962 installed: false,
963 pid: None,
964 detail: format!("launchctl unavailable: {error}"),
965 },
966 }
967}
968
969#[cfg(all(unix, not(target_os = "macos")))]
970fn named_service_status(label: &str) -> ServiceState {
971 match run_tool("systemctl", &["--user", "is-active", label]) {
972 Ok((active, text)) => {
973 let known = run_tool("systemctl", &["--user", "is-enabled", label])
974 .map(|(ok, _)| ok)
975 .unwrap_or(false);
976 ServiceState {
977 kind: "systemd",
978 label: label.into(),
979 installed: active || known,
980 pid: None,
981 detail: if text.is_empty() {
982 "unknown".into()
983 } else {
984 text
985 },
986 }
987 }
988 Err(error) => ServiceState {
989 kind: "systemd",
990 label: label.into(),
991 installed: false,
992 pid: None,
993 detail: format!("systemctl unavailable: {error}"),
994 },
995 }
996}
997
998#[cfg(not(unix))]
999fn named_service_status(label: &str) -> ServiceState {
1000 match run_tool("schtasks", &["/Query", "/TN", label, "/FO", "CSV", "/NH"]) {
1001 Ok((true, text)) => ServiceState {
1003 kind: "schtasks",
1004 label: label.into(),
1005 installed: true,
1006 pid: None,
1007 detail: text
1008 .lines()
1009 .next()
1010 .and_then(|line| line.rsplit(',').next())
1011 .map(|state| state.trim_matches('"').to_string())
1012 .filter(|state| !state.is_empty())
1013 .unwrap_or_else(|| "registered".into()),
1014 },
1015 Ok((false, _)) => ServiceState {
1016 kind: "schtasks",
1017 label: label.into(),
1018 installed: false,
1019 pid: None,
1020 detail: "no scheduled task".into(),
1021 },
1022 Err(error) => ServiceState {
1023 kind: "schtasks",
1024 label: label.into(),
1025 installed: false,
1026 pid: None,
1027 detail: format!("schtasks unavailable: {error}"),
1028 },
1029 }
1030}
1031
1032#[cfg(target_os = "macos")]
1033fn named_platform_install(unit: &ServiceUnit, _label: &str) -> Result<(), TeamsError> {
1034 platform_install(unit)
1035}
1036#[cfg(all(unix, not(target_os = "macos")))]
1037fn named_platform_install(unit: &ServiceUnit, label: &str) -> Result<(), TeamsError> {
1038 let path = unit.path.display().to_string();
1039 for args in [
1040 vec!["--user", "link", path.as_str()],
1041 vec!["--user", "enable", "--now", label],
1042 ] {
1043 let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
1044 action: "install",
1045 detail: format!("systemctl: {error}"),
1046 })?;
1047 if !ok {
1048 return Err(TeamsError::Service {
1049 action: "install",
1050 detail: format!("systemctl {}: {text}", args.join(" ")),
1051 });
1052 }
1053 }
1054 Ok(())
1055}
1056#[cfg(not(unix))]
1057fn named_platform_install(unit: &ServiceUnit, label: &str) -> Result<(), TeamsError> {
1058 let task = unit.path.with_extension("utf16.xml");
1060 let bytes: Vec<u8> = [0xFF, 0xFE]
1061 .into_iter()
1062 .chain(unit.text.encode_utf16().flat_map(u16::to_le_bytes))
1063 .collect();
1064 std::fs::write(&task, bytes).map_err(|source| TeamsError::File {
1065 path: task.clone(),
1066 source,
1067 })?;
1068 let task_path = task.display().to_string();
1069 let created = run_tool(
1070 "schtasks",
1071 &["/Create", "/TN", label, "/XML", task_path.as_str(), "/F"],
1072 )
1073 .map_err(|error| TeamsError::Service {
1074 action: "install",
1075 detail: format!("schtasks: {error}"),
1076 })
1077 .and_then(|(ok, text)| {
1078 if ok {
1079 Ok(())
1080 } else {
1081 Err(TeamsError::Service {
1082 action: "install",
1083 detail: format!("schtasks /Create: {text}"),
1084 })
1085 }
1086 });
1087 if let Err(error) = created {
1088 let _ = std::fs::remove_file(&task);
1089 return Err(error);
1090 }
1091 let _ = run_tool("schtasks", &["/End", "/TN", label]);
1096 let result = [vec!["/Run", "/TN", label]].iter().try_for_each(|args| {
1097 let (ok, text) = run_tool("schtasks", args).map_err(|error| TeamsError::Service {
1098 action: "install",
1099 detail: format!("schtasks: {error}"),
1100 })?;
1101 if ok {
1102 Ok(())
1103 } else {
1104 Err(TeamsError::Service {
1105 action: "install",
1106 detail: format!("schtasks {}: {text}", args[0]),
1107 })
1108 }
1109 });
1110 let _ = std::fs::remove_file(&task);
1111 result
1112}
1113
1114#[cfg(target_os = "macos")]
1115fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
1116 let target = format!("{}/{label}", gui_domain());
1117 let (ok, text) =
1118 run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
1119 action: "uninstall",
1120 detail: format!("launchctl: {error}"),
1121 })?;
1122 if !ok && !text.contains("No such process") && !text.contains("not find") {
1123 return Err(TeamsError::Service {
1124 action: "uninstall",
1125 detail: format!("launchctl bootout {target}: {text}"),
1126 });
1127 }
1128 for _ in 0..50 {
1131 if !named_service_status(label).installed {
1132 break;
1133 }
1134 std::thread::sleep(std::time::Duration::from_millis(100));
1135 }
1136 Ok(())
1137}
1138#[cfg(all(unix, not(target_os = "macos")))]
1139fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
1140 let _ = run_tool("systemctl", &["--user", "disable", "--now", label]);
1141 Ok(())
1142}
1143#[cfg(not(unix))]
1144fn named_platform_uninstall(label: &str) -> Result<(), TeamsError> {
1145 let (ok, text) = run_tool("schtasks", &["/Delete", "/TN", label, "/F"]).map_err(|error| {
1147 TeamsError::Service {
1148 action: "uninstall",
1149 detail: format!("schtasks: {error}"),
1150 }
1151 })?;
1152 if !ok && named_service_status(label).installed {
1153 return Err(TeamsError::Service {
1154 action: "uninstall",
1155 detail: format!("schtasks /Delete: {text}"),
1156 });
1157 }
1158 let env_path = service_env_path(&teams_home(), label);
1162 let stopped = std::process::Command::new("powershell.exe")
1163 .args([
1164 "-NoProfile",
1165 "-NonInteractive",
1166 "-Command",
1167 "Get-CimInstance Win32_Process -Filter \"Name='node.exe' OR Name='conhost.exe'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SUPERCODE_SERVICE_ENV_FILE) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }",
1168 ])
1169 .env("SUPERCODE_SERVICE_ENV_FILE", env_path.display().to_string())
1170 .stdin(std::process::Stdio::null())
1171 .output();
1172 match stopped {
1173 Ok(output) if output.status.success() => Ok(()),
1174 Ok(output) => Err(TeamsError::Service {
1175 action: "uninstall",
1176 detail: format!(
1177 "the task is gone, but what it started may still run: {}",
1178 String::from_utf8_lossy(&output.stderr).trim()
1179 ),
1180 }),
1181 Err(error) => Err(TeamsError::Service {
1182 action: "uninstall",
1183 detail: format!(
1184 "the task is gone, but what it started may still run: powershell: {error}"
1185 ),
1186 }),
1187 }
1188}
1189
1190#[cfg(target_os = "macos")]
1191fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
1192 let path = unit.path.display().to_string();
1193 let (ok, text) =
1194 run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
1195 TeamsError::Service {
1196 action: "install",
1197 detail: format!("launchctl: {error}"),
1198 }
1199 })?;
1200 if !ok {
1201 return Err(TeamsError::Service {
1202 action: "install",
1203 detail: format!("launchctl bootstrap {}: {text}", gui_domain()),
1204 });
1205 }
1206 Ok(())
1207}
1208
1209#[cfg(all(unix, not(target_os = "macos")))]
1212fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
1213 let path = unit.path.display().to_string();
1214 for args in [
1215 vec!["--user", "link", path.as_str()],
1216 vec!["--user", "enable", "--now", SERVICE_NAME],
1217 ] {
1218 let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
1219 action: "install",
1220 detail: format!("systemctl: {error}"),
1221 })?;
1222 if !ok {
1223 return Err(TeamsError::Service {
1224 action: "install",
1225 detail: format!("systemctl {}: {text}", args.join(" ")),
1226 });
1227 }
1228 }
1229 Ok(())
1230}
1231
1232#[cfg(not(unix))]
1233fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
1234 named_platform_install(unit, SERVICE_NAME)
1235}
1236
1237pub fn uninstall_service(home: &Path) -> Result<ServiceState, TeamsError> {
1242 platform_uninstall()?;
1243 let unit_path = home.join(SERVICE_DIR).join(unit_file_name());
1244 for path in [unit_path, service_env_path(home, SERVICE_NAME)] {
1246 match std::fs::remove_file(&path) {
1247 Ok(()) => {}
1248 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1249 Err(source) => return Err(TeamsError::File { path, source }),
1250 }
1251 }
1252 let mut state = service_status();
1255 for _ in 0..40 {
1256 if !state.installed {
1257 break;
1258 }
1259 std::thread::sleep(std::time::Duration::from_millis(100));
1260 state = service_status();
1261 }
1262 Ok(state)
1263}
1264
1265#[cfg(target_os = "macos")]
1266fn platform_uninstall() -> Result<(), TeamsError> {
1267 let target = format!("{}/{SERVICE_NAME}", gui_domain());
1268 let (ok, text) =
1269 run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
1270 action: "uninstall",
1271 detail: format!("launchctl: {error}"),
1272 })?;
1273 if !ok && !text.contains("No such process") && !text.contains("not find") {
1275 return Err(TeamsError::Service {
1276 action: "uninstall",
1277 detail: format!("launchctl bootout {target}: {text}"),
1278 });
1279 }
1280 Ok(())
1281}
1282
1283#[cfg(all(unix, not(target_os = "macos")))]
1284fn platform_uninstall() -> Result<(), TeamsError> {
1285 let _ = run_tool("systemctl", &["--user", "disable", "--now", SERVICE_NAME]);
1286 Ok(())
1287}
1288
1289#[cfg(not(unix))]
1290fn platform_uninstall() -> Result<(), TeamsError> {
1291 named_platform_uninstall(SERVICE_NAME)
1292}