How the daemon-management Package Supervises Processes in Magnitude
The daemon-management package orchestrates the lifecycle of the Magnitude ACN (Agent Client Node) service across macOS, Linux, and Windows by abstracting platform-specific init systems into a unified Effect-TS based interface.
The daemon-management package in the magnitudedev/magnitude repository provides the centralized supervision layer responsible for installing, starting, monitoring, and stopping the Magnitude daemon. It ensures a single, persistent agent runs reliably by handling the transition from temporary just-in-time (JIT) processes to permanent system services.
Core Supervision Flow
The supervision logic is implemented primarily in [packages/daemon-management/src/service.ts](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts). The process follows a strict sequence to guarantee the daemon is correctly installed, healthy, and ready to accept connections.
1. Binary Resolution
resolveServiceCommand (service.ts#L39) determines the exact binary path and version to launch. It checks the ManagedServiceHost for a custom launch command; if none is provided, it delegates to resolveBinaryCommand to fetch the appropriate binary for the current platform.
2. Platform-Specific Unit Generation
The package renders OS-specific service definitions based on the detected platform:
- macOS:
renderMacServerService(service.ts#L59) generates a.plistlaunch agent file. - Linux:
renderLinuxServerService(service.ts#L73) generates asystemduser unit file. - Windows:
renderWindowsServerCommandbuilds the scheduled task command line forschtasks.
3. Installation and Activation
installAndStartService (service.ts#L88) writes the generated unit file to the system-specific location (e.g., ~/Library/LaunchAgents, ~/.config/systemd/user, or the Windows Task Scheduler) and marks it as enabled. It then immediately launches the service using the native control command (launchctl bootstrap, systemctl --user start, or schtasks /Run).
4. Health Probing and Readiness
Once started, the package validates the daemon's state through a tiered health check system:
probeHealth(service.ts#L65) executes an HTTP GET request to${MAGNITUDE_SERVICE_ORIGIN}/healthand decodes the response against the ACN protocol schema.probeReadyverifies that the daemon's revision matches the current CLI version and that its internal state isReady.awaitReady(service.ts#L84) implements a retry loop, callingprobeReadyevery 250 milliseconds for up to one minute until the service reports readiness.
5. JIT Process Cleanup
Before installing the persistent service, stopLocalAcn (service.ts#L17) terminates any locally spawned JIT ACN processes. This prevents port conflicts and ensures only one daemon instance holds the fixed service port.
6. Orchestration Entry Point
startServiceManager (service.ts#L95) acts as the high-level coordinator. It executes the full sequence: resolving the command, checking if an existing service matches the current release via managedServiceIsCurrent, stopping local JIT instances, and invoking installAndStartService. All errors are wrapped in the ServerServiceError type for consistent handling.
Platform-Specific Supervision Details
The daemon-management package adapts its supervision strategy to leverage each operating system's native service manager.
macOS via launchctl
On macOS, the package creates a launch agent at ~/Library/LaunchAgents/dev.magnitude.acn.plist. The generated plist includes a KeepAlive flag that instructs launchctl to restart the daemon automatically if it exits unexpectedly, ensuring high availability without manual intervention.
Linux via systemd
For Linux systems, the package generates a user-level systemd unit file at ~/.config/systemd/user/magnitude.service. The unit configuration sets Restart=on-failure and directs stdout and stderr to the Magnitude-specific log directory, allowing standard journalctl inspection of daemon output.
Windows via schtasks
On Windows, the package registers a scheduled task named MagnitudeInference using schtasks. The task command line is constructed by renderWindowsServerCommand, and a PowerShell configuration script (WINDOWS_RESTART_POLICY_SCRIPT) applies an aggressive restart policy to the task, ensuring the daemon respawns after crashes.
Implementation with Effect-TS
All supervision operations are built on Effect-TS primitives (Effect.gen, Effect.flatMap, Effect.retry). This functional approach makes the supervision workflow composable, cancellable, and resilient to transient failures. Retry policies, error handling, and resource management are handled declaratively, allowing the complex multi-step installation process to fail gracefully and report specific error contexts.
Practical Usage Examples
import { startServiceManager, serviceStatus, stopService } from "@magnitudedev/daemon-management"
import { Effect } from "effect"
// Install and start the persistent Magnitude daemon
Effect.runPromise(startServiceManager())
// Check if the daemon is running and ready
Effect.runPromise(serviceStatus).then(status => {
console.log("Daemon status:", status)
})
// Stop the persistent service and any local JIT instances
Effect.runPromise(stopService())
Key Source Files
- [
packages/daemon-management/src/service.ts](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts): Core supervision implementation including installation, health checks, and orchestration. packages/daemon-management/src/acn-jit/*: Helpers for managing just-in-time (JIT) ACN processes before persistent installation.packages/daemon-management/src/binary.ts: Logic for acquiring the correct binary version and emitting acquisition events.packages/daemon-management/src/version.ts: Defines the current daemon target (DAEMON_TARGET) and version constants.packages/daemon-management/src/errors.ts: Typed error definitions includingServerServiceErrorandAcnAdministrationFailed.
Summary
- The
daemon-managementpackage provides a unified abstraction over macOSlaunchctl, Linuxsystemd, and Windowsschtasks. startServiceManagerinservice.tsis the primary entry point for orchestrating daemon installation and startup.- Health verification via
probeReadyandawaitReadyensures the daemon is running and version-compatible before the CLI proceeds. - The package manages the transition from JIT processes to persistent system services, ensuring no port conflicts occur.
- Built on Effect-TS, the supervision system offers composable, failure-resistant process management with structured error reporting.
Frequently Asked Questions
What happens if the Magnitude daemon crashes on macOS?
The KeepAlive flag in the generated .plist file (created by renderMacServerService) instructs launchctl to restart the service automatically if it exits unexpectedly. This ensures the daemon remains available without requiring manual intervention after a crash.
How does the package prevent multiple ACN instances from running simultaneously?
Before installing a persistent service, the stopLocalAcn function terminates any locally spawned JIT processes. This cleanup guarantees that only one daemon instance—either the JIT version for temporary use or the persistent system service—holds the fixed network port at any given time.
Can I specify a custom binary path instead of using the auto-resolved one?
Yes. The resolveServiceCommand function checks the ManagedServiceHost interface for a custom launch command. If provided, the package bypasses the default resolveBinaryCommand logic and uses your specified binary path and arguments for the service installation.
What is the timeout for waiting for the service to become ready?
The awaitReady function implements a spaced-retry schedule that polls every 250 milliseconds for approximately one minute. If the daemon does not report a Ready state within this window, the operation fails with a timeout error wrapped in ServerServiceError.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →