Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: use Mercury Cloud access keys for LLM gateway auth, skipping JWT rotation when sk-mc- key is present
Salman Qureshi5c9121fa3bdf
diff --git a/src/cloud/pairing-flow.test.ts b/src/cloud/pairing-flow.test.tsindex 626a1867..a52fdeaa 100644--- a/src/cloud/pairing-flow.test.ts+++ b/src/cloud/pairing-flow.test.ts@@ -169,12 +169,13 @@ describe('runCloudPairingFlow', () => {refreshToken: 'new-refresh',agentId: 'agent-2',tier: 'free',+ accessKey: 'sk-mc-agent-2',});vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [] }) }));const result = await runCloudPairingFlow(current);- expect(result?.cloudConfig).toMatchObject({ agentId: 'agent-2', agentApiKey: '' });+ expect(result?.cloudConfig).toMatchObject({ agentId: 'agent-2', agentApiKey: '', accessKey: 'sk-mc-agent-2' });vi.unstubAllGlobals();});});diff --git a/src/cloud/pairing-flow.ts b/src/cloud/pairing-flow.tsindex 7385b7cc..ad413720 100644--- a/src/cloud/pairing-flow.ts+++ b/src/cloud/pairing-flow.ts@@ -80,13 +80,14 @@ export async function runCloudPairingFlow(refreshToken: result.refreshToken,agentId: result.agentId,tier: result.tier || 'free',- agentApiKey: result.apiKey || '',+ agentApiKey: result.apiKey || (result.agentId === config.cloud.agentId ? config.cloud.agentApiKey : ''),+ accessKey: result.accessKey || '',};let model = 'mercury-flash';try {const res = await fetch(`${apiUrl}/v1/models`, {- headers: { Authorization: `Bearer ${result.jwt}` },+ headers: { Authorization: `Bearer ${result.accessKey || result.jwt}` },});if (res.ok) {const data = (await res.json()) as { data?: Array<{ id: string; label: string; discount_percent?: number }> };@@ -128,6 +129,12 @@ export async function runCloudConnect(): Promise<void> {const valid = await validateCloudConnection(config);if (valid) {+ if (config.cloud.accessKey && !(await validateCloudAccessKey(config))) {+ console.log(chalk.yellow(' ⚠ Mercury Cloud API key is no longer valid. Falling back to the current session.'));+ config.cloud.accessKey = '';+ config.providers.mercuryCloud.apiKey = config.cloud.jwt;+ saveConfig(config);+ }console.log(chalk.green(' ✓ Mercury Cloud is already connected.'));console.log(chalk.dim(` Agent ID: ${config.cloud.agentId}`));console.log(chalk.dim(` Tier: ${config.cloud.tier || 'free'}`));@@ -217,7 +224,7 @@ export async function runCloudConnect(): Promise<void> {const previousDefault = config.providers.default;const pairedConfig = updateConfig((latest) => {latest.cloud = result.cloudConfig;- latest.providers.mercuryCloud.apiKey = result.cloudConfig.jwt;+ latest.providers.mercuryCloud.apiKey = result.cloudConfig.accessKey || result.cloudConfig.jwt;latest.providers.mercuryCloud.model = result.model;latest.providers.mercuryCloud.enabled = true;latest.providers.default = 'mercuryCloud';@@ -264,6 +271,7 @@ export async function runCloudDisconnect(): Promise<void> {|| !!config.cloud.refreshToken|| !!config.cloud.agentId|| !!config.cloud.agentApiKey+ || !!config.cloud.accessKey|| config.providers.mercuryCloud.enabled|| !!config.providers.mercuryCloud.apiKey;@@ -273,6 +281,7 @@ export async function runCloudDisconnect(): Promise<void> {latest.cloud.refreshToken = '';latest.cloud.agentId = '';latest.cloud.agentApiKey = '';+ latest.cloud.accessKey = '';latest.providers.mercuryCloud.enabled = false;latest.providers.mercuryCloud.apiKey = '';@@ -429,3 +438,15 @@ async function validateCloudConnection(config: MercuryConfig): Promise<boolean>return false;}}++async function validateCloudAccessKey(config: MercuryConfig): Promise<boolean> {+ try {+ const res = await fetch(`${config.cloud.apiUrl}/v1/models`, {+ headers: { Authorization: `Bearer ${config.cloud.accessKey}` },+ signal: AbortSignal.timeout(10_000),+ });+ return res.ok;+ } catch {+ return false;+ }+}diff --git a/src/cloud/token-store.ts b/src/cloud/token-store.tsindex b0ca6ac6..31694bd8 100644--- a/src/cloud/token-store.ts+++ b/src/cloud/token-store.ts@@ -105,7 +105,7 @@ export class CloudTokenStore {if (this.liveConfig) {this.liveConfig.cloud.jwt = jwt;this.liveConfig.cloud.refreshToken = refreshTokenValue;- this.liveConfig.providers.mercuryCloud.apiKey = jwt;+ this.liveConfig.providers.mercuryCloud.apiKey = this.liveConfig.cloud.accessKey || jwt;}for (const listener of this.listeners) {try { listener({ jwt, refreshToken: refreshTokenValue }); } catch (err) {@@ -123,7 +123,7 @@ export class CloudTokenStore {this.assertActivePersistedIdentity(config);config.cloud.jwt = jwt;config.cloud.refreshToken = refreshTokenValue;- config.providers.mercuryCloud.apiKey = jwt;+ config.providers.mercuryCloud.apiKey = config.cloud.accessKey || jwt;});this.setTokens(jwt, refreshTokenValue);}diff --git a/src/cloud/types.ts b/src/cloud/types.tsindex 31ca1143..802e8ff4 100644--- a/src/cloud/types.ts+++ b/src/cloud/types.ts@@ -7,6 +7,7 @@ export interface CloudConfig {agentId: string;tier: string;agentApiKey: string;+ accessKey: string;}export interface PairingResult {@@ -15,6 +16,7 @@ export interface PairingResult {agentId: string;tier: string;apiKey?: string;+ accessKey?: string;}export interface TokenRefreshResult {diff --git a/src/core/agent.ts b/src/core/agent.tsindex 15af9cd9..b42abc1c 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1075,7 +1075,7 @@ export class Agent {const catalog = await fetchProviderModelCatalog(provider.name as any, provider.name === 'mercuryCloud'? {...provider,- apiKey: this.config.cloud.jwt || provider.apiKey,+ apiKey: this.config.cloud.accessKey || this.config.cloud.jwt || provider.apiKey,baseUrl: this.config.cloud.apiUrl || provider.baseUrl,}: provider);diff --git a/src/index.ts b/src/index.tsindex 4ef6b5ef..28c811da 100644--- a/src/index.ts+++ b/src/index.ts@@ -2408,8 +2408,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {if (payload) {config.cloud.jwt = payload.jwt;config.cloud.refreshToken = payload.refreshToken;- config.providers.mercuryCloud.apiKey = payload.jwt;- providers.updateApiKey('mercuryCloud', payload.jwt);+ const llmKey = config.cloud.accessKey || payload.jwt;+ config.providers.mercuryCloud.apiKey = llmKey;+ providers.updateApiKey('mercuryCloud', llmKey);logger.info('Mercury Cloud token refreshed and saved');}});diff --git a/src/providers/mercury-cloud.ts b/src/providers/mercury-cloud.tsindex 724b73f3..0aa68a81 100644--- a/src/providers/mercury-cloud.ts+++ b/src/providers/mercury-cloud.ts@@ -13,6 +13,7 @@ export class MercuryCloudProvider extends BaseProvider {private modelInstance: ReturnType<ReturnType<typeof createOpenAI>['languageModel']>;private tokenStore: CloudTokenStore | null;private removeTokenListener: (() => void) | null = null;+ private readonly usesAccessKey: boolean;constructor(config: ProviderConfig, tokenStore: CloudTokenStore | null = null) {super(config);@@ -20,7 +21,8 @@ export class MercuryCloudProvider extends BaseProvider {this.model = config.model;this.tokenStore = tokenStore;- const jwt = tokenStore?.getJwt() ?? config.apiKey ?? 'cloud-jwt-placeholder';+ this.usesAccessKey = config.apiKey?.startsWith('sk-mc-') ?? false;+ const jwt = this.usesAccessKey ? config.apiKey! : tokenStore?.getJwt() ?? config.apiKey ?? 'cloud-jwt-placeholder';this.client = createOpenAI({apiKey: jwt,baseURL: config.baseUrl?.endsWith('/v1') ? config.baseUrl : `${config.baseUrl}/v1`,@@ -32,7 +34,7 @@ export class MercuryCloudProvider extends BaseProvider {// replaces the old independent 3-minute proactive refresh timer, which// raced the WS client for the single-use refresh token and eventually// burned it.- if (tokenStore) {+ if (tokenStore && !this.usesAccessKey) {this.removeTokenListener = tokenStore.addListener((tokens) => {this.rebuildClient(tokens.jwt);});@@ -78,7 +80,7 @@ export class MercuryCloudProvider extends BaseProvider {provider: this.name,};} catch (err: any) {- if (this.isRetryableError(err) && this.tokenStore) {+ if (this.isRetryableError(err) && this.tokenStore && !this.usesAccessKey) {logger.warn('Mercury Cloud 401 — refreshing token and retrying...');try {const rotated = await this.tokenStore.rotate();@@ -124,7 +126,7 @@ export class MercuryCloudProvider extends BaseProvider {// streamText previously had no 401-retry path, which meant a streaming// chat would fail where a non-streaming chat would recover. Retry once// after a reactive rotation.- if (!this.isRetryableError(err) || !this.tokenStore) throw err;+ if (!this.isRetryableError(err) || !this.tokenStore || this.usesAccessKey) throw err;logger.warn('Mercury Cloud stream 401 — refreshing token and retrying...');try {const rotated = await this.tokenStore.rotate();@@ -157,7 +159,7 @@ export class MercuryCloudProvider extends BaseProvider {}async ensureFreshToken(): Promise<void> {- if (!this.tokenStore) return;+ if (!this.tokenStore || this.usesAccessKey) return;try {const jwt = await this.tokenStore.rotateIfExpired();this.rebuildClient(jwt);@@ -172,7 +174,7 @@ export class MercuryCloudProvider extends BaseProvider {}getModelInstance(): any {- if (this.tokenStore?.isJwtNearExpiry()) {+ if (!this.usesAccessKey && this.tokenStore?.isJwtNearExpiry()) {this.tokenStore.rotateIfExpired().catch((err) => {logger.warn({ err: err.message }, 'Mercury Cloud token refresh failed in getModelInstance');});diff --git a/src/utils/config.ts b/src/utils/config.tsindex cb0ac92e..c2b74d10 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -76,6 +76,7 @@ export interface CloudConfig {agentId: string;tier: string;agentApiKey: string;+ accessKey?: string;}export interface MercuryConfig {@@ -241,6 +242,7 @@ export function getDefaultConfig(): MercuryConfig {agentId: getEnv('MERCURY_CLOUD_AGENT_ID', ''),tier: getEnv('MERCURY_CLOUD_TIER', 'free'),agentApiKey: getEnv('MERCURY_CLOUD_AGENT_API_KEY', ''),+ accessKey: getEnv('MERCURY_CLOUD_ACCESS_KEY', ''),},providers: {default: getEnv('DEFAULT_PROVIDER', 'deepseek') as ProviderName,@@ -461,7 +463,9 @@ export function normalizeCloudConfig(config: MercuryConfig): MercuryConfig {}if (!config.cloud.wsUrl) config.cloud.wsUrl = deriveCloudWsUrl(config.cloud.apiUrl);config.providers.mercuryCloud.baseUrl = config.cloud.apiUrl;- if (config.cloud.jwt && !config.providers.mercuryCloud.apiKey) {+ if (config.cloud.accessKey) {+ config.providers.mercuryCloud.apiKey = config.cloud.accessKey;+ } else if (config.cloud.jwt && !config.providers.mercuryCloud.apiKey) {config.providers.mercuryCloud.apiKey = config.cloud.jwt;}return config;