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(providers): bots always get a provider that works; rejected keys are skipped; doctor flags malformed keys (1.3.3)

Salman Qureshi8b2078b8e238
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec3c870c..4b7249f6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## 1.3.3 — hotfix: bots always get a provider that works
+
+- **A bot never fails on a provider that cannot answer.** A new bot (from Telegram, the TUI or the web) runs on the default LLM; if the configured default has no key or its key is rejected (401), Mercury uses the first usable provider instead, and a provider that rejects its key is remembered and skipped — for bots, the main agent's fallback chain and the default — until the key is changed. A bot turn that hit a bad key now retries on another provider instead of dead-lettering.
+- **`mercury doctor` flags keys that cannot be right** (e.g. an OpenAI key that starts with `2sk-` instead of `sk-`) before anything is tried.
+
## 1.3.2 — hotfix: /code, the launch pad, and /stop from the default launch
- **Launch pad on `mercury`.** The default launch attaches to the daemon (ADR-024) and the attach screen had dropped the launch pad — the wordmark, provider/skills/web/budget rows and tip the main TUI opens with. It is back, fed by real runtime state, above the session picker.
diff --git a/README.md b/README.md
index 8d814775..80ca894b 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
</p>
<p align="center">
- <strong>🔖 Current Stable: v1.3.2 — Steady Mercury</strong>
+ <strong>🔖 Current Stable: v1.3.3 — Steady Mercury</strong>
</p>
<p align="center">
diff --git a/package-lock.json b/package-lock.json
index 52f576c7..da6aa3a4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.2",
+ "version": "1.3.3",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.2",
+ "version": "1.3.3",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/package.json b/package.json
index 9edb5fe8..001fc480 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.2",
+ "version": "1.3.3",
"description": "Soul-driven AI agent with Second Brain memory, permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"type": "module",
"main": "dist/index.js",
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 3bdab17f..63e69997 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -819,8 +819,17 @@ export class BotManager {
// a failure that will retry is not an escalation; one headed for the
// DLQ is (the flag is durable via the row — the constructor rehydrates
// it from the newest journal row on restart).
+ // A rejected key is permanent for THAT provider, not for the bot:
+ // remember it, and if another usable provider exists the next attempt
+ // runs there (resolveProvider skips rejected providers).
+ let authSwitch = false;
+ const usedProvider = turn.input.provider?.name;
+ if (output.status === 'failed' && output.reasonCode === 'provider_auth' && usedProvider) {
+ this.providers.markAuthFailure?.(usedProvider);
+ authSwitch = resolveProvider(this.providers, manifest, this.config).name !== usedProvider;
+ }
const willRetry = output.status === 'failed' && !!output.reasonCode
- && isTransientFailure(output.reasonCode) && job.attempts + 1 < MAX_TRANSIENT_ATTEMPTS;
+ && (isTransientFailure(output.reasonCode) || authSwitch) && job.attempts + 1 < MAX_TRANSIENT_ATTEMPTS;
const turnLimited = output.status === 'failed' && isTurnLimitFailure(output.reasonCode);
const routineKey = job.trigger === 'cron' ? (job.routineId ?? `bot:${botId}:cron`) : undefined;
const record: BotRunRecord = {
@@ -2095,15 +2104,16 @@ export class BotManager {
function resolveProvider(providers: ProviderRegistry, manifest: BotManifest, config?: MercuryConfig) {
const requested = manifest.model?.provider;
- const provider = requested ? providers.get(requested) : undefined;
+ const getUsable = typeof providers.getUsable === 'function' ? providers.getUsable.bind(providers) : (name?: string) => (name ? providers.get(name) : undefined);
+ const provider = getUsable(requested);
if (provider) return provider;
if (requested) {
- logger.warn({ botId: manifest.id, requested }, 'Bot provider not registered — falling back to default');
+ logger.warn({ botId: manifest.id, requested }, 'Bot provider not registered or not usable (no key / key rejected) — falling back to default');
}
// Crew lane (ADR-021): stage work on a cheaper provider when the fleet
// config names one and the crew bot has no choice of its own.
const crewProvider = manifest.parent ? config?.bots?.fleets?.crewProvider : undefined;
- const crewLane = crewProvider ? providers.get(crewProvider) : undefined;
+ const crewLane = getUsable(crewProvider);
if (crewLane) return crewLane;
return providers.getDefault();
}
diff --git a/src/index.ts b/src/index.ts
index 4f2788e6..f73d9ae5 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -3969,6 +3969,12 @@ program
.option('--platform', 'Show platform compatibility diagnostics')
.option('--storage', 'Show SQLite backend, database files and row counts')
.action(async (opts) => {
+ {
+ // Keys that cannot be right — say so before anything is tried.
+ const { checkKeyShapes } = await import('./providers/key-shape.js');
+ const warnings = checkKeyShapes(loadConfig().providers as unknown as Record<string, { apiKey?: string; enabled?: boolean }>);
+ for (const w of warnings) console.log(chalk.yellow(` ⚠ ${w.provider} API key looks wrong: ${w.problem}. Fix it with \`mercury doctor\` → providers, or in ~/.mercury/mercury.yaml.`));
+ }
if (opts.platform) {
runPlatformDoctor();
return;
diff --git a/src/providers/key-shape.test.ts b/src/providers/key-shape.test.ts
new file mode 100644
index 00000000..8c3e540a
--- /dev/null
+++ b/src/providers/key-shape.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { checkKeyShapes } from './key-shape.js';
+
+describe('API key shape check (doctor)', () => {
+ it('flags a pasted prefix typo and whitespace, passes real shapes and unknown providers', () => {
+ const w = checkKeyShapes({
+ openai: { apiKey: '2sk-proj-abc', enabled: true },
+ anthropic: { apiKey: 'sk-ant-xyz', enabled: true },
+ deepseek: { apiKey: 'sk-1 23', enabled: true },
+ grok: { apiKey: 'xai-ok', enabled: true },
+ ollamaCloud: { apiKey: 'whatever', enabled: true },
+ disabled: { apiKey: 'nope', enabled: false },
+ });
+ expect(w.map((x) => x.provider).sort()).toEqual(['deepseek', 'openai']);
+ expect(w.find((x) => x.provider === 'openai')?.problem).toContain('"2sk-pr…"');
+ });
+});
diff --git a/src/providers/key-shape.ts b/src/providers/key-shape.ts
new file mode 100644
index 00000000..d811ebb7
--- /dev/null
+++ b/src/providers/key-shape.ts
@@ -0,0 +1,26 @@
+/**
+ * Cheap sanity checks on API keys — the shapes vendors publish. A key that
+ * fails one is wrong before any request is made (a pasted "2sk-proj…" cost
+ * a fleet a day of 401s). Warnings only: shapes change, and an unknown
+ * provider has no rule.
+ */
+export interface KeyShapeWarning { provider: string; problem: string }
+
+const RULES: Record<string, { re: RegExp; expect: string }> = {
+ openai: { re: /^sk-/, expect: 'starts with "sk-"' },
+ anthropic: { re: /^sk-ant-/, expect: 'starts with "sk-ant-"' },
+ deepseek: { re: /^sk-/, expect: 'starts with "sk-"' },
+ grok: { re: /^xai-/, expect: 'starts with "xai-"' },
+};
+
+export function checkKeyShapes(providers: Record<string, { apiKey?: string; enabled?: boolean } | undefined>): KeyShapeWarning[] {
+ const out: KeyShapeWarning[] = [];
+ for (const [name, cfg] of Object.entries(providers)) {
+ const rule = RULES[name];
+ const key = cfg?.apiKey?.trim();
+ if (!rule || !key || cfg?.enabled === false) continue;
+ if (/\s/.test(key)) { out.push({ provider: name, problem: 'contains whitespace' }); continue; }
+ if (!rule.re.test(key)) out.push({ provider: name, problem: `${rule.expect}; this one starts with "${key.slice(0, 6)}…"` });
+ }
+ return out;
+}
diff --git a/src/providers/registry.test.ts b/src/providers/registry.test.ts
index 551b1890..61e1d559 100644
--- a/src/providers/registry.test.ts
+++ b/src/providers/registry.test.ts
@@ -71,3 +71,36 @@ describe('ProviderRegistry fallback order', () => {
expect(new Set(names).size).toBe(names.length);
});
});
+
+describe('usable providers (a bot always gets a provider that can answer)', () => {
+ function fake(name: string, available = true) {
+ return { name, isAvailable: () => available, getModel: () => 'm', getModelInstance: () => ({}) } as never;
+ }
+ function registryWith(defaultName: string, providers: Array<[string, boolean]>) {
+ const r = Object.create(ProviderRegistry.prototype) as ProviderRegistry;
+ Object.assign(r, { providers: new Map(providers.map(([n, a]) => [n, fake(n, a)])), defaultName, lastSuccessful: null, authFailed: new Set(), warnedUnusableDefault: false });
+ return r;
+ }
+
+ it('a default without credentials hands over to the first usable provider', () => {
+ const r = registryWith('openai', [['openai', false], ['ollamaCloud', true]]);
+ expect(r.getDefault().name).toBe('ollamaCloud');
+ expect(r.isUsable('openai')).toBe(false);
+ });
+
+ it('a rejected key takes the provider out of defaults and fallbacks until the key changes', () => {
+ const r = registryWith('openai', [['openai', true], ['anthropic', true]]);
+ expect(r.getDefault().name).toBe('openai');
+ r.markAuthFailure('openai');
+ expect(r.getDefault().name).toBe('anthropic');
+ expect([...r.getFallbackIterator()].map((p) => p.name)).toEqual(['anthropic']);
+ expect(r.getUsable('openai')).toBeUndefined();
+ r.updateApiKey('openai', 'sk-new');
+ expect(r.getDefault().name).toBe('openai');
+ });
+
+ it('with nothing usable the configured default is still returned (its error is the honest one)', () => {
+ const r = registryWith('openai', [['openai', false]]);
+ expect(r.getDefault().name).toBe('openai');
+ });
+});
diff --git a/src/providers/registry.ts b/src/providers/registry.ts
index 9b6c3b09..2bc13375 100644
--- a/src/providers/registry.ts
+++ b/src/providers/registry.ts
@@ -48,6 +48,10 @@ export class ProviderRegistry {
private providers: Map<string, BaseProvider> = new Map();
private defaultName: string;
private lastSuccessful: string | null = null;
+ /** Providers that answered 401 this process: a wrong key does not fix itself between turns. */
+ private authFailed?: Set<string>;
+ private warnedUnusableDefault = false;
+ private get rejected(): Set<string> { return (this.authFailed ??= new Set<string>()); }
private constructor(defaultName: string) {
this.defaultName = defaultName;
@@ -124,6 +128,27 @@ export class ProviderRegistry {
updateApiKey(name: string, apiKey: string): void {
const provider = this.providers.get(name) as (BaseProvider & { updateToken?: (token: string) => void }) | undefined;
provider?.updateToken?.(apiKey);
+ this.rejected.delete(name);
+ }
+
+ /** The provider rejected its key (401). It is skipped for defaults, fallbacks and bots until the key changes. */
+ markAuthFailure(name: string): void {
+ if (this.rejected.has(name)) return;
+ this.rejected.add(name);
+ logger.warn({ provider: name }, 'Provider rejected its API key — skipping it until the key is updated (mercury doctor)');
+ }
+
+ /** Registered, has credentials, and has not been rejected for them. */
+ isUsable(name: string): boolean {
+ const provider = this.providers.get(name);
+ // Test doubles may omit isAvailable; a registered provider without the
+ // method is treated as available.
+ const available = typeof provider?.isAvailable === "function" ? provider.isAvailable() : !!provider;
+ return !!provider && available && !this.rejected.has(name);
+ }
+
+ getUsable(name: string | undefined): BaseProvider | undefined {
+ return name && this.isUsable(name) ? this.providers.get(name) : undefined;
}
getDefault(): BaseProvider {
@@ -132,13 +157,25 @@ export class ProviderRegistry {
// failure silently moved every following turn — often to a weaker
// model — until restart. The fallback chain still handles outages per
// turn; lastSuccessful is kept for diagnostics only.
+ //
+ // "Leads" means: when it can actually answer. A default with no key, or
+ // one whose key was rejected, hands over to the first usable provider —
+ // a bot created from a phone must never fail every turn because the
+ // configured default has a typo in its key.
const provider = this.providers.get(this.defaultName);
- if (!provider) {
- const first = this.providers.values().next().value;
- if (!first) throw new Error('No LLM providers available — configure API keys');
- return first;
+ if (provider && this.isUsable(this.defaultName)) return provider;
+ const usable = [...this.providers.entries()].find(([name]) => this.isUsable(name))?.[1];
+ if (usable) {
+ if (!this.warnedUnusableDefault) {
+ this.warnedUnusableDefault = true;
+ logger.warn({ default: this.defaultName, using: usable.name }, 'Default provider is not usable (no key, or key rejected) — using the first usable provider');
+ }
+ return usable;
}
- return provider;
+ if (provider) return provider;
+ const first = this.providers.values().next().value;
+ if (!first) throw new Error('No LLM providers available — configure API keys');
+ return first;
}
getFallbackIterator(preferredName?: string): IterableIterator<BaseProvider> {
@@ -147,8 +184,8 @@ export class ProviderRegistry {
const defaultProvider = preferredProvider || this.getDefault();
ordered.push(defaultProvider);
const rest: BaseProvider[] = [];
- for (const [, provider] of this.providers) {
- if (provider !== defaultProvider) {
+ for (const [name, provider] of this.providers) {
+ if (provider !== defaultProvider && !this.rejected.has(name)) {
rest.push(provider);
}
}