{"record":{"id":"098376f8f13cf04a","repo":"mastra-ai/mastra","slug":"not-logged-in-to-xai","errorCode":null,"errorMessage":"Not logged in to xAI.","messagePattern":"Not logged in to xAI\\.","errorType":"exception","errorClass":"ProviderAuthRequiredError","httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/providers/xai.ts","lineNumber":48,"sourceCode":"\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n  authStorageInstance = storage ?? null;\n}\n\n/**\n * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n  return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n    const storage = opts.authStorage ?? getAuthStorage();\n    storage.reload();\n\n    const cred = storage.get(XAI_PROVIDER_ID);\n    if (!cred || cred.type !== 'oauth') {\n      throw new ProviderAuthRequiredError('Not logged in to xAI.');\n    }\n\n    // getApiKey() refreshes the access token if it has expired.\n    const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);\n    if (!accessToken) {\n      throw new ProviderAuthRequiredError('Failed to refresh the xAI token.');\n    }\n\n    // Preserve existing headers, strip auth-related ones. Explicit init\n    // headers override headers carried by an incoming Request.\n    const headers = new Headers(url instanceof Request ? url.headers : undefined);\n    if (init?.headers) {\n      new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n    }\n    headers.delete('authorization');\n    headers.delete('x-api-key');\n\n    headers.set('Authorization', `Bearer ${accessToken}`);","sourceCodeStart":30,"sourceCodeEnd":66,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/providers/xai.ts#L30-L66","documentation":"buildXAIOAuthFetch wraps fetch to authenticate xAI (Grok) API calls with an OAuth bearer token. Before each request it reloads the credential store and requires an 'xai' credential of type 'oauth'. If none exists or the type differs, it throws ProviderAuthRequiredError('Not logged in to xAI.').","triggerScenarios":"Any xAI model request routed through the OAuth fetch wrapper when the credential store has no 'xai' entry, or the entry's type is not 'oauth' (e.g. api-key credential or null after reload).","commonSituations":"User never completed xAI OAuth login; credentials cleared or logged out; an API-key credential stored under 'xai' so the type check fails; fresh/empty credential store in CI or tests; custom authStorage (opts.authStorage) that was never populated.","solutions":["Run the xAI OAuth login flow to store the 'xai' oauth credential.","Verify the credentials store contains an 'xai' entry with type 'oauth'.","If using API-key auth instead, use an api-key-based fetch/provider rather than buildXAIOAuthFetch.","Check the opts.authStorage you pass actually contains the xai credential."],"exampleFix":"// before\nconst fetchWithOAuth = buildXAIOAuthFetch(); // throws if never logged in\n// after\nif (!credentialStore.get('xai') || credentialStore.get('xai').type !== 'oauth') {\n  await xaiLogin(); // OAuth flow\n}\nconst fetchWithOAuth = buildXAIOAuthFetch({ authStorage: credentialStore });","handlingStrategy":"validation","validationCode":"const cred = storage.get('xai');\nif (!cred || cred.type !== 'oauth') {\n  throw new Error('xAI login required; run the xAI OAuth flow first');\n}","typeGuard":"function isXAIOAuthCred(c: unknown): c is { type: 'oauth' } {\n  return !!c && typeof c === 'object' && (c as any).type === 'oauth';\n}","tryCatchPattern":"try {\n  return await fetchWithOAuth(url, init);\n} catch (e) {\n  if (e instanceof ProviderAuthRequiredError && /Not logged in/.test(e.message)) {\n    await xaiLogin();\n    return await fetchWithOAuth(url, init);\n  }\n  throw e;\n}","preventionTips":["Check xAI login state before constructing the provider.","Keep one shared AuthStorage instance across login and request paths.","Avoid mixing api-key and oauth credentials under the same provider id."],"tags":["auth","oauth","xai","login-required"],"backgroundTag":"provider-not-authenticated","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}