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.

feat: manage model providers and voice keys from clients; setup mode

Salman Qureshi07bb518fa5b6
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 20d30b6c..7ff3ad95 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -14,7 +14,7 @@ import type { TokenBudget } from '../utils/tokens.js';
import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { ScheduledTaskManifest } from './scheduler.js';
import { DeepSeekProvider } from '../providers/deepseek.js';
-import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../providers/registry.js';
+import { createProvider } from '../providers/registry.js';
import type { BaseProvider } from '../providers/base.js';
import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
@@ -2147,9 +2147,9 @@ export class Agent {
}
this.config.providers.default = providerName as any;
- const previousProviders = this.providers;
- this.providers = await ProviderRegistryImpl.create(this.config, getCloudTokenStore());
- previousProviders.destroy();
+ // In place: bots, kanban and the IDE hold this same registry, so a new
+ // instance would leave them on the old (destroyed) providers.
+ await this.providers.reload(this.config, getCloudTokenStore());
const selected = this.providers.getDefault();
const model = selected.getModel();
@@ -2196,6 +2196,23 @@ export class Agent {
return this.switchSessionProvider(providerName);
}
+ /**
+ * Apply provider settings saved elsewhere (desktop Settings, dashboard)
+ * without a restart. Re-reads mercury.yaml so this in-memory config can't
+ * later write a stale key back over the new one, then reloads the shared
+ * registry in place.
+ */
+ async reloadProviders(): Promise<{ ok: boolean; providers: string[]; default: string; model: string }> {
+ const fresh = loadConfig();
+ Object.assign(this.config.providers, fresh.providers);
+ this.config.memory.learning = { ...this.config.memory.learning, provider: fresh.memory.learning?.provider };
+ if (fresh.bots?.fleets && this.config.bots?.fleets) this.config.bots.fleets.crewProvider = fresh.bots.fleets.crewProvider;
+ const { registered } = await this.providers.reload(this.config, getCloudTokenStore());
+ const current = this.getCurrentProvider();
+ updateCliProviderStatus(this.channels.get('cli'), current.name, current.model);
+ return { ok: registered.length > 0, providers: registered, default: current.name, model: current.model };
+ }
+
async birth(): Promise<void> {
this.lifecycle.transition('birthing');
logger.info({ name: this.config.identity.name }, 'Mercury is being born...');
diff --git a/src/index.ts b/src/index.ts
index 9efce57b..38c5eac0 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -95,6 +95,9 @@ import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/prov
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, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop } from './web/server.js';
+import { validateApiKey, validateBaseUrl, validateModelName } from './providers/provider-meta.js';
+import { setFirstProviderHandler, setProvidersReload } from './web/api/providers.js';
+import { spawnDetachedRestart } from './cli/daemon.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';
import { startLoopLagMonitor } from './utils/loop-lag.js';
import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';
@@ -315,78 +318,6 @@ async function chooseDefaultProvider(config: MercuryConfig): Promise<void> {
}
}
-function looksLikeToken(value: string, minLength: number = 20): boolean {
- return value.length >= minLength && !/\s/.test(value) && /[A-Za-z]/.test(value) && /\d/.test(value);
-}
-
-function validateApiKey(provider: ProviderName, value: string): string | null {
- if (provider === 'openai') {
- return /^sk-(proj-|svcacct-)?[A-Za-z0-9_-]{16,}$/i.test(value)
- ? null
- : 'OpenAI keys must start with `sk-`, `sk-proj-`, or `sk-svcacct-`.';
- }
-
- if (provider === 'anthropic') {
- return /^sk-ant-[A-Za-z0-9_-]{16,}$/i.test(value)
- ? null
- : 'Anthropic keys must start with `sk-ant-`.';
- }
-
- if (provider === 'deepseek') {
- return /^sk-[A-Za-z0-9_-]{16,}$/i.test(value)
- ? null
- : 'DeepSeek keys must start with `sk-`.';
- }
-
- if (provider === 'grok') {
- return looksLikeToken(value)
- ? null
- : 'Grok keys must look like a real API token: long, no spaces, and not plain text.';
- }
-
- if (provider === 'ollamaCloud') {
- return looksLikeToken(value)
- ? null
- : 'Ollama Cloud keys must look like a real API token: long, no spaces, and not plain text.';
- }
-
- if (provider === 'lmStudio') {
- return null;
- }
-
- if (provider === 'mimo') {
- return /^sk-[A-Za-z0-9_-]{16,}$/i.test(value)
- ? null
- : 'MiMo keys must start with `sk-`.';
- }
-
- if (provider === 'mimoTokenPlan') {
- return /^tp-[A-Za-z0-9_-]{16,}$/i.test(value)
- ? null
- : 'MiMo Token Plan keys must start with `tp-`.';
- }
-
- return null;
-}
-
-function validateBaseUrl(value: string): string | null {
- try {
- const parsed = new URL(value);
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- return 'Base URL must start with http:// or https://.';
- }
- return null;
- } catch {
- return 'Please enter a valid URL.';
- }
-}
-
-function validateModelName(value: string): string | null {
- if (!value.trim()) return 'Model name is required.';
- if (/\s/.test(value)) return 'Model name cannot contain spaces.';
- return null;
-}
-
async function chooseProviderModel(
providerLabel: string,
recommendedModel: string,
@@ -2521,6 +2452,20 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
if (!providers.hasProviders()) {
if (isDaemon) {
logger.error('No LLM providers available. Run `mercury doctor` to configure providers.');
+ if (config.web.enabled) {
+ // Setup mode: keep the API up so Mercury Desktop or the dashboard
+ // can connect a provider (there is no terminal on a desktop
+ // install). The first working provider restarts into normal mode.
+ setFirstProviderHandler(() => {
+ logger.info('A provider is connected; restarting out of setup mode');
+ if (!spawnDetachedRestart()) logger.error('Could not restart out of setup mode; run `mercury restart`');
+ });
+ startWebServer();
+ writeAttachToken();
+ updateWebStatus({ running: true, pid: process.pid, state: 'setup' });
+ setShutdownHandler(() => { void stopWebServer().finally(() => { releaseRuntimeProcess('daemon'); process.exit(0); }); });
+ logger.warn('Setup mode: connect a model provider from Mercury Desktop or the dashboard');
+ }
return;
}
console.log(chalk.red(' No LLM providers available. Run `mercury doctor` to configure providers.'));
@@ -3527,6 +3472,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setWebProgrammingMode(agent.programmingMode);
setWebBgTasks(agent.backgroundTasks);
setWebModelSwitch((provider, model) => agent.switchProvider(provider, model));
+ setProvidersReload(() => agent.reloadProviders());
setWebStop(() => agent.stopAllWork('stopped'));
setWebCurrentProvider(() => agent.getCurrentProvider());
// Live bottom bar for attached terminals and the dashboard: one snapshot,
diff --git a/src/plugins/voice-check.test.ts b/src/plugins/voice-check.test.ts
new file mode 100644
index 00000000..b5f15be3
--- /dev/null
+++ b/src/plugins/voice-check.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+import { checkVoiceKey } from './voice-check.js';
+
+const reply = (status: number, body: unknown) => vi.fn().mockResolvedValue({ status, json: async () => body } as Response);
+
+describe('voice key check', () => {
+ it('ElevenLabs: a good key lists voices', async () => {
+ const f = reply(200, { voices: [{ voice_id: 'v1', name: 'Rachel' }, { voice_id: 'v2', name: 'Adam' }] });
+ const r = await checkVoiceKey('elevenlabs', 'sk_abc123', { fetch: f });
+ expect(r).toMatchObject({ ok: true, verified: true });
+ expect(r.voices).toEqual([{ id: 'v1', name: 'Rachel' }, { id: 'v2', name: 'Adam' }]);
+ expect(f.mock.calls[0][1].headers['xi-api-key']).toBe('sk_abc123');
+ });
+
+ it('a rejected key says so, by vendor name', async () => {
+ const r = await checkVoiceKey('deepgram', 'bad-key-123', { fetch: reply(401, {}) });
+ expect(r).toMatchObject({ ok: false, verified: true });
+ expect(r.message).toMatch(/Deepgram rejected/);
+ });
+
+ it('Gemini lists only live voice models', async () => {
+ const f = reply(200, { models: [{ name: 'models/gemini-2.5-flash' }, { name: 'models/gemini-live-2.5-flash-preview' }, { name: 'models/gemini-2.5-flash-native-audio-dialog' }] });
+ const r = await checkVoiceKey('gemini', 'AIzaKey123', { fetch: f });
+ expect(r.models).toEqual(['gemini-live-2.5-flash-preview', 'gemini-2.5-flash-native-audio-dialog']);
+ });
+
+ it('Qwen tries the mainland host when the international one rejects the key', async () => {
+ const f = vi.fn()
+ .mockResolvedValueOnce({ status: 401, json: async () => ({}) })
+ .mockResolvedValueOnce({ status: 200, json: async () => ({ data: [] }) });
+ const r = await checkVoiceKey('qwen', 'sk-dash123', { fetch: f as unknown as typeof fetch });
+ expect(r.ok).toBe(true);
+ expect(f.mock.calls[1][0]).toContain('dashscope.aliyuncs.com');
+ });
+
+ it('Azure needs its endpoint before it can check', async () => {
+ const f = reply(200, {});
+ expect((await checkVoiceKey('azure', 'abc123', { fetch: f })).ok).toBe(false);
+ expect(f).not.toHaveBeenCalled();
+ });
+
+ it('vendors with no check endpoint are honest about it', async () => {
+ const r = await checkVoiceKey('sarvam', 'key-123');
+ expect(r).toMatchObject({ ok: true, verified: false });
+ expect(r.message).toMatch(/first time/);
+ });
+
+ it('empty, masked or spaced keys never reach the network', async () => {
+ const f = reply(200, {});
+ for (const k of ['', 'ab cd', 'sk-a••••b3c4']) expect((await checkVoiceKey('cartesia', k, { fetch: f })).ok).toBe(false);
+ expect(f).not.toHaveBeenCalled();
+ });
+
+ it('a timeout reads as a timeout', async () => {
+ const f = vi.fn().mockRejectedValue(new Error('The operation was aborted due to timeout'));
+ const r = await checkVoiceKey('assemblyai', 'k123', { fetch: f as unknown as typeof fetch });
+ expect(r.message).toMatch(/10 seconds/);
+ });
+});
diff --git a/src/plugins/voice-check.ts b/src/plugins/voice-check.ts
new file mode 100644
index 00000000..ec25fd7f
--- /dev/null
+++ b/src/plugins/voice-check.ts
@@ -0,0 +1,107 @@
+/**
+ * Check a voice vendor's key before the user relies on it: one cheap,
+ * read-only call per vendor. Where the vendor lists voices, they come back
+ * too, for the voice menu. Vendors with no read-only endpoint say so
+ * plainly instead of pretending ("checked on first use").
+ */
+
+export const VOICE_VENDORS = ['elevenlabs', 'deepgram', 'assemblyai', 'cartesia', 'gemini', 'qwen', 'azure', 'sarvam', 'minimax'] as const;
+export type VoiceVendor = (typeof VOICE_VENDORS)[number];
+
+/** The env name each vendor's key is stored under (the Optimus plugin's `secret`). */
+export const VOICE_KEY_ENV: Record<VoiceVendor, string> = {
+ elevenlabs: 'ELEVENLABS_API_KEY', deepgram: 'DEEPGRAM_API_KEY', assemblyai: 'ASSEMBLYAI_API_KEY', cartesia: 'CARTESIA_API_KEY',
+ gemini: 'GEMINI_API_KEY', qwen: 'DASHSCOPE_API_KEY', azure: 'AZURE_OPENAI_API_KEY', sarvam: 'SARVAM_API_KEY', minimax: 'MINIMAX_API_KEY',
+};
+
+export interface VoiceCheck {
+ ok: boolean;
+ /** false when the vendor offers no way to check a key without using it. */
+ verified: boolean;
+ message: string;
+ voices?: Array<{ id: string; name: string }>;
+ models?: string[];
+}
+
+type Fetch = typeof fetch;
+
+const LABEL: Record<VoiceVendor, string> = {
+ elevenlabs: 'ElevenLabs', deepgram: 'Deepgram', assemblyai: 'AssemblyAI', cartesia: 'Cartesia', gemini: 'Gemini', qwen: 'Qwen (DashScope)',
+ azure: 'Azure OpenAI', sarvam: 'Sarvam', minimax: 'MiniMax',
+};
+
+async function call(f: Fetch, url: string, headers: Record<string, string>): Promise<{ status: number; body: unknown }> {
+ const res = await f(url, { headers, signal: AbortSignal.timeout(10_000) });
+ let body: unknown = null;
+ try { body = await res.json(); } catch { /* not JSON */ }
+ return { status: res.status, body };
+}
+
+function verdict(vendor: VoiceVendor, status: number): VoiceCheck | null {
+ if (status === 401 || status === 403) return { ok: false, verified: true, message: `${LABEL[vendor]} rejected this key. Copy it again from your ${LABEL[vendor]} account.` };
+ if (status === 429) return { ok: true, verified: true, message: `${LABEL[vendor]} accepted the key but is rate-limiting it right now.` };
+ if (status >= 400) return { ok: false, verified: true, message: `${LABEL[vendor]} answered ${status}. Try again in a moment.` };
+ return null;
+}
+
+export async function checkVoiceKey(vendor: VoiceVendor, key: string, opts: { endpoint?: string; fetch?: Fetch } = {}): Promise<VoiceCheck> {
+ const f = opts.fetch ?? fetch;
+ const k = key.trim();
+ if (!k) return { ok: false, verified: false, message: `Add your ${LABEL[vendor]} key first.` };
+ if (/\s/.test(k) || k.includes('•')) return { ok: false, verified: false, message: 'Paste the full key, with no spaces.' };
+ try {
+ switch (vendor) {
+ case 'elevenlabs': {
+ const r = await call(f, 'https://api.elevenlabs.io/v1/voices', { 'xi-api-key': k });
+ const bad = verdict(vendor, r.status); if (bad) return bad;
+ const voices = ((r.body as { voices?: Array<{ voice_id: string; name: string }> })?.voices ?? []).map((v) => ({ id: v.voice_id, name: v.name }));
+ return { ok: true, verified: true, message: `Connected. ${voices.length} voices available.`, voices };
+ }
+ case 'cartesia': {
+ const r = await call(f, 'https://api.cartesia.ai/voices', { 'X-API-Key': k, 'Cartesia-Version': '2024-06-10' });
+ const bad = verdict(vendor, r.status); if (bad) return bad;
+ const list = Array.isArray(r.body) ? r.body : ((r.body as { data?: unknown[] })?.data ?? []);
+ const voices = (list as Array<{ id: string; name: string }>).map((v) => ({ id: v.id, name: v.name }));
+ return { ok: true, verified: true, message: `Connected. ${voices.length} voices available.`, voices };
+ }
+ case 'deepgram': {
+ const r = await call(f, 'https://api.deepgram.com/v1/projects', { Authorization: `Token ${k}` });
+ return verdict(vendor, r.status) ?? { ok: true, verified: true, message: 'Connected.' };
+ }
+ case 'assemblyai': {
+ const r = await call(f, 'https://api.assemblyai.com/v2/transcript?limit=1', { Authorization: k });
+ return verdict(vendor, r.status) ?? { ok: true, verified: true, message: 'Connected.' };
+ }
+ case 'gemini': {
+ const r = await call(f, `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(k)}&pageSize=1000`, {});
+ if (r.status === 400) return { ok: false, verified: true, message: 'Gemini rejected this key. Copy it again from Google AI Studio.' };
+ const bad = verdict(vendor, r.status); if (bad) return bad;
+ const models = ((r.body as { models?: Array<{ name: string }> })?.models ?? []).map((m) => m.name.replace(/^models\//, '')).filter((m) => /live|native-audio|realtime/i.test(m));
+ return { ok: true, verified: true, message: models.length ? `Connected. ${models.length} live voice models.` : 'Connected.', models };
+ }
+ case 'qwen': {
+ // International and mainland accounts live on different hosts; a key only works on its own.
+ for (const host of ['https://dashscope-intl.aliyuncs.com', 'https://dashscope.aliyuncs.com']) {
+ const r = await call(f, `${host}/compatible-mode/v1/models`, { Authorization: `Bearer ${k}` });
+ if (r.status === 401 || r.status === 403) continue;
+ return verdict(vendor, r.status) ?? { ok: true, verified: true, message: 'Connected.' };
+ }
+ return { ok: false, verified: true, message: 'DashScope rejected this key on both the international and mainland endpoints.' };
+ }
+ case 'azure': {
+ const endpoint = (opts.endpoint ?? '').trim().replace(/\/+$/, '');
+ if (!/^https:\/\//.test(endpoint)) return { ok: false, verified: false, message: 'Add your Azure endpoint (https://<name>.openai.azure.com) to check the key.' };
+ const r = await call(f, `${endpoint}/openai/models?api-version=2024-10-21`, { 'api-key': k });
+ if (r.status === 404) return { ok: false, verified: true, message: 'The endpoint answered, but it is not an Azure OpenAI resource. Check the URL.' };
+ return verdict(vendor, r.status) ?? { ok: true, verified: true, message: 'Connected.' };
+ }
+ case 'sarvam':
+ case 'minimax':
+ return { ok: true, verified: false, message: `Saved. ${LABEL[vendor]} has no way to check a key without using it, so it is checked the first time you talk.` };
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { ok: false, verified: false, message: /timeout|abort/i.test(msg) ? `${LABEL[vendor]} didn't answer in 10 seconds. Check your connection.` : `Couldn't reach ${LABEL[vendor]}: ${msg}` };
+ }
+ return { ok: false, verified: false, message: 'Unknown voice service.' };
+}
diff --git a/src/providers/provider-meta.ts b/src/providers/provider-meta.ts
new file mode 100644
index 00000000..da81c697
--- /dev/null
+++ b/src/providers/provider-meta.ts
@@ -0,0 +1,117 @@
+import type { ProviderName } from '../utils/config.js';
+
+/**
+ * What each model provider is and how to connect it, shared by the terminal
+ * setup (`mercury setup` / `doctor`) and the desktop and dashboard Settings,
+ * so a key that one rejects the other rejects too.
+ */
+
+export type ProviderKind = 'cloud' | 'gateway' | 'local' | 'account';
+
+export interface ProviderMeta {
+ label: string;
+ /** cloud: a vendor key · gateway: one key, many vendors' models · local: runs on your machine · account: sign-in, not a key. */
+ kind: ProviderKind;
+ blurb: string;
+ needsKey: boolean;
+ /** The user must type the base URL (no sensible default). */
+ needsBaseUrl: boolean;
+ /** Where to get a key. */
+ keyUrl?: string;
+ /** Example key prefix for the input placeholder. */
+ keyHint?: string;
+ /** Configured only through `mercury doctor` (OAuth), not with a key. */
+ signInOnly?: boolean;
+}
+
+export const PROVIDER_META: Record<ProviderName, ProviderMeta> = {
+ aimlapi: { label: 'AI/ML API', kind: 'gateway', blurb: '350+ models from every major lab on one key.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://aimlapi.com/app/keys' },
+ mercuryCloud: { label: 'Mercury Cloud', kind: 'account', blurb: 'Hosted by Cosmic Stack. No keys; sign in with your Mercury account.', needsKey: false, needsBaseUrl: false, signInOnly: true },
+ openai: { label: 'OpenAI', kind: 'cloud', blurb: 'GPT models. The same key powers voice and voice notes.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://platform.openai.com/api-keys', keyHint: 'sk-…' },
+ anthropic: { label: 'Anthropic', kind: 'cloud', blurb: 'Claude models.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://console.anthropic.com/settings/keys', keyHint: 'sk-ant-…' },
+ deepseek: { label: 'DeepSeek', kind: 'cloud', blurb: 'DeepSeek chat and reasoning models.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://platform.deepseek.com/api_keys', keyHint: 'sk-…' },
+ grok: { label: 'Grok (xAI)', kind: 'cloud', blurb: 'Grok models. The same key powers Grok voice.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://console.x.ai', keyHint: 'xai-…' },
+ atlascloud: { label: 'Atlas Cloud', kind: 'gateway', blurb: 'Open models (Qwen, DeepSeek, Llama) on one key.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://www.atlascloud.ai' },
+ ollamaCloud: { label: 'Ollama Cloud', kind: 'cloud', blurb: 'Large open models hosted by Ollama.', needsKey: true, needsBaseUrl: false, keyUrl: 'https://ollama.com/settings/keys' },
+ ollamaLocal: { label: 'Ollama (this computer)', kind: 'local', blurb: 'Models you run yourself with Ollama. Free and private.', needsKey: false, needsBaseUrl: false },
+ lmStudio: { label: 'LM Studio', kind: 'local', blurb: 'Models served by LM Studio on this computer.', needsKey: false, needsBaseUrl: false },
+ atomicChat: { label: 'Atomic Chat', kind: 'local', blurb: 'Models served by Atomic Chat on this computer.', needsKey: false, needsBaseUrl: false },
+ litellm: { label: 'LiteLLM proxy', kind: 'gateway', blurb: 'Your own LiteLLM gateway in front of any vendors.', needsKey: false, needsBaseUrl: true },
+ openaiCompat: { label: 'OpenAI-compatible', kind: 'gateway', blurb: 'Any endpoint that speaks the OpenAI API (OpenRouter, Together, Groq, vLLM…).', needsKey: false, needsBaseUrl: true },
+ mimo: { label: 'MiMo (Xiaomi)', kind: 'cloud', blurb: 'Xiaomi MiMo models.', needsKey: true, needsBaseUrl: false, keyHint: 'sk-…' },
+ mimoTokenPlan: { label: 'MiMo Token Plan', kind: 'cloud', blurb: 'Xiaomi MiMo on a token plan.', needsKey: true, needsBaseUrl: false, keyHint: 'tp-…' },
+ chatgptWeb: { label: 'ChatGPT Plus/Pro', kind: 'account', blurb: 'Your ChatGPT subscription. Sign in once with `mercury doctor`.', needsKey: false, needsBaseUrl: false, signInOnly: true },
+ githubCopilot: { label: 'GitHub Copilot', kind: 'account', blurb: 'Your Copilot subscription. Sign in once with `mercury doctor`.', needsKey: false, needsBaseUrl: false, signInOnly: true },
+};
+
+export function looksLikeToken(value: string, minLength: number = 20): boolean {
+ return value.length >= minLength && !/\s/.test(value) && /[A-Za-z]/.test(value) && /\d/.test(value);
+}
+
+export function validateApiKey(provider: ProviderName, value: string): string | null {
+ if (provider === 'openai') {
+ return /^sk-(proj-|svcacct-)?[A-Za-z0-9_-]{16,}$/i.test(value)
+ ? null
+ : 'OpenAI keys must start with `sk-`, `sk-proj-`, or `sk-svcacct-`.';
+ }
+
+ if (provider === 'anthropic') {
+ return /^sk-ant-[A-Za-z0-9_-]{16,}$/i.test(value)
+ ? null
+ : 'Anthropic keys must start with `sk-ant-`.';
+ }
+
+ if (provider === 'deepseek') {
+ return /^sk-[A-Za-z0-9_-]{16,}$/i.test(value)
+ ? null
+ : 'DeepSeek keys must start with `sk-`.';
+ }
+
+ if (provider === 'grok') {
+ return looksLikeToken(value)
+ ? null
+ : 'Grok keys must look like a real API token: long, no spaces, and not plain text.';
+ }
+
+ if (provider === 'ollamaCloud') {
+ return looksLikeToken(value)
+ ? null
+ : 'Ollama Cloud keys must look like a real API token: long, no spaces, and not plain text.';
+ }
+
+ if (provider === 'lmStudio') {
+ return null;
+ }
+
+ if (provider === 'mimo') {
+ return /^sk-[A-Za-z0-9_-]{16,}$/i.test(value)
+ ? null
+ : 'MiMo keys must start with `sk-`.';
+ }
+
+ if (provider === 'mimoTokenPlan') {
+ return /^tp-[A-Za-z0-9_-]{16,}$/i.test(value)
+ ? null
+ : 'MiMo Token Plan keys must start with `tp-`.';
+ }
+
+ return null;
+}
+
+export function validateBaseUrl(value: string): string | null {
+ try {
+ const parsed = new URL(value);
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ return 'Base URL must start with http:// or https://.';
+ }
+ return null;
+ } catch {
+ return 'Please enter a valid URL.';
+ }
+}
+
+export function validateModelName(value: string): string | null {
+ if (!value.trim()) return 'Model name is required.';
+ if (/\s/.test(value)) return 'Model name cannot contain spaces.';
+ return null;
+}
diff --git a/src/providers/registry.ts b/src/providers/registry.ts
index 2bc13375..56ab3868 100644
--- a/src/providers/registry.ts
+++ b/src/providers/registry.ts
@@ -108,6 +108,27 @@ export class ProviderRegistry {
return registry;
}
+ /**
+ * Re-read providers from config in place: every holder of this registry
+ * (agent, bots, kanban, IDE) sees new keys and models on its next call,
+ * with no restart. Rejected keys get a fresh chance; the default follows
+ * config. Keeps the old set if the new config yields no provider at all.
+ */
+ async reload(config: MercuryConfig, tokenStore?: import('../cloud/token-store.js').CloudTokenStore | null): Promise<{ registered: string[] }> {
+ const next = await ProviderRegistry.create(config, tokenStore);
+ if (!next.hasProviders()) return { registered: [] };
+ const previous = this.providers;
+ this.providers = next.providers;
+ this.defaultName = config.providers.default;
+ this.lastSuccessful = null;
+ this.authFailed = undefined;
+ this.warnedUnusableDefault = false;
+ for (const [name, provider] of previous) {
+ if (this.providers.get(name) !== provider) (provider as BaseProvider & { destroy?: () => void }).destroy?.();
+ }
+ return { registered: [...this.providers.keys()] };
+ }
+
get(name?: string): BaseProvider | undefined {
const key = name || this.defaultName;
return this.providers.get(key);
diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.ts
index 62b69eae..f9afafcd 100644
--- a/src/utils/provider-models.ts
+++ b/src/utils/provider-models.ts
@@ -1,3 +1,4 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
import type { ProviderConfig, ProviderName } from './config.js';
import { fetchChatGPTModels } from '../auth/chatgpt-models.js';
import { fetchGitHubModels } from '../auth/github-models.js';
@@ -223,8 +224,11 @@ function prioritizeModels(models: string[], preferred: readonly string[]): strin
return [...preferredMatches, ...others];
}
+/** Per-call cap: the CLI picker shows 50; the desktop Settings asks for every model. */
+const modelLimit = new AsyncLocalStorage<number>();
+
function limitModels(models: string[]): string[] {
- return models.slice(0, MAX_MODEL_OPTIONS);
+ return models.slice(0, modelLimit.getStore() ?? MAX_MODEL_OPTIONS);
}
function isOpenAIChatModel(id: string): boolean {
@@ -559,7 +563,13 @@ async function fetchMercuryCloudModels(config: ProviderConfig): Promise<Provider
export async function fetchProviderModelCatalog(
provider: ProviderName,
config: ProviderConfig,
+ opts: { limit?: number } = {},
): Promise<ProviderModelCatalog> {
+ if (opts.limit !== undefined) return modelLimit.run(Math.max(1, opts.limit), () => fetchCatalog(provider, config));
+ return fetchCatalog(provider, config);
+}
+
+async function fetchCatalog(provider: ProviderName, config: ProviderConfig): Promise<ProviderModelCatalog> {
if (provider === 'mercuryCloud') {
return fetchMercuryCloudModels(config);
}
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 60efc304..5d275853 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -38,6 +38,8 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'usage.history', // GET /api/usage/history?days= — tokens per local day
'brain.people', // PATCH/merge persons, person checks, GET /api/brain/graph/v2
'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)
+ 'providers.manage', // GET /api/providers/settings, POST /api/providers/:id/check (live, unsaved), PUT /api/providers/roles; saves apply live; health.setupRequired
+ 'voice.check', // POST /api/voice/check { vendor, key?, endpoint? }
'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links
]);
diff --git a/src/web/api/providers-route.test.ts b/src/web/api/providers-route.test.ts
new file mode 100644
index 00000000..29486347
--- /dev/null
+++ b/src/web/api/providers-route.test.ts
@@ -0,0 +1,152 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// mercury.yaml's path is fixed when config.ts loads: point MERCURY_HOME at a
+// temp dir with one working provider before importing the routes.
+const home = await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ for (const k of ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'DEEPSEEK_API_KEY', 'GROK_API_KEY', 'AIMLAPI_API_KEY', 'DEFAULT_PROVIDER']) delete process.env[k];
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-providers-route-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [
+ 'identity:',
+ ' owner: Test',
+ 'providers:',
+ ' default: deepseek',
+ ' deepseek:',
+ ' name: deepseek',
+ ' apiKey: sk-saveddeepseekkey0000000000',
+ ' baseUrl: https://api.deepseek.com/v1',
+ ' model: deepseek-chat',
+ ' enabled: true',
+ '',
+ ].join('\n'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const catalog = vi.hoisted(() => ({ fn: vi.fn() }));
+vi.mock('../../utils/provider-models.js', () => ({ fetchProviderModelCatalog: catalog.fn }));
+
+import providers, { setFirstProviderHandler, setProvidersReload } from './providers.js';
+
+function call(method: string, path: string, body?: unknown) {
+ return providers.request(`http://127.0.0.1${path}`, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+}
+const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');
+
+afterEach(() => {
+ catalog.fn.mockReset();
+ setProvidersReload(null);
+ setFirstProviderHandler(null);
+});
+
+describe('providers settings', () => {
+ it('lists every provider with masked keys, the default and roles', async () => {
+ const res = await call('GET', '/api/providers/settings');
+ const body = await res.json() as any;
+ expect(body.default).toEqual({ provider: 'deepseek', model: 'deepseek-chat' });
+ const ds = body.providers.find((p: { id: string }) => p.id === 'deepseek');
+ expect(ds).toMatchObject({ label: 'DeepSeek', kind: 'cloud', configured: true, isDefault: true, hasKey: true });
+ expect(ds.apiKey).toBe('sk-s••••0000');
+ expect(JSON.stringify(body)).not.toContain('saveddeepseekkey');
+ expect(body.providers.find((p: { id: string }) => p.id === 'chatgptWeb').signInOnly).toBe(true);
+ expect(body.setupRequired).toBe(false);
+ });
+
+ it('checks an unsaved key: shape first, with no network call', async () => {
+ const res = await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-wrong-shape-1234567890' });
+ const body = await res.json() as any;
+ expect(body).toMatchObject({ ok: false, field: 'apiKey' });
+ expect(body.error).toMatch(/sk-ant-/);
+ expect(catalog.fn).not.toHaveBeenCalled();
+ });
+
+ it('never accepts the masked form of a key', async () => {
+ const res = await call('POST', '/api/providers/deepseek/check', { apiKey: 'sk-s••••0000' });
+ expect((await res.json() as any).error).toMatch(/hidden form/);
+ const save = await call('POST', '/api/providers/deepseek', { apiKey: 'sk-s••••0000' });
+ expect(save.status).toBe(400);
+ expect(yaml()).toContain('sk-saveddeepseekkey0000000000');
+ });
+
+ it('checks live and returns every model, recommended first, without saving', async () => {
+ const many = Array.from({ length: 120 }, (_, i) => `claude-model-${i}`);
+ catalog.fn.mockResolvedValue({ recommendedModel: 'claude-sonnet-x', models: many });
+ const res = await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx' });
+ const body = await res.json() as any;
+ expect(body.ok).toBe(true);
+ expect(body.models[0]).toBe('claude-sonnet-x');
+ expect(body.models.length).toBe(121);
+ expect(catalog.fn.mock.calls[0][1].apiKey).toBe('sk-ant-abcdefghijklmnopqrstuvwx');
+ expect(catalog.fn.mock.calls[0][2]).toEqual({ limit: 5000 });
+ expect(yaml()).not.toContain('sk-ant-abcdefghijklmnopqrstuvwx');
+ });
+
+ it('points a vendor rejection at the key field', async () => {
+ catalog.fn.mockRejectedValue(new Error('Anthropic rejected the API key (401). Please re-enter it.'));
+ const body = await (await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx' })).json() as any;
+ expect(body).toMatchObject({ ok: false, field: 'apiKey' });
+ });
+
+ it('saves, then applies live through the reloader', async () => {
+ const reload = vi.fn().mockResolvedValue({ ok: true, providers: ['deepseek', 'anthropic'], default: 'deepseek', model: 'deepseek-chat' });
+ setProvidersReload(reload);
+ const res = await call('POST', '/api/providers/anthropic', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx', model: 'claude-sonnet-x', enabled: true });
+ const body = await res.json() as any;
+ expect(res.status).toBe(200);
+ expect(body).toMatchObject({ success: true, applied: true, restartRequired: false });
+ expect(body.provider).toMatchObject({ configured: true, model: 'claude-sonnet-x' });
+ expect(reload).toHaveBeenCalledOnce();
+ expect(yaml()).toContain('sk-ant-abcdefghijklmnopqrstuvwx');
+ });
+
+ it('rejects a bad model and a bad URL with the field to fix', async () => {
+ const m = await call('POST', '/api/providers/anthropic', { model: 'has spaces in it' });
+ expect(await m.json() as any).toMatchObject({ field: 'model' });
+ const u = await call('POST', '/api/providers/openaiCompat', { baseUrl: 'ftp://nope', model: 'x', enabled: true });
+ expect(u.status).toBe(400);
+ expect(await u.json() as any).toMatchObject({ field: 'baseUrl' });
+ });
+
+ it('sets the default model and job roles, only to connected providers', async () => {
+ const bad = await call('PUT', '/api/providers/roles', { default: { provider: 'grok', model: 'grok-4' } });
+ expect(bad.status).toBe(400);
+ const ok = await call('PUT', '/api/providers/roles', { default: { provider: 'anthropic', model: 'claude-opus-x' }, learning: 'deepseek', crew: null });
+ expect(ok.status).toBe(200);
+ const s = await (await call('GET', '/api/providers/settings')).json() as any;
+ expect(s.default).toEqual({ provider: 'anthropic', model: 'claude-opus-x' });
+ expect(s.roles.learning).toBe('deepseek');
+ });
+
+ it('forgetting the default key hands the default to another working provider', async () => {
+ const res = await call('DELETE', '/api/providers/anthropic/key');
+ expect(res.status).toBe(200);
+ const s = await (await call('GET', '/api/providers/settings')).json() as any;
+ expect(s.default.provider).toBe('deepseek');
+ expect(s.providers.find((p: { id: string }) => p.id === 'anthropic')).toMatchObject({ hasKey: false, enabled: false, configured: false });
+ });
+
+ it('refuses keys for sign-in providers', async () => {
+ const res = await call('POST', '/api/providers/chatgptWeb', { apiKey: 'sk-abcdefghijklmnopqrstuvwx' });
+ expect(res.status).toBe(400);
+ });
+
+ it('in setup mode, the first working provider restarts the runtime', async () => {
+ vi.useFakeTimers();
+ const restart = vi.fn();
+ setFirstProviderHandler(restart);
+ expect((await (await call('GET', '/api/providers/settings')).json() as any).setupRequired).toBe(true);
+ const body = await (await call('POST', '/api/providers/grok', { apiKey: 'xai-abcdefghijklmnopqrstuvwxyz123456', model: 'grok-4', enabled: true })).json() as any;
+ expect(body).toMatchObject({ success: true, restarting: true });
+ vi.advanceTimersByTime(400);
+ expect(restart).toHaveBeenCalledOnce();
+ vi.useRealTimers();
+ });
+});
diff --git a/src/web/api/providers.ts b/src/web/api/providers.ts
index cde3b9db..19e5de35 100644
--- a/src/web/api/providers.ts
+++ b/src/web/api/providers.ts
@@ -1,5 +1,7 @@
import { Hono } from 'hono';
-import { loadConfig, saveConfig, type ProviderConfig, type ProviderName } from '../../utils/config.js';
+import { getActiveProviders, isProviderConfigured, loadConfig, saveConfig, type MercuryConfig, type ProviderConfig, type ProviderName } from '../../utils/config.js';
+import { PROVIDER_META, validateApiKey, validateBaseUrl, validateModelName } from '../../providers/provider-meta.js';
+import { logger } from '../../utils/logger.js';
function maskApiKey(key: string): string {
if (!key || key.length < 8) return key ? '••••••' : '';
@@ -12,43 +14,257 @@ function maskApiKey(key: string): string {
*/
const RECOMMENDED_PROVIDER = 'aimlapi';
-const providers = new Hono();
+const NAMES = Object.keys(PROVIDER_META) as ProviderName[];
-providers.get('/api/providers', (c) => {
- const config = loadConfig();
- const list = Object.entries(config.providers).filter(([k]) => k !== 'default').map(([name, p]: [string, any]) => ({
+/**
+ * How a save reaches the running agent. Registered by the runtime; without
+ * it (setup mode, tests) a save is durable and applies on the next start.
+ */
+type Reloader = () => Promise<{ ok: boolean; providers: string[]; default: string; model: string }>;
+let reloader: Reloader | null = null;
+export function setProvidersReload(fn: Reloader | null): void { reloader = fn; }
+
+/** Setup mode: the runtime came up with no provider. The first working one restarts it into normal mode. */
+let onFirstProvider: (() => void) | null = null;
+export function setFirstProviderHandler(fn: (() => void) | null): void { onFirstProvider = fn; }
+export function isSetupRequired(): boolean { return !!onFirstProvider; }
+
+async function apply(): Promise<{ applied: boolean; restarting?: boolean; error?: string }> {
+ if (onFirstProvider) {
+ if (getActiveProviders(loadConfig()).length === 0) return { applied: false };
+ const restart = onFirstProvider;
+ onFirstProvider = null;
+ setTimeout(restart, 300);
+ return { applied: false, restarting: true };
+ }
+ if (!reloader) return { applied: false };
+ try {
+ const r = await reloader();
+ return { applied: r.ok };
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Provider reload failed; the save applies on restart');
+ return { applied: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+function isName(name: unknown): name is ProviderName {
+ return typeof name === 'string' && (NAMES as string[]).includes(name);
+}
+
+function describe(name: ProviderName, p: ProviderConfig, config: MercuryConfig) {
+ const meta = PROVIDER_META[name];
+ return {
+ id: name,
name: p.name || name,
+ label: meta.label,
+ kind: meta.kind,
+ blurb: meta.blurb,
+ needsKey: meta.needsKey,
+ needsBaseUrl: meta.needsBaseUrl,
+ signInOnly: !!meta.signInOnly,
+ keyUrl: meta.keyUrl ?? null,
+ keyHint: meta.keyHint ?? null,
apiKey: p.apiKey ? maskApiKey(p.apiKey) : '',
hasKey: !!p.apiKey,
baseUrl: p.baseUrl,
model: p.model,
enabled: p.enabled,
+ configured: isProviderConfigured(p),
+ isDefault: config.providers.default === name,
recommended: name === RECOMMENDED_PROVIDER,
- }));
+ };
+}
+
+/** A pasted mask ("sk-a••••b3c4") is never a key. */
+function looksMasked(key: string): boolean {
+ return key.includes('•');
+}
+
+/** Merge what the user typed over what is saved; an omitted key keeps the saved one. */
+function draft(saved: ProviderConfig, body: { apiKey?: unknown; baseUrl?: unknown; model?: unknown }): ProviderConfig {
+ return {
+ ...saved,
+ apiKey: typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : saved.apiKey,
+ baseUrl: typeof body.baseUrl === 'string' && body.baseUrl.trim() ? body.baseUrl.trim().replace(/\/+$/, '') : saved.baseUrl,
+ model: typeof body.model === 'string' ? body.model.trim() : saved.model,
+ };
+}
+
+type Problem = { field: 'apiKey' | 'baseUrl'; error: string };
+
+/** Field-level problems before any network call. */
+function problems(name: ProviderName, pc: ProviderConfig, body: { apiKey?: unknown }): Problem[] {
+ const meta = PROVIDER_META[name];
+ const out: Problem[] = [];
+ if (typeof body.apiKey === 'string' && body.apiKey.trim()) {
+ const key = body.apiKey.trim();
+ if (looksMasked(key)) out.push({ field: 'apiKey', error: 'That is the hidden form of the saved key. Paste the full key, or leave the field empty to keep the saved one.' });
+ else if (/\s/.test(key)) out.push({ field: 'apiKey', error: 'The key has spaces in it. Copy it again without spaces or line breaks.' });
+ else {
+ const shape = validateApiKey(name, key);
+ if (shape) out.push({ field: 'apiKey', error: shape.replace(/`/g, '"') });
+ }
+ }
+ if (meta.needsKey && !pc.apiKey && !out.some((p) => p.field === 'apiKey')) out.push({ field: 'apiKey', error: `${meta.label} needs an API key.` });
+ if (pc.baseUrl || meta.needsBaseUrl) {
+ const bad = pc.baseUrl ? validateBaseUrl(pc.baseUrl) : 'A base URL is required.';
+ if (bad) out.push({ field: 'baseUrl', error: bad });
+ }
+ return out;
+}
+
+/** Which field a failed live check points at, from the vendor's message. */
+function blame(message: string): 'apiKey' | 'baseUrl' | undefined {
+ if (/key|auth|401|403|unauthori[sz]ed|forbidden|credential/i.test(message)) return 'apiKey';
+ if (/url|connect|reach|ECONN|ENOTFOUND|fetch failed|timed? ?out|abort/i.test(message)) return 'baseUrl';
+ return undefined;
+}
+
+const providers = new Hono();
+
+/** Every provider, with masked keys. The array shape is what the web dashboard reads. */
+providers.get('/api/providers', (c) => {
+ const config = loadConfig();
+ const list = NAMES.filter((n) => config.providers[n]).map((n) => describe(n, config.providers[n], config));
return c.json(list);
});
-providers.post('/api/providers/:name', async (c) => {
- const providerName = c.req.param('name') as ProviderName;
- const body = await c.req.json();
+/** Everything the Settings screen needs in one call: providers, the default, and roles. */
+providers.get('/api/providers/settings', (c) => {
const config = loadConfig();
+ const def = config.providers.default;
+ return c.json({
+ providers: NAMES.filter((n) => config.providers[n]).map((n) => describe(n, config.providers[n], config)),
+ default: { provider: def, model: config.providers[def]?.model ?? '' },
+ roles: {
+ learning: config.memory.learning?.provider ?? null,
+ crew: config.bots?.fleets?.crewProvider ?? null,
+ },
+ setupRequired: isSetupRequired(),
+ });
+});
- const validNames: ProviderName[] = ['aimlapi', 'mercuryCloud', 'openai', 'anthropic', 'deepseek', 'grok', 'atlascloud', 'ollamaCloud', 'ollamaLocal', 'atomicChat', 'openaiCompat', 'litellm', 'lmStudio', 'mimo', 'mimoTokenPlan'];
- if (!validNames.includes(providerName)) {
- return c.json({ error: 'Unknown provider' }, 400);
+/**
+ * Check a key or URL before saving: its shape first, then a live call that
+ * lists the models it can use. Nothing is written. The full list comes back
+ * (not the terminal picker's 50) so the model menu can offer every model.
+ */
+providers.post('/api/providers/:name/check', async (c) => {
+ const name = c.req.param('name');
+ if (!isName(name)) return c.json({ ok: false, error: 'Unknown provider' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as { apiKey?: unknown; baseUrl?: unknown };
+ const config = loadConfig();
+ const pc = draft(config.providers[name], body);
+ const issues = PROVIDER_META[name].signInOnly ? [] : problems(name, pc, body);
+ if (issues.length) return c.json({ ok: false, error: issues[0].error, field: issues[0].field, problems: issues });
+ const started = Date.now();
+ try {
+ const { fetchProviderModelCatalog } = await import('../../utils/provider-models.js');
+ const catalog = await fetchProviderModelCatalog(name, pc, { limit: 5000 });
+ const models = [...new Set([catalog.recommendedModel, ...catalog.models].filter(Boolean))];
+ return c.json({ ok: true, models, recommendedModel: catalog.recommendedModel, ms: Date.now() - started });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Connection failed';
+ return c.json({ ok: false, error: message, field: blame(message), ms: Date.now() - started });
}
+});
- const p = config.providers[providerName];
- if (body.apiKey !== undefined) p.apiKey = body.apiKey;
- if (body.baseUrl !== undefined) p.baseUrl = body.baseUrl;
- if (body.model !== undefined) p.model = body.model;
- if (body.enabled !== undefined) p.enabled = body.enabled;
+/** Forget a provider's key and turn it off. */
+providers.delete('/api/providers/:name/key', async (c) => {
+ const name = c.req.param('name');
+ if (!isName(name) || PROVIDER_META[name].signInOnly) return c.json({ error: 'Unknown provider' }, 400);
+ const config = loadConfig();
+ const p = config.providers[name];
+ p.apiKey = '';
+ p.enabled = false;
+ handOverDefault(config, name);
+ saveConfig(config);
+ const result = await apply();
+ return c.json({ success: true, provider: describe(name, p, config), ...result });
+});
+
+/**
+ * Who does what: the default chat model, the model Mercury learns about you
+ * with, and the one bot crews use. `null` for a role means "same as chat".
+ */
+providers.put('/api/providers/roles', async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as { default?: { provider?: unknown; model?: unknown }; learning?: unknown; crew?: unknown };
+ const config = loadConfig();
+ const active = new Set(getActiveProviders(config).map((p) => p.name));
+ const usable = (v: unknown): v is ProviderName => isName(v) && active.has(v);
+ if (body.default !== undefined) {
+ const { provider, model } = body.default ?? {};
+ if (!usable(provider)) return c.json({ error: 'Connect that provider before making it the default.', field: 'default' }, 400);
+ if (model !== undefined) {
+ const bad = typeof model === 'string' ? validateModelName(model) : 'Pick a model.';
+ if (bad) return c.json({ error: bad, field: 'default' }, 400);
+ config.providers[provider].model = (model as string).trim();
+ }
+ config.providers.default = provider;
+ }
+ for (const role of ['learning', 'crew'] as const) {
+ const v = body[role];
+ if (v === undefined) continue;
+ if (v !== null && v !== '' && !usable(v)) return c.json({ error: 'Connect that provider before giving it a job.', field: role }, 400);
+ const value = v ? (v as string) : undefined;
+ if (role === 'learning') config.memory.learning = { ...config.memory.learning, provider: value };
+ else if (config.bots?.fleets) config.bots.fleets.crewProvider = value;
+ }
+ saveConfig(config);
+ const result = await apply();
+ return c.json({ success: true, ...result, restartRequired: !result.applied && !result.restarting });
+});
+
+/**
+ * Save a provider. Validates the fields (never stores a masked key), writes
+ * mercury.yaml, then applies it to the running agent with no restart.
+ */
+providers.post('/api/providers/:name', async (c) => {
+ const name = c.req.param('name');
+ if (!isName(name)) return c.json({ error: 'Unknown provider' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as { apiKey?: unknown; baseUrl?: unknown; model?: unknown; enabled?: unknown };
+ const config = loadConfig();
+ const p = config.providers[name];
+ const meta = PROVIDER_META[name];
+ if (meta.signInOnly && (body.apiKey !== undefined || body.baseUrl !== undefined)) {
+ return c.json({ error: `${meta.label} signs in with your account (run \`mercury doctor\`); it has no key to set.` }, 400);
+ }
+
+ const next = draft(p, body);
+ if (body.apiKey === '' || body.apiKey === null) next.apiKey = '';
+ if (body.baseUrl === '' || body.baseUrl === null) next.baseUrl = '';
+ if (body.model !== undefined) {
+ const bad = typeof body.model === 'string' && body.model.trim() ? validateModelName(body.model) : 'Pick a model.';
+ if (bad) return c.json({ error: bad, field: 'model' }, 400);
+ }
+ if (body.enabled !== undefined && typeof body.enabled !== 'boolean') return c.json({ error: 'enabled must be true or false' }, 400);
+ const willBeOn = typeof body.enabled === 'boolean' ? body.enabled : p.enabled;
+ if (willBeOn && !meta.signInOnly) {
+ const issues = problems(name, next, body);
+ if (issues.length) return c.json({ error: issues[0].error, field: issues[0].field, problems: issues }, 400);
+ }
+
+ p.apiKey = next.apiKey;
+ p.baseUrl = next.baseUrl;
+ p.model = next.model;
+ if (typeof body.enabled === 'boolean') p.enabled = body.enabled;
+ if (!p.enabled) handOverDefault(config, name);
+ // The first provider anyone connects becomes the default.
+ if (p.enabled && isProviderConfigured(p) && !isProviderConfigured(config.providers[config.providers.default])) config.providers.default = name;
saveConfig(config);
- // Keys and models are read at boot — the save is durable, not live.
- return c.json({ success: true, restartRequired: true });
+ const result = await apply();
+ return c.json({ success: true, provider: describe(name, p, config), ...result, restartRequired: !result.applied && !result.restarting });
});
+/** Turning off (or forgetting) the default hands the default to another working provider. */
+function handOverDefault(config: MercuryConfig, name: ProviderName): void {
+ if (config.providers.default !== name) return;
+ const other = getActiveProviders(config).find((x) => x.name !== name);
+ if (other) config.providers.default = other.name as ProviderName;
+}
+
+/** The old test route: checks what is saved. Kept for the web dashboard; new clients use /check. */
providers.post('/api/providers/:name/test', async (c) => {
const providerName = c.req.param('name') as ProviderName;
const config = loadConfig();
diff --git a/src/web/api/status.ts b/src/web/api/status.ts
index f1efbfaf..a520e858 100644
--- a/src/web/api/status.ts
+++ b/src/web/api/status.ts
@@ -75,7 +75,7 @@ status.get('/api/health', (c) => {
if (!isLoopbackRequest(c) && !authenticateRequest(c)) return c.json({ error: 'Not found' }, 404);
const lag = getLoopLag();
const plugins = peekPluginManager()?.health();
- return c.json({ ok: true, pid: process.pid, version: versionString(), ...apiContract(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) }, ...(plugins ? { plugins: { safeMode: plugins.safeMode, running: plugins.running, tools: plugins.tools } } : {}) });
+ return c.json({ ok: true, pid: process.pid, version: versionString(), ...apiContract(), state: currentStatus.state, booting: currentStatus.state === 'booting', setupRequired: currentStatus.state === 'setup', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) }, ...(plugins ? { plugins: { safeMode: plugins.safeMode, running: plugins.running, tools: plugins.tools } } : {}) });
});
status.get('/api/status', (c) => {
diff --git a/src/web/api/voice.ts b/src/web/api/voice.ts
index 869da307..b6d06377 100644
--- a/src/web/api/voice.ts
+++ b/src/web/api/voice.ts
@@ -1,5 +1,7 @@
import { Hono } from 'hono';
import { voiceFeed, VOICE_ACTIONS, type VoiceAction } from '../../plugins/voice-feed.js';
+import { checkVoiceKey, VOICE_KEY_ENV, VOICE_VENDORS, type VoiceVendor } from '../../plugins/voice-check.js';
+import { secretValue } from '../../plugins/store.js';
/**
* Live voice (Optimus) for clients:
@@ -12,6 +14,18 @@ const voice = new Hono();
voice.get('/api/voice', (c) => c.json(voiceFeed.snapshot()));
+/**
+ * POST /api/voice/check { vendor, key?, endpoint? }: is this voice key good?
+ * With no key, checks the saved one. Read-only; nothing is stored.
+ */
+voice.post('/api/voice/check', async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as { vendor?: unknown; key?: unknown; endpoint?: unknown };
+ if (typeof body.vendor !== 'string' || !(VOICE_VENDORS as readonly string[]).includes(body.vendor)) return c.json({ ok: false, verified: false, message: 'Unknown voice service.' }, 400);
+ const vendor = body.vendor as VoiceVendor;
+ const key = typeof body.key === 'string' && body.key.trim() ? body.key : secretValue(VOICE_KEY_ENV[vendor]) ?? '';
+ return c.json(await checkVoiceKey(vendor, key, { endpoint: typeof body.endpoint === 'string' ? body.endpoint : undefined }));
+});
+
voice.get('/api/voice/events', (c) => {
const stream = new ReadableStream({
start(controller) {