{"record":{"id":"4cbad5d28bb56ff7","repo":"mastra-ai/mastra","slug":"failed-to-refresh-the-openai-codex-token","errorCode":null,"errorMessage":"Failed to refresh the OpenAI Codex token.","messagePattern":"Failed to refresh the OpenAI Codex token\\.","errorType":"exception","errorClass":"ProviderAuthRequiredError","httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/providers/openai-codex.ts","lineNumber":142,"sourceCode":" * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand\n * fetch (`buildCodexStagehandFetch`).\n */\nasync function getCodexBearer(\n  authStorage?: CredentialStore,\n): Promise<{ accessToken: string; accountId: string | undefined }> {\n  const storage = authStorage ?? getAuthStorage();\n  storage.reload();\n\n  const cred = storage.get('openai-codex');\n  if (!cred || cred.type !== 'oauth') {\n    throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n  }\n\n  let accessToken = cred.access;\n  if (Date.now() >= cred.expires) {\n    const refreshedToken = await storage.getApiKey('openai-codex');\n    if (!refreshedToken) {\n      throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n    }\n    accessToken = refreshedToken;\n    storage.reload();\n  }\n\n  return { accessToken, accountId: (cred as any).accountId as string | undefined };\n}\n\n/**\n * Build a fetch function that handles OpenAI Codex OAuth.\n * Preserves non-authorization headers from init.\n * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions\n * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the\n * SDK already targets the correct URL.\n */\nexport function buildOpenAICodexOAuthFetch(\n  opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/providers/openai-codex.ts#L124-L160","documentation":"getCodexBearer checks the stored access token's expiry (Date.now() >= cred.expires) and, when expired, calls storage.getApiKey('openai-codex') to perform a refresh. If the refresh yields no token, it throws ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.'), since a valid bearer cannot be produced for the request.","triggerScenarios":"A request through the Codex OAuth fetch when the stored access token is expired AND storage.getApiKey('openai-codex') returns null/undefined — the refresh-token exchange fails or no refresh token is stored.","commonSituations":"Refresh token revoked or expired (long offline period, re-auth elsewhere invalidating the session); network failure reaching the OpenAI token endpoint; missing refresh-token field in the stored credential; clock skew.","solutions":["Re-run the OpenAI Codex OAuth login to get a fresh access/refresh token pair.","Verify network connectivity to OpenAI's token endpoint (proxy/firewall).","Check that the stored credential includes a refresh token field.","Catch ProviderAuthRequiredError and trigger interactive re-login automatically."],"exampleFix":"// before\nconst { accessToken } = await getCodexBearer(storage); // throws when refresh fails\n// after\nlet bearer;\ntry {\n  bearer = await getCodexBearer(storage);\n} catch (e) {\n  if (e instanceof ProviderAuthRequiredError) await codexLogin();\n  bearer = await getCodexBearer(storage);\n}","handlingStrategy":"retry","validationCode":"const cred = storage.get('openai-codex');\nif (cred?.type === 'oauth' && Date.now() >= cred.expires) {\n  const refreshed = await storage.getApiKey('openai-codex');\n  if (!refreshed) console.warn('Codex refresh failed; re-login required');\n}","typeGuard":"null","tryCatchPattern":"try {\n  return await codexFetch(url, init);\n} catch (e) {\n  if (e instanceof ProviderAuthRequiredError && /refresh/.test(e.message)) {\n    await codexLogin(); // refresh token is dead; full re-auth\n    return await codexFetch(url, init);\n  }\n  throw e;\n}","preventionTips":["Refresh tokens before expiry in long-running processes.","Monitor network reachability to OpenAI's token endpoint.","Treat refresh failure as requiring full re-authentication, not just retry."],"tags":["auth","oauth","openai-codex","token-refresh"],"backgroundTag":"oauth-token-refresh-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}