Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(cli): auto-heal a running-but-unresponsive runtime on launch
Salman Qureshie54f4f7cb80d
diff --git a/src/cli/attach-health.test.ts b/src/cli/attach-health.test.tsnew file mode 100644index 00000000..ab69c80c--- /dev/null+++ b/src/cli/attach-health.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';+import { waitForRuntimeHealth } from './attach.js';++/** Fake health probe configurable per test. */+function clientWith(behavior: () => Promise<void>): { healthCheck: () => Promise<void>; calls: () => number } {+ let calls = 0;+ return {+ healthCheck: async () => { calls++; return behavior(); },+ calls: () => calls,+ };+}++describe('waitForRuntimeHealth (attach boot-grace retry)', () => {+ it('returns ok on the first healthy probe', async () => {+ const client = clientWith(async () => {});+ const result = await waitForRuntimeHealth(client, 300);+ expect(result.ok).toBe(true);+ expect(client.calls()).toBe(1);+ });++ it('retries a still-booting runtime until it responds', async () => {+ let n = 0;+ const client = clientWith(async () => {+ n++;+ if (n < 3) throw new Error('Unable to connect');+ });+ const result = await waitForRuntimeHealth(client, 5_000);+ expect(result.ok).toBe(true);+ expect(client.calls()).toBe(3);+ });++ it('gives up unhealthy after the boot-grace window expires', async () => {+ const client = clientWith(async () => { throw new Error('Unable to connect'); });+ const result = await waitForRuntimeHealth(client, 400);+ expect(result.ok).toBe(false);+ expect(result.message).toBe('Unable to connect');+ expect(client.calls()).toBeGreaterThan(1);+ });++ it('does not retry an auth failure — a rotated token never self-heals', async () => {+ const client = clientWith(async () => { throw new Error('auth'); });+ const result = await waitForRuntimeHealth(client, 5_000);+ expect(result.ok).toBe(false);+ expect(result.message).toBe('auth');+ expect(client.calls()).toBe(1);+ });+});\ No newline at end of filediff --git a/src/cli/attach.ts b/src/cli/attach.tsindex b8c508c5..b5d571bd 100644--- a/src/cli/attach.ts+++ b/src/cli/attach.ts@@ -258,6 +258,8 @@ export interface AttachTarget {pid: number | null;}+const RUNTIME_BOOT_GRACE_MS = 15_000;+/*** Resolve the running runtime to attach to. Prefers the foreground TUI* process, falls back to the daemon. Returns null when no runtime is alive.@@ -272,13 +274,46 @@ export function findAttachTarget(): AttachTarget | null {return { baseUrl: `http://127.0.0.1:${getWebPort()}`, token, pid };}+/**+ * Ride out a runtime that is still booting: the web endpoint comes up some+ * seconds into boot (channels and bot crew replay run first), so a one-shot+ * health check classified every slow boot as a broken runtime. Retries until+ * the grace window expires. An `auth` failure is not retryable — the token+ * rotated, which means the runtime restarted while we were reading it.+ */+export async function waitForRuntimeHealth(+ client: Pick<AttachClient, 'healthCheck'>,+ graceMs: number,+): Promise<{ ok: boolean; message?: string }> {+ const deadline = Date.now() + graceMs;+ for (;;) {+ try {+ await client.healthCheck();+ return { ok: true };+ } catch (err) {+ const message = String((err as Error)?.message || err);+ if (message === 'auth') return { ok: false, message };+ if (Date.now() >= deadline) return { ok: false, message };+ await new Promise(resolve => setTimeout(resolve, 750));+ }+ }+}++export interface AttachRunOptions {+ /** Explicit `mercury attach` invocation — a failed attach sets exit code 1.+ * Auto-attach launch paths leave the exit code alone so they can self-heal. */+ exitOnFailure?: boolean;+}++export type AttachResult = 'attached' | 'unavailable' | 'unhealthy';+/*** Entry point for `mercury attach` (and the auto-attach path when a second* `mercury` invocation finds the runtime already running). Connects, opens* the TUI, and returns when the user detaches (Ctrl+C). The runtime is* never touched from here.*/-export async function runAttach(): Promise<void> {+export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResult> {const { render } = await import('ink');const React = await import('react');const { AttachTui } = await import('../ui/attach-tui.js');@@ -293,22 +328,29 @@ export async function runAttach(): Promise<void> {console.error(' Cannot attach: web is disabled or no attach token was written at boot.');console.error(' Enable web (mercury doctor), or `mercury stop` and start again.');}- process.exitCode = 1;- return;+ if (opts.exitOnFailure) process.exitCode = 1;+ return 'unavailable';}const client = new AttachClient(target.baseUrl, target.token);try {await client.healthCheck();- } catch (err) {- const message = String((err as Error)?.message || err);- console.error(` Runtime is not responding at ${target.baseUrl} (${message}).`);- if (message === 'auth') {- console.error(' The attach token rotated — the runtime restarted since the token was read.');- console.error(' Run `mercury attach` again.');+ } catch (firstErr) {+ // Not up yet — either booting or broken. Give it the boot-grace window.+ console.log(chalk.dim(' Waiting for the runtime to respond...'));+ const health = await waitForRuntimeHealth(client, RUNTIME_BOOT_GRACE_MS);+ if (health.ok === false) {+ const message = String((firstErr as Error)?.message || firstErr);+ if (message === 'auth') {+ console.error(' The attach token rotated — the runtime restarted since the token was read.');+ console.error(' Run `mercury attach` again.');+ } else {+ console.error(` Runtime (PID: ${target.pid}) is not responding at ${target.baseUrl} — likely hung, or its web server never bound.`);+ console.error(` Recover with \`mercury stop\`, then launch again. Daemon log: ${getDaemonStatus().logPath}`);+ }+ if (opts.exitOnFailure) process.exitCode = 1;+ return 'unhealthy';}- process.exitCode = 1;- return;}const instance = render(React.createElement(AttachTui, {@@ -318,4 +360,5 @@ export async function runAttach(): Promise<void> {}));await instance.waitUntilExit();console.log(chalk.dim(` Detached. Runtime still running${target.pid ? ` (PID ${target.pid})` : ''} — \`mercury stop\` stops it.`));+ return 'attached';}\ No newline at end of filediff --git a/src/index.ts b/src/index.tsindex 0f374cba..61ca9530 100644--- a/src/index.ts+++ b/src/index.ts@@ -2219,6 +2219,33 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {console.log('');}+/**+ * The runtime passed the PID-liveness check but its web endpoint is dead — a+ * hung process, or a web server that failed to bind (EADDRINUSE leaves the+ * daemon alive but web-less). Without this, the single-runtime rule bricked+ * the launcher: every `mercury` invocation attached into the dead end and+ * exited, and only a user who knew to run `mercury stop` could recover.+ * The user's intent when typing `mercury` is to chat, so restart and boot.+ */+/**+ * Auto-attach entry for launch paths that found a "running" runtime. Attach,+ * or — when the runtime proved unresponsive — heal it and boot fresh.+ */+async function attachOrHeal(): Promise<void> {+ const result = await runAttach();+ if (result === 'attached') return;+ if (result !== 'unhealthy') { process.exitCode = 1; return; }+ await healRuntimeAndBoot();+}++async function healRuntimeAndBoot(): Promise<void> {+ console.log(chalk.yellow(' Runtime is not responding — restarting it...'));+ await stopForegroundRuntime();+ await stopDaemon();+ autoDaemonize();+ await runAgent();+}+function autoDaemonize(): void {const daemon = getDaemonStatus();if (daemon.running && daemon.pid) {@@ -3686,13 +3713,13 @@ programconst daemon = getDaemonStatus();if (daemon.running && daemon.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.`));- await runAttach();+ await attachOrHeal();return;}const foreground = getForegroundRuntimeStatus();if (foreground.running && foreground.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));- await runAttach();+ await attachOrHeal();return;}autoDaemonize();@@ -3723,13 +3750,13 @@ programconst daemon = getDaemonStatus();if (daemon.running && daemon.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.`));- await runAttach();+ await attachOrHeal();return;}const foreground = getForegroundRuntimeStatus();if (foreground.running && foreground.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));- await runAttach();+ await attachOrHeal();return;}await runAgent();@@ -3743,7 +3770,7 @@ program.command('attach').description('Attach this terminal to an already-running Mercury runtime (chat + live streaming)').action(async () => {- await runAttach();+ await runAttach({ exitOnFailure: true });});program@@ -4883,7 +4910,7 @@ cloudconst daemon = getDaemonStatus();if (daemon.running && daemon.pid) {console.log(chalk.cyan(`\n ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.\n`));- await runAttach();+ await attachOrHeal();return;}console.log(chalk.cyan('\n Launching Mercury...\n'));diff --git a/src/web/server.ts b/src/web/server.tsindex 3d88b031..88eba6b5 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -247,7 +247,10 @@ export function startWebServer(): { port: number; url: string } {server.on('error', (err: any) => {if (err?.code === 'EADDRINUSE') {- logger.warn(`Port ${port} is already in use. Web dashboard unavailable.`);+ // The runtime stays alive for its channels, but with no web listener+ // every attach health check fails — the launcher treats that as an+ // unresponsive runtime and restarts it. Log the shape of that state.+ logger.warn(`Port ${port} is already in use — web dashboard unavailable. Attach/launch will report the runtime as unresponsive and restart it.`);} else {logger.error({ err: err.message }, 'Web server error');}