Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix: overhauled daemonization — auto-daemonize on start, stale PID cleanup, SIGHUP handling

Salman Qureshi349c5d250be8
diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts
index 7476f57e..4be16aeb 100644
--- a/src/cli/daemon.ts
+++ b/src/cli/daemon.ts
@@ -40,20 +40,18 @@ function isProcessRunning(pid: number): boolean {
export function getDaemonStatus(): { running: boolean; pid: number | null; logPath: string } {
const pid = readPid();
if (!pid) return { running: false, pid: null, logPath: logPath() };
- return { running: isProcessRunning(pid), pid, logPath: logPath() };
+ const running = isProcessRunning(pid);
+ if (!running) {
+ try { unlinkSync(pidPath()); } catch {}
+ return { running: false, pid: null, logPath: logPath() };
+ }
+ return { running, pid, logPath: logPath() };
}
-export function startBackground(): void {
+export function ensureDaemonRunning(): { pid: number; fresh: boolean } {
const status = getDaemonStatus();
if (status.running && status.pid) {
- console.log(chalk.yellow(` Mercury is already running (PID: ${status.pid})`));
- console.log(chalk.dim(` Use \`mercury stop\` to stop it first.`));
- console.log('');
- process.exit(1);
- }
-
- if (status.pid && !status.running) {
- try { unlinkSync(pidPath()); } catch {}
+ return { pid: status.pid, fresh: false };
}
const home = getMercuryHome();
@@ -74,14 +72,27 @@ export function startBackground(): void {
child.unref();
+ if (!child.pid) {
+ throw new Error('Failed to spawn daemon process');
+ }
+
writeFileSync(pidPath(), String(child.pid));
+ return { pid: child.pid, fresh: true };
+}
- console.log('');
- console.log(chalk.green(` Mercury started in background (PID: ${child.pid})`));
- console.log(chalk.dim(` Logs: ${logFile}`));
- console.log(chalk.dim(` Use \`mercury stop\` to stop.`));
- console.log(chalk.dim(` Use \`mercury logs\` to view logs.`));
- console.log('');
+export function startBackground(): void {
+ try {
+ const result = ensureDaemonRunning();
+ console.log('');
+ console.log(chalk.green(` Mercury started in background (PID: ${result.pid})`));
+ console.log(chalk.dim(` Logs: ${logPath()}`));
+ console.log(chalk.dim(` Use \`mercury stop\` to stop.`));
+ console.log(chalk.dim(` Use \`mercury logs\` to view logs.`));
+ console.log('');
+ } catch (err: any) {
+ console.log(chalk.red(` Failed to start: ${err.message}`));
+ process.exit(1);
+ }
}
export function stopDaemon(): void {
@@ -131,8 +142,6 @@ export function restartDaemon(): void {
}
try { unlinkSync(pidPath()); } catch {}
console.log(chalk.green(' Mercury stopped.'));
- } else if (status.pid) {
- try { unlinkSync(pidPath()); } catch {}
}
console.log(chalk.yellow(' Starting Mercury...'));
@@ -147,45 +156,14 @@ export function showLogs(): void {
return;
}
const content = readFileSync(logFile, 'utf-8');
- const lines = content.split('\n').slice(-100);
+ const lines = content.split(/\r?\n/).slice(-100);
console.log(lines.join('\n'));
}
export function tryAutoDaemonize(): boolean {
try {
- const status = getDaemonStatus();
- if (status.running && status.pid) {
- return true;
- }
-
- if (status.pid && !status.running) {
- try { unlinkSync(pidPath()); } catch {}
- }
-
- const home = getMercuryHome();
- if (!existsSync(home)) {
- mkdirSync(home, { recursive: true });
- }
-
- const logFile = logPath();
- const isWin = process.platform === 'win32';
- const outFd = openSync(logFile, 'a');
-
- const child = spawn(process.execPath, [process.argv[1], 'start', '--daemon'], {
- detached: true,
- stdio: ['ignore', outFd, outFd],
- env: { ...process.env },
- windowsHide: isWin,
- });
-
- child.unref();
-
- if (!child.pid) {
- return false;
- }
-
- writeFileSync(pidPath(), String(child.pid));
- return true;
+ const result = ensureDaemonRunning();
+ return result.pid > 0;
} catch {
return false;
}
diff --git a/src/index.ts b/src/index.ts
index 341d4be5..8de69a95 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -795,7 +795,7 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
function autoDaemonize(): void {
const daemon = getDaemonStatus();
- if (daemon.running) {
+ if (daemon.running && daemon.pid) {
return;
}
@@ -812,11 +812,11 @@ function autoDaemonize(): void {
const ok = tryAutoDaemonize();
if (ok) {
const status = getDaemonStatus();
- console.log(chalk.green(` ✓ Mercury is running in background (PID: ${status.pid})`));
- console.log(chalk.green(' ✓ Auto-starts on login. Auto-restarts on crash.'));
+ console.log(chalk.green(` \u2713 Mercury is running in background (PID: ${status.pid})`));
+ console.log(chalk.green(' \u2713 Auto-starts on login. Auto-restarts on crash.'));
console.log(chalk.dim(' Use `mercury stop` to stop. `mercury restart` to restart.'));
} else {
- console.log(chalk.dim(' Background mode not available. Run `mercury up` to set it up.'));
+ console.log(chalk.yellow(' Background mode not available. Run `mercury start` to set it up.'));
}
console.log('');
}
@@ -1026,6 +1026,23 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
+
+ if (!isDaemon && process.platform !== 'win32') {
+ process.on('SIGHUP', () => {
+ logger.info('SIGHUP received — terminal closed. Daemonizing.');
+ try {
+ const result = tryAutoDaemonize();
+ if (result) {
+ logger.info(`Forked daemon. Foreground process exiting.`);
+ } else {
+ logger.warn('SIGHUP received but daemonization failed. Shutting down.');
+ }
+ } catch {
+ logger.warn('SIGHUP received but daemonization failed. Shutting down.');
+ }
+ process.exit(0);
+ });
+ }
}
const program = new Command();
@@ -1041,14 +1058,16 @@ program
autoDaemonize();
return;
}
+ autoDaemonize();
await runAgent();
});
program
.command('start')
- .description('Start Mercury agent')
+ .description('Start Mercury — runs as a daemon by default, use --foreground to attach to terminal')
.option('-v, --verbose', 'Show debug logs')
- .option('-d, --detached', 'Run in background (daemon mode)')
+ .option('-f, --foreground', 'Run in foreground (attached to terminal)')
+ .option('-d, --detached', 'Run in background (daemon mode) — same as default')
.option('--daemon', 'Internal flag for daemon child process')
.action(async (opts) => {
if (opts.daemon) {
@@ -1056,16 +1075,18 @@ program
return;
}
- if (opts.detached) {
- startBackground();
+ if (!isSetupComplete()) {
+ await configure();
+ autoDaemonize();
return;
}
- if (!isSetupComplete()) {
- await configure();
+ if (opts.foreground) {
+ await runAgent();
return;
}
- await runAgent();
+
+ startBackground();
});
program
@@ -1084,14 +1105,15 @@ program
program
.command('up')
- .description('Ensure Mercury is running persistently — installs service if needed, starts daemon')
+ .description('Start Mercury as a persistent daemon (same as `mercury start`)')
.action(async () => {
if (!isSetupComplete()) {
await configure();
+ autoDaemonize();
+ return;
}
const daemon = getDaemonStatus();
-
if (daemon.running && daemon.pid) {
console.log('');
console.log(chalk.green(` Mercury is already running (PID: ${daemon.pid})`));
@@ -1106,7 +1128,6 @@ program
installService();
}
- console.log(chalk.cyan(' Starting Mercury in background...'));
startBackground();
});