Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(code): whitelabeled provider-failure + switch notices in Mercury Code
Salman Qureshi345d40c24e61
diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 868a2fcb..c229b755 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -1001,6 +1001,23 @@ export class CLIChannel extends BaseChannel {}}+ /**+ * Durable system notice (provider fallback errors, switch announcements).+ * Unlike the heartbeat, it RENDERS in Mercury Code (heartbeat rows are+ * filtered out of the coding transcript) and it is NOT removed when the+ * turn ends — the user must still see, after the response, that a provider+ * failed and the task continued on another route.+ */+ sendSystemNotice(content: string): void {+ const msg: ChatMessage = {+ id: `notice-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,+ role: 'system',+ content,+ timestamp: Date.now(),+ };+ this.trimAndSetMessages([...this.state.chatMessages, msg]);+ }+/*** Real-time tool event: called at TOOL EXECUTION START (from the AI SDK's* onToolCallStart), not after the LLM step completes. The step shows asdiff --git a/src/core/agent.ts b/src/core/agent.tsindex a6f4b7d7..85734f2b 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -407,6 +407,34 @@ function looksResearchy(text: string): boolean {/** No answer to the Mercury Code hand-off prompt is treated as "keep chatting". */export const MERCURY_CODE_HANDOFF_TIMEOUT_MS = 45_000;+/**+ * Whitelabel a provider error into one short, respectful line for the chat:+ * the user gets the real reason (token expired, rate limit, server error) —+ * never a stack trace or raw HTTP dump.+ */+export function whitelabelProviderError(err: any): string {+ const raw = String(err?.message || err || 'unknown error');+ const body = typeof (err as any)?.responseBody === 'string' ? (err as any).responseBody : '';+ const combined = `${raw} ${body}`;++ if (/401|invalid[_ -]?api[_ -]?key|token expired|expired token|invalid_api_key|unauthorized|authentication|credential/i.test(combined)) {+ return 'Access token expired or rejected (credentials)';+ }+ if (/403|forbidden|permission/i.test(combined)) {+ return 'The provider refused the request (permissions/quota)';+ }+ if (/429|rate limit|too many requests/i.test(combined)) {+ return 'Rate limited — too many requests right now';+ }+ if (/max[_ -]?tokens|context (length|window)|too large|exceed/i.test(combined)) {+ return 'The request exceeded the model limit';+ }+ if (/(5\d\d|bad gateway|service unavailable|timeout|timed out|ECONNRESET|ENOTFOUND|fetch failed|network)/i.test(combined)) {+ return 'Provider server error or network timeout';+ }+ return raw.split('\n')[0].replace(/\s+/g, ' ').slice(0, 120) || 'unknown error';+}+/*** Coding-shaped task detector for the Mercury Code hand-off prompt.* Conservative — only messages that clearly describe build/repair work on a@@ -1475,6 +1503,26 @@ export class Agent {return /timeout|timed out|network|socket|connection|temporar|unavailable|overloaded|rate.?limit|\b429\b|\b5\d\d\b|econn|fetch failed|stalled/.test(message);}+ /**+ * Durable provider fallback notice. On the CLI TUI (Mercury Code included)+ * it goes through sendSystemNotice — a durable system row that renders in+ * the coding transcript and survives the turn; on other channels it rides+ * the heartbeat or a plain send as before.+ */+ private async sendFallbackNotice(msg: ChannelMessage, line: string): Promise<void> {+ const channel = this.channels.getChannelForMessage(msg);+ if (!channel || msg.channelType === 'internal') return;+ if (channel instanceof CLIChannel) {+ channel.sendSystemNotice(line);+ return;+ }+ if (channel instanceof WebChannel) {+ channel.sendHeartbeat(line, msg.channelId);+ return;+ }+ await channel.send(line, msg.channelId);+ }+private async sendProgressNotice(msg: ChannelMessage, message: string): Promise<void> {const channel = this.channels.getChannelForMessage(msg);if (!channel || msg.channelType === 'internal') return;@@ -2287,11 +2335,16 @@ export class Agent {// limit) — showing only the last error hides the real fix from the// user.const providerFailures = new Map<string, string>();+ // Per-turn dedupe for the whitelabeled fallback notices — the same+ // provider failing repeatedly (guard rounds, retries) must not spam the+ // transcript with identical lines.+ const noticedProviderFailures = new Set<string>();// Guard-round provider rotation cursor (round 1 = current provider,// then walks the fallback chain — a narration-locked model is not the// only worker the agent has).let guardProviderCursor = 0;- for (const provider of [...providersForAttempt, ...providersForAttempt]) {+ const providerChain = [...providersForAttempt, ...providersForAttempt];+ for (const provider of providerChain) {// Per-attempt latency accounting: the only way to answer "why is// coding slow" with data instead of guesses.const attemptStartedAt = Date.now();@@ -3205,8 +3258,19 @@ export class Agent {break;}logger.warn({ provider: provider.name, err: err.message }, 'Provider failed, trying fallback');- await this.sendProgressNotice(msg, 'Hit a hiccup with that connection — switching routes and continuing...')- .catch((e) => logger.warn({ e }, 'channel send failed'));+ // Whitelabeled, durable notice: the user sees WHICH provider failed,+ // WHY (one respectful line, no stack), and WHERE the task continues —+ // rendered in Mercury Code too (heartbeat rows are filtered there).+ // Same provider failing twice in one turn does not repeat the line.+ const failureKey = `${provider.name}:${(err?.message || String(err)).slice(0, 80)}`;+ if (!noticedProviderFailures.has(failureKey)) {+ noticedProviderFailures.add(failureKey);+ const nextName = providerChain[providerChain.indexOf(provider) + 1]?.name;+ const line = nextName+ ? `⚠ ${provider.name}: ${whitelabelProviderError(err)} — switching to \`${nextName}\` and continuing.`+ : `⚠ ${provider.name}: ${whitelabelProviderError(err)} — no fallback left; retrying the chain.`;+ await this.sendFallbackNotice(msg, line).catch((e) => logger.warn({ e }, 'channel send failed'));+ }}}diff --git a/src/core/provider-error-notice.test.ts b/src/core/provider-error-notice.test.tsnew file mode 100644index 00000000..f542ca47--- /dev/null+++ b/src/core/provider-error-notice.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import { whitelabelProviderError } from './agent.js';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { CLIChannel } from '../channels/cli.js';++const cliSrc = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'channels', 'cli.ts'), 'utf8');++/**+ * Whitelabeled fallback errors: when a provider fails mid-task (expired+ * token, rate limit…) the user must see a short, respectful line naming the+ * provider, the reason, and where the task continues — rendered DURABLY in+ * Mercury Code (heartbeat rows are filtered out of the coding transcript, so+ * the old generic heartbeat notice never showed there).+ */+describe('whitelabelProviderError', () => {+ it('maps auth/token failures to a respectful one-liner', () => {+ expect(whitelabelProviderError({ message: 'Request failed with status code 401' })).toContain('token');+ expect(whitelabelProviderError({+ message: 'Incorrect API key provided',+ statusCode: 401,+ responseBody: '{"error":{"code":"invalid_api_key"}}',+ })).toContain('credentials');+ expect(whitelabelProviderError({ message: 'JWT token expired at 1757…' })).toContain('expired');+ });++ it('maps rate limits, limits, and server errors', () => {+ expect(whitelabelProviderError({ message: '429 Too Many Requests' })).toContain('Rate limited');+ expect(whitelabelProviderError({ message: 'context length exceeded' })).toContain('model limit');+ expect(whitelabelProviderError({ message: 'fetch failed: ECONNRESET' })).toContain('server error or network timeout');+ });++ it('keeps unknown errors concise (first line, no stack)', () => {+ const out = whitelabelProviderError({ message: 'weird provider quirk\n at deep stack frame\n more frames' });+ expect(out).toBe('weird provider quirk');+ expect(out).not.toContain('at ');+ });+});++describe('durable fallback notices', () => {+ it('sendSystemNotice renders a durable system row that survives clearHeartbeat', () => {+ const channel = new CLIChannel();+ channel.sendHeartbeat('thinking…');+ channel.sendSystemNotice('⚠ deepseek: Access token expired or rejected — switching to `openai` and continuing.');+ channel.clearHeartbeat();++ const messages = channel.getTuiState().chatMessages;+ const notice = messages.find((m) => m.content.includes('deepseek: Access token expired'));+ expect(notice).toBeDefined();+ expect(notice!.role).toBe('system');+ expect(notice!.id.startsWith('heartbeat-')).toBe(false); // must render in Mercury Code+ expect(messages.some((m) => m.id.startsWith('heartbeat-'))).toBe(false); // heartbeat cleared+ });++ it('cli: the notice path is wired into the provider failure catch block', () => {+ // The per-failure line names provider + whitelabeled reason + next hop.+ expect(cliSrc).toContain('sendSystemNotice');+ expect(agentCliWiring()).toBe(true);+ });+});++function agentCliWiring(): boolean {+ const agentSrc = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'agent.ts'), 'utf8');+ return agentSrc.includes('sendFallbackNotice(msg, line)')+ && agentSrc.includes('whitelabelProviderError(err)} — switching to')+ && /noticedProviderFailures/.test(agentSrc);+}\ No newline at end of file