Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(supergrok): add SuperGrok provider via xAI OAuth device flow (#17001)

YuTengjing595bbdec2f78
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index b6de5c3f5b6..76d3eca2136 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -13,16 +13,19 @@ import {
type ComfyUIKeyVault,
type GithubCopilotKeyVault,
type OpenAICompatibleKeyVault,
+ type SuperGrokKeyVault,
type VertexAIKeyVault,
} from '@lobechat/types';
import { safeParseJSON } from '@lobechat/utils';
import { ModelProvider } from 'model-bank';
+import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';
import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
import { AiProviderModel } from '@/database/models/aiProvider';
import { type LobeChatDatabase } from '@/database/type';
import { getLLMConfig } from '@/envs/llm';
import { createLLMGenerationTracingHook } from '@/server/services/llmGenerationTracing/hook';
+import { ensureFreshOAuthToken } from '@/server/services/oauthDeviceFlow/refresh';
import { KeyVaultsGateKeeper } from '../KeyVaultsEncrypt';
import apiKeyManager from './apiKeyManager';
@@ -38,6 +41,7 @@ type ProviderKeyVaults = OpenAICompatibleKeyVault &
CloudflareKeyVault &
ComfyUIKeyVault &
GithubCopilotKeyVault &
+ SuperGrokKeyVault &
VertexAIKeyVault;
/**
@@ -147,6 +151,16 @@ export const buildPayloadFromKeyVaults = (
};
}
+ case ModelProvider.SuperGrok: {
+ // OAuth-only provider: the (already refreshed) access token IS the
+ // bearer credential for api.x.ai β€” expose it as apiKey so the runtime
+ // stays a stateless OpenAI-compatible client.
+ return {
+ apiKey: keyVaults.oauthAccessToken,
+ runtimeProvider,
+ };
+ }
+
default: {
return {
apiKey: keyVaults.apiKey,
@@ -259,6 +273,11 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>
};
}
+ case ModelProvider.SuperGrok: {
+ // OAuth-only: never fall back to env API keys
+ return { apiKey: payload.apiKey };
+ }
+
case ModelProvider.ComfyUI: {
const {
COMFYUI_BASE_URL,
@@ -432,7 +451,27 @@ export const initModelRuntimeFromDB = async (
// 3. Build ClientSecretPayload from keyVaults based on runtimeProvider
// This ensures provider-specific fields (e.g., cloudflareBaseURLOrAccountID) are included
- const keyVaults = (providerConfig?.keyVaults || {}) as ProviderKeyVaults;
+ let keyVaults = (providerConfig?.keyVaults || {}) as ProviderKeyVaults;
+
+ // 3.5. OAuth device-flow providers with rotating refresh tokens (e.g.
+ // SuperGrok): proactively refresh + persist the token pair before building
+ // the payload. Mounted here because every server-side LLM call path (webapi
+ // chat, agent runtime transport, async image/video, lambda routers)
+ // converges on this function.
+ const oauthDeviceFlowConfig = DEFAULT_MODEL_PROVIDER_LIST.find((p) => p.id === provider)?.settings
+ ?.oauthDeviceFlow;
+ if (oauthDeviceFlowConfig?.refreshTokenGrant) {
+ const freshKeyVaults = await ensureFreshOAuthToken({
+ config: oauthDeviceFlowConfig,
+ db,
+ keyVaults,
+ providerId: provider,
+ userId,
+ workspaceId,
+ });
+ keyVaults = { ...keyVaults, ...freshKeyVaults } as ProviderKeyVaults;
+ }
+
const payload = buildPayloadFromKeyVaults(keyVaults, runtimeProvider);
// 4. Get business hooks (billing in cloud, undefined in OSS)
diff --git a/apps/server/src/routers/lambda/oauthDeviceFlow.ts b/apps/server/src/routers/lambda/oauthDeviceFlow.ts
index d52acaf20d6..c4c24d867d1 100644
--- a/apps/server/src/routers/lambda/oauthDeviceFlow.ts
+++ b/apps/server/src/routers/lambda/oauthDeviceFlow.ts
@@ -8,6 +8,7 @@ import { AiProviderModel } from '@/database/models/aiProvider';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { parseJwtExpiry } from '@/server/services/oauthDeviceFlow';
import {
getOAuthService,
GithubCopilotOAuthService,
@@ -15,7 +16,6 @@ import {
const oauthProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
return opts.next({
@@ -95,6 +95,7 @@ export const oauthDeviceFlowRouter = router({
interval: deviceCodeResponse.interval,
userCode: deviceCodeResponse.userCode,
verificationUri: deviceCodeResponse.verificationUri,
+ verificationUriComplete: deviceCodeResponse.verificationUriComplete,
};
}),
@@ -159,15 +160,20 @@ export const oauthDeviceFlowRouter = router({
const pollResult = await service.pollForToken(config, input.deviceCode);
if (pollResult.status === 'success' && pollResult.tokens) {
+ // Expiry: prefer the explicit expires_in, fall back to the JWT exp
+ // claim β€” some providers (e.g. xAI) don't always return expires_in.
+ const expiresAt = pollResult.tokens.expiresIn
+ ? Date.now() + pollResult.tokens.expiresIn * 1000
+ : parseJwtExpiry(pollResult.tokens.accessToken);
+
// Save tokens to keyVaults
await ctx.aiProviderModel.updateConfig(
input.providerId,
{
keyVaults: {
oauthAccessToken: pollResult.tokens.accessToken,
- oauthTokenExpiresAt: pollResult.tokens.expiresIn
- ? String(Date.now() + pollResult.tokens.expiresIn * 1000)
- : undefined,
+ oauthRefreshToken: pollResult.tokens.refreshToken,
+ oauthTokenExpiresAt: expiresAt ? String(expiresAt) : undefined,
},
},
ctx.gateKeeper.encrypt,
@@ -194,6 +200,7 @@ export const oauthDeviceFlowRouter = router({
githubAvatarUrl: undefined,
githubUsername: undefined,
oauthAccessToken: undefined,
+ oauthRefreshToken: undefined,
oauthTokenExpiresAt: undefined,
},
},
diff --git a/apps/server/src/services/oauthDeviceFlow/__tests__/index.test.ts b/apps/server/src/services/oauthDeviceFlow/__tests__/index.test.ts
index e2ee9c721b4..b8ab4b2a4e0 100644
--- a/apps/server/src/services/oauthDeviceFlow/__tests__/index.test.ts
+++ b/apps/server/src/services/oauthDeviceFlow/__tests__/index.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { OAuthDeviceFlowService } from '../index';
+import { OAuthDeviceFlowService, OAuthInvalidGrantError, parseJwtExpiry } from '../index';
// Mock fetch
const mockFetch = vi.fn();
@@ -237,4 +237,93 @@ describe('OAuthDeviceFlowService', () => {
expect(result.tokens?.tokenType).toBe('bearer');
});
});
+
+ describe('refreshAccessToken', () => {
+ it('should exchange the refresh token with a refresh_token grant', async () => {
+ mockFetch.mockResolvedValueOnce({
+ json: () =>
+ Promise.resolve({
+ access_token: 'new-access',
+ expires_in: 3600,
+ refresh_token: 'new-refresh',
+ token_type: 'bearer',
+ }),
+ ok: true,
+ });
+
+ const result = await service.refreshAccessToken(mockConfig, 'old-refresh');
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ mockConfig.tokenEndpoint,
+ expect.objectContaining({
+ body: expect.stringContaining('grant_type=refresh_token'),
+ method: 'POST',
+ }),
+ );
+ expect(result).toEqual({
+ accessToken: 'new-access',
+ expiresIn: 3600,
+ refreshToken: 'new-refresh',
+ scope: undefined,
+ tokenType: 'bearer',
+ });
+ });
+
+ it('should fall back to the old refresh token when the provider does not rotate', async () => {
+ mockFetch.mockResolvedValueOnce({
+ json: () => Promise.resolve({ access_token: 'new-access' }),
+ ok: true,
+ });
+
+ const result = await service.refreshAccessToken(mockConfig, 'old-refresh');
+
+ expect(result.refreshToken).toBe('old-refresh');
+ });
+
+ it('should throw OAuthInvalidGrantError on invalid_grant', async () => {
+ mockFetch.mockResolvedValueOnce({
+ json: () => Promise.resolve({ error: 'invalid_grant' }),
+ ok: false,
+ status: 400,
+ });
+
+ await expect(service.refreshAccessToken(mockConfig, 'dead-refresh')).rejects.toBeInstanceOf(
+ OAuthInvalidGrantError,
+ );
+ });
+
+ it('should throw a generic error on other failures', async () => {
+ mockFetch.mockResolvedValueOnce({
+ json: () => Promise.resolve({ error: 'server_error' }),
+ ok: false,
+ status: 500,
+ });
+
+ await expect(service.refreshAccessToken(mockConfig, 'refresh')).rejects.toThrow(
+ 'Failed to refresh access token',
+ );
+ });
+ });
+});
+
+describe('parseJwtExpiry', () => {
+ const buildJwt = (claims: object) => {
+ const encode = (obj: object) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+ return `${encode({ alg: 'none' })}.${encode(claims)}.sig`;
+ };
+
+ it('should parse the exp claim as a ms timestamp', () => {
+ expect(parseJwtExpiry(buildJwt({ exp: 1_700_000_000 }))).toBe(1_700_000_000_000);
+ });
+
+ it('should return undefined for opaque tokens', () => {
+ expect(parseJwtExpiry('gho_notajwt')).toBeUndefined();
+ });
+
+ it('should return undefined when exp is missing or malformed', () => {
+ expect(parseJwtExpiry(buildJwt({ sub: 'user' }))).toBeUndefined();
+ expect(parseJwtExpiry(buildJwt({ exp: 'soon' }))).toBeUndefined();
+ expect(parseJwtExpiry(undefined)).toBeUndefined();
+ expect(parseJwtExpiry('')).toBeUndefined();
+ });
});
diff --git a/apps/server/src/services/oauthDeviceFlow/__tests__/refresh.test.ts b/apps/server/src/services/oauthDeviceFlow/__tests__/refresh.test.ts
new file mode 100644
index 00000000000..44123cc3600
--- /dev/null
+++ b/apps/server/src/services/oauthDeviceFlow/__tests__/refresh.test.ts
@@ -0,0 +1,330 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ensureFreshOAuthToken } from '../refresh';
+
+const { mockGetAiProviderById, mockUpdateConfig } = vi.hoisted(() => ({
+ mockGetAiProviderById: vi.fn(),
+ mockUpdateConfig: vi.fn(),
+}));
+
+vi.mock('@/database/models/aiProvider', () => ({
+ // class-based mock so it survives vi.clearAllMocks/resetAllMocks
+ AiProviderModel: class {
+ getAiProviderById = mockGetAiProviderById;
+ updateConfig = mockUpdateConfig;
+ },
+}));
+
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: {
+ getUserKeyVaults: vi.fn(),
+ initWithEnvKey: () => Promise.resolve({ encrypt: (s: string) => s }),
+ },
+}));
+
+const mockFetch = vi.fn();
+global.fetch = mockFetch;
+
+/** Build an unsigned JWT with the given exp claim (seconds) */
+const buildJwt = (expSeconds: number) => {
+ const encode = (obj: object) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+ return `${encode({ alg: 'none' })}.${encode({ exp: expSeconds })}.sig`;
+};
+
+const config = {
+ clientId: 'test-client-id',
+ deviceCodeEndpoint: 'https://auth.example.com/device/code',
+ refreshTokenGrant: true,
+ scopes: ['offline_access'],
+ tokenEndpoint: 'https://auth.example.com/token',
+};
+
+const db = {} as any;
+
+let userSeq = 0;
+/** Fresh identity per test to avoid single-flight key collisions */
+const makeParams = (keyVaults: any) => ({
+ config,
+ db,
+ keyVaults,
+ providerId: 'supergrok',
+ userId: `user-${++userSeq}`,
+});
+
+const tokenResponse = (body: object, ok = true) => ({
+ json: () => Promise.resolve(body),
+ ok,
+ status: ok ? 200 : 400,
+});
+
+describe('ensureFreshOAuthToken', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns keyVaults untouched when not connected via OAuth', async () => {
+ const keyVaults = { apiKey: 'sk-xxx' };
+ const result = await ensureFreshOAuthToken(makeParams(keyVaults));
+
+ expect(result).toBe(keyVaults);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('returns keyVaults untouched when there is no refresh token', async () => {
+ const keyVaults = { oauthAccessToken: 'access-token' };
+ const result = await ensureFreshOAuthToken(makeParams(keyVaults));
+
+ expect(result).toBe(keyVaults);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('skips refresh when the token is still fresh', async () => {
+ const keyVaults = {
+ oauthAccessToken: 'access-token',
+ oauthRefreshToken: 'refresh-token',
+ oauthTokenExpiresAt: String(Date.now() + 30 * 60 * 1000),
+ };
+
+ const result = await ensureFreshOAuthToken(makeParams(keyVaults));
+
+ expect(result).toBe(keyVaults);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('refreshes when the stored expiry is within the skew window', async () => {
+ mockFetch.mockResolvedValueOnce(
+ tokenResponse({
+ access_token: 'new-access',
+ expires_in: 3600,
+ refresh_token: 'new-refresh',
+ token_type: 'bearer',
+ }),
+ );
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() + 30 * 1000),
+ }),
+ );
+
+ expect(result.oauthAccessToken).toBe('new-access');
+ expect(result.oauthRefreshToken).toBe('new-refresh');
+ expect(Number(result.oauthTokenExpiresAt)).toBeGreaterThan(Date.now() + 3000 * 1000);
+
+ // refresh_token grant request shape
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe(config.tokenEndpoint);
+ expect(init.body).toContain('grant_type=refresh_token');
+ expect(init.body).toContain('refresh_token=old-refresh');
+
+ // rotated pair persisted before returning
+ expect(mockUpdateConfig).toHaveBeenCalledWith(
+ 'supergrok',
+ expect.objectContaining({
+ keyVaults: expect.objectContaining({
+ oauthAccessToken: 'new-access',
+ oauthRefreshToken: 'new-refresh',
+ }),
+ }),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('refreshes when only the JWT exp claim says the token is expiring', async () => {
+ mockFetch.mockResolvedValueOnce(
+ tokenResponse({ access_token: 'new-access', refresh_token: 'new-refresh' }),
+ );
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ // no stored expiry β€” JWT exp in the past is the only signal
+ oauthAccessToken: buildJwt(Math.floor(Date.now() / 1000) - 10),
+ oauthRefreshToken: 'old-refresh',
+ }),
+ );
+
+ expect(result.oauthAccessToken).toBe('new-access');
+ });
+
+ it('derives expiry from the new JWT when expires_in is missing', async () => {
+ const exp = Math.floor(Date.now() / 1000) + 1800;
+ mockFetch.mockResolvedValueOnce(
+ tokenResponse({ access_token: buildJwt(exp), refresh_token: 'new-refresh' }),
+ );
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ );
+
+ expect(Number(result.oauthTokenExpiresAt)).toBe(exp * 1000);
+ });
+
+ it('keeps the old refresh token when the provider does not rotate', async () => {
+ mockFetch.mockResolvedValueOnce(tokenResponse({ access_token: 'new-access' }));
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ );
+
+ expect(result.oauthRefreshToken).toBe('old-refresh');
+ });
+
+ it('collapses concurrent refreshes onto a single HTTP call', async () => {
+ mockFetch.mockResolvedValue(
+ tokenResponse({ access_token: 'new-access', refresh_token: 'new-refresh' }),
+ );
+
+ const params = makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ });
+
+ const [a, b, c] = await Promise.all([
+ ensureFreshOAuthToken(params),
+ ensureFreshOAuthToken(params),
+ ensureFreshOAuthToken(params),
+ ]);
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(a.oauthAccessToken).toBe('new-access');
+ expect(b).toBe(a);
+ expect(c).toBe(a);
+ });
+
+ it('still returns fresh tokens when persisting fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockFetch.mockResolvedValueOnce(
+ tokenResponse({ access_token: 'new-access', refresh_token: 'new-refresh' }),
+ );
+ mockUpdateConfig.mockRejectedValueOnce(new Error('db down'));
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ );
+
+ expect(result.oauthAccessToken).toBe('new-access');
+ expect(consoleError).toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ describe('invalid_grant self-healing', () => {
+ it('uses stored credentials when another instance already rotated to a fresh pair', async () => {
+ mockFetch.mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' }, false));
+ mockGetAiProviderById.mockResolvedValueOnce({
+ keyVaults: {
+ oauthAccessToken: 'rotated-access',
+ oauthRefreshToken: 'rotated-refresh',
+ oauthTokenExpiresAt: String(Date.now() + 30 * 60 * 1000),
+ },
+ });
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ );
+
+ expect(result.oauthAccessToken).toBe('rotated-access');
+ // no second refresh call needed
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries once with the stored refresh token when the rotated access token is also stale', async () => {
+ mockFetch
+ .mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' }, false))
+ .mockResolvedValueOnce(
+ tokenResponse({
+ access_token: 'second-access',
+ expires_in: 3600,
+ refresh_token: 'second-refresh',
+ }),
+ );
+ mockGetAiProviderById.mockResolvedValueOnce({
+ keyVaults: {
+ oauthAccessToken: 'rotated-but-stale-access',
+ oauthRefreshToken: 'rotated-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ },
+ });
+
+ const result = await ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ );
+
+ expect(result.oauthAccessToken).toBe('second-access');
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ const [, retryInit] = mockFetch.mock.calls[1];
+ expect(retryInit.body).toContain('refresh_token=rotated-refresh');
+ });
+
+ it('throws InvalidProviderAPIKey when the stored refresh token matches the rejected one', async () => {
+ mockFetch.mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' }, false));
+ mockGetAiProviderById.mockResolvedValueOnce({
+ keyVaults: {
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ },
+ });
+
+ await expect(
+ ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+
+ // keyVaults must NOT be cleared on failure
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
+
+ it('throws InvalidProviderAPIKey when the retry also gets invalid_grant', async () => {
+ mockFetch
+ .mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' }, false))
+ .mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' }, false));
+ mockGetAiProviderById.mockResolvedValueOnce({
+ keyVaults: {
+ oauthAccessToken: 'rotated-but-stale-access',
+ oauthRefreshToken: 'rotated-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ },
+ });
+
+ await expect(
+ ensureFreshOAuthToken(
+ makeParams({
+ oauthAccessToken: 'old-access',
+ oauthRefreshToken: 'old-refresh',
+ oauthTokenExpiresAt: String(Date.now() - 1000),
+ }),
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+ });
+ });
+});
diff --git a/apps/server/src/services/oauthDeviceFlow/index.ts b/apps/server/src/services/oauthDeviceFlow/index.ts
index bb8299a54c6..b874553c3fb 100644
--- a/apps/server/src/services/oauthDeviceFlow/index.ts
+++ b/apps/server/src/services/oauthDeviceFlow/index.ts
@@ -6,6 +6,11 @@ export interface DeviceCodeResponse {
interval: number;
userCode: string;
verificationUri: string;
+ /**
+ * Optional verification URI with the user_code already embedded (RFC 8628
+ * Β§3.3.1), so the user doesn't need to type the code manually.
+ */
+ verificationUriComplete?: string;
}
export interface TokenResponse {
@@ -23,6 +28,42 @@ export interface PollResult {
tokens?: TokenResponse;
}
+/**
+ * Thrown by `refreshAccessToken` when the authorization server rejects the
+ * refresh_token as invalid/expired/already-consumed (`invalid_grant`).
+ * Callers use this signal to re-read persisted credentials (another instance
+ * may have rotated the token) before treating the grant as truly dead.
+ */
+export class OAuthInvalidGrantError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'OAuthInvalidGrantError';
+ }
+}
+
+/**
+ * Parse the `exp` claim (ms timestamp) from a JWT access token WITHOUT
+ * verifying the signature. Only used to decide when to proactively refresh β€”
+ * never for trust decisions. Returns undefined for opaque / non-JWT tokens.
+ */
+export const parseJwtExpiry = (token: string | undefined): number | undefined => {
+ if (!token) return undefined;
+
+ const parts = token.split('.');
+ if (parts.length < 2) return undefined;
+
+ try {
+ const payload = Buffer.from(parts[1].replaceAll('-', '+').replaceAll('_', '/'), 'base64');
+ const claims = JSON.parse(payload.toString('utf8'));
+
+ if (typeof claims?.exp !== 'number') return undefined;
+
+ return claims.exp * 1000;
+ } catch {
+ return undefined;
+ }
+};
+
export class OAuthDeviceFlowService {
/**
* Initiate OAuth Device Flow by requesting a device code
@@ -53,6 +94,7 @@ export class OAuthDeviceFlowService {
interval: data.interval ?? config.defaultPollingInterval ?? 5,
userCode: data.user_code,
verificationUri: data.verification_uri || data.verification_url,
+ verificationUriComplete: data.verification_uri_complete,
};
}
@@ -112,4 +154,54 @@ export class OAuthDeviceFlowService {
throw new Error('Unexpected response from token endpoint');
}
+
+ /**
+ * Exchange a refresh_token for a new access token (RFC 6749 Β§6).
+ *
+ * The provider may rotate the refresh_token: when the response carries a new
+ * one the old one is invalidated server-side, so callers MUST persist
+ * `refreshToken` from the returned tokens before relying on them.
+ */
+ async refreshAccessToken(
+ config: OAuthDeviceFlowConfig,
+ refreshToken: string,
+ ): Promise<TokenResponse> {
+ const response = await fetch(config.tokenEndpoint, {
+ body: new URLSearchParams({
+ client_id: config.clientId,
+ grant_type: 'refresh_token',
+ refresh_token: refreshToken,
+ }).toString(),
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ method: 'POST',
+ });
+
+ const data = await response.json().catch(() => ({}));
+
+ if (!response.ok || data.error) {
+ // invalid_grant = refresh token expired / revoked / already consumed
+ if (data.error === 'invalid_grant') {
+ throw new OAuthInvalidGrantError(data.error_description || 'invalid_grant');
+ }
+
+ throw new Error(
+ `Failed to refresh access token: ${response.status} ${data.error || ''} ${data.error_description || ''}`.trim(),
+ );
+ }
+
+ if (!data.access_token) throw new Error('Unexpected response from token endpoint');
+
+ return {
+ accessToken: data.access_token,
+ expiresIn: data.expires_in,
+ // Rotation is optional per RFC 6749 β€” keep the old token when the
+ // provider doesn't rotate.
+ refreshToken: data.refresh_token || refreshToken,
+ scope: data.scope,
+ tokenType: data.token_type || 'bearer',
+ };
+ }
}
diff --git a/apps/server/src/services/oauthDeviceFlow/refresh.ts b/apps/server/src/services/oauthDeviceFlow/refresh.ts
new file mode 100644
index 00000000000..4d69fbf8b5a
--- /dev/null
+++ b/apps/server/src/services/oauthDeviceFlow/refresh.ts
@@ -0,0 +1,215 @@
+import { AgentRuntimeError } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import debug from 'debug';
+
+import { AiProviderModel } from '@/database/models/aiProvider';
+import { type LobeChatDatabase } from '@/database/type';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { type OAuthDeviceFlowConfig } from '@/types/aiProvider';
+
+import { OAuthDeviceFlowService, OAuthInvalidGrantError, parseJwtExpiry } from './index';
+
+const log = debug('lobe-server:oauth-token-refresh');
+
+/**
+ * Refresh the access token this long before it actually expires, so a request
+ * dispatched right at the boundary doesn't hit a mid-flight 401.
+ */
+const REFRESH_SKEW_MS = 120_000;
+
+/**
+ * Fallback access-token lifetime when the provider returns neither
+ * `expires_in` nor a parseable JWT `exp` claim.
+ */
+const DEFAULT_TOKEN_TTL_MS = 3600 * 1000;
+
+export interface OAuthTokenKeyVaults {
+ oauthAccessToken?: string;
+ oauthRefreshToken?: string;
+ oauthTokenExpiresAt?: number | string;
+}
+
+interface EnsureFreshOAuthTokenParams {
+ config: OAuthDeviceFlowConfig;
+ db: LobeChatDatabase;
+ keyVaults: OAuthTokenKeyVaults;
+ providerId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * In-process single-flight registry: concurrent requests for the same
+ * user/provider collapse onto one refresh HTTP call. Critical for rotating
+ * refresh tokens (single use) β€” two parallel refreshes with the same token
+ * would invalidate each other.
+ */
+const inflight = new Map<string, Promise<OAuthTokenKeyVaults>>();
+
+const isExpiring = (keyVaults: OAuthTokenKeyVaults): boolean => {
+ const now = Date.now();
+
+ // Stored expiry is best-effort (the provider may not return expires_in),
+ // so the JWT exp claim acts as a second opinion: expiring when EITHER
+ // signal says so, and when neither is available we conservatively refresh.
+ const storedExpiresAt = keyVaults.oauthTokenExpiresAt
+ ? Number(keyVaults.oauthTokenExpiresAt)
+ : undefined;
+ const jwtExpiresAt = parseJwtExpiry(keyVaults.oauthAccessToken);
+
+ if (!storedExpiresAt && !jwtExpiresAt) return true;
+
+ if (storedExpiresAt && storedExpiresAt - now <= REFRESH_SKEW_MS) return true;
+
+ return Boolean(jwtExpiresAt && jwtExpiresAt - now <= REFRESH_SKEW_MS);
+};
+
+const readStoredKeyVaults = async (
+ db: LobeChatDatabase,
+ userId: string,
+ providerId: string,
+ workspaceId?: string,
+): Promise<OAuthTokenKeyVaults> => {
+ const aiProviderModel = new AiProviderModel(db, userId, workspaceId);
+ const providerConfig = await aiProviderModel.getAiProviderById(
+ providerId,
+ KeyVaultsGateKeeper.getUserKeyVaults,
+ );
+
+ return (providerConfig?.keyVaults || {}) as OAuthTokenKeyVaults;
+};
+
+const persistKeyVaults = async (
+ db: LobeChatDatabase,
+ userId: string,
+ providerId: string,
+ keyVaults: OAuthTokenKeyVaults,
+ workspaceId?: string,
+) => {
+ const aiProviderModel = new AiProviderModel(db, userId, workspaceId);
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+
+ await aiProviderModel.updateConfig(
+ providerId,
+ {
+ keyVaults: {
+ oauthAccessToken: keyVaults.oauthAccessToken,
+ oauthRefreshToken: keyVaults.oauthRefreshToken,
+ oauthTokenExpiresAt:
+ keyVaults.oauthTokenExpiresAt === undefined
+ ? undefined
+ : String(keyVaults.oauthTokenExpiresAt),
+ },
+ },
+ gateKeeper.encrypt,
+ KeyVaultsGateKeeper.getUserKeyVaults,
+ );
+};
+
+const throwInvalidGrant = (providerId: string): never => {
+ // Deliberately do NOT clear keyVaults here: the stored state is the only
+ // evidence for debugging, and the user just needs to re-connect from the
+ // provider settings page (which overwrites it).
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey, {
+ message: `OAuth refresh token for provider "${providerId}" is no longer valid, please re-connect`,
+ });
+};
+
+const refreshAndPersist = async (
+ params: EnsureFreshOAuthTokenParams,
+): Promise<OAuthTokenKeyVaults> => {
+ const { config, db, keyVaults, providerId, userId, workspaceId } = params;
+ const service = new OAuthDeviceFlowService();
+ const usedRefreshToken = keyVaults.oauthRefreshToken!;
+
+ let tokens;
+ try {
+ tokens = await service.refreshAccessToken(config, usedRefreshToken);
+ } catch (error) {
+ if (!(error instanceof OAuthInvalidGrantError)) throw error;
+
+ // invalid_grant self-heal: with rotating refresh tokens, "our" token being
+ // rejected usually means another server instance already consumed it and
+ // persisted a newer pair. Re-read the DB before declaring the grant dead.
+ log('invalid_grant for %s:%s, re-reading stored credentials', userId, providerId);
+ const stored = await readStoredKeyVaults(db, userId, providerId, workspaceId);
+
+ // Same token in the DB as the one that was just rejected β†’ truly dead.
+ if (!stored.oauthRefreshToken || stored.oauthRefreshToken === usedRefreshToken) {
+ throwInvalidGrant(providerId);
+ }
+
+ // Another instance rotated: its access token may already be fresh enough.
+ if (stored.oauthAccessToken && !isExpiring(stored)) return stored;
+
+ // Otherwise retry ONCE with the newer stored refresh token.
+ try {
+ tokens = await service.refreshAccessToken(config, stored.oauthRefreshToken!);
+ } catch (retryError) {
+ if (retryError instanceof OAuthInvalidGrantError) throwInvalidGrant(providerId);
+ throw retryError;
+ }
+ }
+
+ const expiresAt =
+ (tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined) ??
+ parseJwtExpiry(tokens.accessToken) ??
+ Date.now() + DEFAULT_TOKEN_TTL_MS;
+
+ const nextKeyVaults: OAuthTokenKeyVaults = {
+ oauthAccessToken: tokens.accessToken,
+ oauthRefreshToken: tokens.refreshToken,
+ oauthTokenExpiresAt: expiresAt,
+ };
+
+ // Persist BEFORE returning: on a multi-instance server, using a rotated
+ // token pair without writing it back would strand every other instance
+ // (and the next request on this one) with a consumed refresh token.
+ try {
+ await persistKeyVaults(db, userId, providerId, nextKeyVaults, workspaceId);
+ } catch (error) {
+ // The rotated pair only exists in memory now. Still serve this request β€”
+ // the next one will go through the invalid_grant self-heal path.
+ console.error(
+ `[oauth-token-refresh] failed to persist rotated tokens for ${providerId}:`,
+ error,
+ );
+ }
+
+ return nextKeyVaults;
+};
+
+/**
+ * Ensure the OAuth access token in `keyVaults` is fresh, refreshing and
+ * persisting it when it is about to expire.
+ *
+ * Designed for providers with rotating refresh tokens (e.g. xAI / SuperGrok):
+ * - proactive refresh at `expiresAt - 2min`, with the JWT `exp` claim as a
+ * fallback expiry signal
+ * - in-process single-flight per user/provider
+ * - persist-then-use ordering, with invalid_grant "re-read & retry once"
+ * self-healing for multi-instance rotation races
+ *
+ * Returns the key vaults to use for this request (possibly refreshed).
+ * Throws `InvalidProviderAPIKey` when the grant is irrecoverably invalid.
+ */
+export const ensureFreshOAuthToken = async (
+ params: EnsureFreshOAuthTokenParams,
+): Promise<OAuthTokenKeyVaults> => {
+ const { keyVaults, providerId, userId, workspaceId } = params;
+
+ // Not connected via OAuth (or nothing to refresh with) β€” leave untouched.
+ if (!keyVaults.oauthAccessToken || !keyVaults.oauthRefreshToken) return keyVaults;
+
+ if (!isExpiring(keyVaults)) return keyVaults;
+
+ const flightKey = `${userId}:${workspaceId ?? ''}:${providerId}`;
+
+ let flight = inflight.get(flightKey);
+ if (!flight) {
+ flight = refreshAndPersist(params).finally(() => inflight.delete(flightKey));
+ inflight.set(flightKey, flight);
+ }
+
+ return flight;
+};
diff --git a/packages/model-bank/package.json b/packages/model-bank/package.json
index 5140979a576..b492b2aa1bb 100644
--- a/packages/model-bank/package.json
+++ b/packages/model-bank/package.json
@@ -71,6 +71,7 @@
"./stepfun": "./src/aiModels/stepfun.ts",
"./straico": "./src/aiModels/straico.ts",
"./streamlake": "./src/aiModels/streamlake.ts",
+ "./superGrok": "./src/aiModels/superGrok.ts",
"./taichu": "./src/aiModels/taichu.ts",
"./tencentcloud": "./src/aiModels/tencentcloud.ts",
"./togetherai": "./src/aiModels/togetherai.ts",
diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.ts
index 3904b0c1d9c..308b3bacdff 100644
--- a/packages/model-bank/src/aiModels/index.ts
+++ b/packages/model-bank/src/aiModels/index.ts
@@ -65,6 +65,7 @@ import { default as spark } from './spark';
import { default as stepfun } from './stepfun';
import { default as straico } from './straico';
import { default as streamlake } from './streamlake';
+import { default as supergrok } from './superGrok';
import { default as taichu } from './taichu';
import { default as tencentcloud } from './tencentcloud';
import { default as togetherai } from './togetherai';
@@ -173,6 +174,7 @@ const staticModelMap: ModelsMap = {
stepfun,
straico,
streamlake,
+ supergrok,
taichu,
tencentcloud,
togetherai,
@@ -287,6 +289,7 @@ export { default as spark } from './spark';
export { default as stepfun } from './stepfun';
export { default as straico } from './straico';
export { default as streamlake } from './streamlake';
+export { default as supergrok } from './superGrok';
export { default as taichu } from './taichu';
export { default as tencentcloud } from './tencentcloud';
export { default as togetherai } from './togetherai';
diff --git a/packages/model-bank/src/aiModels/superGrok.ts b/packages/model-bank/src/aiModels/superGrok.ts
new file mode 100644
index 00000000000..244beb70022
--- /dev/null
+++ b/packages/model-bank/src/aiModels/superGrok.ts
@@ -0,0 +1,35 @@
+import type { AIChatModelCard } from '../types/aiModel';
+
+// Grok models available through the SuperGrok / X Premium subscription.
+// Same model ids as the `xai` provider, but without pricing: usage is
+// covered by the flat-rate subscription, so per-token cost would mislead.
+// Only the latest generation is listed by default β€” older models can still
+// be pulled in via the remote model list.
+// ref: https://docs.x.ai/docs/models
+const superGrokChatModels: AIChatModelCard[] = [
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ structuredOutput: true,
+ vision: true,
+ },
+ contextWindowTokens: 500_000,
+ description:
+ "SpaceXAI's flagship model for coding, agentic tasks, and knowledge work β€” configurable reasoning (low/medium/high, always on).",
+ displayName: 'Grok 4.5',
+ enabled: true,
+ family: 'grok',
+ generation: 'grok-4.5',
+ id: 'grok-4.5',
+ releasedAt: '2026-07-08',
+ settings: {
+ extendParams: ['grok4_5ReasoningEffort'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+];
+
+export default superGrokChatModels;
diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.ts
index 4ff62048a2a..a2c766a54fd 100644
--- a/packages/model-bank/src/const/modelProvider.ts
+++ b/packages/model-bank/src/const/modelProvider.ts
@@ -64,6 +64,7 @@ export enum ModelProvider {
Stepfun = 'stepfun',
Straico = 'straico',
StreamLake = 'streamlake',
+ SuperGrok = 'supergrok',
Taichu = 'taichu',
TencentCloud = 'tencentcloud',
TogetherAI = 'togetherai',
diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.ts
index cb3a2e2fc61..c039229555f 100644
--- a/packages/model-bank/src/modelProviders/index.ts
+++ b/packages/model-bank/src/modelProviders/index.ts
@@ -67,6 +67,7 @@ import SparkProvider from './spark';
import StepfunProvider from './stepfun';
import StraicoProvider from './straico';
import StreamLakeProvider from './streamlake';
+import SuperGrokProvider from './superGrok';
import TaichuProvider from './taichu';
import TencentcloudProvider from './tencentcloud';
import TogetherAIProvider from './togetherai';
@@ -182,6 +183,7 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [
Ai21Provider,
UpstageProvider,
XAIProvider,
+ SuperGrokProvider,
JinaProvider,
SambaNovaProvider,
CohereProvider,
@@ -302,6 +304,7 @@ export { default as SparkProviderCard } from './spark';
export { default as StepfunProviderCard } from './stepfun';
export { default as StraicoProviderCard } from './straico';
export { default as StreamLakeProviderCard } from './streamlake';
+export { default as SuperGrokProviderCard } from './superGrok';
export { default as TaichuProviderCard } from './taichu';
export { default as TencentCloudProviderCard } from './tencentcloud';
export { default as TogetherAIProviderCard } from './togetherai';
diff --git a/packages/model-bank/src/modelProviders/superGrok.ts b/packages/model-bank/src/modelProviders/superGrok.ts
new file mode 100644
index 00000000000..cdeb793936d
--- /dev/null
+++ b/packages/model-bank/src/modelProviders/superGrok.ts
@@ -0,0 +1,41 @@
+import type { ModelProviderCard } from '@/types/llm';
+
+/**
+ * SuperGrok / X Premium subscription access to Grok models via xAI OAuth
+ * device flow (RFC 8628). Requests hit the same OpenAI-compatible
+ * `https://api.x.ai/v1` endpoint as the `xai` provider, but authenticate
+ * with a rotating OAuth token pair instead of an API key.
+ *
+ * The client_id below is xAI's public Grok-CLI OAuth client β€” the same one
+ * used by opencode, officially endorsed by xAI: https://x.ai/news/grok-opencode
+ */
+const SuperGrok: ModelProviderCard = {
+ chatModels: [],
+ checkModel: 'grok-4.5',
+ description:
+ 'Access Grok models with your SuperGrok or X Premium subscription, no API key required.',
+ disableBrowserRequest: true,
+ id: 'supergrok',
+ modelsUrl: 'https://docs.x.ai/docs/models',
+ name: 'SuperGrok',
+ settings: {
+ authType: 'oauthDeviceFlow',
+ // OAuth tokens are refreshed and persisted server-side; browser requests
+ // would bypass the refresh pipeline, so they are hard-disabled.
+ disableBrowserRequest: true,
+ oauthDeviceFlow: {
+ clientId: 'b1a00492-073a-47ea-816f-4c329264a828',
+ defaultPollingInterval: 5,
+ deviceCodeEndpoint: 'https://auth.x.ai/oauth2/device/code',
+ refreshTokenGrant: true,
+ scopes: ['openid', 'profile', 'email', 'offline_access', 'grok-cli:access', 'api:access'],
+ tokenEndpoint: 'https://auth.x.ai/oauth2/token',
+ },
+ sdkType: 'openai',
+ showApiKey: false,
+ showChecker: true,
+ },
+ url: 'https://x.ai/grok',
+};
+
+export default SuperGrok;
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index 2576a72bd69..97afd10874a 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -70,6 +70,7 @@ export { LobeQwenAI } from './providers/qwen';
export { LobeStepfunAI } from './providers/stepfun';
export { LobeStraicoAI } from './providers/straico';
export { LobeStreamLakeAI } from './providers/streamlake';
+export { LobeSuperGrokAI } from './providers/superGrok';
export { LobeTogetherAI } from './providers/togetherai';
export { LobeVolcengineAI } from './providers/volcengine';
export { LobeVolcengineCodingPlanAI } from './providers/volcengineCodingPlan';
diff --git a/packages/model-runtime/src/providers/superGrok/index.ts b/packages/model-runtime/src/providers/superGrok/index.ts
new file mode 100644
index 00000000000..bd86c07254b
--- /dev/null
+++ b/packages/model-runtime/src/providers/superGrok/index.ts
@@ -0,0 +1,44 @@
+import { ModelProvider } from 'model-bank';
+
+import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
+import {
+ handleXAIChatCompletionPayload,
+ handleXAIResponsesPayload,
+ type XAIModelCard,
+} from '../xai';
+
+/**
+ * SuperGrok / X Premium subscription access to Grok models.
+ *
+ * Talks to the exact same OpenAI-compatible `https://api.x.ai/v1` endpoint as
+ * the `xai` provider (payload handling is shared), but authenticates with an
+ * OAuth access token instead of an API key. The token is refreshed and
+ * injected server-side (see `apps/server` oauthDeviceFlow refresh service) β€”
+ * this runtime stays a stateless bearer client, receiving the fresh token as
+ * `apiKey`.
+ *
+ * Chat only: image/video generation is not exposed through the subscription
+ * OAuth scope.
+ */
+export const LobeSuperGrokAI = createOpenAICompatibleRuntime({
+ baseURL: 'https://api.x.ai/v1',
+ chatCompletion: {
+ handlePayload: handleXAIChatCompletionPayload,
+ useResponse: true,
+ },
+ debug: {
+ chatCompletion: () => process.env.DEBUG_SUPERGROK_CHAT_COMPLETION === '1',
+ responses: () => process.env.DEBUG_SUPERGROK_RESPONSES === '1',
+ },
+ models: async ({ client }) => {
+ const modelsPage = (await client.models.list()) as any;
+ const modelList: XAIModelCard[] = modelsPage.data;
+
+ return processModelList(modelList, MODEL_LIST_CONFIGS.xai, 'supergrok');
+ },
+ provider: ModelProvider.SuperGrok,
+ responses: {
+ handlePayload: handleXAIResponsesPayload,
+ },
+});
diff --git a/packages/model-runtime/src/providers/xai/index.test.ts b/packages/model-runtime/src/providers/xai/index.test.ts
index 01ac155fa15..1da3fab28ba 100644
--- a/packages/model-runtime/src/providers/xai/index.test.ts
+++ b/packages/model-runtime/src/providers/xai/index.test.ts
@@ -7,6 +7,10 @@ import { testProvider } from '../../providerTestUtils';
import type { XAIModelCard } from './index';
import { LobeXAI } from './index';
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+
testProvider({
Runtime: LobeXAI,
provider: ModelProvider.XAI,
diff --git a/packages/model-runtime/src/providers/xai/index.ts b/packages/model-runtime/src/providers/xai/index.ts
index 1afa8d156cd..305cd7534a3 100644
--- a/packages/model-runtime/src/providers/xai/index.ts
+++ b/packages/model-runtime/src/providers/xai/index.ts
@@ -102,15 +102,38 @@ const mapResponseFormatToResponsesText = (
};
};
+/**
+ * Payload handlers shared with the `supergrok` provider, which talks to the
+ * same api.x.ai endpoint (authenticated via OAuth instead of an API key).
+ */
+export const handleXAIChatCompletionPayload = (payload: ChatStreamPayload) =>
+ ({
+ ...pruneUnsupportedChatCompletionParameters(payload),
+ apiMode: 'responses',
+ stream: payload.stream ?? true,
+ }) as any;
+
+export const handleXAIResponsesPayload = (payload: ChatStreamPayload) => {
+ const { enabledSearch, response_format, text, tools, ...rest } =
+ stripUnsupportedPenaltyParameters(payload);
+ const sanitizedTools = sanitizeXAITools(tools);
+
+ const xaiTools = enabledSearch
+ ? [...(sanitizedTools || []), { type: 'web_search' }, { type: 'x_search' }]
+ : sanitizedTools;
+
+ return {
+ ...rest,
+ tools: xaiTools,
+ text: mapResponseFormatToResponsesText(response_format, text),
+ include: ['reasoning.encrypted_content'],
+ } as any;
+};
+
export const LobeXAI = createOpenAICompatibleRuntime({
baseURL: 'https://api.x.ai/v1',
chatCompletion: {
- handlePayload: (payload) =>
- ({
- ...pruneUnsupportedChatCompletionParameters(payload),
- apiMode: 'responses',
- stream: payload.stream ?? true,
- }) as any,
+ handlePayload: handleXAIChatCompletionPayload,
useResponse: true,
},
createImage: createXAIImage,
@@ -134,21 +157,6 @@ export const LobeXAI = createOpenAICompatibleRuntime({
},
provider: ModelProvider.XAI,
responses: {
- handlePayload: (payload) => {
- const { enabledSearch, response_format, text, tools, ...rest } =
- stripUnsupportedPenaltyParameters(payload);
- const sanitizedTools = sanitizeXAITools(tools);
-
- const xaiTools = enabledSearch
- ? [...(sanitizedTools || []), { type: 'web_search' }, { type: 'x_search' }]
- : sanitizedTools;
-
- return {
- ...rest,
- tools: xaiTools,
- text: mapResponseFormatToResponsesText(response_format, text),
- include: ['reasoning.encrypted_content'],
- } as any;
- },
+ handlePayload: handleXAIResponsesPayload,
},
});
diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.ts
index b829c7579a5..69d5f7ad6e6 100644
--- a/packages/model-runtime/src/runtimeMap.ts
+++ b/packages/model-runtime/src/runtimeMap.ts
@@ -63,6 +63,7 @@ import { LobeSparkAI } from './providers/spark';
import { LobeStepfunAI } from './providers/stepfun';
import { LobeStraicoAI } from './providers/straico';
import { LobeStreamLakeAI } from './providers/streamlake';
+import { LobeSuperGrokAI } from './providers/superGrok';
import { LobeTaichuAI } from './providers/taichu';
import { LobeTencentCloudAI } from './providers/tencentcloud';
import { LobeTogetherAI } from './providers/togetherai';
@@ -147,6 +148,7 @@ export const providerRuntimeMap = {
stepfun: LobeStepfunAI,
straico: LobeStraicoAI,
streamlake: LobeStreamLakeAI,
+ supergrok: LobeSuperGrokAI,
taichu: LobeTaichuAI,
tencentcloud: LobeTencentCloudAI,
togetherai: LobeTogetherAI,
diff --git a/packages/model-runtime/src/utils/modelParse.ts b/packages/model-runtime/src/utils/modelParse.ts
index c9923d24f22..cf523afed10 100644
--- a/packages/model-runtime/src/utils/modelParse.ts
+++ b/packages/model-runtime/src/utils/modelParse.ts
@@ -280,9 +280,11 @@ const isKeywordListMatch = (modelId: string, keywords: readonly string[]): boole
* @param provider Provider type
* @returns Matching local model configuration
*/
+// Accepts either a provider id or a model-family key β€” at runtime it simply
+// looks up a same-named export in model-bank and skips when absent.
const findKnownModelByProvider = async (
modelId: string,
- provider: keyof typeof MODEL_LIST_CONFIGS,
+ provider: ModelProviderKey | keyof typeof MODEL_LIST_CONFIGS,
): Promise<any> => {
const lowerModelId = modelId.toLowerCase();
@@ -667,13 +669,13 @@ const processModelCard = (
export const processModelList = async (
modelList: Array<{ id: string }>,
config: ModelProcessorConfig,
- provider?: keyof typeof MODEL_LIST_CONFIGS,
+ provider?: ModelProviderKey,
): Promise<ChatModelCard[]> => {
const { loadModels } = await import('model-bank');
const builtinModels = await loadModels();
// If provider is provided, try to get the local configuration for that provider
- const providerLocalConfig = await getProviderLocalConfig(provider as ModelProviderKey);
+ const providerLocalConfig = await getProviderLocalConfig(provider);
return Promise.all(
modelList.map(async (model) => {
diff --git a/packages/types/src/aiProvider.ts b/packages/types/src/aiProvider.ts
index 490c0cb0d2f..5250e09dea0 100644
--- a/packages/types/src/aiProvider.ts
+++ b/packages/types/src/aiProvider.ts
@@ -43,6 +43,13 @@ export interface OAuthDeviceFlowConfig {
* URL to request device code
*/
deviceCodeEndpoint: string;
+ /**
+ * Whether the provider issues a refresh_token (e.g. via `offline_access`
+ * scope) that the server should use to renew the access token before it
+ * expires. Providers with rotating refresh tokens (e.g. xAI) rely on the
+ * server-side refresh pipeline persisting the rotated pair on every renewal.
+ */
+ refreshTokenGrant?: boolean;
/**
* OAuth scopes
*/
@@ -73,6 +80,11 @@ export interface OAuthDeviceFlowKeyVault {
* OAuth access token (e.g., GitHub's ghu_xxx)
*/
oauthAccessToken?: string;
+ /**
+ * OAuth refresh token. May rotate on every refresh (e.g. xAI) β€” always
+ * persist the value returned by the latest refresh response.
+ */
+ oauthRefreshToken?: string;
/**
* OAuth token expiration timestamp (ms)
*/
@@ -203,6 +215,7 @@ const OAuthDeviceFlowConfigSchema = z.object({
clientId: z.string(),
defaultPollingInterval: z.number().optional(),
deviceCodeEndpoint: z.string(),
+ refreshTokenGrant: z.boolean().optional(),
scopes: z.array(z.string()),
tokenEndpoint: z.string(),
tokenExchangeEndpoint: z.string().optional(),
diff --git a/packages/types/src/user/settings/keyVaults.ts b/packages/types/src/user/settings/keyVaults.ts
index efdd4ef4bbf..a55af38bcfd 100644
--- a/packages/types/src/user/settings/keyVaults.ts
+++ b/packages/types/src/user/settings/keyVaults.ts
@@ -63,6 +63,21 @@ export interface GithubCopilotKeyVault {
oauthAccessToken?: string;
}
+export interface SuperGrokKeyVault {
+ /**
+ * xAI OAuth access token (JWT, ~1h lifetime)
+ */
+ oauthAccessToken?: string;
+ /**
+ * xAI OAuth refresh token. Rotates on every refresh β€” single use.
+ */
+ oauthRefreshToken?: string;
+ /**
+ * Access token expiration timestamp (ms)
+ */
+ oauthTokenExpiresAt?: string;
+}
+
export interface SearchEngineKeyVaults {
searchxng?: {
apiKey?: string;
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
index 4b1f5e78f28..32a39729c08 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx
@@ -185,7 +185,13 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
hasAutoClosedRef.current = false;
setIsAuthenticating(true);
- await startAuth();
+ const info = await startAuth();
+
+ // Auto-open the verification page right away β€” the Connect click still
+ // counts as transient user activation, so popup blockers normally allow
+ // it. The manual "open browser" button stays as a fallback when blocked.
+ const uri = info?.verificationUriComplete || info?.verificationUri;
+ if (uri) window.open(uri, '_blank');
}, [canManageProvider, startAuth]);
const handleCancelAuth = useCallback(() => {
@@ -194,10 +200,12 @@ const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(
}, [cancelAuth]);
const handleOpenBrowser = useCallback(() => {
- if (deviceCodeInfo?.verificationUri) {
- window.open(deviceCodeInfo.verificationUri, '_blank');
+ // Prefer the code-prefilled URI so the user doesn't need to type the code
+ const uri = deviceCodeInfo?.verificationUriComplete || deviceCodeInfo?.verificationUri;
+ if (uri) {
+ window.open(uri, '_blank');
}
- }, [deviceCodeInfo?.verificationUri]);
+ }, [deviceCodeInfo?.verificationUri, deviceCodeInfo?.verificationUriComplete]);
// Reset hasAutoClosedRef when starting new auth
useEffect(() => {
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts
index fb49b719ca1..c3ee94e4f02 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts
@@ -13,6 +13,11 @@ interface DeviceCodeInfo {
interval: number;
userCode: string;
verificationUri: string;
+ /**
+ * Verification URI with the user_code pre-filled (RFC 8628 Β§3.3.1), offered
+ * by some providers (e.g. xAI) so the user can skip typing the code.
+ */
+ verificationUriComplete?: string;
}
interface UseOAuthDeviceFlowOptions {
@@ -24,7 +29,8 @@ interface UseOAuthDeviceFlowResult {
cancelAuth: () => void;
deviceCodeInfo?: DeviceCodeInfo;
error?: string;
- startAuth: () => Promise<void>;
+ /** Returns the device code info on success so callers can e.g. auto-open the verification page */
+ startAuth: () => Promise<DeviceCodeInfo | undefined>;
state: AuthState;
}
@@ -133,6 +139,7 @@ export function useOAuthDeviceFlow({
interval: response.interval,
userCode: response.userCode,
verificationUri: response.verificationUri,
+ verificationUriComplete: response.verificationUriComplete,
};
setDeviceCodeInfo(info);
@@ -152,6 +159,8 @@ export function useOAuthDeviceFlow({
startPolling(info.deviceCode, info.interval);
}
}, 2000);
+
+ return info;
} catch {
setState('error');
setError('authError');