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(runtime): one runtime owns the fleet — the terminal attaches, never boots a second copy (ADR-024)

Salman Qureshi59061dc8ebfa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bfe4e24..01ea41ba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## Unreleased — one runtime (ADR-024)
+
+- **The terminal no longer runs a second copy of Mercury.** Launching `mercury` with no daemon used to spawn the daemon *and* boot a full runtime in the terminal — Telegram, the scheduler and every bot ran twice, and the second copy ran on the thread that paints your keystrokes. That was the typing lag, and the Telegram "terminated by other getUpdates" (409) conflicts. Now the terminal spawns the daemon and attaches to it; a foreground runtime beside a live daemon (`mercury code`, recovery) is a terminal for the main agent only — no bots, no channels, no web port.
+- **Attach waits for a booting daemon** (token not written yet, token rotated at bind) instead of failing on the first read.
+- **Event-loop stall monitor**: `/api/health` reports `loopLag` (p99 / worst stall over the last 10 s) and stalls ≥250 ms are logged with a warning, so lag is a number, not a feeling.
+
## Unreleased — instant attach
- **Slash commands no longer show "Processing".** `/memory`, `/bots`, `/help` and friends are answered without the model; the turn indicator and heartbeat are raised only when a command actually falls through to a model turn. (`/memory` opens a menu that stays open as long as you use it — with the spinner up it looked like a hung agent.)
diff --git a/DECISIONS.md b/DECISIONS.md
index ea4e80bd..b06a300a 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -209,3 +209,9 @@
- **Crew lane**: `resolveProvider` sends a crew bot with no provider of its own to `bots.fleets.crewProvider` when set.
- **Alternatives considered**: tasks as rows in the SQLite queue (two backends to extend, no gain at this volume); waking the lead per result with a smarter prompt (still N turns); a scheduler-driven pipeline outside the task model (two orchestration paths); summarising the whole journal into the prompt (unbounded — five rows is the budget).
- **Consequence**: A fleet of five crew costs one lead turn to dispatch and one to synthesise, not seven. Pipelines run with zero lead turns in the middle. A bot's continuity is three things it never has to write: the journal digest, its note, and its memory. `bot_send(task)` callers see a digest instead of "✅ Task complete (job …)"; existing tests were updated accordingly. Wave 3 (cost views, run viewer, fleet kill switch, onboarding presets) is UI on top of this data.
+
+## ADR-024: One runtime owns the fleet — the terminal attaches
+
+- **Context**: `mercury` with no daemon ran `autoDaemonize(); await runAgent();` — it spawned the daemon and then booted a second, full runtime in the foreground process. Both constructed a `BotManager` on the same `queue.db`, both registered the Telegram channel (Telegram answers 409 "terminated by other getUpdates" to competing pollers — nine such conflicts in one day's daemon-error.log), and the foreground copy ran bot turns, tool executions and context compaction on the thread that renders the TUI. Once bots were made always-alive (liveness contract, §2.14), that second copy had enough work to make typing and menus visibly lag on every machine. A port conflict (a stale global install holding :6174) made the "heal" path take the same route on every launch.
+- **Decision**: One process is the runtime. `bootDaemonThenAttach()` replaces spawn-then-boot at launch and in recovery: spawn the daemon, attach to it (`runAttach` now waits for the attach token and tolerates a token rotated during boot); only when no daemon can run here (Termux, unsupported platform) does the terminal become the runtime. A foreground runtime that finds a live daemon (`daemonOwnsRuntime`: `mercury code`, an attach that could not connect) wires the CLI channel only (`ChannelRegistry({ cliOnly })`), creates no `BotManager`, and does not bind the web port — it is a terminal for the main agent. The event loop is measured (`monitorEventLoopDelay`): `/api/health` reports `loopLag`, and stalls ≥250 ms are logged.
+- **Consequence**: Bots and channels run exactly once, in the daemon, on their own thread; the TUI process renders keystrokes and nothing else. The attach TUI is what most sessions see (the daemon auto-starts on login), so parity gaps in it — TUI-only bot threads (`/bots open`), the `/telegram` menu — are now visible and worth closing. Lag has a number: if `loopLag.maxMs` is high in the daemon, something in a bot turn is synchronous and should move off the thread.
diff --git a/src/channels/registry.ts b/src/channels/registry.ts
index f5a49685..c277df54 100644
--- a/src/channels/registry.ts
+++ b/src/channels/registry.ts
@@ -11,8 +11,14 @@ import { logger } from '../utils/logger.js';
export class ChannelRegistry {
private channels: Map<ChannelType, Channel> = new Map();
- constructor(config: MercuryConfig) {
+ /**
+ * @param opts.cliOnly — a foreground runtime beside a live daemon: the daemon
+ * owns Telegram/Signal/Discord/Slack (a second poller on the same token
+ * fights it — Telegram answers 409 to both), so only the terminal is wired.
+ */
+ constructor(config: MercuryConfig, opts: { cliOnly?: boolean } = {}) {
this.register('cli', new CLIChannel(config.identity.name));
+ if (opts.cliOnly) return;
if (config.channels.telegram.enabled && config.channels.telegram.botToken) {
this.register('telegram', new TelegramChannel(config));
diff --git a/src/cli/attach-health.test.ts b/src/cli/attach-health.test.ts
index ffa292e2..eb6428ff 100644
--- a/src/cli/attach-health.test.ts
+++ b/src/cli/attach-health.test.ts
@@ -62,4 +62,19 @@ describe('waitForRuntimeHealth (attach boot-grace retry)', () => {
expect(result.ok).toBe(true);
expect(client.calls()).toBe(4);
});
+
+ it('with a client factory, a rotated token (auth) is retried until the fresh token works', async () => {
+ let n = 0;
+ const factory = () => clientWith(async () => { n++; if (n < 3) throw new Error('auth'); });
+ const result = await waitForRuntimeHealth(factory, 5_000);
+ expect(result.ok).toBe(true);
+ expect(n).toBe(3);
+ });
+
+ it('a factory that has no token yet keeps waiting instead of failing', async () => {
+ let n = 0;
+ const result = await waitForRuntimeHealth(() => (++n < 3 ? null : clientWith(async () => {})), 5_000);
+ expect(result.ok).toBe(true);
+ expect(n).toBe(3);
+ });
});
diff --git a/src/cli/attach.ts b/src/cli/attach.ts
index 915b875c..83cc4038 100644
--- a/src/cli/attach.ts
+++ b/src/cli/attach.ts
@@ -346,24 +346,47 @@ export function isFinalHealthFailure(message: string): boolean {
return message === 'auth' || message.startsWith('foreign:');
}
+type HealthProbe = Pick<AttachClient, 'healthCheck'>;
+
+/**
+ * `client` may be a factory: a fresh client per attempt re-reads the attach
+ * token, which a booting daemon rotates at bind time — then 'auth' is
+ * retried until the grace window ends instead of failing on the first read.
+ */
export async function waitForRuntimeHealth(
- client: Pick<AttachClient, 'healthCheck'>,
+ client: HealthProbe | (() => HealthProbe | null),
graceMs: number,
): Promise<{ ok: boolean; message?: string }> {
const deadline = Date.now() + graceMs;
+ const factory = typeof client === 'function';
for (;;) {
try {
- await client.healthCheck();
+ const probe = factory ? (client as () => HealthProbe | null)() : (client as HealthProbe);
+ if (!probe) throw new Error('no attach token yet');
+ await probe.healthCheck();
return { ok: true };
} catch (err) {
const message = String((err as Error)?.message || err);
- if (isFinalHealthFailure(message)) return { ok: false, message };
+ if (message.startsWith('foreign:')) return { ok: false, message };
+ if (message === 'auth' && !factory) return { ok: false, message };
if (Date.now() >= deadline) return { ok: false, message };
await new Promise(resolve => setTimeout(resolve, 250));
}
}
}
+/** A runtime pid is alive but has not written its attach token yet (booting). */
+async function waitForAttachTarget(graceMs: number): Promise<AttachTarget | null> {
+ const deadline = Date.now() + graceMs;
+ for (;;) {
+ const target = findAttachTarget();
+ if (target) return target;
+ const alive = getForegroundRuntimeStatus().running || getDaemonStatus().running;
+ if (!alive || Date.now() >= deadline) return null;
+ await new Promise(resolve => setTimeout(resolve, 250));
+ }
+}
+
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. */
@@ -384,7 +407,7 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu
const { AttachTui } = await import('../ui/attach-tui.js');
const chalk = (await import('chalk')).default;
- const target = findAttachTarget();
+ const target = await waitForAttachTarget(RUNTIME_BOOT_GRACE_MS);
if (!target) {
const runtimeRunning = getForegroundRuntimeStatus().running || getDaemonStatus().running;
if (!runtimeRunning) {
@@ -397,24 +420,22 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu
return 'unavailable';
}
+ // A fresh client per attempt: the token file is re-read, so a daemon that
+ // rotates its token while booting is caught up with instead of refused.
+ const freshClient = (): AttachClient | null => {
+ const token = readAttachToken();
+ return token ? new AttachClient(target.baseUrl, token, target.pids) : null;
+ };
let client = new AttachClient(target.baseUrl, target.token, target.pids);
try {
await client.healthCheck();
} catch (firstErr) {
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.
+ let health: { ok: boolean; message?: string } = { ok: false, message };
+ if (!message.startsWith('foreign:')) {
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);
+ health = await waitForRuntimeHealth(freshClient, RUNTIME_BOOT_GRACE_MS);
+ if (health.ok) client = freshClient() ?? client;
}
if (health.ok === false) {
message = health.message ?? message;
diff --git a/src/cli/single-runtime.test.ts b/src/cli/single-runtime.test.ts
new file mode 100644
index 00000000..79b66647
--- /dev/null
+++ b/src/cli/single-runtime.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { ChannelRegistry } from '../channels/registry.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+const index = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.ts'), 'utf8');
+
+/**
+ * ONE runtime owns the fleet (ADR-024). Launching `mercury` with no daemon
+ * used to spawn the daemon AND boot a second full runtime in the terminal:
+ * every bot turn then ran on the thread that paints keystrokes, and two
+ * Telegram pollers made Telegram answer 409 to both. The terminal attaches
+ * to the daemon; a foreground runtime beside a live daemon is a terminal
+ * for the main agent only.
+ */
+describe('single runtime', () => {
+ it('launch and recovery spawn the daemon and attach — never spawn and boot a second runtime', () => {
+ // The one remaining spawn-then-boot is `mercury code`, which needs the
+ // in-process TUI — and runAgent() beside the daemon is a terminal only.
+ const spawnThenBoot = index.match(/autoDaemonize\(\);\n\s*await runAgent\(\);/g) ?? [];
+ expect(spawnThenBoot).toHaveLength(1);
+ expect(index.slice(0, index.indexOf(spawnThenBoot[0] ?? "")).trimEnd()).toMatch(/Mercury Code needs the in-process TUI[^\n]*\n[^\n]*\(ADR-024\)\.$/);
+ expect(index).toContain('async function bootDaemonThenAttach()');
+ expect(index.split('await bootDaemonThenAttach();').length - 1).toBeGreaterThanOrEqual(2);
+ });
+
+ it('a foreground runtime beside a live daemon runs no bots, no channels, no web', () => {
+ expect(index).toContain('const daemonOwnsRuntime = !isDaemon && getDaemonStatus().running;');
+ expect(index).toContain('new ChannelRegistry(config, { cliOnly: daemonOwnsRuntime })');
+ expect(index).toContain('if (config.bots?.enabled && !daemonOwnsRuntime) {');
+ expect(index).toContain('Web, channels and bots are served by the background daemon');
+ expect(index).toContain('agent.terminalOnly = daemonOwnsRuntime;');
+ });
+
+ it('ChannelRegistry cliOnly wires the terminal and nothing else', () => {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.channels.telegram.enabled = true;
+ config.channels.telegram.botToken = '123:abc';
+ const full = new ChannelRegistry(config);
+ const cliOnly = new ChannelRegistry(config, { cliOnly: true });
+ expect(full.get('telegram')).toBeDefined();
+ expect(cliOnly.get('telegram')).toBeUndefined();
+ expect(cliOnly.get('cli')).toBeDefined();
+ });
+});
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 3642b66c..b3194008 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -544,6 +544,12 @@ export class Agent {
supervisor?: import('../core/supervisor.js').SubAgentSupervisor;
botManager?: import('../bots/bot-manager.js').BotManager;
/** Bot awaiting a persona from the next message (post-create setup flow). */
+ /**
+ * A terminal beside a live daemon (ADR-024): the daemon owns persisted
+ * schedules, interrupted-work recovery and undelivered replies — running
+ * them here too would fire every cron twice and replay work twice.
+ */
+ terminalOnly = false;
pendingPersonaFor: string | null = null;
/** The chat whose next message is the persona (Telegram/web/Discord — channels without a bot thread). */
pendingPersonaChannelId: string | null = null;
@@ -1987,14 +1993,18 @@ export class Agent {
async wake(): Promise<void> {
this.lifecycle.transition('onboarding');
this.lifecycle.transition('idle');
- this.scheduler.restorePersistedTasks();
- this.scheduler.startHeartbeat();
+ if (!this.terminalOnly) {
+ this.scheduler.restorePersistedTasks();
+ this.scheduler.startHeartbeat();
+ }
await this.channels.startAll();
this.running = true;
- const recovered = this.workLedger.recoverInterrupted();
- for (const entry of recovered) this.queueMessage(entry.message, entry.key);
- await this.replayUndeliveredResponses();
+ if (!this.terminalOnly) {
+ const recovered = this.workLedger.recoverInterrupted();
+ for (const entry of recovered) this.queueMessage(entry.message, entry.key);
+ await this.replayUndeliveredResponses();
+ }
this.startOutboxRetry();
void this.processQueue();
diff --git a/src/index.ts b/src/index.ts
index e69f1bae..18572979 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -87,6 +87,7 @@ 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, setShutdownHandler } from './web/server.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
+import { startLoopLagMonitor } from './utils/loop-lag.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
let pkgVersion: string;
@@ -2239,14 +2240,31 @@ async function healRuntimeAndBoot(): Promise<void> {
console.log(chalk.yellow(' Runtime is not responding — restarting it...'));
await stopForegroundRuntime();
await stopDaemon();
- autoDaemonize();
+ await bootDaemonThenAttach();
+}
+
+/**
+ * The daemon is the runtime; the terminal attaches to it. Only when no
+ * daemon can run here (Termux, unsupported platform) does the terminal
+ * become the runtime itself.
+ */
+async function bootDaemonThenAttach(): Promise<void> {
+ if (!autoDaemonize()) {
+ await runAgent();
+ return;
+ }
+ const result = await runAttach();
+ if (result === 'attached') return;
+ // The daemon came up but we could not attach (web disabled, port taken):
+ // a terminal for the main agent only — runAgent() sees the live daemon
+ // and leaves channels, bots and the port to it.
await runAgent();
}
-function autoDaemonize(): void {
+function autoDaemonize(): boolean {
const daemon = getDaemonStatus();
if (daemon.running && daemon.pid) {
- return;
+ return true;
}
console.log(chalk.dim(' Setting up background mode...'));
@@ -2275,6 +2293,7 @@ function autoDaemonize(): void {
console.log(chalk.yellow(' Background mode not available. Run `mercury start` to set it up.'));
}
console.log('');
+ return getDaemonStatus().running;
}
function runPlatformDoctor(): void {
@@ -2328,6 +2347,13 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// launchd/systemd units carry a pinned PATH; Task Scheduler cannot.
if (isDaemon) pinDaemonPathOnWindows();
registerRuntimeProcess(runtimeMode);
+ // ONE runtime owns channels, bots and the web port. A foreground runtime
+ // beside a live daemon (mercury code, a recovery boot) is a terminal for
+ // the main agent only: a second fleet in the TUI process ran every bot
+ // turn on the thread that paints keystrokes, and a second Telegram poller
+ // made Telegram answer 409 to both. (ADR-024)
+ const daemonOwnsRuntime = !isDaemon && getDaemonStatus().running;
+ startLoopLagMonitor();
// Crash forensics: V8 fatal errors (heap OOM etc.) print a native stack
// that scrolls away with the TUI. Ask V8 to keep a stack trace for the
@@ -2403,6 +2429,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
logger.info(`${name} is waking up (daemon mode)...`);
}
+ if (daemonOwnsRuntime) logger.info({ daemonPid: getDaemonStatus().pid }, 'Background daemon owns channels, bots and web — this terminal runs the main agent only');
const tokenBudget = new TokenBudget(config);
// Initialize the shared cloud token store before providers so the
@@ -2474,7 +2501,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
logger.warn(`Second brain disabled: ${SECOND_BRAIN_UNAVAILABLE_MESSAGE}`);
}
- const channels = new ChannelRegistry(config);
+ const channels = new ChannelRegistry(config, { cliOnly: daemonOwnsRuntime });
const webChannel = new WebChannel(config.identity.name);
channels.register('web', webChannel);
const capabilities = new CapabilityRegistry(skillLoader, scheduler, tokenBudget, undefined, userMemory ?? undefined);
@@ -2592,6 +2619,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
);
agent.setSkillLoader(skillLoader);
+ agent.terminalOnly = daemonOwnsRuntime;
if (supervisor) {
agent.setSupervisor(supervisor);
@@ -2599,7 +2627,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// Mercury Bots: fleet manager runs outside the main message queue.
let botManager: BotManager | undefined;
- if (config.bots?.enabled) {
+ if (config.bots?.enabled && !daemonOwnsRuntime) {
const bot = new BotManager({
config,
providers,
@@ -3564,7 +3592,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
console.log(chalk.green(` ${name} is live. Type a message and press Enter.`));
console.log(chalk.dim(' Ctrl+C to exit · /help for commands'));
- if (config.web.enabled) {
+ if (daemonOwnsRuntime) {
+ console.log(chalk.dim(` Web, channels and bots are served by the background daemon (PID ${getDaemonStatus().pid}).`));
+ } else if (config.web.enabled) {
startWebServer();
// Rotate the machine-local attach token for this boot so second
// terminals can connect without the web login flow.
@@ -3782,8 +3812,7 @@ program
await attachOrHeal();
return;
}
- autoDaemonize();
- await runAgent();
+ await bootDaemonThenAttach();
});
program
@@ -4917,6 +4946,8 @@ program
console.log('');
return;
}
+ // Mercury Code needs the in-process TUI. Beside the daemon it just
+ // spawned, runAgent() is a terminal for the main agent only (ADR-024).
autoDaemonize();
await runAgent();
});
diff --git a/src/utils/loop-lag.ts b/src/utils/loop-lag.ts
new file mode 100644
index 00000000..8ba5f0aa
--- /dev/null
+++ b/src/utils/loop-lag.ts
@@ -0,0 +1,42 @@
+import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';
+import { logger } from './logger.js';
+
+/**
+ * Event-loop stall monitor. Typing lag in the TUI and late Telegram replies
+ * are almost always the main thread being held by synchronous work; this
+ * makes that measurable (/api/health, doctor) instead of a feeling.
+ */
+let histogram: IntervalHistogram | null = null;
+let last = { p99Ms: 0, maxMs: 0, at: 0 };
+let timer: NodeJS.Timeout | null = null;
+
+export const LOOP_STALL_WARN_MS = 250;
+
+export function startLoopLagMonitor(windowMs = 10_000): void {
+ if (histogram) return;
+ histogram = monitorEventLoopDelay({ resolution: 20 });
+ histogram.enable();
+ timer = setInterval(() => {
+ if (!histogram) return;
+ const p99Ms = histogram.percentile(99) / 1e6;
+ const maxMs = histogram.max / 1e6;
+ last = { p99Ms, maxMs, at: Date.now() };
+ if (maxMs >= LOOP_STALL_WARN_MS) {
+ logger.warn({ maxMs: Math.round(maxMs), p99Ms: Math.round(p99Ms) }, 'Event loop stalled — something synchronous held the main thread');
+ }
+ histogram.reset();
+ }, windowMs);
+ timer.unref();
+}
+
+export function stopLoopLagMonitor(): void {
+ if (timer) clearInterval(timer);
+ timer = null;
+ histogram?.disable();
+ histogram = null;
+}
+
+/** Last window's event-loop delay: p99 and worst stall, in ms. */
+export function getLoopLag(): { p99Ms: number; maxMs: number; at: number } {
+ return { ...last };
+}
diff --git a/src/web/api/status.ts b/src/web/api/status.ts
index 03a30d64..5b47969e 100644
--- a/src/web/api/status.ts
+++ b/src/web/api/status.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isLoopbackRequest } from '../middleware.js';
+import { getLoopLag } from '../../utils/loop-lag.js';
export interface AgentStatus {
running: boolean;
@@ -59,7 +60,8 @@ function versionString(): string {
*/
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' });
+ const lag = getLoopLag();
+ return c.json({ ok: true, pid: process.pid, version: versionString(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) } });
});
status.get('/api/status', (c) => {