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(windows): service install quoting, realpath dist resolution, HKCU Run fallback; PowerShell blocklist (#13)

Salman Qureshi3fa53d901f18
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 5ab789a3..875cdaee 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -4,6 +4,22 @@ import { homedir } from 'node:os';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { getMercuryHome } from '../utils/config.js';
import { logger } from '../utils/logger.js';
+import { BLOCKED_COMMANDS } from './shell/blocklist.js';
+
+/**
+ * Command-pattern glob → anchored, case-insensitive RegExp. `*` matches any
+ * text, `?` one character; everything else is literal. Regex metacharacters
+ * are escaped so `C:\\*` means "C:\ then anything" (not "C: + any char"),
+ * `curl * | sh` is one pattern (not an alternation), and `rm -rf .` matches
+ * only a literal dot.
+ */
+export function globToRegExp(pattern: string): RegExp {
+ const source = pattern
+ .split(/([*?])/)
+ .map((part) => (part === '*' ? '.*' : part === '?' ? '.' : part.replace(/[.+^${}()|[\]\\\/]/g, '\\$&')))
+ .join('');
+ return new RegExp(`^${source}$`, 'i');
+}
export interface FileScope {
path: string;
@@ -55,33 +71,9 @@ const DEFAULT_MANIFEST: PermissionsManifest = {
},
shell: {
enabled: true,
- blocked: [
- 'sudo *',
- 'rm -rf /',
- 'rm -rf ~',
- 'rm -rf /*',
- 'mkfs *',
- 'dd if=*',
- 'chmod 777 /',
- 'chown * /',
- ':(){ :|:& };:',
- 'shutdown *',
- 'reboot *',
- 'halt *',
- 'init 0',
- 'init 6',
- 'kill -9 1',
- '> /dev/sda',
- 'mv /* /dev/null',
- 'del /s /q C:\\*',
- 'rmdir /s /q C:\\*',
- 'format *',
- 'icacls * C:\\* /grant',
- 'net user *',
- 'netsh *',
- 'reg delete *',
- 'cmd /c rd /s /q *',
- ],
+ // Single source of truth: shell/blocklist.ts (also carries the
+ // PowerShell forms — Set-ExecutionPolicy, Remove-Item -Recurse roots).
+ blocked: [...BLOCKED_COMMANDS],
autoApproved: [
'ls *',
'cat *',
@@ -814,9 +806,8 @@ export class PermissionManager {
}
private matchPattern(command: string, pattern: string): boolean {
- const regexStr = '^' + pattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$';
try {
- return new RegExp(regexStr, 'i').test(command);
+ return globToRegExp(pattern).test(command);
} catch {
return command.startsWith(pattern.replace(/ \*$/, ''));
}
diff --git a/src/capabilities/shell/blocklist.test.ts b/src/capabilities/shell/blocklist.test.ts
new file mode 100644
index 00000000..93d38b54
--- /dev/null
+++ b/src/capabilities/shell/blocklist.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { BLOCKED_COMMANDS, NEEDS_APPROVAL_COMMANDS } from './blocklist.js';
+import { PermissionManager, globToRegExp } from '../permissions.js';
+
+const matches = (command: string, pattern: string) => globToRegExp(pattern).test(command);
+const blocked = (cmd: string) => BLOCKED_COMMANDS.some((p) => matches(cmd, p));
+const needsApproval = (cmd: string) => NEEDS_APPROVAL_COMMANDS.some((p) => matches(cmd, p));
+
+describe('shell blocklist — Windows / PowerShell gaps', () => {
+ it('blocks Set-ExecutionPolicy bare and wrapped in powershell/pwsh', () => {
+ expect(blocked('Set-ExecutionPolicy Unrestricted')).toBe(true);
+ expect(blocked('set-executionpolicy -Scope CurrentUser Bypass')).toBe(true);
+ expect(blocked('powershell -Command Set-ExecutionPolicy Bypass')).toBe(true);
+ expect(blocked('powershell.exe -NoProfile -c "Set-ExecutionPolicy Unrestricted -Force"')).toBe(true);
+ expect(blocked('pwsh -c Set-ExecutionPolicy RemoteSigned')).toBe(true);
+ expect(blocked('Get-ExecutionPolicy')).toBe(false);
+ });
+
+ it('blocks PowerShell recursive deletes of a drive root or home in either argument order', () => {
+ for (const cmd of [
+ 'Remove-Item -Recurse -Force C:\\',
+ 'Remove-Item -Recurse -Force C:\\*',
+ 'Remove-Item -Recurse -Force -Path C:\\',
+ 'Remove-Item C:\\ -Recurse',
+ 'Remove-Item C:\\* -Force -Recurse',
+ 'Remove-Item -Path C:\\ -Recurse -Force',
+ 'remove-item -r D:\\',
+ 'rm -r ~',
+ 'rm -rf ~\\*',
+ 'rm -Recurse -Force ~/*',
+ 'ri -r C:\\',
+ 'rmdir -Recurse C:\\',
+ 'rd -r ~',
+ 'del -Recurse -Force /',
+ 'erase -r /*',
+ ]) {
+ expect(blocked(cmd), cmd).toBe(true);
+ }
+ });
+
+ it('does not block relative-path recursive deletes inside a project (those need approval instead)', () => {
+ for (const cmd of [
+ 'Remove-Item -Recurse -Force node_modules',
+ 'rm -r build',
+ 'rm -rf ./node_modules',
+ 'Remove-Item .\\tmp -Recurse',
+ 'Remove-Item -Path .\\dist -Recurse -Force',
+ ]) {
+ expect(blocked(cmd), cmd).toBe(false);
+ expect(needsApproval(cmd), cmd).toBe(true);
+ }
+ // Absolute-path recursive deletes are blocked, mirroring the existing
+ // `rm -rf /*` and `del /s /q C:\*` policy on the other shells.
+ expect(blocked('Remove-Item -Recurse -Force C:\\Users\\jane\\proj\\dist')).toBe(true);
+ expect(blocked('rm -rf /home/jane/proj/dist')).toBe(true);
+ expect(blocked('rd /s /q C:\\Users\\jane\\proj\\dist')).toBe(true);
+ });
+
+ it('routes pwsh like powershell — approval, never auto-approve', () => {
+ expect(needsApproval('pwsh -c Get-ChildItem')).toBe(true);
+ expect(needsApproval('powershell -c Get-ChildItem')).toBe(true);
+ expect(blocked('pwsh -c Get-ChildItem')).toBe(false);
+ });
+
+ it('keeps the POSIX root/home forms and the cmd.exe `rd /s /q C:\\` gap closed', () => {
+ for (const cmd of ['rm -rf /', 'rm -fr ~', 'rm -rf /*', 'rd /s /q C:\\', 'rd /s /q C:\\*']) {
+ expect(blocked(cmd), cmd).toBe(true);
+ }
+ });
+
+ it('is what the default permission manifest enforces (not a parallel copy)', async () => {
+ const pm = new PermissionManager();
+ const manifestBlocked = pm.getManifest().capabilities.shell.blocked;
+ for (const pattern of BLOCKED_COMMANDS) expect(manifestBlocked).toContain(pattern);
+ await expect(pm.checkShellCommand('Set-ExecutionPolicy Unrestricted')).resolves.toMatchObject({ allowed: false });
+ await expect(pm.checkShellCommand('Remove-Item -Recurse -Force C:\\')).resolves.toMatchObject({ allowed: false });
+ });
+});
diff --git a/src/capabilities/shell/blocklist.ts b/src/capabilities/shell/blocklist.ts
index 17736cb1..b80d5137 100644
--- a/src/capabilities/shell/blocklist.ts
+++ b/src/capabilities/shell/blocklist.ts
@@ -1,3 +1,27 @@
+/**
+ * Shell command patterns. Matching is a case-insensitive glob over the whole
+ * command segment: `*` → any text, `?` → one character, everything else
+ * literal (see `globToRegExp` in ../permissions.ts).
+ */
+
+function windowsRecursiveDeleteRoots(): string[] {
+ const cmdlets = ['Remove-Item', 'rm', 'ri', 'rmdir', 'rd', 'del', 'erase'];
+ // Targets: drive root (`C:\`, `C:\*`), home (`~`, `~\`, `~/`), POSIX root.
+ const targets = ['?:\\', '?:\\*', '~', '~\\*', '~/*', '/', '/*'];
+ const out: string[] = [];
+ for (const cmd of cmdlets) {
+ for (const target of targets) {
+ out.push(`${cmd} -r* ${target}`); // Remove-Item -Recurse -Force C:\
+ out.push(`${cmd} -r* * ${target}`); // Remove-Item -Recurse -Force -Path C:\
+ out.push(`${cmd} ${target} -r*`); // Remove-Item C:\ -Recurse
+ out.push(`${cmd} ${target} * -r*`); // Remove-Item C:\ -Force -Recurse
+ out.push(`${cmd} -Path ${target} -r*`); // Remove-Item -Path C:\ -Recurse
+ out.push(`${cmd} -Path ${target} * -r*`);
+ }
+ }
+ return out;
+}
+
export const BLOCKED_COMMANDS = [
'sudo *',
'rm -rf /',
@@ -21,14 +45,27 @@ export const BLOCKED_COMMANDS = [
'kill -9 1',
'> /dev/sda',
'mv /* /dev/null',
+ // ── Windows / cmd.exe ──
'del /s /q C:\\*',
'rmdir /s /q C:\\*',
+ 'rd /s /q C:\\*',
'format *',
'icacls * C:\\* /grant',
'net user *',
'netsh *',
'reg delete *',
'cmd /c rd /s /q *',
+ // ── PowerShell ──
+ // Execution-policy changes disable the script-signing guard machine- or
+ // user-wide; never something an agent should flip. Covers the bare cmdlet
+ // and the `powershell -Command` / `pwsh -c` wrapped forms.
+ 'Set-ExecutionPolicy *',
+ 'powershell*Set-ExecutionPolicy *',
+ 'pwsh*Set-ExecutionPolicy *',
+ // Recursive deletes of a drive root, the home directory, or everything, in
+ // either argument order. `rm`, `ri`, `rmdir`, `rd`, `del`, `erase` are the
+ // PowerShell aliases of Remove-Item; `-r*` also matches `-Recurse`/`-rf`.
+ ...windowsRecursiveDeleteRoots(),
];
export const AUTO_APPROVED_COMMANDS = [
@@ -85,6 +122,9 @@ export const NEEDS_APPROVAL_COMMANDS = [
'robocopy *',
'del *',
'rd /s *',
+ 'Remove-Item *',
+ 'ri *',
'powershell *',
+ 'pwsh *',
'cmd /c *',
-];
\ No newline at end of file
+];
diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts
new file mode 100644
index 00000000..96c822c4
--- /dev/null
+++ b/src/cli/service.test.ts
@@ -0,0 +1,171 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import {
+ buildLaunchAgentPlist,
+ buildRunKeyAddCommand,
+ buildRunKeyDeleteCommand,
+ buildSchtasksCreateCommand,
+ buildSystemdUnit,
+ buildWindowsCommandLine,
+ buildWindowsTaskXml,
+ encodeWindowsTaskXml,
+ quoteWindowsArg,
+ resolveDistPath,
+ runKeyLaunchArgs,
+ WIN_RUN_KEY,
+ WIN_TASK_NAME,
+} from './service.js';
+
+/**
+ * Service-file contract: the strings handed to launchd / systemd / Task
+ * Scheduler / reg.exe must survive paths with spaces (Windows' default
+ * `C:\Program Files\nodejs\node.exe`), and the dist path must resolve from
+ * the real entry script on every npm layout — not from `bin/../lib`.
+ */
+
+const WIN_ARGS = [
+ 'C:\\Program Files\\nodejs\\node.exe',
+ 'C:\\Users\\Jane Doe\\AppData\\Roaming\\npm\\node_modules\\@cosmicstack\\mercury-agent\\dist\\index.js',
+ 'start',
+ '--daemon',
+];
+
+describe('Windows command-line quoting', () => {
+ it('quotes only the words that need it and escapes embedded quotes', () => {
+ expect(quoteWindowsArg('start')).toBe('start');
+ expect(quoteWindowsArg('C:\\Program Files\\nodejs\\node.exe')).toBe('"C:\\Program Files\\nodejs\\node.exe"');
+ expect(quoteWindowsArg('say "hi"')).toBe('"say \\"hi\\""');
+ expect(quoteWindowsArg('')).toBe('""');
+ });
+
+ it('builds the launch command line with spaced paths intact', () => {
+ expect(buildWindowsCommandLine(WIN_ARGS)).toBe(
+ '"C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Jane Doe\\AppData\\Roaming\\npm\\node_modules\\@cosmicstack\\mercury-agent\\dist\\index.js" start --daemon',
+ );
+ });
+
+ it('escapes the nested quotes inside schtasks /tr "…" (#13)', () => {
+ const cmd = buildSchtasksCreateCommand(WIN_ARGS);
+ expect(cmd).toBe(
+ `schtasks /create /tn "${WIN_TASK_NAME}" /tr "\\"C:\\Program Files\\nodejs\\node.exe\\" \\"C:\\Users\\Jane Doe\\AppData\\Roaming\\npm\\node_modules\\@cosmicstack\\mercury-agent\\dist\\index.js\\" start --daemon" /sc onlogon /rl limited /f`,
+ );
+ // The /tr payload is exactly one cmd.exe argument: every inner quote is escaped,
+ // so the only bare quotes are the ones wrapping /tn and /tr values.
+ const bareQuotes = cmd.replace(/\\"/g, '').match(/"/g) ?? [];
+ expect(bareQuotes).toHaveLength(4);
+ });
+
+ it('escapes the nested quotes in the HKCU Run `reg add /d "…"` payload', () => {
+ const cmd = buildRunKeyAddCommand(runKeyLaunchArgs(WIN_ARGS));
+ expect(cmd.startsWith(`reg add "${WIN_RUN_KEY}" /v MercuryAgent /t REG_SZ /d "`)).toBe(true);
+ expect(cmd.endsWith('" /f')).toBe(true);
+ expect(cmd).toContain('\\"C:\\Program Files\\nodejs\\node.exe\\" \\"C:\\Users\\Jane Doe\\');
+ // The Run entry launches `mercury start` (spawns the hidden daemon and
+ // exits) — never `--daemon`, which would pin a console window open.
+ expect(cmd).not.toContain('--daemon');
+ expect(cmd).toContain('index.js\\" start"');
+ expect(buildRunKeyDeleteCommand()).toBe(`reg delete "${WIN_RUN_KEY}" /v MercuryAgent /f`);
+ });
+});
+
+describe('Windows Task Scheduler XML', () => {
+ it('separates Command from Arguments, scopes the logon trigger, and sets restart-on-failure', () => {
+ const xml = buildWindowsTaskXml(WIN_ARGS, { workingDirectory: 'C:\\Users\\Jane Doe', userId: 'DESKTOP\\Jane Doe' });
+ expect(xml).toContain('<Command>C:\\Program Files\\nodejs\\node.exe</Command>');
+ expect(xml).toContain(
+ '<Arguments>&quot;C:\\Users\\Jane Doe\\AppData\\Roaming\\npm\\node_modules\\@cosmicstack\\mercury-agent\\dist\\index.js&quot; start --daemon</Arguments>',
+ );
+ expect(xml).toContain('<WorkingDirectory>C:\\Users\\Jane Doe</WorkingDirectory>');
+ expect(xml).toContain('<LogonTrigger>');
+ expect(xml).toContain('<UserId>DESKTOP\\Jane Doe</UserId>');
+ expect(xml).toContain('<RunLevel>LeastPrivilege</RunLevel>');
+ expect(xml).toContain('<LogonType>InteractiveToken</LogonType>');
+ // Crash recovery + no 72h kill + single instance.
+ expect(xml).toMatch(/<RestartOnFailure>\s*<Interval>PT1M<\/Interval>\s*<Count>3<\/Count>\s*<\/RestartOnFailure>/);
+ expect(xml).toContain('<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>');
+ expect(xml).toContain('<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>');
+ });
+
+ it('omits UserId when the account is unknown and XML-escapes the description', () => {
+ const xml = buildWindowsTaskXml(WIN_ARGS, { workingDirectory: 'C:\\', description: 'A & B <c>' });
+ expect(xml).not.toContain('<UserId>');
+ expect(xml).toContain('<Description>A &amp; B &lt;c&gt;</Description>');
+ });
+
+ it('encodes the task file as UTF-16LE with a BOM (what schtasks /xml reads)', () => {
+ const buf = encodeWindowsTaskXml('<Task/>');
+ expect(buf[0]).toBe(0xff);
+ expect(buf[1]).toBe(0xfe);
+ expect(buf.toString('utf16le').slice(1)).toBe('<Task/>');
+ });
+});
+
+describe('launchd plist and systemd unit', () => {
+ const opts = { mercuryHome: '/Users/jane/.mercury', userHome: '/Users/jane', pathEnv: '/usr/local/bin:/usr/bin:/bin' };
+ const args = ['/usr/local/bin/node', '/usr/local/lib/node_modules/@cosmicstack/mercury-agent/dist/index.js', 'start', '--daemon'];
+
+ it('plist lists every launch word as its own <string> and wires logs/env', () => {
+ const plist = buildLaunchAgentPlist(args, opts);
+ expect(plist).toContain('<string>com.cosmicstack.mercury</string>');
+ for (const a of args) expect(plist).toContain(` <string>${a}</string>`);
+ expect(plist).toContain('<string>/Users/jane/.mercury/daemon.log</string>');
+ expect(plist).toContain('<string>/Users/jane/.mercury/daemon-error.log</string>');
+ expect(plist).toContain('<key>HOME</key>\n <string>/Users/jane</string>');
+ expect(plist).toMatch(/<key>KeepAlive<\/key>\s*<dict>\s*<key>SuccessfulExit<\/key>\s*<false\/>/);
+ });
+
+ it('plist XML-escapes a path with an ampersand', () => {
+ const plist = buildLaunchAgentPlist(['/opt/a&b/node', 'start'], opts);
+ expect(plist).toContain('<string>/opt/a&amp;b/node</string>');
+ });
+
+ it('systemd unit quotes ExecStart words that contain spaces', () => {
+ const unit = buildSystemdUnit(['/opt/my node/bin/node', '/opt/mercury/dist/index.js', 'start', '--daemon'], opts);
+ expect(unit).toContain('ExecStart="/opt/my node/bin/node" /opt/mercury/dist/index.js start --daemon');
+ expect(unit).toContain('Restart=on-failure');
+ expect(unit).toContain('StandardOutput=append:/Users/jane/.mercury/daemon.log');
+ expect(unit).toContain('WantedBy=default.target');
+ });
+});
+
+describe('resolveDistPath', () => {
+ let root: string;
+ afterEach(() => { if (root) rmSync(root, { recursive: true, force: true }); });
+
+ it('follows the POSIX npm bin symlink to the real dist/index.js', () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'mercury-dist-posix-')));
+ const dist = join(root, 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist');
+ mkdirSync(dist, { recursive: true });
+ mkdirSync(join(root, 'bin'));
+ writeFileSync(join(dist, 'index.js'), '// entry');
+ symlinkSync(join('..', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js'), join(root, 'bin', 'mercury'));
+ expect(resolveDistPath(join(root, 'bin', 'mercury'))).toBe(join(dist, 'index.js'));
+ });
+
+ it('resolves the Windows npm layout, where argv[1] is already the real dist/index.js (no bin/../lib)', () => {
+ // %APPDATA%\npm\node_modules\... — the .cmd shim hands node the real file.
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'mercury-dist-win-')));
+ const dist = join(root, 'npm', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist');
+ mkdirSync(dist, { recursive: true });
+ writeFileSync(join(dist, 'index.js'), '// entry');
+ const resolved = resolveDistPath(join(dist, 'index.js'));
+ expect(resolved).toBe(join(dist, 'index.js'));
+ expect(resolved).not.toContain(join('npm', '..', 'lib'));
+ });
+
+ it('falls back to the module location when argv[1] is not a real file (bun-virtual path)', () => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-dist-self-'));
+ const self = join(root, 'dist', 'index.js');
+ mkdirSync(join(root, 'dist'));
+ writeFileSync(self, '// bundle');
+ expect(resolveDistPath('/$bunfs/root/mercury', pathToFileURL(self).href)).toBe(self);
+ });
+
+ it('falls back to the nvm guess when nothing else resolves', () => {
+ const guess = resolveDistPath(undefined, 'file:///nowhere/src/cli/service.ts', 'v20.11.0');
+ expect(guess.endsWith(join('.nvm', 'versions', 'node', 'v20.11.0', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js'))).toBe(true);
+ });
+});
diff --git a/src/cli/service.ts b/src/cli/service.ts
index 405aa02b..bb9a22fb 100644
--- a/src/cli/service.ts
+++ b/src/cli/service.ts
@@ -1,16 +1,32 @@
-import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs';
+import { existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync } from 'node:fs';
import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import chalk from 'chalk';
import { execSync } from 'node:child_process';
import { getMercuryHome } from '../utils/config.js';
import { logger } from '../utils/logger.js';
-import { isStandaloneBinary } from './daemon.js';
+import { isStandaloneBinary, getDaemonStatus, tryAutoDaemonize } from './daemon.js';
import { isTermux } from '../utils/platform.js';
-const SERVICE_NAME = 'mercury';
const SERVICE_DESC = 'Mercury — Soul-Driven AI Agent';
-const WIN_TASK_NAME = 'MercuryAgent';
+export const WIN_TASK_NAME = 'MercuryAgent';
+/** Per-user autostart key — writable without elevation. */
+export const WIN_RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
+export const WIN_RUN_VALUE = 'MercuryAgent';
+const WIN_TASK_XML_FILE = 'MercuryAgent.task.xml';
+
+/**
+ * How Mercury autostarts on Windows:
+ * - `task`: a Task Scheduler logon task (`schtasks /create /xml`) — the
+ * preferred form: Task Scheduler tracks the daemon process, restarts it
+ * on failure, and `schtasks /end` stops it.
+ * - `run-key`: an `HKCU\...\Run` entry. Fallback for standard (non-admin)
+ * users, for whom logon-triggered tasks are refused with "Access is
+ * denied". No restart-on-failure; the entry launches `mercury start`,
+ * which spawns the hidden daemon and exits.
+ */
+export type WindowsServiceMode = 'task' | 'run-key';
export function isServiceInstalled(): boolean {
const platform = process.platform;
@@ -22,12 +38,7 @@ export function isServiceInstalled(): boolean {
} else if (platform === 'linux') {
return existsSync(join(homedir(), '.config', 'systemd', 'user', 'mercury.service'));
} else if (platform === 'win32') {
- try {
- execSync(`schtasks /query /tn "${WIN_TASK_NAME}"`, { stdio: 'pipe', shell: 'cmd.exe' });
- return true;
- } catch {
- return false;
- }
+ return getWindowsServiceMode() !== null;
}
return false;
}
@@ -45,6 +56,10 @@ export function isServiceRunning(): boolean {
return true;
}
if (process.platform === 'win32') {
+ if (getWindowsServiceMode() === 'run-key') {
+ // The Run entry only launches the daemon; its liveness is the pid file.
+ return getDaemonStatus().running;
+ }
const output = execSync(`schtasks /query /tn "${WIN_TASK_NAME}" /fo list /v`, { encoding: 'utf-8', shell: 'cmd.exe' });
return /^Status:\s+Running\s*$/im.test(output);
}
@@ -56,11 +71,40 @@ function getNodeBinPath(): string {
return process.execPath;
}
-function getDistPath(): string {
- if (!process.argv[1]) {
- return join(homedir(), '.nvm', 'versions', 'node', `v${process.version.slice(1)}`, 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');
+/**
+ * Resolve the on-disk `dist/index.js` a service file should launch.
+ *
+ * `argv[1]` is the entry script as invoked: on POSIX npm installs that is the
+ * `bin/mercury` symlink (→ `lib/node_modules/@cosmicstack/mercury-agent/dist/
+ * index.js`), on Windows npm installs the `.cmd` shim already hands node the
+ * real `%APPDATA%\npm\node_modules\...\dist\index.js`. `realpathSync` folds
+ * both into the real file, so no layout assumption (`bin/../lib/...`) is
+ * needed. Fallbacks: this module's own location (the bundle IS dist/index.js),
+ * then the legacy nvm guess.
+ */
+export function resolveDistPath(
+ argv1: string | undefined,
+ moduleUrl: string = import.meta.url,
+ nodeVersion: string = process.version,
+): string {
+ if (argv1) {
+ try {
+ return realpathSync(argv1);
+ } catch {
+ // argv[1] is not a real file (bun-virtual path, deleted shim) — fall through.
+ }
+ }
+ try {
+ const self = fileURLToPath(moduleUrl);
+ if (/[\\/]dist[\\/]index\.(?:m?js|cjs)$/i.test(self) && existsSync(self)) return self;
+ } catch {
+ // not a file: URL (unusual bundler) — fall through.
}
- return join(process.argv[1], '..', '..', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');
+ return join(homedir(), '.nvm', 'versions', 'node', `v${nodeVersion.replace(/^v/, '')}`, 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');
+}
+
+function getDistPath(): string {
+ return resolveDistPath(process.argv[1]);
}
/**
@@ -97,7 +141,7 @@ export function installService(): boolean {
} else if (platform === 'linux') {
installLinux();
} else if (platform === 'win32') {
- installWindows();
+ return installWindows() !== null;
} else {
console.log(chalk.yellow(` System service is not supported on this platform (${platform}).`));
console.log(chalk.dim(' Run `mercury up` manually to start the daemon for this session.'));
@@ -166,12 +210,9 @@ export function teardownService(): { removed: boolean; path?: string; hint?: str
}
if (platform === 'win32') {
- try {
- execSync(`schtasks /delete /tn "${WIN_TASK_NAME}" /f`, { stdio: 'pipe', shell: 'cmd.exe' });
- return { removed: true, path: `scheduled task ${WIN_TASK_NAME}` };
- } catch {
- return { removed: false };
- }
+ const removed = removeWindowsAutostart();
+ if (removed.length === 0) return { removed: false };
+ return { removed: true, path: removed.join(' + ') };
}
return { removed: false, hint: `Unsupported platform for service teardown: ${platform}` };
@@ -215,6 +256,12 @@ export function restartService(): void {
}
if (process.platform === 'win32') {
+ if (getWindowsServiceMode() === 'run-key') {
+ // No scheduler owns the process: stop the tracked daemon, respawn it.
+ stopTrackedDaemonSync();
+ if (!tryAutoDaemonize()) throw new Error('Failed to respawn the Mercury daemon');
+ return;
+ }
try {
execSync(`schtasks /end /tn "${WIN_TASK_NAME}"`, { stdio: 'pipe', shell: 'cmd.exe' });
} catch {}
@@ -238,6 +285,10 @@ export function stopService(): boolean {
return !isServiceRunning();
}
if (process.platform === 'win32') {
+ if (getWindowsServiceMode() === 'run-key') {
+ stopTrackedDaemonSync();
+ return !isServiceRunning();
+ }
try { execSync(`schtasks /end /tn "${WIN_TASK_NAME}"`, { stdio: 'inherit', shell: 'cmd.exe' }); } catch {}
return waitForServiceStop();
}
@@ -254,6 +305,22 @@ function waitForServiceStop(): boolean {
return !isServiceRunning();
}
+/**
+ * Synchronous stop of the pid-file daemon (Windows run-key mode only). The
+ * async, graceful path is `stopDaemon()` in daemon.ts — callers that can
+ * await should use that; this is the sync fallback for `stopService()`.
+ */
+function stopTrackedDaemonSync(): void {
+ const status = getDaemonStatus();
+ if (!status.running || !status.pid) return;
+ try { process.kill(status.pid); } catch { return; }
+ const deadline = Date.now() + 5_000;
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
+ while (Date.now() < deadline && getDaemonStatus().running) {
+ Atomics.wait(waitBuffer, 0, 0, 100);
+ }
+}
+
function showTermuxServiceHelp(action: 'install' | 'uninstall' | 'status'): void {
console.log('');
console.log(chalk.yellow(` System service ${action} is not supported on Termux yet (no systemd on Android).`));
@@ -264,24 +331,32 @@ function showTermuxServiceHelp(action: 'install' | 'uninstall' | 'status'): void
console.log('');
}
-function installMac(): void {
- const plistDir = join(homedir(), 'Library', 'LaunchAgents');
- const plistPath = join(plistDir, 'com.cosmicstack.mercury.plist');
+// ─── Service file builders (pure; unit-tested) ───────────────────────────────
- if (!existsSync(plistDir)) {
- mkdirSync(plistDir, { recursive: true });
- }
+export interface ServiceFileOptions {
+ /** Where daemon stdout/stderr go (`~/.mercury`). */
+ mercuryHome: string;
+ /** Account home — WorkingDirectory and HOME for the daemon. */
+ userHome: string;
+ /** PATH the daemon inherits. */
+ pathEnv: string;
+}
- const nodeBin = getNodeBinPath();
- const scriptPath = getDistPath();
- const home = getMercuryHome();
- const logPath = join(home, 'daemon.log');
- const errPath = join(home, 'daemon-error.log');
+function xmlEscape(value: string): string {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
- const launchArgs = getServiceLaunchArgs();
- const programArgsXml = launchArgs.map((a) => ` <string>${a}</string>`).join('\n');
+/** macOS LaunchAgent plist for the given launch argv. */
+export function buildLaunchAgentPlist(launchArgs: string[], opts: ServiceFileOptions): string {
+ const logPath = join(opts.mercuryHome, 'daemon.log');
+ const errPath = join(opts.mercuryHome, 'daemon-error.log');
+ const programArgsXml = launchArgs.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
+ 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>
@@ -299,20 +374,193 @@ ${programArgsXml}
<false/>
</dict>
<key>StandardOutPath</key>
- <string>${logPath}</string>
+ <string>${xmlEscape(logPath)}</string>
<key>StandardErrorPath</key>
- <string>${errPath}</string>
+ <string>${xmlEscape(errPath)}</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
- <string>${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}</string>
+ <string>${xmlEscape(opts.pathEnv)}</string>
<key>HOME</key>
- <string>${homedir()}</string>
+ <string>${xmlEscape(opts.userHome)}</string>
</dict>
<key>WorkingDirectory</key>
- <string>${homedir()}</string>
+ <string>${xmlEscape(opts.userHome)}</string>
</dict>
</plist>`;
+}
+
+/** Quote one ExecStart= word per systemd.service(5) (double quotes, `\"` inside). */
+function quoteSystemdWord(arg: string): string {
+ return /[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg;
+}
+
+/** systemd --user unit for the given launch argv. */
+export function buildSystemdUnit(launchArgs: string[], opts: ServiceFileOptions): string {
+ const execStart = launchArgs.map(quoteSystemdWord).join(' ');
+ return `[Unit]
+Description=${SERVICE_DESC}
+After=network.target
+
+[Service]
+Type=simple
+ExecStart=${execStart}
+Restart=on-failure
+RestartSec=5
+Environment=PATH=${opts.pathEnv}
+Environment=HOME=${opts.userHome}
+WorkingDirectory=${opts.userHome}
+StandardOutput=append:${join(opts.mercuryHome, 'daemon.log')}
+StandardError=append:${join(opts.mercuryHome, 'daemon-error.log')}
+
+[Install]
+WantedBy=default.target`;
+}
+
+/**
+ * Quote one argv word for a Windows command line (CreateProcess rules as
+ * read by node.exe / the CRT): wrap in double quotes when it has whitespace
+ * or quotes, escape embedded quotes as `\"`.
+ */
+export function quoteWindowsArg(arg: string): string {
+ if (arg.length === 0) return '""';
+ if (!/[\s"]/.test(arg)) return arg;
+ return `"${arg.replace(/"/g, '\\"')}"`;
+}
+
+/** A full Windows command line for the launch argv (what the daemon is started with). */
+export function buildWindowsCommandLine(launchArgs: string[]): string {
+ return launchArgs.map(quoteWindowsArg).join(' ');
+}
+
+/**
+ * `schtasks /create ... /tr "<command line>"` for cmd.exe. The `/tr` payload
+ * is itself a quoted cmd.exe argument, so the launch command line's own
+ * quotes must be escaped as `\"` inside it — otherwise a `node.exe` under
+ * `C:\Program Files` splits the task into `C:\Program` + garbage.
+ * Kept as the manual-fallback hint; the install path uses the XML form.
+ */
+export function buildSchtasksCreateCommand(launchArgs: string[], taskName: string = WIN_TASK_NAME): string {
+ const tr = buildWindowsCommandLine(launchArgs).replace(/"/g, '\\"');
+ return `schtasks /create /tn "${taskName}" /tr "${tr}" /sc onlogon /rl limited /f`;
+}
+
+export interface WindowsTaskOptions {
+ /** WorkingDirectory for the daemon (account home). */
+ workingDirectory: string;
+ /** `DOMAIN\user` the logon trigger is scoped to; omitted → any user logon. */
+ userId?: string;
+ description?: string;
+}
+
+/**
+ * Task Scheduler task definition for `schtasks /create /xml`. Command and
+ * Arguments are separate XML elements, so the quoting trap of `/tr` cannot
+ * recur, and the XML form is the only way to set what `/sc onlogon` cannot:
+ * - RestartOnFailure (3 tries, 1 min apart) — crash recovery;
+ * - ExecutionTimeLimit PT0S — the `/create` default (PT72H) would kill the
+ * daemon after three days;
+ * - MultipleInstancesPolicy IgnoreNew — one daemon per user.
+ * Runs with the interactive token at least privilege (no elevation prompt).
+ */
+export function buildWindowsTaskXml(launchArgs: string[], opts: WindowsTaskOptions): string {
+ const [command, ...rest] = launchArgs;
+ const userIdXml = opts.userId ? `\n <UserId>${xmlEscape(opts.userId)}</UserId>` : '';
+ return `<?xml version="1.0" encoding="UTF-16"?>
+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
+ <RegistrationInfo>
+ <Description>${xmlEscape(opts.description ?? SERVICE_DESC)}</Description>
+ </RegistrationInfo>
+ <Triggers>
+ <LogonTrigger>
+ <Enabled>true</Enabled>${userIdXml}
+ </LogonTrigger>
+ </Triggers>
+ <Principals>
+ <Principal id="Author">
+ <LogonType>InteractiveToken</LogonType>
+ <RunLevel>LeastPrivilege</RunLevel>
+ </Principal>
+ </Principals>
+ <Settings>
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
+ <AllowHardTerminate>true</AllowHardTerminate>
+ <StartWhenAvailable>true</StartWhenAvailable>
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
+ <AllowStartOnDemand>true</AllowStartOnDemand>
+ <Enabled>true</Enabled>
+ <Hidden>false</Hidden>
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
+ <WakeToRun>false</WakeToRun>
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
+ <Priority>7</Priority>
+ <RestartOnFailure>
+ <Interval>PT1M</Interval>
+ <Count>3</Count>
+ </RestartOnFailure>
+ </Settings>
+ <Actions Context="Author">
+ <Exec>
+ <Command>${xmlEscape(command)}</Command>
+ <Arguments>${xmlEscape(buildWindowsCommandLine(rest))}</Arguments>
+ <WorkingDirectory>${xmlEscape(opts.workingDirectory)}</WorkingDirectory>
+ </Exec>
+ </Actions>
+</Task>`;
+}
+
+/** `schtasks /create /xml` must read UTF-16LE with a BOM. */
+export function encodeWindowsTaskXml(xml: string): Buffer {
+ return Buffer.from(`\uFEFF${xml}`, 'utf16le');
+}
+
+/**
+ * `reg add` for the per-user Run key (no elevation). The `/d` payload is a
+ * quoted cmd.exe argument; reg.exe reads `\"` as a literal quote.
+ */
+export function buildRunKeyAddCommand(launchArgs: string[]): string {
+ const data = buildWindowsCommandLine(launchArgs).replace(/"/g, '\\"');
+ return `reg add "${WIN_RUN_KEY}" /v ${WIN_RUN_VALUE} /t REG_SZ /d "${data}" /f`;
+}
+
+export function buildRunKeyDeleteCommand(): string {
+ return `reg delete "${WIN_RUN_KEY}" /v ${WIN_RUN_VALUE} /f`;
+}
+
+/**
+ * Launch argv for the Run-key fallback: `mercury start` (no `--daemon`)
+ * spawns the hidden, detached daemon and exits, so the login console window
+ * only flashes instead of staying open for the daemon's lifetime. A direct
+ * `--daemon` launch (what the scheduled task uses, so Task Scheduler owns the
+ * process) would leave a visible console at every logon.
+ */
+export function runKeyLaunchArgs(serviceLaunchArgs: string[]): string[] {
+ return serviceLaunchArgs.filter((a) => a !== '--daemon');
+}
+
+// ─── macOS ───────────────────────────────────────────────────────────────────
+
+function serviceFileOptions(): ServiceFileOptions {
+ return {
+ mercuryHome: getMercuryHome(),
+ userHome: homedir(),
+ pathEnv: process.env.PATH || '/usr/local/bin:/usr/bin:/bin',
+ };
+}
+
+function installMac(): void {
+ const plistDir = join(homedir(), 'Library', 'LaunchAgents');
+ const plistPath = join(plistDir, 'com.cosmicstack.mercury.plist');
+
+ if (!existsSync(plistDir)) {
+ mkdirSync(plistDir, { recursive: true });
+ }
+
+ const opts = serviceFileOptions();
+ const logPath = join(opts.mercuryHome, 'daemon.log');
+ const plist = buildLaunchAgentPlist(getServiceLaunchArgs(), opts);
writeFileSync(plistPath, plist, 'utf-8');
@@ -381,6 +629,8 @@ function showMacStatus(): void {
console.log('');
}
+// ─── Linux ───────────────────────────────────────────────────────────────────
+
function installLinux(): void {
const systemdDir = join(homedir(), '.config', 'systemd', 'user');
@@ -389,31 +639,8 @@ function installLinux(): void {
}
const servicePath = join(systemdDir, 'mercury.service');
- const nodeBin = getNodeBinPath();
- const scriptPath = getDistPath();
- const home = getMercuryHome();
-
- const execStart = getServiceLaunchArgs()
- .map((a) => (/[\s"]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a))
- .join(' ');
-
- const service = `[Unit]
-Description=${SERVICE_DESC}
-After=network.target
-
-[Service]
-Type=simple
-ExecStart=${execStart}
-Restart=on-failure
-RestartSec=5
-Environment=PATH=${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}
-Environment=HOME=${homedir()}
-WorkingDirectory=${homedir()}
-StandardOutput=append:${join(home, 'daemon.log')}
-StandardError=append:${join(home, 'daemon-error.log')}
-
-[Install]
-WantedBy=default.target`;
+ const opts = serviceFileOptions();
+ const service = buildSystemdUnit(getServiceLaunchArgs(), opts);
writeFileSync(servicePath, service, 'utf-8');
@@ -438,7 +665,7 @@ WantedBy=default.target`;
console.log('');
console.log(chalk.green(' Mercury service installed (systemd --user)'));
console.log(chalk.dim(` Service: ${servicePath}`));
- console.log(chalk.dim(` Logs: ${join(home, 'daemon.log')}`));
+ console.log(chalk.dim(` Logs: ${join(opts.mercuryHome, 'daemon.log')}`));
console.log(chalk.dim(' Auto-starts on login. Auto-restarts on crash (5s delay).'));
console.log('');
console.log(chalk.dim(' Uninstall: mercury service uninstall'));
@@ -497,65 +724,193 @@ function showLinuxStatus(): void {
console.log('');
}
-function installWindows(): void {
- const nodeBin = getNodeBinPath();
- const scriptPath = getDistPath();
+// ─── Windows ─────────────────────────────────────────────────────────────────
+
+function windowsTaskExists(): boolean {
+ try {
+ execSync(`schtasks /query /tn "${WIN_TASK_NAME}"`, { stdio: 'pipe', shell: 'cmd.exe' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function windowsRunKeyExists(): boolean {
+ try {
+ execSync(`reg query "${WIN_RUN_KEY}" /v ${WIN_RUN_VALUE}`, { stdio: 'pipe', shell: 'cmd.exe' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Which autostart form is installed (task wins when both exist). */
+export function getWindowsServiceMode(): WindowsServiceMode | null {
+ if (process.platform !== 'win32') return null;
+ if (windowsTaskExists()) return 'task';
+ if (windowsRunKeyExists()) return 'run-key';
+ return null;
+}
+
+/** Remove every autostart form; returns the labels of what was removed. */
+function removeWindowsAutostart(): string[] {
+ const removed: string[] = [];
+ if (windowsTaskExists()) {
+ try {
+ execSync(`schtasks /delete /tn "${WIN_TASK_NAME}" /f`, { stdio: 'pipe', shell: 'cmd.exe' });
+ removed.push(`scheduled task ${WIN_TASK_NAME}`);
+ } catch {}
+ }
+ if (windowsRunKeyExists()) {
+ try {
+ execSync(buildRunKeyDeleteCommand(), { stdio: 'pipe', shell: 'cmd.exe' });
+ removed.push(`${WIN_RUN_KEY}\\${WIN_RUN_VALUE}`);
+ } catch {}
+ }
+ try { unlinkSync(join(getMercuryHome(), WIN_TASK_XML_FILE)); } catch {}
+ return removed;
+}
+
+function windowsUserId(): string | undefined {
+ const user = process.env.USERNAME;
+ if (!user) return undefined;
+ const domain = process.env.USERDOMAIN;
+ return domain ? `${domain}\\${user}` : user;
+}
+
+function errorText(err: unknown): string {
+ const e = err as { stderr?: Buffer | string; stdout?: Buffer | string; message?: string };
+ const out = [e?.stderr, e?.stdout].map((b) => (b ? String(b) : '')).join(' ').trim();
+ return (out || e?.message || String(err)).replace(/\s+/g, ' ').trim();
+}
+
+/**
+ * Install the Windows autostart. Tries the Task Scheduler logon task (XML
+ * definition: proper quoting, restart-on-failure, no 72h time limit). When
+ * Task Scheduler refuses — logon triggers need elevation for standard
+ * users ("Access is denied") — falls back to an HKCU Run entry, which any
+ * user can write. Reports which form was installed. Returns the mode, or
+ * null when neither could be installed.
+ */
+function installWindows(): WindowsServiceMode | null {
const home = getMercuryHome();
const logPath = join(home, 'daemon.log');
+ const launchArgs = getServiceLaunchArgs();
+ const schtasksHint = buildSchtasksCreateCommand(launchArgs);
+
+ if (!existsSync(home)) mkdirSync(home, { recursive: true });
- const cmd = getServiceLaunchArgs().map((a) => `"${a}"`).join(' ');
+ // A previous fallback install must not double-start the daemon.
+ const hadRunKey = windowsRunKeyExists();
+ let taskError = '';
+ const xmlPath = join(home, WIN_TASK_XML_FILE);
try {
- execSync(
- `schtasks /create /tn "${WIN_TASK_NAME}" /tr "${cmd}" /sc onlogon /rl limited /f`,
- { stdio: 'inherit', shell: 'cmd.exe' }
- );
- } catch {
- console.log(chalk.yellow(' schtasks create failed. Try running from an Administrator cmd:'));
- console.log(chalk.dim(` schtasks /create /tn "${WIN_TASK_NAME}" /tr "${cmd}" /sc onlogon /rl limited /f`));
+ const xml = buildWindowsTaskXml(launchArgs, { workingDirectory: homedir(), userId: windowsUserId() });
+ writeFileSync(xmlPath, encodeWindowsTaskXml(xml));
+ execSync(`schtasks /create /tn "${WIN_TASK_NAME}" /xml "${xmlPath}" /f`, { stdio: 'pipe', shell: 'cmd.exe' });
+ } catch (err) {
+ taskError = errorText(err);
+ logger.debug({ err: taskError }, 'schtasks /create /xml failed; trying HKCU Run fallback');
}
+ if (!taskError) {
+ if (hadRunKey) {
+ try { execSync(buildRunKeyDeleteCommand(), { stdio: 'pipe', shell: 'cmd.exe' }); } catch {}
+ }
+ try {
+ execSync(`schtasks /run /tn "${WIN_TASK_NAME}"`, { stdio: 'pipe', shell: 'cmd.exe' });
+ } catch {
+ console.log(chalk.yellow(' Task created but failed to start immediately. It will start on next login.'));
+ }
+
+ console.log('');
+ console.log(chalk.green(' Mercury service installed (Windows Task Scheduler)'));
+ console.log(chalk.dim(` Task: ${WIN_TASK_NAME}`));
+ console.log(chalk.dim(' Trigger: on logon'));
+ console.log(chalk.dim(` Logs: ${logPath}`));
+ console.log(chalk.dim(' Auto-starts on login. Auto-restarts on crash (3 tries, 1 min apart).'));
+ console.log('');
+ console.log(chalk.dim(' Uninstall: mercury service uninstall'));
+ console.log('');
+ return 'task';
+ }
+
+ const denied = /access is denied|0x80070005|E_ACCESSDENIED/i.test(taskError);
+ console.log(chalk.yellow(` Task Scheduler refused the logon task${denied ? ' (needs an elevated prompt for standard users)' : ''}:`));
+ console.log(chalk.dim(` ${taskError}`));
+ console.log(chalk.dim(' Falling back to a per-user startup entry (HKCU Run key — no elevation needed).'));
+
try {
- execSync(`schtasks /run /tn "${WIN_TASK_NAME}"`, { stdio: 'inherit', shell: 'cmd.exe' });
- } catch {
- console.log(chalk.yellow(' Task created but failed to start immediately. It will start on next login.'));
+ execSync(buildRunKeyAddCommand(runKeyLaunchArgs(launchArgs)), { stdio: 'pipe', shell: 'cmd.exe' });
+ } catch (err) {
+ console.log(chalk.red(` Could not write the startup entry either: ${errorText(err)}`));
+ console.log(chalk.yellow(' Install the scheduled task from an Administrator prompt:'));
+ console.log(chalk.dim(` ${schtasksHint}`));
+ console.log(chalk.dim(' Mercury will still run for this session; run `mercury up` after each login until then.'));
+ console.log('');
+ return null;
+ }
+
+ if (!getDaemonStatus().running) {
+ if (!tryAutoDaemonize()) {
+ console.log(chalk.yellow(' Startup entry written but the daemon failed to start now. It will start on next login.'));
+ }
}
console.log('');
- console.log(chalk.green(' Mercury service installed (Windows Task Scheduler)'));
- console.log(chalk.dim(` Task: ${WIN_TASK_NAME}`));
- console.log(chalk.dim(` Trigger: on logon`));
+ console.log(chalk.green(' Mercury autostart installed (Windows Run key — standard user)'));
+ console.log(chalk.dim(` Entry: ${WIN_RUN_KEY}\\${WIN_RUN_VALUE}`));
+ console.log(chalk.dim(' Trigger: on logon'));
console.log(chalk.dim(` Logs: ${logPath}`));
- console.log(chalk.dim(' Auto-starts on login. Use --daemon flag for crash recovery.'));
+ console.log(chalk.yellow(' Auto-starts on login. No crash recovery in this mode — for restart-on-failure,'));
+ console.log(chalk.yellow(' run `mercury service install` from an Administrator prompt (installs a scheduled task).'));
console.log('');
console.log(chalk.dim(' Uninstall: mercury service uninstall'));
console.log('');
+ return 'run-key';
}
function uninstallWindows(): void {
- try {
- execSync(`schtasks /delete /tn "${WIN_TASK_NAME}" /f`, { stdio: 'inherit', shell: 'cmd.exe' });
- console.log('');
- console.log(chalk.green(' Mercury service uninstalled'));
- console.log('');
- } catch {
- console.log(chalk.yellow(' Task not found or failed to delete. Remove manually:'));
+ const removed = removeWindowsAutostart();
+ if (removed.length === 0) {
+ console.log(chalk.yellow(' Mercury autostart not found or failed to delete. Remove manually:'));
console.log(chalk.dim(` schtasks /delete /tn "${WIN_TASK_NAME}" /f`));
+ console.log(chalk.dim(` ${buildRunKeyDeleteCommand()}`));
console.log('');
+ return;
}
+ console.log('');
+ console.log(chalk.green(' Mercury service uninstalled'));
+ for (const label of removed) console.log(chalk.dim(` Removed: ${label}`));
+ console.log('');
}
function showWindowsStatus(): void {
- try {
- const output = execSync(`schtasks /query /tn "${WIN_TASK_NAME}" /fo list`, {
- encoding: 'utf-8',
- shell: 'cmd.exe',
- }).trim();
- console.log(output);
- console.log('');
- } catch {
- console.log(chalk.yellow(' Mercury service is not installed.'));
- console.log(chalk.dim(' Run `mercury service install` to set it up.'));
+ const mode = getWindowsServiceMode();
+ if (mode === 'task') {
+ try {
+ const output = execSync(`schtasks /query /tn "${WIN_TASK_NAME}" /fo list`, {
+ encoding: 'utf-8',
+ shell: 'cmd.exe',
+ }).trim();
+ console.log(` ${chalk.green('Autostart: Task Scheduler logon task')}`);
+ console.log(output);
+ console.log('');
+ return;
+ } catch {
+ // fall through to the generic message
+ }
+ }
+ if (mode === 'run-key') {
+ const daemon = getDaemonStatus();
+ console.log(` ${chalk.green('Autostart: HKCU Run entry')} ${chalk.dim(`(${WIN_RUN_KEY}\\${WIN_RUN_VALUE})`)}`);
+ console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.yellow('not running')}`);
+ console.log(chalk.dim(' No crash recovery in this mode; an Administrator `mercury service install` upgrades it to a scheduled task.'));
console.log('');
+ return;
}
+ console.log(chalk.yellow(' Mercury service is not installed.'));
+ console.log(chalk.dim(' Run `mercury service install` to set it up.'));
+ console.log('');
}