Skip to content

Self-improving AI Employees for everyone

feat(machina): Phase D.2 -- migrate `daemon:*` (NSSM / systemd / launchd)

trohitgb8d13fe5ec7e
diff --git a/machina/cli.py b/machina/cli.py
index 771de8e3..72321e81 100644
--- a/machina/cli.py
+++ b/machina/cli.py
@@ -10,6 +10,7 @@ import typer
from machina.commands.build import build_command
from machina.commands.clean import clean_command
+from machina.commands.daemon import app as daemon_app
from machina.commands.dev import dev_command
from machina.commands.docs import app as docs_app
from machina.commands.start import start_command
@@ -47,6 +48,7 @@ app.command("build", help="Install toolchain + build client + sync Python + veri
)
app.add_typer(version_app, name="version")
app.add_typer(docs_app, name="docs")
+app.add_typer(daemon_app, name="daemon")
if __name__ == "__main__":
diff --git a/machina/commands/daemon.py b/machina/commands/daemon.py
new file mode 100644
index 00000000..a09b4e54
--- /dev/null
+++ b/machina/commands/daemon.py
@@ -0,0 +1,435 @@
+"""``machina daemon`` -- replaces ``scripts/daemon.js``.
+
+Cross-platform service installer:
+- Windows -> NSSM
+- Linux -> systemd
+- macOS -> launchd
+
+Each verb (install / uninstall / status / start / stop / restart)
+dispatches to the appropriate platform implementation. The daemon
+runs ``uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning``
+out of ``server/.venv/`` regardless of platform; the only thing that
+varies is HOW the OS supervises the resulting process.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import typer
+from dotenv import dotenv_values
+
+from machina.colors import console
+from machina.platform_ import IS_MACOS, IS_WINDOWS, project_root
+
+
+SERVICE_NAME = "MachinaOs"
+PLIST_LABEL = "com.machina.backend"
+
+
+app = typer.Typer(
+ name="daemon",
+ help="Install/manage MachinaOS as a system service.",
+ no_args_is_help=True,
+ add_completion=False,
+)
+
+
+# ---------------------------------------------------------------- helpers
+
+def _install_dir(override: str | None) -> Path:
+ return Path(override).resolve() if override else project_root()
+
+
+def _venv_python(install_dir: Path) -> Path:
+ if IS_WINDOWS:
+ return install_dir / "server" / ".venv" / "Scripts" / "python.exe"
+ return install_dir / "server" / ".venv" / "bin" / "python"
+
+
+def _server_dir(install_dir: Path) -> Path:
+ return install_dir / "server"
+
+
+def _logs_dir(install_dir: Path) -> Path:
+ return install_dir / "logs"
+
+
+def _ensure_built(install_dir: Path) -> None:
+ py = _venv_python(install_dir)
+ if not py.exists():
+ console.print(f"[red]Python venv not found at {py}[/]")
+ console.print('Run "machina build" first.')
+ raise typer.Exit(code=1)
+
+
+def _run(argv: list[str], *, ignore_error: bool = False) -> int:
+ """Inherit-stdio run; honours ``ignore_error`` like the JS version."""
+ proc = subprocess.run(argv)
+ if proc.returncode != 0 and not ignore_error:
+ console.print(f"[red]Command failed:[/] {' '.join(argv)}")
+ raise typer.Exit(code=proc.returncode)
+ return proc.returncode
+
+
+def _has(cmd: str) -> bool:
+ return shutil.which(cmd) is not None
+
+
+# ============================================================== Windows
+
+def _nssm_check() -> None:
+ if not _has("nssm"):
+ console.print("[red]NSSM not found. Install from https://nssm.cc/[/]")
+ console.print("Or use: winget install nssm")
+ raise typer.Exit(code=1)
+
+
+def _windows_install(install_dir: Path) -> None:
+ _nssm_check()
+ _ensure_built(install_dir)
+
+ py = _venv_python(install_dir)
+ server = _server_dir(install_dir)
+ logs = _logs_dir(install_dir)
+ logs.mkdir(parents=True, exist_ok=True)
+
+ console.print(f"Installing {SERVICE_NAME} service...")
+ console.print(f" Directory: {install_dir}")
+ console.print(f" Python: {py}")
+
+ # Remove any pre-existing service quietly first.
+ _run(["nssm", "stop", SERVICE_NAME], ignore_error=True)
+ _run(["nssm", "remove", SERVICE_NAME, "confirm"], ignore_error=True)
+
+ _run([
+ "nssm", "install", SERVICE_NAME, str(py),
+ "-m", "uvicorn", "main:app",
+ "--host", "0.0.0.0", "--port", "3010", "--log-level", "warning",
+ ])
+ _run(["nssm", "set", SERVICE_NAME, "AppDirectory", str(server)])
+
+ # Load .env vars + the standard PYTHON* knobs.
+ env_pairs = [f"PYTHONPATH={server}", "PYTHONUTF8=1"]
+ env_file = install_dir / ".env"
+ if env_file.exists():
+ for key, value in dotenv_values(env_file).items():
+ if key and value:
+ env_pairs.append(f"{key}={value}")
+ _run(["nssm", "set", SERVICE_NAME, "AppEnvironmentExtra", " ".join(env_pairs)])
+ _run(["nssm", "set", SERVICE_NAME, "Start", "SERVICE_AUTO_START"])
+ log_file = str(logs / "service.log")
+ _run(["nssm", "set", SERVICE_NAME, "AppStdout", log_file])
+ _run(["nssm", "set", SERVICE_NAME, "AppStderr", log_file])
+ _run(["nssm", "set", SERVICE_NAME, "AppRotateFiles", "1"])
+ _run(["nssm", "set", SERVICE_NAME, "AppRotateBytes", "10485760"]) # 10MB
+
+ console.print("[green]Service installed successfully.[/]")
+ console.print(f"Logs: {log_file}")
+
+
+def _windows_uninstall(_: Path) -> None:
+ _nssm_check()
+ _run(["nssm", "stop", SERVICE_NAME], ignore_error=True)
+ _run(["nssm", "remove", SERVICE_NAME, "confirm"], ignore_error=True)
+ console.print("Service uninstalled.")
+
+
+def _windows_status(_: Path) -> None:
+ _nssm_check()
+ _run(["nssm", "status", SERVICE_NAME], ignore_error=True)
+
+
+def _windows_start(_: Path) -> None:
+ _nssm_check()
+ _run(["nssm", "start", SERVICE_NAME])
+
+
+def _windows_stop(_: Path) -> None:
+ _nssm_check()
+ _run(["nssm", "stop", SERVICE_NAME])
+
+
+def _windows_restart(_: Path) -> None:
+ _nssm_check()
+ _run(["nssm", "restart", SERVICE_NAME])
+
+
+# ============================================================== Linux (systemd)
+
+_LINUX_UNIT = "/etc/systemd/system/machina.service"
+
+
+def _linux_unit_text(install_dir: Path, *, service_user: str, memory: str) -> str:
+ venv = install_dir / "server" / ".venv"
+ server = install_dir / "server"
+ return f"""[Unit]
+Description=MachinaOs Backend
+After=network.target
+
+[Service]
+Type=simple
+User={service_user}
+WorkingDirectory={server}
+EnvironmentFile=-{install_dir}/.env
+Environment=PYTHONPATH={server}
+Environment=PYTHONUTF8=1
+Environment=PATH={venv}/bin:/usr/local/bin:/usr/bin:/bin
+ExecStart={venv}/bin/uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning
+Restart=always
+RestartSec=5
+StartLimitIntervalSec=60
+StartLimitBurst=5
+
+# Resource limits
+MemoryMax={memory}
+
+[Install]
+WantedBy=multi-user.target
+"""
+
+
+def _linux_install(install_dir: Path, *, service_user: str, memory: str) -> None:
+ _ensure_built(install_dir)
+ console.print(f"Installing {SERVICE_NAME} service...")
+ console.print(f" Directory: {install_dir}")
+ console.print(f" User: {service_user}")
+ console.print(f" Memory limit: {memory}")
+
+ tmp = Path("/tmp/machina.service")
+ tmp.write_text(_linux_unit_text(install_dir, service_user=service_user, memory=memory))
+
+ _run(["sudo", "cp", str(tmp), _LINUX_UNIT])
+ _run(["sudo", "systemctl", "daemon-reload"])
+ _run(["sudo", "systemctl", "enable", "machina"])
+
+ console.print("[green]Service installed successfully.[/]")
+ console.print("Start with: sudo systemctl start machina")
+ console.print("View logs: journalctl -u machina -f")
+
+
+def _linux_uninstall(_: Path) -> None:
+ _run(["sudo", "systemctl", "stop", "machina"], ignore_error=True)
+ _run(["sudo", "systemctl", "disable", "machina"], ignore_error=True)
+ if Path(_LINUX_UNIT).exists():
+ _run(["sudo", "rm", _LINUX_UNIT])
+ _run(["sudo", "systemctl", "daemon-reload"])
+ console.print("Service uninstalled.")
+
+
+def _linux_status(_: Path) -> None:
+ _run(["systemctl", "status", "machina"], ignore_error=True)
+
+
+def _linux_start(_: Path) -> None:
+ _run(["sudo", "systemctl", "start", "machina"])
+
+
+def _linux_stop(_: Path) -> None:
+ _run(["sudo", "systemctl", "stop", "machina"])
+
+
+def _linux_restart(_: Path) -> None:
+ _run(["sudo", "systemctl", "restart", "machina"])
+
+
+# ============================================================== macOS (launchd)
+
+def _mac_plist_path() -> Path:
+ return Path.home() / "Library" / "LaunchAgents" / f"{PLIST_LABEL}.plist"
+
+
+def _mac_plist_text(install_dir: Path) -> str:
+ venv = install_dir / "server" / ".venv"
+ server = install_dir / "server"
+ logs = _logs_dir(install_dir)
+ return f"""<?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>{PLIST_LABEL}</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>{venv}/bin/uvicorn</string>
+ <string>main:app</string>
+ <string>--host</string>
+ <string>0.0.0.0</string>
+ <string>--port</string>
+ <string>3010</string>
+ <string>--log-level</string>
+ <string>warning</string>
+ </array>
+ <key>WorkingDirectory</key>
+ <string>{server}</string>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key>
+ <string>{venv}/bin:/usr/local/bin:/usr/bin:/bin</string>
+ <key>PYTHONPATH</key>
+ <string>{server}</string>
+ <key>PYTHONUTF8</key>
+ <string>1</string>
+ </dict>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>{logs}/service.log</string>
+ <key>StandardErrorPath</key>
+ <string>{logs}/service.log</string>
+</dict>
+</plist>
+"""
+
+
+def _mac_install(install_dir: Path) -> None:
+ _ensure_built(install_dir)
+ logs = _logs_dir(install_dir)
+ logs.mkdir(parents=True, exist_ok=True)
+
+ console.print(f"Installing {SERVICE_NAME} service...")
+ console.print(f" Directory: {install_dir}")
+
+ plist_path = _mac_plist_path()
+ plist_path.parent.mkdir(parents=True, exist_ok=True)
+ _run(["launchctl", "unload", str(plist_path)], ignore_error=True)
+ plist_path.write_text(_mac_plist_text(install_dir))
+
+ console.print("[green]Service installed successfully.[/]")
+ console.print(f"Plist: {plist_path}")
+ console.print(f"Logs: {logs}/service.log")
+ console.print('Start with: machina daemon start')
+
+
+def _mac_uninstall(_: Path) -> None:
+ plist_path = _mac_plist_path()
+ _run(["launchctl", "unload", str(plist_path)], ignore_error=True)
+ if plist_path.exists():
+ plist_path.unlink()
+ console.print("Service uninstalled.")
+
+
+def _mac_status(_: Path) -> None:
+ proc = subprocess.run(["launchctl", "list"], capture_output=True, text=True)
+ for line in proc.stdout.splitlines():
+ if "machina" in line:
+ console.print(line)
+
+
+def _mac_start(_: Path) -> None:
+ _run(["launchctl", "load", str(_mac_plist_path())])
+
+
+def _mac_stop(_: Path) -> None:
+ _run(["launchctl", "unload", str(_mac_plist_path())])
+
+
+def _mac_restart(install_dir: Path) -> None:
+ _mac_stop(install_dir)
+ _mac_start(install_dir)
+
+
+# ---------------------------------------------------------------- dispatch
+
+def _platform_label() -> str:
+ if IS_WINDOWS:
+ return "Windows (NSSM)"
+ if IS_MACOS:
+ return "macOS (launchd)"
+ return "Linux (systemd)"
+
+
+# Common Typer options reused by every verb.
+_dir_opt = typer.Option(None, "--dir", help="Installation directory (default: project root).")
+_user_opt = typer.Option(
+ None, "--user",
+ help="Service user (Linux only; default: current user).",
+)
+_memory_opt = typer.Option(
+ "2G", "--memory",
+ help="Memory limit (Linux only; default: 2G).",
+)
+
+
+def install_cmd(
+ dir: str | None = _dir_opt,
+ user: str | None = _user_opt,
+ memory: str = _memory_opt,
+) -> None:
+ """Install MachinaOS as a system service for the current platform."""
+ install_dir = _install_dir(dir)
+ if IS_WINDOWS:
+ _windows_install(install_dir)
+ elif IS_MACOS:
+ _mac_install(install_dir)
+ else:
+ service_user = user or os.environ.get("USER") or os.environ.get("USERNAME") or "root"
+ _linux_install(install_dir, service_user=service_user, memory=memory)
+
+
+def _dispatch_simple(verb: str, install_dir: Path) -> None:
+ handlers = {
+ ("windows", "uninstall"): _windows_uninstall,
+ ("windows", "status"): _windows_status,
+ ("windows", "start"): _windows_start,
+ ("windows", "stop"): _windows_stop,
+ ("windows", "restart"): _windows_restart,
+ ("mac", "uninstall"): _mac_uninstall,
+ ("mac", "status"): _mac_status,
+ ("mac", "start"): _mac_start,
+ ("mac", "stop"): _mac_stop,
+ ("mac", "restart"): _mac_restart,
+ ("linux", "uninstall"): _linux_uninstall,
+ ("linux", "status"): _linux_status,
+ ("linux", "start"): _linux_start,
+ ("linux", "stop"): _linux_stop,
+ ("linux", "restart"): _linux_restart,
+ }
+ platform = "windows" if IS_WINDOWS else "mac" if IS_MACOS else "linux"
+ handlers[(platform, verb)](install_dir)
+
+
[email protected]("uninstall")
+def uninstall_cmd(dir: str | None = _dir_opt) -> None:
+ """Remove the system service."""
+ _dispatch_simple("uninstall", _install_dir(dir))
+
+
+def status_cmd(dir: str | None = _dir_opt) -> None:
+ """Show service status (NSSM / systemctl / launchctl)."""
+ _dispatch_simple("status", _install_dir(dir))
+
+
+def start_cmd(dir: str | None = _dir_opt) -> None:
+ """Start the system service."""
+ _dispatch_simple("start", _install_dir(dir))
+
+
+def stop_cmd(dir: str | None = _dir_opt) -> None:
+ """Stop the system service."""
+ _dispatch_simple("stop", _install_dir(dir))
+
+
+def restart_cmd(dir: str | None = _dir_opt) -> None:
+ """Restart the system service."""
+ _dispatch_simple("restart", _install_dir(dir))
+
+
+def _root() -> None:
+ """Cross-platform service installer.
+
+ Platform: detected from sys.platform (Windows -> NSSM,
+ macOS -> launchd, Linux -> systemd).
+ """
diff --git a/machina/tests/test_daemon.py b/machina/tests/test_daemon.py
new file mode 100644
index 00000000..c74e759b
--- /dev/null
+++ b/machina/tests/test_daemon.py
@@ -0,0 +1,68 @@
+"""Smoke tests for ``machina.commands.daemon``."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+from machina.commands import daemon
+
+
+def test_install_dir_uses_project_root_by_default():
+ with patch.object(daemon, "project_root", return_value=Path("/proj")):
+ assert daemon._install_dir(None) == Path("/proj")
+
+
+def test_install_dir_resolves_explicit_override(tmp_path: Path):
+ assert daemon._install_dir(str(tmp_path)) == tmp_path.resolve()
+
+
+def test_venv_python_chooses_layout_per_platform():
+ install_dir = Path("/x")
+ with patch.object(daemon, "IS_WINDOWS", True):
+ assert daemon._venv_python(install_dir).name == "python.exe"
+ with patch.object(daemon, "IS_WINDOWS", False):
+ assert daemon._venv_python(install_dir).name == "python"
+
+
+def test_linux_unit_text_includes_user_memory_and_paths(tmp_path: Path):
+ text = daemon._linux_unit_text(
+ tmp_path, service_user="bob", memory="3G",
+ )
+ assert "User=bob" in text
+ assert "MemoryMax=3G" in text
+ assert f"WorkingDirectory={tmp_path / 'server'}" in text
+ assert "ExecStart=" in text
+ assert "uvicorn main:app" in text
+
+
+def test_mac_plist_text_uses_label_and_paths(tmp_path: Path):
+ text = daemon._mac_plist_text(tmp_path)
+ assert f"<string>{daemon.PLIST_LABEL}</string>" in text
+ assert "main:app" in text
+ assert "0.0.0.0" in text
+
+
+def test_mac_plist_path_under_launchagents():
+ path = daemon._mac_plist_path()
+ assert path.name == f"{daemon.PLIST_LABEL}.plist"
+ # Sanity: should resolve under user's home Library/LaunchAgents.
+ assert "LaunchAgents" in str(path)
+
+
+def test_dispatch_simple_routes_per_platform():
+ """Each verb hits the right handler for the current platform."""
+ install_dir = Path("/x")
+ with patch.object(daemon, "_windows_status") as win, \
+ patch.object(daemon, "_linux_status") as lin, \
+ patch.object(daemon, "_mac_status") as mac:
+ if sys.platform == "win32":
+ daemon._dispatch_simple("status", install_dir)
+ win.assert_called_once_with(install_dir)
+ elif sys.platform == "darwin":
+ daemon._dispatch_simple("status", install_dir)
+ mac.assert_called_once_with(install_dir)
+ else:
+ daemon._dispatch_simple("status", install_dir)
+ lin.assert_called_once_with(install_dir)
diff --git a/package.json b/package.json
index ec12a5d2..a8f93057 100644
--- a/package.json
+++ b/package.json
@@ -81,12 +81,12 @@
"docs:nodes:check": "python -m machina docs nodes --check",
"deploy": "bash deploy.sh",
"deploy:gcp": "bash deploy.sh",
- "daemon:install": "node scripts/daemon.js install",
- "daemon:uninstall": "node scripts/daemon.js uninstall",
- "daemon:status": "node scripts/daemon.js status",
- "daemon:start": "node scripts/daemon.js start",
- "daemon:stop": "node scripts/daemon.js stop",
- "daemon:restart": "node scripts/daemon.js restart",
+ "daemon:install": "python -m machina daemon install",
+ "daemon:uninstall": "python -m machina daemon uninstall",
+ "daemon:status": "python -m machina daemon status",
+ "daemon:start": "python -m machina daemon start",
+ "daemon:stop": "python -m machina daemon stop",
+ "daemon:restart": "python -m machina daemon restart",
"version:sync": "python -m machina version sync",
"prepublishOnly": "python -m machina version sync && node -e \"const p=require('./package.json'); if(!p.bin||!p.version){process.exit(1)}\"",
"preinstall": "node scripts/preinstall.js",
diff --git a/scripts/daemon.js b/scripts/daemon.js
deleted file mode 100755
index 6631f7b2..00000000
--- a/scripts/daemon.js
+++ /dev/null
@@ -1,451 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cross-platform service installer for MachinaOS.
- * Works on: Windows (NSSM), Linux (systemd), macOS (launchd)
- *
- * Usage:
- * node scripts/service.js install [OPTIONS]
- * node scripts/service.js uninstall
- * node scripts/service.js status
- * node scripts/service.js start
- * node scripts/service.js stop
- * node scripts/service.js restart
- *
- * Options:
- * --dir=PATH Installation directory (default: current directory)
- * --user=USER Service user (default: current user)
- * --memory=LIMIT Memory limit (default: 2G, Linux only)
- */
-import { execSync, spawnSync } from 'child_process';
-import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { homedir } from 'os';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const ROOT = resolve(__dirname, '..');
-
-// Platform detection
-const isWindows = process.platform === 'win32';
-const isMac = process.platform === 'darwin';
-const isLinux = process.platform === 'linux';
-
-// Service name
-const SERVICE_NAME = 'MachinaOs';
-
-// Parse command line arguments
-const args = process.argv.slice(2);
-const command = args[0] || 'help';
-const options = {};
-args.slice(1).forEach(arg => {
- const match = arg.match(/^--(\w+)=(.+)$/);
- if (match) {
- options[match[1]] = match[2];
- }
-});
-
-// Default options
-const installDir = options.dir || ROOT;
-const serviceUser = options.user || (isWindows ? process.env.USERNAME : process.env.USER);
-const memoryLimit = options.memory || '2G';
-
-function run(cmd, opts = {}) {
- try {
- return execSync(cmd, {
- encoding: 'utf-8',
- stdio: opts.silent ? 'pipe' : 'inherit',
- shell: true,
- ...opts
- });
- } catch (e) {
- if (!opts.ignoreError) {
- throw e;
- }
- return '';
- }
-}
-
-function runSilent(cmd) {
- try {
- execSync(cmd, { encoding: 'utf-8', stdio: 'pipe', shell: true });
- return true;
- } catch {
- return false;
- }
-}
-
-// ============================================================================
-// Windows (NSSM)
-// ============================================================================
-
-function windowsCheckNssm() {
- if (!runSilent('where nssm')) {
- console.log('NSSM not found. Install from https://nssm.cc/');
- console.log('Or use: winget install nssm');
- process.exit(1);
- }
-}
-
-function windowsInstall() {
- windowsCheckNssm();
-
- const pythonExe = resolve(installDir, 'server', '.venv', 'Scripts', 'python.exe');
- const serverDir = resolve(installDir, 'server');
- const logsDir = resolve(installDir, 'logs');
-
- if (!existsSync(pythonExe)) {
- console.log(`Python venv not found at ${pythonExe}`);
- console.log('Run "npm run build" first.');
- process.exit(1);
- }
-
- // Create logs directory
- if (!existsSync(logsDir)) {
- mkdirSync(logsDir, { recursive: true });
- }
-
- console.log(`Installing ${SERVICE_NAME} service...`);
- console.log(` Directory: ${installDir}`);
- console.log(` Python: ${pythonExe}`);
-
- // Remove existing service if present
- run(`nssm stop ${SERVICE_NAME}`, { ignoreError: true, silent: true });
- run(`nssm remove ${SERVICE_NAME} confirm`, { ignoreError: true, silent: true });
-
- // Install service
- run(`nssm install ${SERVICE_NAME} "${pythonExe}" -m uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning`);
- run(`nssm set ${SERVICE_NAME} AppDirectory "${serverDir}"`);
- // Load .env variables for the service
- const envFile = resolve(installDir, '.env');
- let envExtra = `PYTHONPATH=${serverDir} PYTHONUTF8=1`;
- if (existsSync(envFile)) {
- for (const line of readFileSync(envFile, 'utf-8').split('\n')) {
- const match = line.match(/^([^#=]+)=(.*)$/);
- if (match) {
- const key = match[1].trim();
- const val = match[2].trim().replace(/^["']|["']$/g, '');
- if (key && val) envExtra += ` ${key}=${val}`;
- }
- }
- }
- run(`nssm set ${SERVICE_NAME} AppEnvironmentExtra "${envExtra}"`);
- run(`nssm set ${SERVICE_NAME} Start SERVICE_AUTO_START`);
- run(`nssm set ${SERVICE_NAME} AppStdout "${logsDir}\\service.log"`);
- run(`nssm set ${SERVICE_NAME} AppStderr "${logsDir}\\service.log"`);
- run(`nssm set ${SERVICE_NAME} AppRotateFiles 1`);
- run(`nssm set ${SERVICE_NAME} AppRotateBytes 10485760`); // 10MB
-
- console.log('Service installed successfully.');
- console.log(`Logs: ${logsDir}\\service.log`);
-}
-
-function windowsUninstall() {
- windowsCheckNssm();
- run(`nssm stop ${SERVICE_NAME}`, { ignoreError: true });
- run(`nssm remove ${SERVICE_NAME} confirm`, { ignoreError: true });
- console.log('Service uninstalled.');
-}
-
-function windowsStatus() {
- windowsCheckNssm();
- run(`nssm status ${SERVICE_NAME}`, { ignoreError: true });
-}
-
-function windowsStart() {
- windowsCheckNssm();
- run(`nssm start ${SERVICE_NAME}`);
-}
-
-function windowsStop() {
- windowsCheckNssm();
- run(`nssm stop ${SERVICE_NAME}`);
-}
-
-function windowsRestart() {
- windowsCheckNssm();
- run(`nssm restart ${SERVICE_NAME}`);
-}
-
-// ============================================================================
-// Linux (systemd)
-// ============================================================================
-
-function linuxGenerateServiceFile() {
- const venvPath = resolve(installDir, 'server', '.venv');
- const serverDir = resolve(installDir, 'server');
-
- return `[Unit]
-Description=MachinaOs Backend
-After=network.target
-
-[Service]
-Type=simple
-User=${serviceUser}
-WorkingDirectory=${serverDir}
-EnvironmentFile=-${installDir}/.env
-Environment=PYTHONPATH=${serverDir}
-Environment=PYTHONUTF8=1
-Environment=PATH=${venvPath}/bin:/usr/local/bin:/usr/bin:/bin
-ExecStart=${venvPath}/bin/uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning
-Restart=always
-RestartSec=5
-StartLimitIntervalSec=60
-StartLimitBurst=5
-
-# Resource limits
-MemoryMax=${memoryLimit}
-
-[Install]
-WantedBy=multi-user.target
-`;
-}
-
-function linuxInstall() {
- const venvPath = resolve(installDir, 'server', '.venv', 'bin', 'python');
-
- if (!existsSync(venvPath)) {
- console.log(`Python venv not found at ${venvPath}`);
- console.log('Run "npm run build" first.');
- process.exit(1);
- }
-
- console.log(`Installing ${SERVICE_NAME} service...`);
- console.log(` Directory: ${installDir}`);
- console.log(` User: ${serviceUser}`);
- console.log(` Memory limit: ${memoryLimit}`);
-
- const serviceContent = linuxGenerateServiceFile();
- const tempFile = '/tmp/machina.service';
- writeFileSync(tempFile, serviceContent);
-
- run(`sudo cp ${tempFile} /etc/systemd/system/machina.service`);
- run('sudo systemctl daemon-reload');
- run('sudo systemctl enable machina');
-
- console.log('Service installed successfully.');
- console.log('Start with: sudo systemctl start machina');
- console.log('View logs: journalctl -u machina -f');
-}
-
-function linuxUninstall() {
- run('sudo systemctl stop machina', { ignoreError: true });
- run('sudo systemctl disable machina', { ignoreError: true });
- if (existsSync('/etc/systemd/system/machina.service')) {
- run('sudo rm /etc/systemd/system/machina.service');
- }
- run('sudo systemctl daemon-reload');
- console.log('Service uninstalled.');
-}
-
-function linuxStatus() {
- run('systemctl status machina', { ignoreError: true });
-}
-
-function linuxStart() {
- run('sudo systemctl start machina');
-}
-
-function linuxStop() {
- run('sudo systemctl stop machina');
-}
-
-function linuxRestart() {
- run('sudo systemctl restart machina');
-}
-
-// ============================================================================
-// macOS (launchd)
-// ============================================================================
-
-function macGeneratePlist() {
- const venvPath = resolve(installDir, 'server', '.venv');
- const serverDir = resolve(installDir, 'server');
- const logsDir = resolve(installDir, 'logs');
-
- return `<?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>com.machina.backend</string>
- <key>ProgramArguments</key>
- <array>
- <string>${venvPath}/bin/uvicorn</string>
- <string>main:app</string>
- <string>--host</string>
- <string>0.0.0.0</string>
- <string>--port</string>
- <string>3010</string>
- <string>--log-level</string>
- <string>warning</string>
- </array>
- <key>WorkingDirectory</key>
- <string>${serverDir}</string>
- <key>EnvironmentVariables</key>
- <dict>
- <key>PATH</key>
- <string>${venvPath}/bin:/usr/local/bin:/usr/bin:/bin</string>
- <key>PYTHONPATH</key>
- <string>${serverDir}</string>
- <key>PYTHONUTF8</key>
- <string>1</string>
- </dict>
- <key>RunAtLoad</key>
- <true/>
- <key>KeepAlive</key>
- <true/>
- <key>StandardOutPath</key>
- <string>${logsDir}/service.log</string>
- <key>StandardErrorPath</key>
- <string>${logsDir}/service.log</string>
-</dict>
-</plist>
-`;
-}
-
-function macGetPlistPath() {
- return resolve(homedir(), 'Library', 'LaunchAgents', 'com.machina.backend.plist');
-}
-
-function macInstall() {
- const venvPath = resolve(installDir, 'server', '.venv', 'bin', 'python');
- const logsDir = resolve(installDir, 'logs');
-
- if (!existsSync(venvPath)) {
- console.log(`Python venv not found at ${venvPath}`);
- console.log('Run "npm run build" first.');
- process.exit(1);
- }
-
- // Create logs directory
- if (!existsSync(logsDir)) {
- mkdirSync(logsDir, { recursive: true });
- }
-
- console.log(`Installing ${SERVICE_NAME} service...`);
- console.log(` Directory: ${installDir}`);
-
- const plistContent = macGeneratePlist();
- const plistPath = macGetPlistPath();
-
- // Ensure LaunchAgents directory exists
- const launchAgentsDir = dirname(plistPath);
- if (!existsSync(launchAgentsDir)) {
- mkdirSync(launchAgentsDir, { recursive: true });
- }
-
- // Unload existing if present
- run(`launchctl unload "${plistPath}"`, { ignoreError: true, silent: true });
-
- writeFileSync(plistPath, plistContent);
-
- console.log('Service installed successfully.');
- console.log(`Plist: ${plistPath}`);
- console.log(`Logs: ${logsDir}/service.log`);
- console.log('Start with: node scripts/service.js start');
-}
-
-function macUninstall() {
- const plistPath = macGetPlistPath();
- run(`launchctl unload "${plistPath}"`, { ignoreError: true });
- if (existsSync(plistPath)) {
- unlinkSync(plistPath);
- }
- console.log('Service uninstalled.');
-}
-
-function macStatus() {
- run('launchctl list | grep machina', { ignoreError: true });
-}
-
-function macStart() {
- const plistPath = macGetPlistPath();
- run(`launchctl load "${plistPath}"`);
-}
-
-function macStop() {
- const plistPath = macGetPlistPath();
- run(`launchctl unload "${plistPath}"`);
-}
-
-function macRestart() {
- macStop();
- macStart();
-}
-
-// ============================================================================
-// Main
-// ============================================================================
-
-function showHelp() {
- console.log(`
-MachinaOS Service Manager
-
-Usage: node scripts/service.js <command> [options]
-
-Commands:
- install Install as system service
- uninstall Remove system service
- status Show service status
- start Start the service
- stop Stop the service
- restart Restart the service
-
-Options:
- --dir=PATH Installation directory (default: current)
- --user=USER Service user (Linux only, default: current user)
- --memory=LIMIT Memory limit (Linux only, default: 2G)
-
-Platform: ${isWindows ? 'Windows (NSSM)' : isMac ? 'macOS (launchd)' : 'Linux (systemd)'}
-
-Examples:
- node scripts/service.js install
- node scripts/service.js install --dir=/opt/machina --user=machina
- node scripts/service.js status
- node scripts/service.js restart
-`);
-}
-
-// Dispatch to platform-specific functions
-const handlers = {
- windows: {
- install: windowsInstall,
- uninstall: windowsUninstall,
- status: windowsStatus,
- start: windowsStart,
- stop: windowsStop,
- restart: windowsRestart,
- },
- linux: {
- install: linuxInstall,
- uninstall: linuxUninstall,
- status: linuxStatus,
- start: linuxStart,
- stop: linuxStop,
- restart: linuxRestart,
- },
- mac: {
- install: macInstall,
- uninstall: macUninstall,
- status: macStatus,
- start: macStart,
- stop: macStop,
- restart: macRestart,
- },
-};
-
-const platform = isWindows ? 'windows' : isMac ? 'mac' : 'linux';
-
-if (command === 'help' || command === '--help' || command === '-h') {
- showHelp();
- process.exit(0);
-}
-
-const handler = handlers[platform][command];
-if (!handler) {
- console.log(`Unknown command: ${command}`);
- showHelp();
- process.exit(1);
-}
-
-handler();