Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(core): eliminate all 12 silent task failure paths
Salman Qureshib3378cb8ee63
diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 308b2cee..96a6a55d 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -464,17 +464,39 @@ export class CLIChannel extends BaseChannel {isThinking: true,});- for await (const chunk of content) {- full += chunk;- const now = Date.now();- if (now - lastRender >= 16) {+ try {+ for await (const chunk of content) {+ full += chunk;+ const now = Date.now();+ if (now - lastRender >= 16) {+ this.update({+ chatMessages: this.state.chatMessages.map((m) =>+ m.id === msgId ? { ...m, content: full, streaming: true } : m,+ ),+ });+ lastRender = now;+ }+ }+ } catch (err) {+ // Stream was interrupted (API disconnect, abort, etc.). Save+ // whatever partial text we accumulated so the user doesn't lose it.+ logger.warn({ err, partialLen: full.length }, 'CLI stream interrupted, saving partial text');+ if (full.length > 0) {+ this.update({+ chatMessages: this.state.chatMessages.map((m) =>+ m.id === msgId ? { ...m, content: full + '\n\n⚠ Stream was interrupted. Partial response shown above.', streaming: false } : m,+ ),+ isThinking: false,+ });+ } else {this.update({chatMessages: this.state.chatMessages.map((m) =>- m.id === msgId ? { ...m, content: full, streaming: true } : m,+ m.id === msgId ? { ...m, content: '⚠ Stream was interrupted before any response was generated.', streaming: false } : m,),+ isThinking: false,});- lastRender = now;}+ return full;}this.update({diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 852b15c3..fa058df2 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -165,7 +165,7 @@ export class TelegramChannel extends BaseChannel {if (this.onPermissionMode) {this.onPermissionMode(mode, chatId);}- }).catch(() => {});+ }).catch((e: any) => logger.warn({ e }, 'telegram permission ask failed'));this.permissionModes.set(chatId, 'ask-me');}@@ -194,7 +194,7 @@ export class TelegramChannel extends BaseChannel {if (this.onPermissionMode) {this.onPermissionMode(mode, chatId);}- }).catch(() => {});+ }).catch((e: any) => logger.warn({ e }, 'telegram permission ask failed'));return;}@@ -364,7 +364,7 @@ export class TelegramChannel extends BaseChannel {const resolved = path.resolve(filePath);if (!fs.existsSync(resolved)) {for (const chatId of chatIds) {- await this.bot.api.sendMessage(chatId, `File not found: ${filePath}`).catch(() => {});+ await this.bot.api.sendMessage(chatId, `File not found: ${filePath}`).catch((e: any) => logger.warn({ e }, "telegram send failed"));}return;}@@ -388,7 +388,7 @@ export class TelegramChannel extends BaseChannel {logger.info({ file: resolved, chatId }, 'File sent via Telegram');} catch (err: any) {logger.error({ err: err.message, file: resolved, chatId }, 'Telegram sendFile failed');- await this.bot.api.sendMessage(chatId, `Failed to send file: ${err.message}`).catch(() => {});+ await this.bot.api.sendMessage(chatId, `Failed to send file: ${err.message}`).catch((e: any) => logger.warn({ e }, "telegram send failed"));}}}@@ -416,7 +416,7 @@ export class TelegramChannel extends BaseChannel {try {await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });} catch (err: any) {- await this.bot.api.sendMessage(chatId, this.stripHtml(html)).catch(() => {});+ await this.bot.api.sendMessage(chatId, this.stripHtml(html)).catch((e: any) => logger.warn({ e }, "telegram html send failed"));}}return full;@@ -476,9 +476,9 @@ export class TelegramChannel extends BaseChannel {startTypingLoop(chatId: number): void {this.stopTypingLoop();- this.bot?.api.sendChatAction(chatId, 'typing').catch(() => {});+ this.bot?.api.sendChatAction(chatId, 'typing').catch((e: any) => logger.warn({ e }, "telegram sendChatAction failed"));this.typingInterval = setInterval(() => {- this.bot?.api.sendChatAction(chatId, 'typing').catch(() => {});+ this.bot?.api.sendChatAction(chatId, 'typing').catch((e: any) => logger.warn({ e }, "telegram sendChatAction failed"));}, 4000);}@@ -791,7 +791,7 @@ export class TelegramChannel extends BaseChannel {} catch {await this.bot.api.sendMessage(admin.chatId, message, {reply_markup: keyboard,- }).catch(() => {});+ }).catch((e: any) => logger.warn({ e }, "telegram send failed"));}}}@@ -819,7 +819,7 @@ export class TelegramChannel extends BaseChannel {const request = findTelegramPendingRequest(this.config, requestUserId);if (!request) {await ctx.answerCallbackQuery({ text: 'Already handled' });- await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));return;}@@ -832,7 +832,7 @@ export class TelegramChannel extends BaseChannel {saveConfig(this.config);await ctx.answerCallbackQuery({ text: 'Approved' });- await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));await this.sendDirectMessage(request.chatId,`Telegram access approved. You can now chat with Mercury.\n\nTelegram access: ${getTelegramAccessSummary(this.config)}`,@@ -850,7 +850,7 @@ export class TelegramChannel extends BaseChannel {saveConfig(this.config);await ctx.answerCallbackQuery({ text: 'Rejected' });- await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));await this.sendDirectMessage(request.chatId,'Your Telegram access request was rejected. This bot is not available to you.',@@ -948,7 +948,7 @@ export class TelegramChannel extends BaseChannel {await ctx.answerCallbackQuery({ text: 'Recent memories' });const recent = this.chatCommandContext.memoryRecent(10);if (recent.length === 0) {- await this.bot.api.sendMessage(chatId, 'No memories yet.').catch(() => {});+ await this.bot.api.sendMessage(chatId, 'No memories yet.').catch((e: any) => logger.warn({ e }, "telegram send failed"));return;}const lines = ['<b>Recent Memories:</b>\n'];@@ -972,7 +972,7 @@ export class TelegramChannel extends BaseChannel {await this.bot.api.sendMessage(chatId, currentlyPaused? 'Learning resumed. Mercury will remember new things from conversations.': 'Learning paused. Mercury will not store new memories until resumed.',- ).catch(() => {});+ ).catch((e: any) => logger.warn({ e }, "telegram send failed"));await this.sendMemoryKeyboard(chatId);return;}@@ -994,7 +994,7 @@ export class TelegramChannel extends BaseChannel {if (action === 'clear_yes') {const cleared = this.chatCommandContext.memoryClear();await ctx.answerCallbackQuery({ text: `Cleared ${cleared} memories` });- await this.bot.api.sendMessage(chatId, `Cleared ${cleared} memories.`).catch(() => {});+ await this.bot.api.sendMessage(chatId, `Cleared ${cleared} memories.`).catch((e: any) => logger.warn({ e }, "telegram send failed"));return;}@@ -1011,7 +1011,7 @@ export class TelegramChannel extends BaseChannel {const subconsciousMemories = this.chatCommandContext.memoryGetSubconscious(5);const subconsciousTotal = this.chatCommandContext.memorySummary().subconsciousTotal;if (subconsciousMemories.length === 0) {- await this.bot.api.sendMessage(chatId, '💤 <b>Subconscious Memory</b>\n\nNo subconscious memories yet. Memories move here after 30 days of not being referenced, and are recalled automatically when relevant to a conversation.').catch(() => {});+ await this.bot.api.sendMessage(chatId, '💤 <b>Subconscious Memory</b>\n\nNo subconscious memories yet. Memories move here after 30 days of not being referenced, and are recalled automatically when relevant to a conversation.').catch((e: any) => logger.warn({ e }, "telegram send failed"));return;}const lines = ['💤 <b>Subconscious Memory (first 5 by recency):</b>\n'];@@ -1543,7 +1543,7 @@ export class TelegramChannel extends BaseChannel {try {await this.bot?.api.sendMessage(chatId, chunk, { parse_mode: 'HTML' });} catch {- await this.bot?.api.sendMessage(chatId, this.stripHtml(chunk)).catch(() => {});+ await this.bot?.api.sendMessage(chatId, this.stripHtml(chunk)).catch((e: any) => logger.warn({ e }, "telegram html send failed"));}}}@@ -1555,7 +1555,7 @@ export class TelegramChannel extends BaseChannel {try {await this.bot?.api.sendMessage(chatId, html, { parse_mode: 'HTML' });} catch {- await this.bot?.api.sendMessage(chatId, this.stripHtml(html)).catch(() => {});+ await this.bot?.api.sendMessage(chatId, this.stripHtml(html)).catch((e: any) => logger.warn({ e }, "telegram html send failed"));}}@@ -1583,7 +1583,7 @@ export class TelegramChannel extends BaseChannel {try {await this.bot.api.sendMessage(chatId, mdToTelegram(content), { parse_mode: 'HTML' });} catch {- await this.bot.api.sendMessage(chatId, content).catch(() => {});+ await this.bot.api.sendMessage(chatId, content).catch((e: any) => logger.warn({ e }, "telegram send failed"));}}diff --git a/src/cli/watchdog.ts b/src/cli/watchdog.tsindex 72dd1b9c..223b6b6e 100644--- a/src/cli/watchdog.ts+++ b/src/cli/watchdog.ts@@ -1,4 +1,5 @@import { logger } from '../utils/logger.js';+import { writeCrashFlag } from '../core/crash-flag.js';const MAX_RESTARTS = 10;const RESTART_WINDOW_MS = 60_000;@@ -18,6 +19,13 @@ export async function runWithWatchdog(agentFn: () => Promise<void>): Promise<voiif (restartCount >= MAX_RESTARTS) {logger.error({ restartCount }, 'Max restarts exceeded within 60s. Exiting.');+ writeCrashFlag({+ reason: `Max restarts exceeded (${restartCount} crashes in 60s). Last error: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300),+ timestamp: Date.now(),+ });+ // Last-gasp: synchronous stderr write so the log always shows+ // even if the logger is broken.+ process.stderr.write(`[mercury] FATAL: Max restarts exceeded (${restartCount} in 60s). Last error: ${err instanceof Error ? err.message : String(err)}\n`);process.exit(1);}diff --git a/src/core/agent.ts b/src/core/agent.tsindex b5315885..86c0d4c9 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -356,7 +356,7 @@ export class Agent {supervisor.setNotifyCallback(async (channelType, channelId, message) => {const channel = this.channels.get(channelType as any);if (channel) {- await channel.send(message, channelId).catch(() => {});+ await channel.send(message, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}});supervisor.setLifecycleCallback((event) => {@@ -712,7 +712,7 @@ export class Agent {void channel.send(`⚠ Task stalled (no progress for ${stallSec}s). Stopped to avoid hanging. You can retry or use /bg current sooner for long tasks.`,msg.channelId,- ).catch(() => {});+ ).catch((e) => logger.warn({ e }, 'channel send failed'));return;}@@ -728,7 +728,7 @@ export class Agent {void channel.send(`⏳ Working... ${elapsedSec}s elapsed${stepInfo}.${narrativeBlock}${handoffHint}`,msg.channelId,- ).catch(() => {});+ ).catch((e) => logger.warn({ e }, 'channel send failed'));// Escalate: 20s → 30s → 45s → 60s (cap)if (heartbeatCount <= 2) {@@ -773,11 +773,11 @@ export class Agent {const cliCh = this.channels.get('cli');if (cliCh) {- (cliCh as CLIChannel).send(message).catch(() => {});+ (cliCh as CLIChannel).send(message).catch((e) => logger.warn({ e }, 'channel send failed'));}const tgCh = this.channels.get('telegram');if (tgCh) {- tgCh.send(message).catch(() => {});+ tgCh.send(message).catch((e) => logger.warn({ e }, 'channel send failed'));}this.syncBgTasksToTui();@@ -880,7 +880,7 @@ export class Agent {const channel = this.channels.getChannelForMessage(msg);if (channel) {const agentLines = runningAgents.map(a => ` 🔄 ${a.id}: ${a.task.slice(0, 45)}${a.task.length > 45 ? '...' : ''}`);- await channel.send(`**Multi-agent mode** — ${runningAgents.length} agent${runningAgents.length > 1 ? 's' : ''} active:\n${agentLines.join('\n')}`, msg.channelId).catch(() => {});+ await channel.send(`**Multi-agent mode** — ${runningAgents.length} agent${runningAgents.length > 1 ? 's' : ''} active:\n${agentLines.join('\n')}`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}}}@@ -977,12 +977,12 @@ export class Agent {const notice = this.saverMode.consumeAutoActivationNotice();if (notice && msg.channelType !== 'internal') {const ch = this.channels.get(msg.channelType as any);- if (ch) await ch.send(notice, msg.channelId).catch(() => {});+ if (ch) await ch.send(notice, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}this.syncSaverToCli();} else if (transition.deactivated && msg.channelType !== 'internal') {const ch = this.channels.get(msg.channelType as any);- if (ch) await ch.send('⚡ Token Saver Mode auto-disengaged (usage dropped). Normal response settings restored.', msg.channelId).catch(() => {});+ if (ch) await ch.send('⚡ Token Saver Mode auto-disengaged (usage dropped). Normal response settings restored.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));this.syncSaverToCli();}}@@ -1138,7 +1138,7 @@ export class Agent {content: `[Routing] User clarified: use the \`${chosenName}\` skill. Invoke it via \`use_skill\` with name="${chosenName}" before doing anything else.`,});if (channel) {- await channel.send(`Routing to **${chosenName}**.`, msg.channelId).catch(() => {});+ await channel.send(`Routing to **${chosenName}**.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}}// If the user picked "None of these" we just fall through silently.@@ -1160,7 +1160,7 @@ export class Agent {if (plan.batches.length > 0) {const channel = this.channels.getChannelForMessage(msg);if (channel) {- await channel.send(`🧠 Routing to ${topBatch.skills.length} skills in **${topBatch.categoryLabel}**: ${matchedSkillNames.join(', ')}.`, msg.channelId).catch(() => {});+ await channel.send(`🧠 Routing to ${topBatch.skills.length} skills in **${topBatch.categoryLabel}**: ${matchedSkillNames.join(', ')}.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}const batchResults = await this.skillBatcher.execute(plan, trimmed, msg.channelId, msg.channelType);@@ -1191,7 +1191,7 @@ export class Agent {const channel = this.channels.getChannelForMessage(msg);if (channel) {- await channel.typing(msg.channelId).catch(() => {});+ await channel.typing(msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));this.markProgress();}@@ -1279,7 +1279,7 @@ export class Agent {if (loopDetector.detectAbsoluteLimit()) {logger.warn('Absolute tool call limit reached — aborting');if (channel && msg.channelType !== 'internal') {- await channel.send('⚠ Tool call limit reached (25 calls). Stopping to prevent runaway loop.', msg.channelId).catch(() => {});+ await channel.send('⚠ Tool call limit reached (25 calls). Stopping to prevent runaway loop.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1292,7 +1292,7 @@ export class Agent {logger.warn({ tool: hardLoop.tool, count: hardLoop.count }, 'Hard loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send(`☿ **Mercury Autopilot** · Identical call loop — ${hardLoop.tool} called ${hardLoop.count}x with same params. Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Identical call loop — ${hardLoop.tool} called ${hardLoop.count}x with same params. Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1302,7 +1302,7 @@ export class Agent {logger.warn({ tool: similarLoop.tool, count: similarLoop.count }, 'Failing loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send(`☿ **Mercury Autopilot** · Failing loop — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Failing loop — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1334,7 +1334,7 @@ export class Agent {});if (!shouldContinue) {logger.warn({ tool: analysis.tool, count: analysis.count }, 'Mercury Autopilot: AI verdict — unproductive, aborting');- await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} repeated ${analysis.count}x with low progress (${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} repeated ${analysis.count}x with low progress (${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));loopAbortController.abort();return;}@@ -1342,7 +1342,7 @@ export class Agent {// Not yet at check limit — let it continue with a noteloopDetector.reset();loopWarningSent = false;- await channel.send(`☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));} else {loopWarningSent = true;const shouldContinue = await channel.askToContinue(@@ -1360,7 +1360,7 @@ export class Agent {// verdict === 'stuck'if (this.capabilities.permissions.isAutoApproveAll()) {logger.warn({ tool: analysis.tool, count: analysis.count, diversity: analysis.paramDiversity, successRate: analysis.successRate }, 'Mercury Autopilot: stuck loop detected');- await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} is stuck (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} is stuck (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));loopAbortController.abort();return;} else {@@ -1381,7 +1381,7 @@ export class Agent {if (channel && msg.channelType !== 'internal') {if (channel instanceof CLIChannel) {for (const tc of toolCalls) {- void (channel as CLIChannel).sendToolFeedback(tc.toolName, tc.input as Record<string, any>).catch(() => {});+ void (channel as CLIChannel).sendToolFeedback(tc.toolName, tc.input as Record<string, any>).catch((e) => logger.warn({ e }, 'channel send failed'));}if (toolResults) {for (let i = 0; i < toolResults.length; i++) {@@ -1395,14 +1395,14 @@ export class Agent {} else if (channel instanceof TelegramChannel) {const tgCh = channel as TelegramChannel;for (const tc of toolCalls) {- void tgCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch(() => {});+ void tgCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}if (toolResults) {for (let i = 0; i < toolResults.length; i++) {const tr = toolResults[i] as any;const tcName = toolCalls[i]?.toolName as string | undefined;if (tcName) {- await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch(() => {});+ await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}}}@@ -1421,7 +1421,7 @@ export class Agent {}}} else {- await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});+ await channel.send(` [Using: ${names}]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}this.markProgress();}@@ -1435,7 +1435,7 @@ export class Agent {logger.warn('Reasoning loop detected — model keeps thinking without acting, aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send('⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch(() => {});+ await channel.send('⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1445,7 +1445,7 @@ export class Agent {logger.warn({ pattern: textRepeat.pattern, count: textRepeat.count }, 'Text repetition loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch(() => {});+ await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();}@@ -1522,7 +1522,7 @@ export class Agent {if (loopDetector.detectAbsoluteLimit()) {logger.warn('Absolute tool call limit reached — aborting');if (channel && msg.channelType !== 'internal') {- await channel.send('⚠ Tool call limit reached (25 calls). Stopping to prevent runaway loop.', msg.channelId).catch(() => {});+ await channel.send('⚠ Tool call limit reached (25 calls). Stopping to prevent runaway loop.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1535,7 +1535,7 @@ export class Agent {logger.warn({ tool: hardLoop.tool, count: hardLoop.count }, 'Hard loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send(`☿ **Mercury Autopilot** · Identical call loop — ${hardLoop.tool} called ${hardLoop.count}x with same params. Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Identical call loop — ${hardLoop.tool} called ${hardLoop.count}x with same params. Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1545,7 +1545,7 @@ export class Agent {logger.warn({ tool: similarLoop.tool, count: similarLoop.count }, 'Failing loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send(`☿ **Mercury Autopilot** · Failing loop — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Failing loop — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1577,7 +1577,7 @@ export class Agent {});if (!shouldContinue) {logger.warn({ tool: analysis.tool, count: analysis.count }, 'Mercury Autopilot: AI verdict — unproductive, aborting');- await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} repeated ${analysis.count}x with low progress (${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} repeated ${analysis.count}x with low progress (${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));loopAbortController.abort();return;}@@ -1585,7 +1585,7 @@ export class Agent {// Not yet at check limit — let it continue with a noteloopDetector.reset();loopWarningSent = false;- await channel.send(`☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));} else {loopWarningSent = true;const shouldContinue = await channel.askToContinue(@@ -1603,7 +1603,7 @@ export class Agent {// verdict === 'stuck'if (this.capabilities.permissions.isAutoApproveAll()) {logger.warn({ tool: analysis.tool, count: analysis.count, diversity: analysis.paramDiversity, successRate: analysis.successRate }, 'Mercury Autopilot: stuck loop detected');- await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} is stuck (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch(() => {});+ await channel.send(`☿ **Mercury Autopilot** · ${analysis.tool} is stuck (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity, ${Math.round(analysis.successRate * 100)}% success). Stopping this path.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));loopAbortController.abort();return;} else {@@ -1624,7 +1624,7 @@ export class Agent {if (channel && msg.channelType !== 'internal') {if (channel instanceof CLIChannel) {for (const tc of toolCalls) {- void (channel as CLIChannel).sendToolFeedback(tc.toolName, tc.input as Record<string, any>).catch(() => {});+ void (channel as CLIChannel).sendToolFeedback(tc.toolName, tc.input as Record<string, any>).catch((e) => logger.warn({ e }, 'channel send failed'));}if (toolResults) {for (let i = 0; i < toolResults.length; i++) {@@ -1638,14 +1638,14 @@ export class Agent {} else if (channel instanceof TelegramChannel) {const tgCh = channel as TelegramChannel;for (const tc of toolCalls) {- void tgCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch(() => {});+ void tgCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}if (toolResults) {for (let i = 0; i < toolResults.length; i++) {const tr = toolResults[i] as any;const tcName = toolCalls[i]?.toolName as string | undefined;if (tcName) {- await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch(() => {});+ await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}}}@@ -1664,7 +1664,7 @@ export class Agent {}}} else {- await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});+ await channel.send(` [Using: ${names}]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}this.markProgress();}@@ -1678,7 +1678,7 @@ export class Agent {logger.warn('Reasoning loop detected — model keeps thinking without acting, aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send('⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch(() => {});+ await channel.send('⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();return;@@ -1688,7 +1688,7 @@ export class Agent {logger.warn({ pattern: textRepeat.pattern, count: textRepeat.count }, 'Text repetition loop detected — aborting');if (!loopWarningSent && channel && msg.channelType !== 'internal') {loopWarningSent = true;- await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch(() => {});+ await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}loopAbortController.abort();}@@ -1727,7 +1727,7 @@ export class Agent {lastError = err;logger.warn({ provider: provider.name, err: err.message }, 'Provider failed, trying fallback');if (channel && msg.channelType !== 'internal') {- await channel.send(` [Provider ${provider.name} failed, trying fallback...]`, msg.channelId).catch(() => {});+ await channel.send(` [Provider ${provider.name} failed, trying fallback...]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}}}@@ -1882,6 +1882,27 @@ export class Agent {this.lifecycle.transition('idle');} catch (err) {logger.error({ err }, 'Error handling message');+ // Always notify the user — they should never have to re-prompt+ // to find out their task died.+ const catchChannel = this.channels.getChannelForMessage(msg);+ if (catchChannel && msg.channelType !== 'internal') {+ const errMsg = err instanceof Error ? err.message : String(err);+ void catchChannel.send(+ `⚠ I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`,+ msg.channelId,+ ).catch((sendErr: any) => logger.warn({ sendErr }, 'Failed to notify user of handler error'));+ }+ // Write crash flag so next startup also reports the failure.+ try {+ const { writeCrashFlag } = await import('./crash-flag.js');+ writeCrashFlag({+ reason: `Unhandled agent error: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300),+ timestamp: Date.now(),+ activeTask: this.currentActivity || undefined,+ channelId: msg.channelId || undefined,+ channelType: msg.channelType || undefined,+ });+ } catch { /* best effort */ }this.lifecycle.transition('idle');} finally {if (wallTimeout) clearTimeout(wallTimeout);@@ -2017,7 +2038,7 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userawait channel.send(` Scheduled task started${skillInfo}: ${manifest.description}\nAll actions auto-approved for this run.`,manifest.sourceChannelId,- ).catch(() => {});+ ).catch((e) => logger.warn({ e }, 'channel send failed'));}let prompt = manifest.prompt || '';@@ -2210,6 +2231,23 @@ RULES:logger.info('Mercury has shut down');}+ /**+ * Notify all active channels with a message. Used before forced exits+ * (SIGTERM, crash, watchdog kill) so the user is never left wondering+ * what happened to their task.+ */+ async notifyAllChannels(message: string): Promise<void> {+ const active = this.channels.getActiveChannels();+ const sends = active.map((type) => {+ const ch = this.channels.get(type);+ if (!ch) return Promise.resolve();+ return ch.send(message).catch((e) => {+ logger.warn({ e, channel: type }, 'Failed to notify channel before exit');+ });+ });+ await Promise.allSettled(sends);+ }+/*** AI self-check: ask the model itself whether repeated tool usage is productive or a loop.* Used in allow-all mode instead of prompting the user.@@ -2307,7 +2345,7 @@ Is this productive iteration or a stuck loop?`,resolve(choices[0]);}, 120000);- channel.send(question, channelId).catch(() => {});+ channel.send(question, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));const tgBot = (channel as any).bot;if (tgBot) {@@ -2315,7 +2353,7 @@ Is this productive iteration or a stuck loop?`,? Number(channelId.split(':')[1]): Number(channelId);- tgBot.api.sendMessage(chatId, question, { reply_markup: kb }).catch(() => {});+ tgBot.api.sendMessage(chatId, question, { reply_markup: kb }).catch((e: any) => logger.warn({ e }, 'channel send failed'));const handler = async (ctx: any) => {const data = ctx.callbackQuery?.data;@@ -2336,7 +2374,7 @@ Is this productive iteration or a stuck loop?`,});}- await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch(() => {});+ await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));return choices[0];}diff --git a/src/core/background-tasks.ts b/src/core/background-tasks.tsindex b49cfbd9..0afcc35a 100644--- a/src/core/background-tasks.ts+++ b/src/core/background-tasks.ts@@ -42,7 +42,7 @@ const MAX_TASKS = 20;const PRUNE_AGE_MS = 60 * 60 * 1000;const SIGTERM_GRACE_MS = 3000;const MAX_PREVIEW = 200;-const DEFAULT_SHELL_TIMEOUT_MS = 0;+const DEFAULT_SHELL_TIMEOUT_MS = 30 * 60 * 1000;const BG_TASKS_FILE = 'background-tasks.json';let taskCounter = 0;@@ -434,6 +434,9 @@ export class BackgroundTaskManager {task.status = 'failed';task.completedAt = Date.now();task.stderr = `${task.stderr}\nRecovered after restart: task was running when process exited.`.trim();+ // Notify the user about recovered (failed) tasks so they don't+ // have to check /bg list to discover what happened.+ this.notifyComplete(task);}this.tasks.set(task.id, task);usedIds.add(task.id);diff --git a/src/core/crash-flag.ts b/src/core/crash-flag.tsnew file mode 100644index 00000000..b5f729c7--- /dev/null+++ b/src/core/crash-flag.ts@@ -0,0 +1,51 @@+/**+ * Crash flag — survival mechanism for ungraceful exits.+ *+ * When Mercury crashes or is killed mid-task, we write a small JSON file+ * to ~/.mercury/.crash-flag so the next startup can report what happened+ * to the user. The flag is deleted after being read.+ *+ * This solves the "silent task death" problem: users who return to+ * Mercury after a crash see "I crashed while working on X" instead of+ * a blank slate they have to investigate.+ */+import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++export interface CrashFlag {+ reason: string;+ timestamp: number;+ activeTask?: string;+ channelId?: string;+ channelType?: string;+}++const CRASH_FLAG_FILE = '.crash-flag';++function crashFlagPath(): string {+ return join(getMercuryHome(), CRASH_FLAG_FILE);+}++export function writeCrashFlag(flag: CrashFlag): void {+ try {+ writeFileSync(crashFlagPath(), JSON.stringify(flag, null, 2), 'utf-8');+ } catch {+ // Best-effort — if the FS is broken we're already in trouble.+ }+}++export function readCrashFlag(): CrashFlag | null {+ const p = crashFlagPath();+ if (!existsSync(p)) return null;+ try {+ const raw = readFileSync(p, 'utf-8');+ return JSON.parse(raw) as CrashFlag;+ } catch {+ return null;+ }+}++export function clearCrashFlag(): void {+ try { unlinkSync(crashFlagPath()); } catch { /* already gone */ }+}\ No newline at end of filediff --git a/src/core/supervisor.ts b/src/core/supervisor.tsindex 247c4684..d608514e 100644--- a/src/core/supervisor.ts+++ b/src/core/supervisor.ts@@ -89,7 +89,7 @@ export class SubAgentSupervisor {private fireLifecycleEvent(event: Parameters<AgentLifecycleCallback>[0]): void {for (const cb of this.lifecycleCallbacks) {- try { cb(event); } catch {}+ try { cb(event); } catch (err) { logger.warn({ err }, 'supervisor lifecycle callback threw'); }}}@@ -189,7 +189,7 @@ export class SubAgentSupervisor {if (entry) {const channelType = entry.sourceChannelType || 'cli';const channelId = entry.sourceChannelId || 'cli';- this.notify(channelType, channelId, `🔄 Agent ${agentId}: ${progress}`).catch(() => {});+ this.notify(channelType, channelId, `🔄 Agent ${agentId}: ${progress}`).catch((e) => logger.warn({ e, agentId }, 'supervisor progress notify failed'));}});@@ -216,6 +216,17 @@ export class SubAgentSupervisor {this.activeAgents.delete(config.id);this.fileLockManager.releaseAll(config.id);this.pausedAgents.delete(config.id);+ // Notify the user — they should never have to discover a crashed+ // sub-agent by re-prompting.+ const entry = this.taskBoard.get(config.id);+ if (entry) {+ const channelType = entry.sourceChannelType || 'cli';+ const channelId = entry.sourceChannelId || 'cli';+ const errMsg = err instanceof Error ? err.message : String(err);+ await this.notify(channelType, channelId,+ `❌ **Agent ${config.id}** crashed unexpectedly: "${entry.task.slice(0, 40)}"\nError: ${errMsg.slice(0, 150)}`,+ ).catch((e) => logger.warn({ e, agentId: config.id }, 'Failed to notify user of sub-agent crash'));+ }await this.processWaitQueue();});}diff --git a/src/index.ts b/src/index.tsindex 30ad9365..4404aa11 100644--- a/src/index.ts+++ b/src/index.ts@@ -1303,6 +1303,23 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {config = ensureCreatorField(config);const name = config.identity.name;+ // Check for crash flag from previous run — if Mercury crashed mid-task,+ // report it to the user immediately so they don't have to investigate.+ const { readCrashFlag, clearCrashFlag } = await import('./core/crash-flag.js');+ const crashFlag = readCrashFlag();+ if (crashFlag) {+ clearCrashFlag();+ const age = Math.round((Date.now() - crashFlag.timestamp) / 1000);+ const timeAgo = age >= 60 ? `${Math.floor(age / 60)}m ago` : `${age}s ago`;+ const msg = `⚠ Mercury crashed ${timeAgo}: ${crashFlag.reason}`;+ if (!isDaemon) {+ console.log(chalk.yellow(` ${msg}`));+ console.log(chalk.dim(' If you had an active task, it was interrupted. You can retry.\n'));+ } else {+ logger.warn({ crashFlag }, 'Previous crash detected');+ }+ }+if (!isDaemon) {logger.info(`${name} is waking up...`);} else {@@ -1803,6 +1820,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {} else {logger.info('Mercury is shutting down (daemon mode)');}+ // Notify all channels that Mercury is stopping — users should never+ // have to re-prompt to discover their task was killed mid-flight.+ try {+ await agent.notifyAllChannels('⚠ Mercury is shutting down. If I was working on something, it has been interrupted. Send a message after restart to continue.');+ } catch { /* best effort */ }if (userMemory) {try {userMemory.consolidate();@@ -1818,7 +1840,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {process.on('SIGTERM', shutdown);if (!isDaemon && process.platform !== 'win32') {- process.on('SIGHUP', () => {+ process.on('SIGHUP', async () => {logger.info('SIGHUP received — terminal closed. Daemonizing.');try {const result = tryAutoDaemonize();@@ -1826,9 +1848,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {logger.info(`Forked daemon. Foreground process exiting.`);} else {logger.warn('SIGHUP received but daemonization failed. Shutting down.');+ // Notify before forced exit+ try {+ await agent.notifyAllChannels('⚠ Mercury lost its terminal and could not daemonize. Shutting down — your task was interrupted.');+ } catch { /* best effort */ }}} catch {logger.warn('SIGHUP received but daemonization failed. Shutting down.');+ try {+ await agent.notifyAllChannels('⚠ Mercury lost its terminal and could not daemonize. Shutting down — your task was interrupted.');+ } catch { /* best effort */ }}process.exit(0);});diff --git a/src/web/server.ts b/src/web/server.tsindex 826bfc55..b26bcba9 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -187,12 +187,19 @@ process.on('exit', () => {process.on('uncaughtException', (err) => {logger.error({ err: err.message }, 'Uncaught exception in web server');- // Don't exit — let Mercury's main process handler decide+ // Write crash flag so next startup can report to the user.+ try {+ const { writeCrashFlag } = require('../core/crash-flag.js');+ writeCrashFlag({ reason: `Uncaught exception: ${err.message}`.slice(0, 300), timestamp: Date.now() });+ } catch { /* best effort */ }});process.on('unhandledRejection', (reason: any) => {logger.warn({ err: reason?.message || reason }, 'Unhandled rejection in web server (non-fatal)');- // Don't exit — unhandled rejections from API routes should not kill Mercury+ try {+ const { writeCrashFlag } = require('../core/crash-flag.js');+ writeCrashFlag({ reason: `Unhandled rejection: ${reason?.message || reason}`.slice(0, 300), timestamp: Date.now() });+ } catch { /* best effort */ }});export function startWebServer(): { port: number; url: string } {