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(service): Termux:Boot autostart for `mercury service install` (P2.8)

Salman Qureshi581b504e98c6
diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts
index 96c822c4..55acd559 100644
--- a/src/cli/service.test.ts
+++ b/src/cli/service.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, it } from 'vitest';
-import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -10,8 +10,19 @@ import {
buildSchtasksCreateCommand,
buildSystemdUnit,
buildWindowsCommandLine,
+ buildTermuxBootScript,
buildWindowsTaskXml,
encodeWindowsTaskXml,
+ installService,
+ isServiceInstalled,
+ isServiceRunning,
+ removeTermuxBootScript,
+ showServiceStatus,
+ stopService,
+ teardownService,
+ termuxBootScriptPath,
+ uninstallService,
+ writeTermuxBootScript,
quoteWindowsArg,
resolveDistPath,
runKeyLaunchArgs,
@@ -169,3 +180,124 @@ describe('resolveDistPath', () => {
expect(guess.endsWith(join('.nvm', 'versions', 'node', 'v20.11.0', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js'))).toBe(true);
});
});
+
+describe('Termux:Boot script (P2.8)', () => {
+ const opts = { prefix: '/data/data/com.termux/files/usr', mercuryHome: '/data/data/com.termux/files/home/.mercury' };
+
+ it('uses the Termux shell, takes a wake lock before `mercury up`, and logs boot output', () => {
+ const script = buildTermuxBootScript(['/data/data/com.termux/files/usr/bin/node', '/data/x/dist/index.js', 'up'], opts);
+ const lines = script.split('\n');
+ expect(lines[0]).toBe('#!/data/data/com.termux/files/usr/bin/sh');
+ const wake = lines.indexOf('termux-wake-lock');
+ const up = lines.findIndex((l) => l.startsWith('/data/data/com.termux/files/usr/bin/node /data/x/dist/index.js up'));
+ expect(wake).toBeGreaterThan(0);
+ expect(up).toBeGreaterThan(wake);
+ expect(lines[up]).toContain('>> /data/data/com.termux/files/home/.mercury/boot.log 2>&1');
+ expect(script).toContain('export PATH="/data/data/com.termux/files/usr/bin:$PATH"');
+ expect(script.endsWith('\n')).toBe(true);
+ });
+
+ it('single-quotes argv words that the boot shell would split or expand', () => {
+ const script = buildTermuxBootScript(["/home/my dir/it's/node", '$HOME/x', 'up'], opts);
+ expect(script).toContain(String.raw`'/home/my dir/it'\''s/node' '$HOME/x' up >>`);
+ });
+
+ it('falls back to the default Termux prefix', () => {
+ expect(buildTermuxBootScript(['mercury', 'up'], { mercuryHome: '/m' }).split('\n')[0])
+ .toBe('#!/data/data/com.termux/files/usr/bin/sh');
+ });
+
+ it('writes ~/.termux/boot/mercury.sh executable under a fake HOME and removes it', () => {
+ const home = mkdtempSync(join(tmpdir(), 'mercury-termux-'));
+ try {
+ const path = writeTermuxBootScript(['mercury', 'up'], { ...opts, home });
+ expect(path).toBe(termuxBootScriptPath(home));
+ expect(path.replace(/\\/g, '/').endsWith('/.termux/boot/mercury.sh')).toBe(true);
+ expect(readFileSync(path, 'utf8')).toContain('termux-wake-lock');
+ if (process.platform !== 'win32') expect(statSync(path).mode & 0o777).toBe(0o755);
+ // Re-install over an existing (non-executable) file restores the mode.
+ if (process.platform !== 'win32') {
+ writeFileSync(path, 'old', { mode: 0o644 });
+ writeTermuxBootScript(['mercury', 'up'], { ...opts, home });
+ expect(statSync(path).mode & 0o777).toBe(0o755);
+ }
+ expect(removeTermuxBootScript(path)).toBe(true);
+ expect(existsSync(path)).toBe(false);
+ // Removing an absent script is still "gone".
+ expect(removeTermuxBootScript(path)).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('service install/uninstall/status on Termux (fake HOME, platform android)', () => {
+ let home: string;
+ const realPlatform = process.platform;
+ let logs: string[];
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-termux-home-'));
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('USERPROFILE', home);
+ vi.stubEnv('MERCURY_HOME', join(home, '.mercury'));
+ vi.stubEnv('TERMUX_VERSION', '0.118.0');
+ vi.stubEnv('PREFIX', '/data/data/com.termux/files/usr');
+ Object.defineProperty(process, 'platform', { value: 'android', configurable: true });
+ logs = [];
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { logs.push(args.join(' ')); });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true });
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it('install writes the boot script and reports it; status and uninstall recognise it', () => {
+ const bootPath = termuxBootScriptPath(home);
+ expect(isServiceInstalled()).toBe(false);
+
+ expect(installService()).toBe(true);
+ expect(existsSync(bootPath)).toBe(true);
+ const script = readFileSync(bootPath, 'utf8');
+ expect(script.split('\n')[0]).toBe('#!/data/data/com.termux/files/usr/bin/sh');
+ expect(script).toMatch(/termux-wake-lock\n.* up >> /);
+ expect(script).not.toContain('--daemon');
+ expect(logs.join('\n')).toContain('Termux:Boot');
+ expect(logs.join('\n')).toContain(bootPath);
+
+ expect(isServiceInstalled()).toBe(true);
+ // Nothing supervises the daemon: no service process to stop or query.
+ expect(isServiceRunning()).toBe(false);
+ expect(stopService()).toBe(true);
+
+ logs.length = 0;
+ showServiceStatus();
+ expect(logs.join('\n')).toContain('Autostart: Termux:Boot script');
+ expect(logs.join('\n')).toContain(bootPath);
+
+ logs.length = 0;
+ expect(uninstallService()).toBe(true);
+ expect(existsSync(bootPath)).toBe(false);
+ expect(logs.join('\n')).toContain('boot script removed');
+ expect(isServiceInstalled()).toBe(false);
+
+ logs.length = 0;
+ showServiceStatus();
+ expect(logs.join('\n')).toMatch(/not installed/);
+ });
+
+ it('uninstall without a boot script reports it and does not exit', () => {
+ expect(uninstallService()).toBe(false);
+ expect(logs.join('\n')).toMatch(/not installed/);
+ });
+
+ it('teardownService (mercury uninstall) removes the boot script', () => {
+ expect(teardownService()).toEqual({ removed: false });
+ installService();
+ expect(teardownService()).toEqual({ removed: true, path: termuxBootScriptPath(home) });
+ expect(existsSync(termuxBootScriptPath(home))).toBe(false);
+ });
+});
diff --git a/src/cli/service.ts b/src/cli/service.ts
index d1f7f654..10d41a34 100644
--- a/src/cli/service.ts
+++ b/src/cli/service.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync } from 'node:fs';
import { join, posix } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
@@ -31,7 +31,7 @@ export type WindowsServiceMode = 'task' | 'run-key';
export function isServiceInstalled(): boolean {
const platform = process.platform;
- if (isTermux()) return false;
+ if (isTermux()) return existsSync(termuxBootScriptPath());
if (platform === 'darwin') {
return existsSync(join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist'));
@@ -45,6 +45,10 @@ export function isServiceInstalled(): boolean {
export function isServiceRunning(): boolean {
if (!isServiceInstalled()) return false;
+ // Termux:Boot only launches `mercury up` at boot; nothing supervises the
+ // daemon afterwards, so there is no service process — callers check the
+ // pid-file daemon (getDaemonStatus) themselves.
+ if (isTermux()) return false;
try {
if (process.platform === 'darwin') {
const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;
@@ -132,8 +136,7 @@ export function installService(): boolean {
const platform = process.platform;
if (isTermux()) {
- showTermuxServiceHelp('install');
- return false;
+ return installTermux();
}
if (platform === 'darwin') {
@@ -154,8 +157,7 @@ export function uninstallService(): boolean {
const platform = process.platform;
if (isTermux()) {
- showTermuxServiceHelp('uninstall');
- return false;
+ return uninstallTermux();
}
if (platform === 'darwin') {
@@ -179,7 +181,13 @@ export function uninstallService(): boolean {
export function teardownService(): { removed: boolean; path?: string; hint?: string } {
const platform = process.platform;
- if (isTermux()) return { removed: false, hint: 'Termux: no system service — nothing to remove' };
+ if (isTermux()) {
+ const bootPath = termuxBootScriptPath();
+ if (!existsSync(bootPath)) return { removed: false };
+ return removeTermuxBootScript(bootPath)
+ ? { removed: true, path: bootPath }
+ : { removed: false, hint: `Remove manually: rm ${bootPath}` };
+ }
if (platform === 'darwin') {
const plistPath = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');
@@ -222,7 +230,7 @@ export function showServiceStatus(): void {
const platform = process.platform;
if (isTermux()) {
- showTermuxServiceHelp('status');
+ showTermuxStatus();
return;
}
@@ -238,6 +246,13 @@ export function showServiceStatus(): void {
export function restartService(): void {
if (!isServiceInstalled()) throw new Error('Mercury system service is not installed');
+ if (isTermux()) {
+ // The boot script is not a supervisor: restart the pid-file daemon.
+ stopTrackedDaemonSync();
+ if (!tryAutoDaemonize()) throw new Error('Failed to respawn the Mercury daemon');
+ return;
+ }
+
if (process.platform === 'darwin') {
const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;
try {
@@ -274,6 +289,8 @@ export function restartService(): void {
export function stopService(): boolean {
if (!isServiceInstalled()) return true;
+ // Termux: no service-owned process (see isServiceRunning).
+ if (isTermux()) return true;
if (process.platform === 'darwin') {
const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;
@@ -321,13 +338,127 @@ function stopTrackedDaemonSync(): void {
}
}
-function showTermuxServiceHelp(action: 'install' | 'uninstall' | 'status'): void {
+// ─── Termux (Termux:Boot) ────────────────────────────────────────────────────
+//
+// Android has no systemd. The Termux:Boot add-on runs every executable in
+// ~/.termux/boot/ once the device has booted; `service install` drops a
+// script there that takes a wake lock (so Android does not doze the daemon)
+// and runs `mercury up`. No crash recovery — the daemon is tracked by its pid
+// file like the Windows run-key mode.
+
+const TERMUX_DEFAULT_PREFIX = '/data/data/com.termux/files/usr';
+const TERMUX_BOOT_MARKER = '# Managed by `mercury service install` — remove with `mercury service uninstall`.';
+
+/** `~/.termux/boot/mercury.sh` (Termux:Boot convention). */
+export function termuxBootScriptPath(home: string = homedir()): string {
+ return posix.join(home, '.termux', 'boot', 'mercury.sh');
+}
+
+/** Single-quote one word for POSIX sh. */
+function shQuote(arg: string): string {
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
+}
+
+export interface TermuxBootOptions {
+ /** Termux $PREFIX (shebang + PATH). */
+ prefix?: string;
+ /** Where boot-time output goes (`~/.mercury`). */
+ mercuryHome: string;
+}
+
+/**
+ * The Termux:Boot script for the given `mercury up` argv (absolute node +
+ * dist path for npm installs, so the boot shell needs no PATH lookup).
+ */
+export function buildTermuxBootScript(upArgs: string[], opts: TermuxBootOptions): string {
+ const prefix = opts.prefix || TERMUX_DEFAULT_PREFIX;
+ const log = posix.join(opts.mercuryHome, 'boot.log');
+ return `#!${prefix}/bin/sh
+${TERMUX_BOOT_MARKER}
+# Termux:Boot runs this after the device boots: keep the CPU awake for the
+# daemon, then start Mercury in the background.
+export PATH="${prefix}/bin:$PATH"
+termux-wake-lock
+${upArgs.map(shQuote).join(' ')} >> ${shQuote(log)} 2>&1
+`;
+}
+
+/** Argv that runs `mercury up` for this install (npm or standalone). */
+function termuxUpArgs(): string[] {
+ return getServiceLaunchArgs().filter((a) => a !== 'start' && a !== '--daemon').concat('up');
+}
+
+/** Write the boot script (mode 0755). Returns its path. */
+export function writeTermuxBootScript(upArgs: string[], opts: TermuxBootOptions & { home?: string }): string {
+ const path = termuxBootScriptPath(opts.home);
+ mkdirSync(posix.dirname(path), { recursive: true });
+ writeFileSync(path, buildTermuxBootScript(upArgs, opts), { encoding: 'utf-8', mode: 0o755 });
+ chmodSync(path, 0o755); // mode is ignored when the file already existed
+ return path;
+}
+
+/** Remove the boot script; true when it is gone afterwards. */
+export function removeTermuxBootScript(path: string = termuxBootScriptPath()): boolean {
+ try {
+ unlinkSync(path);
+ } catch {}
+ return !existsSync(path);
+}
+
+function installTermux(): boolean {
+ let bootPath: string;
+ try {
+ bootPath = writeTermuxBootScript(termuxUpArgs(), { prefix: process.env.PREFIX, mercuryHome: getMercuryHome() });
+ } catch (err) {
+ console.log(chalk.yellow(` Could not write the Termux:Boot script: ${errorText(err)}`));
+ console.log(chalk.dim(' Start Mercury manually with: mercury up'));
+ console.log('');
+ return false;
+ }
+ console.log('');
+ console.log(chalk.green(' Mercury boot script installed (Termux:Boot)'));
+ console.log(chalk.dim(` Script: ${bootPath}`));
+ console.log(chalk.dim(` Logs: ${posix.join(getMercuryHome(), 'daemon.log')} (boot output: ${posix.join(getMercuryHome(), 'boot.log')})`));
+ console.log(chalk.dim(' Starts on device boot (takes a wake lock). No crash recovery on Android.'));
+ console.log(chalk.yellow(' Requires the Termux:Boot add-on (F-Droid / GitHub) — open it once after installing.'));
+ console.log('');
+ console.log(chalk.dim(' Uninstall: mercury service uninstall'));
console.log('');
- console.log(chalk.yellow(` System service ${action} is not supported on Termux yet (no systemd on Android).`));
- console.log(chalk.dim(' Start Mercury manually with: mercury up (or: mercury start)'));
- console.log(chalk.dim(' Check it with: mercury status'));
- console.log(chalk.dim(' Stop it with: mercury stop'));
- console.log(chalk.dim(' For boot startup, install the Termux:Boot add-on and put `mercury up` in ~/.termux/boot/mercury.sh.'));
+ return true;
+}
+
+function uninstallTermux(): boolean {
+ const bootPath = termuxBootScriptPath();
+ if (!existsSync(bootPath)) {
+ console.log(chalk.yellow(' Mercury boot script is not installed (Termux).'));
+ console.log(chalk.dim(` Expected: ${bootPath}`));
+ console.log('');
+ return false;
+ }
+ if (!removeTermuxBootScript(bootPath)) {
+ console.log(chalk.yellow(' Failed to remove the boot script. Remove manually:'));
+ console.log(chalk.dim(` rm ${bootPath}`));
+ console.log('');
+ return false;
+ }
+ console.log('');
+ console.log(chalk.green(' Mercury boot script removed (Termux:Boot)'));
+ console.log(chalk.dim(` Removed: ${bootPath}`));
+ console.log(chalk.dim(' A running daemon keeps running — stop it with: mercury stop'));
+ console.log('');
+ return true;
+}
+
+function showTermuxStatus(): void {
+ const bootPath = termuxBootScriptPath();
+ const daemon = getDaemonStatus();
+ if (existsSync(bootPath)) {
+ console.log(` ${chalk.green('Autostart: Termux:Boot script')} ${chalk.dim(`(${bootPath})`)}`);
+ } else {
+ console.log(chalk.yellow(' Mercury boot script is not installed (Termux).'));
+ console.log(chalk.dim(' Run `mercury service install` to start Mercury on device boot (needs Termux:Boot).'));
+ }
+ console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.yellow('not running')}`);
console.log('');
}