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.

feat(daemon): graceful stop over the local API; upgrade waits for the old process (Windows)

Salman Qureshi2117c3c170ea
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 81171de1..3f2c31f5 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -201,8 +201,31 @@ try {
}
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
- # Windows cannot overwrite a running executable; surface that error.
- if (Test-Path $binPath) { Remove-Item $binPath -Force }
+ # Windows cannot overwrite a running executable. `mercury upgrade` hands
+ # us its own PID in MERCURY_WAIT_PID: wait for it to exit (not a fixed
+ # sleep). Then wait for any other process still running the old binary
+ # (a daemon that has not finished its graceful shutdown yet).
+ if ($env:MERCURY_WAIT_PID) {
+ $waitPid = 0
+ if ([int]::TryParse($env:MERCURY_WAIT_PID, [ref]$waitPid) -and $waitPid -gt 0) {
+ Write-Info "Waiting for Mercury (PID $waitPid) to exit..."
+ Wait-Process -Id $waitPid -Timeout 60 -ErrorAction SilentlyContinue
+ }
+ }
+ if (Test-Path $binPath) {
+ $holders = @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
+ try { $_.Path -and ([IO.Path]::GetFullPath($_.Path) -ieq [IO.Path]::GetFullPath($binPath)) } catch { $false }
+ })
+ if ($holders.Count -gt 0) {
+ Write-Info ("Waiting for running Mercury (PID {0}) to exit..." -f ($holders.Id -join ', '))
+ $holders | Wait-Process -Timeout 30 -ErrorAction SilentlyContinue
+ $still = @($holders | Where-Object { -not $_.HasExited })
+ if ($still.Count -gt 0) {
+ Die ("Mercury is still running (PID {0}). Run `mercury stop` and re-run the installer." -f ($still.Id -join ', '))
+ }
+ }
+ Remove-Item $binPath -Force
+ }
Move-Item -Path $binaryTmp -Destination $binPath -Force
$webDir = Join-Path $binDir 'web'
if (Test-Path $webDir) { Remove-Item $webDir -Recurse -Force }
diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts
index 493476bc..65d30365 100644
--- a/src/cli/daemon.ts
+++ b/src/cli/daemon.ts
@@ -5,6 +5,7 @@ import process from 'node:process';
import chalk from 'chalk';
import { getMercuryHome } from '../utils/config.js';
import { killStaleSignalCliProcesses } from '../signal/jsonrpc.js';
+import { getWebPort, readAttachToken } from '../web/auth.js';
/**
* Detect whether Mercury is running from a standalone, single-file binary
@@ -107,17 +108,18 @@ export async function stopForegroundRuntime(): Promise<boolean> {
const status = getForegroundRuntimeStatus();
if (!status.running || !status.pid) return true;
- try {
- process.kill(status.pid, process.platform === 'win32' ? undefined : 'SIGTERM');
- } catch {
- return false;
+ // Graceful first (the foreground runtime also serves the local API when
+ // the web dashboard is enabled); signal / TerminateProcess as fallback.
+ const graceful = await requestGracefulShutdown(status.pid);
+ if (!graceful) {
+ try {
+ process.kill(status.pid, process.platform === 'win32' ? undefined : 'SIGTERM');
+ } catch {
+ return false;
+ }
}
- const deadline = Date.now() + 5_000;
- while (Date.now() < deadline && isProcessRunning(status.pid)) {
- await new Promise(resolve => setTimeout(resolve, 200));
- }
- if (isProcessRunning(status.pid)) {
+ if (!await waitForExit(status.pid, graceful ? 10_000 : 5_000)) {
try { process.kill(status.pid, 'SIGKILL'); } catch {}
await new Promise(resolve => setTimeout(resolve, 500));
}
@@ -138,6 +140,50 @@ function isProcessRunning(pid: number): boolean {
}
}
+async function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (!isProcessRunning(pid)) return true;
+ await new Promise(resolve => setTimeout(resolve, 200));
+ }
+ return !isProcessRunning(pid);
+}
+
+/**
+ * Ask the runtime to run its own `shutdown()` over the local web API
+ * (`POST /api/shutdown`, attach-token auth, loopback only). Returns true
+ * when the runtime acknowledged — the caller then waits for the pid to
+ * exit. False when there is no token, no listener, the port belongs to
+ * another runtime, or the request times out; the caller falls back to
+ * signals / TerminateProcess.
+ *
+ * This is the only graceful path on Windows: `process.kill(pid)` there is
+ * TerminateProcess, which never runs the runtime's shutdown hooks.
+ */
+export async function requestGracefulShutdown(
+ pid: number,
+ timeoutMs = 2_000,
+ fetchImpl: typeof fetch = fetch,
+): Promise<boolean> {
+ const token = readAttachToken();
+ if (!token) return false;
+ try {
+ const res = await fetchImpl(`http://127.0.0.1:${getWebPort()}/api/shutdown`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!res.ok) return false;
+ const body = await res.json().catch(() => ({})) as { ok?: boolean; pid?: number };
+ if (body?.ok !== true) return false;
+ // A different process answering on the port must not make us believe
+ // *this* pid is going away.
+ return typeof body.pid !== 'number' || body.pid === pid;
+ } catch {
+ return false;
+ }
+}
+
export function getDaemonStatus(): { running: boolean; pid: number | null; logPath: string } {
const pid = readPid();
if (!pid) return { running: false, pid: null, logPath: logPath() };
@@ -215,28 +261,31 @@ export async function stopDaemon(): Promise<boolean> {
return true;
}
- try {
- if (process.platform === 'win32') {
- process.kill(status.pid);
- } else {
- process.kill(status.pid, 'SIGTERM');
- }
- } catch {
- console.log(chalk.red(` Failed to stop PID ${status.pid}. You may need to kill it manually.`));
- killStaleSignalCliProcesses();
- console.log('');
- return false;
- }
-
console.log(chalk.dim(` Stopping Mercury (PID: ${status.pid})...`));
- // Wait up to 5 seconds for the process to exit
- const deadline = Date.now() + 5000;
- while (Date.now() < deadline) {
- if (!isProcessRunning(status.pid)) break;
- await new Promise(resolve => setTimeout(resolve, 200));
+ // 1. Ask the runtime to shut itself down over the local API — the only
+ // path that runs shutdown() on Windows. 2. Otherwise SIGTERM (POSIX)
+ // or TerminateProcess (Windows). 3. SIGKILL as the last resort.
+ const graceful = await requestGracefulShutdown(status.pid);
+ if (!graceful) {
+ try {
+ if (process.platform === 'win32') {
+ process.kill(status.pid);
+ } else {
+ process.kill(status.pid, 'SIGTERM');
+ }
+ } catch {
+ console.log(chalk.red(` Failed to stop PID ${status.pid}. You may need to kill it manually.`));
+ killStaleSignalCliProcesses();
+ console.log('');
+ return false;
+ }
}
+ // A graceful shutdown notifies channels and consolidates memory first —
+ // give it longer than a plain signal before forcing.
+ await waitForExit(status.pid, graceful ? 10_000 : 5_000);
+
if (isProcessRunning(status.pid)) {
console.log(chalk.yellow(' Mercury did not exit gracefully, forcing...'));
try {
diff --git a/src/cli/graceful-stop.test.ts b/src/cli/graceful-stop.test.ts
new file mode 100644
index 00000000..f304cc5c
--- /dev/null
+++ b/src/cli/graceful-stop.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { requestGracefulShutdown } from './daemon.js';
+import { readAttachToken, writeAttachToken } from './../web/auth.js';
+
+/** `mercury stop` asks the runtime first; only an ack for THIS pid counts. */
+describe('requestGracefulShutdown', () => {
+ let home: string;
+ const previousHome = process.env.MERCURY_HOME;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-graceful-'));
+ process.env.MERCURY_HOME = home;
+ });
+ afterEach(() => {
+ if (previousHome === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = previousHome;
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const reply = (status: number, body: unknown) => vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+ it('posts the attach token to the loopback API and accepts an ack for the pid', async () => {
+ writeAttachToken();
+ const f = reply(202, { ok: true, pid: 4242 });
+ expect(await requestGracefulShutdown(4242, 500, f as unknown as typeof fetch)).toBe(true);
+ const [url, init] = f.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/api\/shutdown$/);
+ expect(init.method).toBe('POST');
+ expect((init.headers as Record<string, string>).Authorization).toBe(`Bearer ${readAttachToken()}`);
+ });
+
+ it('is false (→ kill fallback) when another runtime answers, on 4xx/5xx, on network error, or with no token', async () => {
+ writeAttachToken();
+ expect(await requestGracefulShutdown(4242, 500, reply(202, { ok: true, pid: 1 }) as unknown as typeof fetch)).toBe(false);
+ expect(await requestGracefulShutdown(4242, 500, reply(503, { error: 'not ready' }) as unknown as typeof fetch)).toBe(false);
+ const failing = vi.fn(async () => { throw new TypeError('ECONNREFUSED'); });
+ expect(await requestGracefulShutdown(4242, 500, failing as unknown as typeof fetch)).toBe(false);
+ rmSync(join(home, 'attach-token'));
+ const f = reply(202, { ok: true, pid: 4242 });
+ expect(await requestGracefulShutdown(4242, 500, f as unknown as typeof fetch)).toBe(false);
+ expect(f).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/index.ts b/src/index.ts
index ccdebc3e..40a0e883 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -83,7 +83,7 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';
import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler } from './web/server.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -3682,6 +3682,10 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
+ // `mercury stop` / `restart` / `upgrade` ask over the local web API first
+ // (POST /api/shutdown) — on Windows that is the only way shutdown() runs,
+ // since process.kill there is TerminateProcess.
+ setShutdownHandler(() => { void shutdown(); });
if (!isDaemon && process.platform !== 'win32') {
process.on('SIGHUP', async () => {
@@ -4759,8 +4763,10 @@ serviceCmd
const platform = process.platform;
if (platform === 'win32') {
- // Run after this process exits so Windows releases the current executable.
- const psCmd = `Start-Sleep -Seconds 1; irm https://mercuryagent.sh/${installer}.ps1 | iex`;
+ // Run after this process exits so Windows releases the current
+ // executable: wait on our pid (not a fixed sleep), and hand the pid
+ // to the installer so it can wait again before replacing the binary.
+ const psCmd = `$env:MERCURY_WAIT_PID='${process.pid}'; Wait-Process -Id ${process.pid} -Timeout 30 -ErrorAction SilentlyContinue; irm https://mercuryagent.sh/${installer}.ps1 | iex`;
try {
const installer2 = spawn(
'powershell.exe',
diff --git a/src/web/api/lifecycle.ts b/src/web/api/lifecycle.ts
new file mode 100644
index 00000000..bf73e40d
--- /dev/null
+++ b/src/web/api/lifecycle.ts
@@ -0,0 +1,51 @@
+import { Hono } from 'hono';
+import { readAttachToken } from '../auth.js';
+import { isLoopbackRequest } from '../middleware.js';
+
+/**
+ * Local, authenticated shutdown for `mercury stop` / `restart` / `upgrade`.
+ *
+ * Why: on Windows `process.kill(pid)` is TerminateProcess — no signal, so
+ * the runtime's `shutdown()` (channel notices, memory consolidation, SQLite
+ * handle release, pid-file cleanup) never runs. The CLI asks over HTTP
+ * instead and only falls back to killing when this endpoint is unreachable.
+ *
+ * Guarded twice over the ordinary `authGuard`: loopback peers only, and the
+ * machine-local attach token specifically (a browser web session — which
+ * may come from the LAN — cannot stop the daemon).
+ */
+const lifecycle = new Hono();
+
+let shutdownHandler: (() => void) | null = null;
+
+/** Registered by the runtime once its `shutdown()` exists. */
+export function setShutdownHandler(handler: (() => void) | null): void {
+ shutdownHandler = handler;
+}
+
+function bearerToken(header: string | undefined): string | null {
+ if (!header) return null;
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
+ return match ? match[1].trim() : null;
+}
+
+lifecycle.post('/api/shutdown', (c) => {
+ if (!isLoopbackRequest(c)) {
+ return c.json({ error: 'Shutdown is only accepted from this machine' }, 403);
+ }
+ const token = bearerToken(c.req.header('Authorization'));
+ const expected = readAttachToken();
+ if (!token || !expected || token !== expected) {
+ return c.json({ error: 'Shutdown requires the local attach token' }, 403);
+ }
+ if (!shutdownHandler) {
+ return c.json({ error: 'Runtime is not ready to shut down yet' }, 503);
+ }
+ const handler = shutdownHandler;
+ // Reply first, then shut down — the caller needs the ack to know that
+ // the graceful path was taken before it starts waiting on the pid.
+ setTimeout(() => { try { handler(); } catch { /* shutdown() handles its own errors */ } }, 20);
+ return c.json({ ok: true, pid: process.pid }, 202);
+});
+
+export default lifecycle;
diff --git a/src/web/middleware.ts b/src/web/middleware.ts
index 01d7fbe1..fa71bab5 100644
--- a/src/web/middleware.ts
+++ b/src/web/middleware.ts
@@ -9,7 +9,7 @@ const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout']);
* depth: the secret itself is an owner-only file, but a matching token from
* a non-loopback peer must not open the API even if a future bug leaks it.
*/
-function isLoopbackRequest(c: Context): boolean {
+export function isLoopbackRequest(c: Context): boolean {
try {
const address: string = (c.env as any)?.incoming?.socket?.remoteAddress || '';
return ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address);
diff --git a/src/web/server.ts b/src/web/server.ts
index 88eba6b5..d9bf3b7f 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -18,6 +18,7 @@ import botsRoutes, { setBotManager, setBotsWebhookSecret } from './api/bots.js';
import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';
import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';
+import lifecycleRoutes, { setShutdownHandler } from './api/lifecycle.js';
import { BoardManager } from '../core/board-manager.js';
import { isBetterSqlite3Available } from '../memory/second-brain-db.js';
@@ -79,6 +80,7 @@ app.route('/', botsRoutes);
app.route('/', spotifyRoutes);
app.route('/', kanbanRoutes);
app.route('/', ideRoutes);
+app.route('/', lifecycleRoutes);
// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──
app.get('/vendor/*', (c) => {
@@ -193,6 +195,7 @@ if (spaAvailable) {
});
}
+export { setShutdownHandler };
export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;
diff --git a/src/web/shutdown-endpoint.test.ts b/src/web/shutdown-endpoint.test.ts
new file mode 100644
index 00000000..4bde40f9
--- /dev/null
+++ b/src/web/shutdown-endpoint.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Hono } from 'hono';
+import lifecycle, { setShutdownHandler } from './api/lifecycle.js';
+import { readAttachToken, writeAttachToken, createSession } from './auth.js';
+
+/**
+ * POST /api/shutdown: the graceful stop path `mercury stop`/`restart`/
+ * `upgrade` try before killing (the only way shutdown() runs on Windows).
+ * Loopback-only and attach-token-only — a web session must not be enough.
+ */
+describe('POST /api/shutdown', () => {
+ let home: string;
+ const previousHome = process.env.MERCURY_HOME;
+ const app = new Hono().route('/', lifecycle);
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-shutdown-'));
+ process.env.MERCURY_HOME = home;
+ writeAttachToken();
+ });
+
+ afterEach(() => {
+ setShutdownHandler(null);
+ if (previousHome === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = previousHome;
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ function post(token: string | null, remoteAddress = '127.0.0.1') {
+ return app.request(
+ '/api/shutdown',
+ { method: 'POST', headers: token ? { Authorization: `Bearer ${token}` } : {} },
+ { incoming: { socket: { remoteAddress } } },
+ );
+ }
+
+ it('acknowledges with 202 + its pid and then runs the registered shutdown', async () => {
+ const handler = vi.fn();
+ setShutdownHandler(handler);
+ const res = await post(readAttachToken());
+ expect(res.status).toBe(202);
+ expect(await res.json()).toEqual({ ok: true, pid: process.pid });
+ expect(handler).not.toHaveBeenCalled(); // reply first
+ await new Promise((r) => setTimeout(r, 50));
+ expect(handler).toHaveBeenCalledOnce();
+ });
+
+ it('refuses non-loopback peers even with the right token', async () => {
+ setShutdownHandler(vi.fn());
+ const res = await post(readAttachToken(), '10.0.0.7');
+ expect(res.status).toBe(403);
+ });
+
+ it('refuses a web session token and a missing/wrong token', async () => {
+ const handler = vi.fn();
+ setShutdownHandler(handler);
+ expect((await post(createSession())).status).toBe(403);
+ expect((await post(null)).status).toBe(403);
+ expect((await post('deadbeef'.repeat(8))).status).toBe(403);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('answers 503 until the runtime has registered its shutdown', async () => {
+ const res = await post(readAttachToken());
+ expect(res.status).toBe(503);
+ });
+});