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(attach): instant attach — listener first, pid-aware health, no restart on a foreign port

Salman Qureshibcc9fd13b284
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 73cc6924..5c4a097e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased — instant attach
+
+- **`mercury` attaches instantly to a running daemon.** The daemon binds its web listener *first* at boot (channels and bots come after), an unauthenticated loopback `/api/health` answers with pid/version/booting, and the launcher polls every 250 ms instead of 750 ms. A port owned by another process (an old global install, another Mercury) is now reported in one line — *Port 6174 is owned by another Mercury (PID …) — stop it or set web.port* — instead of a 15-second wait followed by a pointless restart. The web server also retries a busy port for 5 s, so a restart right after a stop no longer loses the dashboard.
+
## Unreleased — bots in your pocket (ADR-023)
- **Onboarding from Telegram.** `/bots create <id> "Name" "Description"` in Telegram (or the web chat) now runs the same flow as the TUI: your next message is the persona (keep as-is or convert to the template), then permissions tier, solo vs fleet, and the daily budget — each a tap on Telegram's native buttons that settle in place. Every reply lands in the chat that asked; nothing is lost to the TUI-only bot thread any more.
diff --git a/src/cli/attach-health.test.ts b/src/cli/attach-health.test.ts
index ab69c80c..ffa292e2 100644
--- a/src/cli/attach-health.test.ts
+++ b/src/cli/attach-health.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { waitForRuntimeHealth } from './attach.js';
+import { waitForRuntimeHealth, isFinalHealthFailure } from './attach.js';
/** Fake health probe configurable per test. */
-function clientWith(behavior: () => Promise<void>): { healthCheck: () => Promise<void>; calls: () => number } {
+function clientWith(behavior: () => Promise<void>): { healthCheck: () => Promise<never>; calls: () => number } {
let calls = 0;
return {
- healthCheck: async () => { calls++; return behavior(); },
+ healthCheck: async () => { calls++; await behavior(); return undefined as never; },
calls: () => calls,
};
}
@@ -44,4 +44,22 @@ describe('waitForRuntimeHealth (attach boot-grace retry)', () => {
expect(result.message).toBe('auth');
expect(client.calls()).toBe(1);
});
-});
\ No newline at end of file
+
+ it('does not retry a foreign process on the port — restarting would not free it', async () => {
+ const client = clientWith(async () => { throw new Error('foreign:97738:1.3.0'); });
+ const result = await waitForRuntimeHealth(client, 5_000);
+ expect(result.ok).toBe(false);
+ expect(result.message).toBe('foreign:97738:1.3.0');
+ expect(client.calls()).toBe(1);
+ expect(isFinalHealthFailure('foreign:1:x')).toBe(true);
+ expect(isFinalHealthFailure('booting')).toBe(false);
+ });
+
+ it('keeps polling a runtime that reports booting until it is live', async () => {
+ let n = 0;
+ const client = clientWith(async () => { n++; if (n < 4) throw new Error('booting'); });
+ const result = await waitForRuntimeHealth(client, 5_000);
+ expect(result.ok).toBe(true);
+ expect(client.calls()).toBe(4);
+ });
+});
diff --git a/src/cli/attach.ts b/src/cli/attach.ts
index a24bded9..915b875c 100644
--- a/src/cli/attach.ts
+++ b/src/cli/attach.ts
@@ -100,10 +100,18 @@ export function createSseParser(): SseParser {
};
}
+export interface RuntimeHealth {
+ pid: number | null;
+ version: string;
+ booting: boolean;
+}
+
export class AttachClient {
constructor(
private readonly baseUrl: string,
private readonly token: string,
+ /** Pids a healthy answer may come from (foreground + daemon); any other pid means a foreign process owns the port. */
+ private readonly expectedPids: number[] = [],
) {}
private headers(): Record<string, string> {
@@ -117,14 +125,35 @@ export class AttachClient {
});
}
- /** Cheap authenticated GET to verify the runtime + token before opening the TUI. */
- async healthCheck(timeoutMs = 3000): Promise<void> {
+ /**
+ * Is the runtime we expect answering on this port? Errors are typed by
+ * message: 'booting' (ours, not ready — retry), 'auth' (token rotated),
+ * 'foreign:<pid>:<version>' (another process owns the port — never
+ * retry, never restart), anything else = not listening yet.
+ */
+ async healthCheck(timeoutMs = 2000): Promise<RuntimeHealth> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
- const res = await this.request('/api/chat/models', { signal: controller.signal });
- if (res.status === 401) throw new Error('auth');
+ const res = await this.request('/api/health', { signal: controller.signal });
+ if (res.status === 404) {
+ // Runtime older than /api/health: fall back to the authenticated probe.
+ const legacy = await this.request('/api/chat/models', { signal: controller.signal });
+ if (legacy.status === 401) throw new Error('auth');
+ if (!legacy.ok) throw new Error(`HTTP ${legacy.status}`);
+ return { pid: null, version: '', booting: false };
+ }
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const body = await res.json() as Partial<RuntimeHealth>;
+ const health: RuntimeHealth = { pid: typeof body.pid === 'number' ? body.pid : null, version: String(body.version ?? ''), booting: body.booting === true };
+ if (health.pid !== null && this.expectedPids.length > 0 && !this.expectedPids.includes(health.pid)) {
+ throw new Error(`foreign:${health.pid}:${health.version}`);
+ }
+ if (health.booting) throw new Error('booting');
+ // The listener is ours; make sure the token we read is the one it wrote.
+ const authed = await this.request('/api/chat/models', { signal: controller.signal });
+ if (authed.status === 401) throw new Error('auth');
+ return health;
} finally {
clearTimeout(timer);
}
@@ -285,6 +314,8 @@ export interface AttachTarget {
baseUrl: string;
token: string;
pid: number | null;
+ /** Every live runtime pid (foreground and daemon) — a health answer from any other pid is a foreign process. */
+ pids: number[];
}
const RUNTIME_BOOT_GRACE_MS = 15_000;
@@ -300,7 +331,8 @@ export function findAttachTarget(): AttachTarget | null {
if (pid == null) return null;
const token = readAttachToken();
if (!token) return null; // runtime started before attach tokens existed, or web disabled
- return { baseUrl: `http://127.0.0.1:${getWebPort()}`, token, pid };
+ const pids = [foreground.running ? foreground.pid : null, daemon.running ? daemon.pid : null].filter((p): p is number => typeof p === 'number');
+ return { baseUrl: `http://127.0.0.1:${getWebPort()}`, token, pid, pids };
}
/**
@@ -310,6 +342,10 @@ export function findAttachTarget(): AttachTarget | null {
* the grace window expires. An `auth` failure is not retryable — the token
* rotated, which means the runtime restarted while we were reading it.
*/
+export function isFinalHealthFailure(message: string): boolean {
+ return message === 'auth' || message.startsWith('foreign:');
+}
+
export async function waitForRuntimeHealth(
client: Pick<AttachClient, 'healthCheck'>,
graceMs: number,
@@ -321,9 +357,9 @@ export async function waitForRuntimeHealth(
return { ok: true };
} catch (err) {
const message = String((err as Error)?.message || err);
- if (message === 'auth') return { ok: false, message };
+ if (isFinalHealthFailure(message)) return { ok: false, message };
if (Date.now() >= deadline) return { ok: false, message };
- await new Promise(resolve => setTimeout(resolve, 750));
+ await new Promise(resolve => setTimeout(resolve, 250));
}
}
}
@@ -361,15 +397,34 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu
return 'unavailable';
}
- const client = new AttachClient(target.baseUrl, target.token);
+ let client = new AttachClient(target.baseUrl, target.token, target.pids);
try {
await client.healthCheck();
} 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);
+ let message = String((firstErr as Error)?.message || firstErr);
+ if (message === 'auth') {
+ // The runtime rotates its token at boot; we may have read the old one.
+ const fresh = readAttachToken();
+ if (fresh && fresh !== target.token) {
+ client = new AttachClient(target.baseUrl, fresh, target.pids);
+ try { await client.healthCheck(); message = ''; } catch (again) { message = String((again as Error)?.message || again); }
+ }
+ }
+ let health: { ok: boolean; message?: string } = { ok: message === '' , message };
+ if (!health.ok && !isFinalHealthFailure(message)) {
+ // Not up yet — booting. Poll until the listener answers.
+ console.log(chalk.dim(message === 'booting' ? ' Runtime is booting — attaching as soon as it is up...' : ' Waiting for the runtime to respond...'));
+ health = await waitForRuntimeHealth(client, RUNTIME_BOOT_GRACE_MS);
+ }
if (health.ok === false) {
- const message = String((firstErr as Error)?.message || firstErr);
+ message = health.message ?? message;
+ if (message.startsWith('foreign:')) {
+ const [, pid, version] = message.split(':');
+ console.error(` Port ${new URL(target.baseUrl).port} is owned by another Mercury (PID ${pid}${version ? `, v${version}` : ''}) — the runtime you launched (PID ${target.pid}) has no web listener.`);
+ console.error(` Stop the other one (kill ${pid}) or set web.port in mercury.yaml, then run \`mercury\` again. Restarting would not help.`);
+ if (opts.exitOnFailure) process.exitCode = 1;
+ return 'unavailable';
+ }
if (message === 'auth') {
console.error(' The attach token rotated — the runtime restarted since the token was read.');
console.error(' Run `mercury attach` again.');
diff --git a/src/index.ts b/src/index.ts
index bffd0fd7..e69f1bae 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -3621,10 +3621,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
capabilities.permissions.addTempScope('/', true, true);
}
} else {
- await channels.startAll();
+ // Listener first: a second terminal attaches the moment the daemon is
+ // up, not after every channel and bot has booted. /api/health reports
+ // 'booting' until the rest is live.
if (config.web.enabled) {
startWebServer();
writeAttachToken();
+ updateWebStatus({ running: true, pid: process.pid, state: 'booting' });
+ }
+ await channels.startAll();
+ if (config.web.enabled) {
updateWebStatus({
running: true,
pid: process.pid,
diff --git a/src/web/api/status.ts b/src/web/api/status.ts
index 5588b87a..03a30d64 100644
--- a/src/web/api/status.ts
+++ b/src/web/api/status.ts
@@ -1,4 +1,8 @@
import { Hono } from 'hono';
+import { readFileSync } from 'node:fs';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { isLoopbackRequest } from '../middleware.js';
export interface AgentStatus {
running: boolean;
@@ -36,6 +40,28 @@ export function getStatus(): AgentStatus {
const status = new Hono();
+let runtimeVersion = '';
+function versionString(): string {
+ if (runtimeVersion) return runtimeVersion;
+ try {
+ runtimeVersion = process.env.MERCURY_CHANNEL_VERSION
+ || JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'package.json'), 'utf8')).version
+ || '';
+ } catch { runtimeVersion = ''; }
+ return runtimeVersion;
+}
+
+/**
+ * Liveness for `mercury attach` — no auth, loopback only, answers the
+ * moment the listener is bound (before channels and bots have booted). The
+ * pid lets a launcher tell "my runtime, still booting" from "some other
+ * process owns this port" without a restart.
+ */
+status.get('/api/health', (c) => {
+ if (!isLoopbackRequest(c)) return c.json({ error: 'Not found' }, 404);
+ return c.json({ ok: true, pid: process.pid, version: versionString(), state: currentStatus.state, booting: currentStatus.state === 'booting' });
+});
+
status.get('/api/status', (c) => {
const s = getStatus();
diff --git a/src/web/attach-token.test.ts b/src/web/attach-token.test.ts
index 13e90ad8..4a847b5e 100644
--- a/src/web/attach-token.test.ts
+++ b/src/web/attach-token.test.ts
@@ -99,4 +99,29 @@ function makeContext(path: string, token: string, remoteAddress: string): any {
env: { incoming: { socket: { remoteAddress } } },
json: (body: unknown, status = 200) => ({ body, status }),
};
-}
\ No newline at end of file
+}
+describe('/api/health (attach liveness)', () => {
+ let home: string;
+ const previousHome = process.env.MERCURY_HOME;
+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'mercury-health-')); 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 }); });
+
+ it('passes the auth guard without any token — a launcher must be able to ask before it has one', async () => {
+ let nextCalled = false;
+ const result = await authGuard(makeContext('/api/health', '', '127.0.0.1'), async () => { nextCalled = true; });
+ expect(nextCalled).toBe(true);
+ expect(result).toBeUndefined();
+ });
+
+ it('answers with this process pid on loopback, and hides itself from the network', async () => {
+ const { default: statusRoutes } = await import('./api/status.js');
+ const loopback = await statusRoutes.request('http://127.0.0.1:6174/api/health', {}, { incoming: { socket: { remoteAddress: '127.0.0.1' } } });
+ expect(loopback.status).toBe(200);
+ const body = await loopback.json() as { ok: boolean; pid: number; booting: boolean };
+ expect(body.ok).toBe(true);
+ expect(body.pid).toBe(process.pid);
+ expect(typeof body.booting).toBe('boolean');
+ const remote = await statusRoutes.request('http://127.0.0.1:6174/api/health', {}, { incoming: { socket: { remoteAddress: '10.0.0.7' } } });
+ expect(remote.status).toBe(404);
+ });
+});
diff --git a/src/web/middleware.ts b/src/web/middleware.ts
index fa71bab5..0496e708 100644
--- a/src/web/middleware.ts
+++ b/src/web/middleware.ts
@@ -2,7 +2,7 @@ import { Context, Next } from 'hono';
import { getCookie } from 'hono/cookie';
import { validateSession, getSessionCookieName, readAttachToken } from './auth.js';
-const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout']);
+const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout', '/api/health']);
/**
* The attach token is only honored from loopback connections. Defense in
diff --git a/src/web/server.ts b/src/web/server.ts
index d9bf3b7f..966b3959 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -248,7 +248,15 @@ export function startWebServer(): { port: number; url: string } {
const server = createAdaptorServer({ fetch: app.fetch });
webServer = server;
+ let bindAttempts = 0;
server.on('error', (err: any) => {
+ if (err?.code === 'EADDRINUSE' && bindAttempts < 10) {
+ // A previous instance shutting down keeps the port for a moment;
+ // retry before declaring the dashboard unavailable.
+ bindAttempts++;
+ setTimeout(() => server.listen(port, '127.0.0.1'), 500);
+ return;
+ }
if (err?.code === 'EADDRINUSE') {
// The runtime stays alive for its channels, but with no web listener
// every attach health check fails — the launcher treats that as an