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(cloud): notice a dead session, sign in from any client, recommend Cloud first

Salman Qureshi8cd07c28a5ae
diff --git a/src/cloud/client.ts b/src/cloud/client.ts
index 45e4d755..0d825e93 100644
--- a/src/cloud/client.ts
+++ b/src/cloud/client.ts
@@ -296,6 +296,7 @@ export class MercuryCloudClient {
this.isRefreshing
|| (!this.tokenStore.getRefreshToken() && !this.tokenStore.getAgentApiKey())
|| !this.shouldReconnect
+ || this.tokenStore.isSignedOut?.()
) return;
this.isRefreshing = true;
const generation = this.lifecycleGeneration;
@@ -337,6 +338,9 @@ export class MercuryCloudClient {
private scheduleReconnect(): void {
if (!this.shouldReconnect || this.reconnectTimer) return;
+ // A signed-out session never comes back by retrying; wait for new
+ // credentials (a sign-in restarts the runtime) instead of looping.
+ if (this.tokenStore.isSignedOut?.()) return;
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2);
}
diff --git a/src/cloud/token-store.test.ts b/src/cloud/token-store.test.ts
index 31cac186..67776961 100644
--- a/src/cloud/token-store.test.ts
+++ b/src/cloud/token-store.test.ts
@@ -115,3 +115,38 @@ describe('CloudTokenStore', () => {
expect(mocks.saveConfig).not.toHaveBeenCalled();
});
});
+
+describe('signed-out sessions', () => {
+ it('a refused refresh with no recovery key marks the session signed out; new tokens clear it', async () => {
+ const c = config('old-jwt', 'old-refresh');
+ c.cloud.agentApiKey = '';
+ mocks.loadConfig.mockReturnValue(c);
+ mocks.refreshToken.mockRejectedValue(new Error('Token refresh failed: 401'));
+ const store = new CloudTokenStore('old-jwt', 'old-refresh', c.cloud.apiUrl, c.cloud.agentId, undefined, '');
+ await expect(store.rotate()).rejects.toThrow(/no recovery key/);
+ expect(store.isSignedOut()).toBe(true);
+ expect(store.getAuthState().error).toMatch(/401/);
+ store.setTokens('new-jwt', 'new-refresh');
+ expect(store.isSignedOut()).toBe(false);
+ });
+
+ it('a refused recovery key also signs out; a network error does not', async () => {
+ mocks.loadConfig.mockReturnValue(config());
+ mocks.refreshToken.mockRejectedValue(new Error('fetch failed: ECONNRESET'));
+ mocks.redeemAgentApiKey.mockRejectedValue(new Error('Agent key redeem failed: 403'));
+ const store = new CloudTokenStore('old-jwt', 'old-refresh', 'https://api.example.com', 'agent-1', undefined, 'mcapk_agent_1');
+ await expect(store.rotate()).rejects.toThrow(/403/);
+ expect(store.isSignedOut()).toBe(true);
+ mocks.redeemAgentApiKey.mockRejectedValue(new Error('fetch failed: ECONNRESET'));
+ const flaky = new CloudTokenStore('old-jwt', 'old-refresh', 'https://api.example.com', 'agent-1', undefined, 'mcapk_agent_1');
+ await expect(flaky.rotate()).rejects.toThrow();
+ expect(flaky.isSignedOut()).toBe(false);
+ });
+
+ it('a network failure is not a sign-out', async () => {
+ const { isAuthRejection } = await import('./token-store.js');
+ expect(isAuthRejection(new Error('fetch failed: ECONNRESET'))).toBe(false);
+ expect(isAuthRejection(new Error('Token refresh failed: 401'))).toBe(true);
+ expect(isAuthRejection(new Error('Agent key redeem failed: 403'))).toBe(true);
+ });
+});
diff --git a/src/cloud/token-store.ts b/src/cloud/token-store.ts
index b76726b9..c56a105f 100644
--- a/src/cloud/token-store.ts
+++ b/src/cloud/token-store.ts
@@ -39,6 +39,13 @@ export class CloudTokenStore {
private inflight: Promise<TokenPair> | null = null;
private readonly liveConfig?: MercuryConfig;
private active = true;
+ /**
+ * 'signed-out' once the server has definitively refused both the refresh
+ * token and the agent key: nothing will fix itself, so callers stop
+ * retrying and the owner is asked to sign in again. Fresh tokens clear it.
+ */
+ private authState: 'ok' | 'signed-out' = 'ok';
+ private authError: string | null = null;
constructor(jwt: string, refreshTokenValue: string, apiUrl: string, agentId: string, liveConfig?: MercuryConfig, agentApiKey?: string) {
this.jwt = jwt;
@@ -73,6 +80,21 @@ export class CloudTokenStore {
return this.agentApiKey;
}
+ getAuthState(): { state: 'ok' | 'signed-out'; error: string | null } {
+ return { state: this.authState, error: this.authError };
+ }
+
+ isSignedOut(): boolean {
+ return this.authState === 'signed-out';
+ }
+
+ private markSignedOut(error: unknown): void {
+ const message = error instanceof Error ? error.message : String(error);
+ if (this.authState !== 'signed-out') logger.error({ err: message }, 'Mercury Cloud session expired and cannot renew itself; sign in again (Settings → Models, or `mercury cloud connect`)');
+ this.authState = 'signed-out';
+ this.authError = message;
+ }
+
matchesIdentity(apiUrl: string, agentId: string): boolean {
return this.active && this.apiUrl === apiUrl && this.agentId === agentId;
}
@@ -102,6 +124,8 @@ export class CloudTokenStore {
if (!this.active) throw new Error('Mercury Cloud credentials have been invalidated');
this.jwt = jwt;
this.refreshTokenValue = refreshTokenValue;
+ this.authState = 'ok';
+ this.authError = null;
if (this.liveConfig) {
this.liveConfig.cloud.jwt = jwt;
this.liveConfig.cloud.refreshToken = refreshTokenValue;
@@ -164,17 +188,29 @@ export class CloudTokenStore {
// browser re-pair for remotely-deployed agents.
if (this.agentApiKey) {
logger.warn({ err: (error as Error).message }, 'Refresh token rotation failed; redeeming agent API key');
- return await this.redeemWithAgentKey();
+ try {
+ return await this.redeemWithAgentKey();
+ } catch (redeemError) {
+ if (isAuthRejection(redeemError)) this.markSignedOut(redeemError);
+ throw redeemError;
+ }
}
// No recovery key configured — make the fix obvious instead of an
// opaque 401 loop.
- throw new Error(
+ const final = new Error(
`${(error as Error).message} — no recovery key available. Run "mercury cloud connect" to re-pair.`,
);
+ if (isAuthRejection(error)) this.markSignedOut(final);
+ throw final;
}
} else {
// No refresh token at all — go straight to the agent API key.
- return await this.redeemWithAgentKey();
+ try {
+ return await this.redeemWithAgentKey();
+ } catch (redeemError) {
+ if (isAuthRejection(redeemError)) this.markSignedOut(redeemError);
+ throw redeemError;
+ }
}
})().finally(() => {
this.inflight = null;
@@ -270,6 +306,12 @@ export class CloudTokenStore {
}
}
+/** The server said no (401/403), as opposed to a network blip worth retrying. */
+export function isAuthRejection(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return /\b(401|403)\b|unauthori[sz]ed|forbidden|identity mismatch/i.test(message);
+}
+
function isTokenExpired(jwt: string, skewMs = 60_000): boolean {
const parts = jwt.split('.');
if (parts.length !== 3) return true;
diff --git a/src/index.ts b/src/index.ts
index 38c5eac0..0eac6f35 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -187,8 +187,8 @@ function maskKey(key: string): string {
}
const PROVIDER_OPTIONS: Array<{ key: ProviderName; label: string }> = [
- { key: 'aimlapi', label: 'AI/ML API (recommended — 350+ models on one key)' },
- { key: 'mercuryCloud', label: 'Mercury Cloud (hosted — no API keys needed)' },
+ { key: 'mercuryCloud', label: 'Mercury Cloud (recommended — quick start, no API keys)' },
+ { key: 'aimlapi', label: 'AI/ML API (350+ models on one key)' },
{ key: 'deepseek', label: 'DeepSeek' },
{ key: 'openai', label: 'OpenAI' },
{ key: 'anthropic', label: 'Anthropic' },
diff --git a/src/providers/provider-meta.ts b/src/providers/provider-meta.ts
index da81c697..87d56384 100644
--- a/src/providers/provider-meta.ts
+++ b/src/providers/provider-meta.ts
@@ -25,8 +25,9 @@ export interface ProviderMeta {
}
export const PROVIDER_META: Record<ProviderName, ProviderMeta> = {
+ // First on purpose: the recommended quick start, listed above everything else.
+ mercuryCloud: { label: 'Mercury Cloud', kind: 'account', blurb: 'The quick start: sign in and chat. No API keys; models from every major lab on one account.', needsKey: false, needsBaseUrl: false, signInOnly: true },
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-…' },
diff --git a/src/utils/provider-models.test.ts b/src/utils/provider-models.test.ts
index 25bcb56d..38ded914 100644
--- a/src/utils/provider-models.test.ts
+++ b/src/utils/provider-models.test.ts
@@ -180,3 +180,13 @@ describe('fetchProviderModelCatalog', () => {
expect(catalog.models).not.toContain('black-forest-labs/flux-kontext-pro');
});
});
+
+describe('chat models only', () => {
+ it('drops rerankers, embedders and speech models from model lists', async () => {
+ const { isChatModelId, buildModelCatalog } = await import('./provider-models.js');
+ for (const m of ['nemotron-3.5-rerank-8b:free', 'text-embedding-3-small', 'gpt-4o-mini-tts', 'whisper-1', 'omni-moderation-latest']) expect(isChatModelId(m)).toBe(false);
+ for (const m of ['gpt-4o-mini', 'claude-sonnet-4.6', 'mercury-mini', 'deepseek-chat']) expect(isChatModelId(m)).toBe(true);
+ const c = buildModelCatalog('openaiCompat', ['a-chat', 'b-rerank-1', 'c-embed'], 'b-rerank-1');
+ expect([c.recommendedModel, ...c.models]).toEqual(['a-chat']);
+ });
+});
diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.ts
index f9afafcd..6b8b78b0 100644
--- a/src/utils/provider-models.ts
+++ b/src/utils/provider-models.ts
@@ -289,12 +289,18 @@ function chooseRecommendedModel(
return models[0];
}
+/** Models that can't hold a conversation (rerankers, embedders, speech, images, moderation). */
+const NON_CHAT = /(^|[-_/.:])(rerank(er)?|embed(ding)?s?|whisper|tts|transcribe|moderation|dall-e|image-gen|text-to-speech|speech)([-_/.:]|$)/i;
+export function isChatModelId(id: string): boolean {
+ return !NON_CHAT.test(id);
+}
+
export function buildModelCatalog(
provider: ProviderName,
models: string[],
currentModel?: string,
): ProviderModelCatalog {
- const filtered = uniq(models);
+ const filtered = uniq(models).filter(isChatModelId);
if (filtered.length === 0) {
throw new ProviderModelFetchError('Mercury could not find any supported chat models for this provider.');
}
@@ -553,7 +559,7 @@ async function fetchMercuryCloudModels(config: ProviderConfig): Promise<Provider
const allModels = Array.isArray(data.data) ? data.data : [];
const allowed = allModels.filter((m) => m.available === true).map((m) => m.id);
const ids = allowed.length > 0 ? allowed : allModels.map((m) => m.id);
- const models = uniq(ids);
+ const models = uniq(ids).filter(isChatModelId);
return {
recommendedModel: config.model && models.includes(config.model) ? config.model : models[0] || config.model || 'mercury-mini',
models: limitModels(models.filter((model) => model !== config.model)),
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 5d275853..5845577e 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -39,7 +39,8 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'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? }
+ 'voice.check',
+ 'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // 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/cloud-route.test.ts b/src/web/api/cloud-route.test.ts
new file mode 100644
index 00000000..d58b1ed5
--- /dev/null
+++ b/src/web/api/cloud-route.test.ts
@@ -0,0 +1,116 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// Point MERCURY_HOME at a temp dir with a paired Cloud whose model is a reranker.
+const home = await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-cloud-route-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [
+ 'identity:',
+ ' owner: Test',
+ 'cloud:',
+ ' enabled: true',
+ ' apiUrl: https://cloud.test',
+ ' wsUrl: wss://cloud.test/ws',
+ ' jwt: old.jwt.token',
+ ' refreshToken: ""',
+ ' agentId: agent-1',
+ ' agentApiKey: ""',
+ ' accessKey: sk-mc-access',
+ ' tier: free',
+ 'providers:',
+ ' default: mercuryCloud',
+ ' mercuryCloud:',
+ ' name: mercuryCloud',
+ ' apiKey: sk-mc-access',
+ ' baseUrl: https://cloud.test',
+ ' model: nemotron-3.5-rerank-8b:free',
+ ' enabled: true',
+ '',
+ ].join('\n'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+import cloud, { setCloudTestHooks } from './cloud.js';
+
+const models = (ids: string[]) => vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ data: ids.map((id) => ({ id, available: true })) }) } as unknown as Response);
+const get = (path: string) => cloud.request(`http://127.0.0.1${path}`);
+const post = (path: string) => cloud.request(`http://127.0.0.1${path}`, { method: 'POST' });
+const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');
+
+afterEach(() => vi.useRealTimers());
+
+describe('Mercury Cloud status', () => {
+ it('chat key works but the session is gone and the model is a reranker: asks to sign in', async () => {
+ setCloudTestHooks({ fetch: models(['mercury-mini', 'claude-sonnet-4.6', 'nemotron-3.5-rerank-8b:free', 'text-embedding-3-small']) });
+ const body = await (await get('/api/cloud/status?fresh=1')).json() as any;
+ expect(body.paired).toBe(true);
+ expect(body.chat.ok).toBe(true);
+ expect(body.chat.models).toEqual(['mercury-mini', 'claude-sonnet-4.6']);
+ expect(body.session).toBe('signed-out');
+ expect(body.selfRecovers).toBe(false);
+ expect(body.modelOk).toBe(false);
+ expect(body.action).toBe('sign-in');
+ expect(JSON.stringify(body)).not.toContain('sk-mc-access');
+ });
+
+ it('a rejected chat key reads as signed out, not as a crash', async () => {
+ setCloudTestHooks({ fetch: vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({}) } as unknown as Response) });
+ const body = await (await get('/api/cloud/status?fresh=1')).json() as any;
+ expect(body.chat).toMatchObject({ ok: false });
+ expect(body.chat.error).toMatch(/no longer accepts/);
+ expect(body.action).toBe('sign-in');
+ });
+
+ it('an unreachable Cloud says so', async () => {
+ setCloudTestHooks({ fetch: vi.fn().mockRejectedValue(new Error('The operation was aborted due to timeout')) });
+ const body = await (await get('/api/cloud/status?fresh=1')).json() as any;
+ expect(body.chat.error).toMatch(/10 seconds/);
+ });
+});
+
+describe('Mercury Cloud sign-in from the app', () => {
+ it('pairs in the browser, saves the new session with its recovery key, keeps a chat model, then restarts', async () => {
+ vi.useFakeTimers();
+ const restart = vi.fn().mockReturnValue(true);
+ let approve!: (v: unknown) => void;
+ setCloudTestHooks({
+ start: vi.fn().mockResolvedValue({ code: 'ABCD-1234', pairingUrl: 'https://cloud.test/pair/ABCD-1234' }),
+ poll: vi.fn().mockReturnValue(new Promise((r) => { approve = r; })) as never,
+ restart,
+ });
+ const started = await (await post('/api/cloud/signin')).json() as any;
+ expect(started).toMatchObject({ code: 'ABCD-1234', status: 'pending' });
+ expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('pending');
+
+ approve({ jwt: 'new.jwt.token', refreshToken: 'rt-new', agentId: 'agent-1', tier: 'extended', apiKey: 'agent-key-1', accessKey: 'sk-mc-new' });
+ await vi.waitFor(async () => expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('done'));
+ vi.advanceTimersByTime(400);
+ expect(restart).toHaveBeenCalledOnce();
+
+ const saved = yaml();
+ expect(saved).toContain('rt-new');
+ expect(saved).toContain('agentApiKey: agent-key-1');
+ expect(saved).toContain('sk-mc-new');
+ expect(saved).toContain('model: mercury-mini');
+ expect(saved).not.toContain('rerank');
+ });
+
+ it('a refused pairing reports why, with the upgrade link when the plan is full', async () => {
+ const { PairingFailureError } = await import('../../cloud/pairing.js');
+ setCloudTestHooks({
+ start: vi.fn().mockResolvedValue({ code: 'X', pairingUrl: 'https://cloud.test/pair/X' }),
+ poll: vi.fn().mockRejectedValue(new PairingFailureError('Agent limit reached', { code: 'AGENT_LIMIT_REACHED', upgradeUrl: 'https://cloud.test/upgrade' })) as never,
+ });
+ await cloud.request('http://127.0.0.1/api/cloud/signin', { method: 'DELETE' });
+ await post('/api/cloud/signin');
+ await vi.waitFor(async () => expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('failed'));
+ const body = await (await get('/api/cloud/signin')).json() as any;
+ expect(body.error).toMatch(/limit/);
+ expect(body.upgradeUrl).toBe('https://cloud.test/upgrade');
+ });
+});
diff --git a/src/web/api/cloud.ts b/src/web/api/cloud.ts
new file mode 100644
index 00000000..4ec0328a
--- /dev/null
+++ b/src/web/api/cloud.ts
@@ -0,0 +1,180 @@
+import { Hono } from 'hono';
+import { isProviderConfigured, loadConfig, updateConfig, type MercuryConfig } from '../../utils/config.js';
+import { isChatModelId } from '../../utils/provider-models.js';
+import { MERCURY_CLOUD_API_URL, MERCURY_CLOUD_WS_URL } from '../../cloud/endpoints.js';
+import { PairingFailureError, pollPairingComplete, startPairingFlow } from '../../cloud/pairing.js';
+import { getCloudTokenStore } from '../../cloud/token-store.js';
+import { isCloudRuntimeOnline } from '../../cloud/runtime-status.js';
+import { spawnDetachedRestart } from '../../cli/daemon.js';
+import type { PairingResult } from '../../cloud/types.js';
+import { logger } from '../../utils/logger.js';
+
+/**
+ * Mercury Cloud from any client: is it working, and sign in again when the
+ * session has expired, without a terminal.
+ *
+ * GET /api/cloud/status paired? chat key working? agent session online, offline or signed out?
+ * POST /api/cloud/signin start browser pairing → { code, pairingUrl }; the runtime waits for approval
+ * GET /api/cloud/signin pairing progress: pending | done | failed
+ * DELETE /api/cloud/signin stop waiting
+ *
+ * A finished sign-in saves the new credentials and restarts the runtime so
+ * the agent connection and the provider both start fresh with them.
+ */
+
+type Fetch = typeof fetch;
+let doFetch: Fetch = (...args) => fetch(...args);
+let restart: () => boolean = spawnDetachedRestart;
+let poll: typeof pollPairingComplete = pollPairingComplete;
+let start: typeof startPairingFlow = startPairingFlow;
+/** Test seams. */
+export function setCloudTestHooks(h: { fetch?: Fetch; restart?: () => boolean; poll?: typeof pollPairingComplete; start?: typeof startPairingFlow }): void {
+ if (h.fetch) doFetch = h.fetch;
+ if (h.restart) restart = h.restart;
+ if (h.poll) poll = h.poll;
+ if (h.start) start = h.start;
+}
+
+type SessionState = 'online' | 'offline' | 'signed-out' | 'off';
+
+interface ChatProbe { ok: boolean; models: string[]; error: string | null; at: number; key: string }
+let chatProbe: ChatProbe | null = null;
+
+async function probeChat(config: MercuryConfig, fresh: boolean): Promise<ChatProbe> {
+ const key = config.providers.mercuryCloud.apiKey;
+ const apiUrl = config.cloud.apiUrl || MERCURY_CLOUD_API_URL;
+ if (!fresh && chatProbe && chatProbe.key === key && Date.now() - chatProbe.at < 30_000) return chatProbe;
+ let result: ChatProbe;
+ try {
+ const res = await doFetch(`${apiUrl}/v1/models`, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(10_000) });
+ if (res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { data?: Array<{ id: string; available?: boolean }> };
+ const rows = Array.isArray(body.data) ? body.data : [];
+ const allowed = rows.filter((m) => m.available !== false).map((m) => m.id).filter(isChatModelId);
+ result = { ok: true, models: allowed, error: null, at: Date.now(), key };
+ } else {
+ result = { ok: false, models: [], error: res.status === 401 || res.status === 403 ? 'Mercury Cloud no longer accepts this sign-in.' : `Mercury Cloud answered ${res.status}.`, at: Date.now(), key };
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ result = { ok: false, models: [], error: /timeout|abort/i.test(msg) ? "Mercury Cloud didn't answer in 10 seconds." : `Couldn't reach Mercury Cloud: ${msg}`, at: Date.now(), key };
+ }
+ chatProbe = result;
+ return result;
+}
+
+function sessionState(config: MercuryConfig): SessionState {
+ if (!config.cloud.enabled || !config.cloud.agentId) return 'off';
+ if (isCloudRuntimeOnline(config.cloud.agentId)) return 'online';
+ if (getCloudTokenStore()?.isSignedOut()) return 'signed-out';
+ if (!config.cloud.refreshToken && !config.cloud.agentApiKey) return 'signed-out';
+ return 'offline';
+}
+
+const cloud = new Hono();
+
+cloud.get('/api/cloud/status', async (c) => {
+ const config = loadConfig();
+ const paired = !!(config.cloud.enabled && config.cloud.agentId);
+ const provider = config.providers.mercuryCloud;
+ const chat = provider.apiKey ? await probeChat(config, c.req.query('fresh') === '1') : null;
+ const session = sessionState(config);
+ const model = provider.model;
+ const auth = getCloudTokenStore()?.getAuthState();
+ // What the owner should do next, in order of importance.
+ const action = !paired && !provider.apiKey ? 'sign-in'
+ : chat && !chat.ok ? 'sign-in'
+ : session === 'signed-out' ? 'sign-in'
+ : !isChatModelId(model) || (chat?.ok && chat.models.length > 0 && !chat.models.includes(model)) ? 'pick-model'
+ : null;
+ return c.json({
+ paired,
+ enabled: provider.enabled,
+ isDefault: config.providers.default === 'mercuryCloud',
+ tier: config.cloud.tier || null,
+ model,
+ modelOk: isChatModelId(model) && (!chat?.ok || chat.models.length === 0 || chat.models.includes(model)),
+ chat: chat ? { ok: chat.ok, models: chat.models, error: chat.error } : { ok: false, models: [], error: 'Not signed in.' },
+ session,
+ sessionError: auth?.error ?? null,
+ selfRecovers: !!config.cloud.agentApiKey,
+ action,
+ signin: pairing ? publicPairing() : null,
+ });
+});
+
+// ── Sign in (browser pairing) ────────────────────────────────────────────────
+
+interface Pairing { code: string; pairingUrl: string; status: 'pending' | 'done' | 'failed'; error: string | null; upgradeUrl: string | null; startedAt: number; cancelled: boolean }
+let pairing: Pairing | null = null;
+
+function publicPairing() {
+ if (!pairing) return null;
+ const { code, pairingUrl, status, error, upgradeUrl } = pairing;
+ return { code, pairingUrl, status, error, upgradeUrl };
+}
+
+cloud.post('/api/cloud/signin', async (c) => {
+ if (pairing?.status === 'pending' && Date.now() - pairing.startedAt < 290_000) return c.json(publicPairing());
+ const config = loadConfig();
+ const apiUrl = config.cloud.apiUrl || MERCURY_CLOUD_API_URL;
+ let started: { code: string; pairingUrl: string };
+ try {
+ started = await start(apiUrl, undefined);
+ } catch (err) {
+ return c.json({ error: `Couldn't start sign-in: ${err instanceof Error ? err.message : String(err)}` }, 502);
+ }
+ const current: Pairing = { ...started, status: 'pending', error: null, upgradeUrl: null, startedAt: Date.now(), cancelled: false };
+ pairing = current;
+ void poll(apiUrl, started.code).then((result) => {
+ if (current.cancelled) return;
+ finishSignIn(result);
+ current.status = 'done';
+ chatProbe = null;
+ // Fresh credentials: restart so the agent connection and provider start clean.
+ setTimeout(() => { if (!restart()) logger.error('Signed in to Mercury Cloud, but could not restart; run `mercury restart`'); }, 300);
+ }).catch((err) => {
+ if (current.cancelled) return;
+ current.status = 'failed';
+ current.error = err instanceof Error ? err.message : String(err);
+ if (err instanceof PairingFailureError) current.upgradeUrl = err.details.upgradeUrl ?? null;
+ });
+ return c.json(publicPairing());
+});
+
+cloud.get('/api/cloud/signin', (c) => c.json(publicPairing() ?? { status: 'none' }));
+
+cloud.delete('/api/cloud/signin', (c) => {
+ if (pairing && pairing.status === 'pending') pairing.cancelled = true;
+ pairing = null;
+ return c.json({ ok: true });
+});
+
+/** Save new Cloud credentials, the same way `mercury cloud connect` does, keeping a good model choice. */
+export function finishSignIn(result: PairingResult): void {
+ updateConfig((latest) => {
+ const previous = latest.cloud;
+ latest.cloud = {
+ ...previous,
+ enabled: true,
+ apiUrl: previous.apiUrl || MERCURY_CLOUD_API_URL,
+ wsUrl: previous.wsUrl || MERCURY_CLOUD_WS_URL,
+ jwt: result.jwt,
+ refreshToken: result.refreshToken,
+ agentId: result.agentId,
+ tier: result.tier || previous.tier || 'free',
+ // The long-lived recovery key. Without it an expired session can't heal itself.
+ agentApiKey: result.apiKey || (result.agentId === previous.agentId ? previous.agentApiKey : ''),
+ accessKey: result.accessKey || '',
+ };
+ const p = latest.providers.mercuryCloud;
+ p.apiKey = latest.cloud.accessKey || latest.cloud.jwt;
+ p.enabled = true;
+ if (!p.model || !isChatModelId(p.model)) p.model = 'mercury-mini';
+ // Quick start: Cloud becomes the default unless another working default is already chosen.
+ const def = latest.providers[latest.providers.default];
+ if (latest.providers.default === 'mercuryCloud' || !def || !isProviderConfigured(def)) latest.providers.default = 'mercuryCloud';
+ });
+}
+
+export default cloud;
diff --git a/src/web/api/providers.ts b/src/web/api/providers.ts
index 19e5de35..9852cbaf 100644
--- a/src/web/api/providers.ts
+++ b/src/web/api/providers.ts
@@ -12,7 +12,7 @@ function maskApiKey(key: string): string {
* Surfaced as a badge in the UI. One name rather than a list, so the claim
* stays reviewable and reverting it is a one-line change.
*/
-const RECOMMENDED_PROVIDER = 'aimlapi';
+const RECOMMENDED_PROVIDER = 'mercuryCloud';
const NAMES = Object.keys(PROVIDER_META) as ProviderName[];
diff --git a/src/web/server.ts b/src/web/server.ts
index 8b8fe351..463aaa60 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -12,6 +12,7 @@ import { loadConfig } from '../utils/config.js';
import authRoutes from './api/auth.js';
import statusRoutes, { updateStatus } from './api/status.js';
import providerRoutes from './api/providers.js';
+import cloudRoutes from './api/cloud.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
@@ -91,6 +92,7 @@ app.use('*', authGuard);
app.route('/', authRoutes);
app.route('/', statusRoutes);
app.route('/', providerRoutes);
+app.route('/', cloudRoutes);
app.route('/', configRoutes);
app.route('/', systemRoutes);
app.route('/', brainRoutes);