{"record":{"id":"c4e927586182a4a3","repo":"mastra-ai/mastra","slug":"failed-to-refresh-the-kimi-for-coding-token","errorCode":null,"errorMessage":"Failed to refresh the Kimi For Coding token.","messagePattern":"Failed to refresh the Kimi For Coding token\\.","errorType":"exception","errorClass":"ProviderAuthRequiredError","httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/providers/kimi-coding.ts","lineNumber":39,"sourceCode":"function getAuthStorage(): AuthStorage {\n  if (!authStorageInstance) authStorageInstance = new AuthStorage();\n  return authStorageInstance;\n}\n\nexport function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {\n  return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n    const store = options.credentialStore ?? getAuthStorage();\n    store.reload();\n    const credential = store.get(PROVIDER_ID);\n    if (!credential || credential.type !== 'oauth') {\n      throw new ProviderAuthRequiredError('Not logged in to Kimi For Coding.');\n    }\n    if (!isKimiCodingDeviceId(credential.deviceId)) {\n      throw new ProviderAuthRequiredError('Kimi For Coding credentials are invalid. Please reconnect the account.');\n    }\n    const deviceHeaders = getKimiCodingDeviceHeaders(credential.deviceId);\n    const token = await store.getApiKey(PROVIDER_ID);\n    if (!token) throw new ProviderAuthRequiredError('Failed to refresh the Kimi For Coding token.');\n\n    const headers = new Headers(input instanceof Request ? input.headers : undefined);\n    if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n    for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);\n    headers.delete('authorization');\n    headers.delete('x-api-key');\n    headers.set('Authorization', `Bearer ${token}`);\n    return fetch(input, { ...init, headers });\n  }) as typeof fetch;\n}\n\nexport function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {\n  return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n    const headers = new Headers(input instanceof Request ? input.headers : undefined);\n    if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n    headers.delete('authorization');\n    headers.delete('x-api-key');\n    headers.set('Authorization', `Bearer ${apiKey}`);","sourceCodeStart":21,"sourceCodeEnd":57,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/providers/kimi-coding.ts#L21-L57","documentation":"Once the credential and deviceId pass validation, buildKimiCodingOAuthFetch calls store.getApiKey('kimi-for-coding') to obtain (refreshing if needed) a current bearer token. If that returns no token, it throws ProviderAuthRequiredError('Failed to refresh the Kimi For Coding token.'), because requests cannot be authorized.","triggerScenarios":"A request through the Kimi For Coding OAuth fetch where the stored oauth credential is structurally valid but storage.getApiKey(PROVIDER_ID) returns null/undefined — the refresh-token exchange failed or no token material is stored.","commonSituations":"Expired/revoked refresh token (revoked server-side, password change, long idle period); network failure during refresh causing getApiKey to return nothing; clock skew making tokens look expired; credentials file missing the refresh-token field.","solutions":["Re-run the Kimi For Coding OAuth login to obtain fresh access and refresh tokens.","Check network/proxy connectivity to the Kimi token endpoint, since refresh requires a live call.","Verify the stored credential contains a refresh token, not just an expired access token.","Check system clock accuracy if tokens appear prematurely expired."],"exampleFix":"// before\nconst fetchWithAuth = buildKimiCodingOAuthFetch(); // refresh fails, throws\n// after\ntry {\n  return await fetchWithAuth(input, init);\n} catch (e) {\n  if (e instanceof ProviderAuthRequiredError) await kimiForCodingLogin(); // re-auth then retry\n  throw e;\n}","handlingStrategy":"retry","validationCode":"const token = await store.getApiKey('kimi-for-coding');\nif (!token) console.warn('Kimi token unavailable; re-login needed before requests');","typeGuard":"null","tryCatchPattern":"try {\n  return await fetchWithAuth(input, init);\n} catch (e) {\n  if (e instanceof ProviderAuthRequiredError && /refresh/.test(e.message)) {\n    await kimiForCodingLogin(); // obtain fresh tokens, then retry once\n    return await fetchWithAuth(input, init);\n  }\n  throw e;\n}","preventionTips":["Refresh tokens periodically during long sessions instead of only on-demand.","Ensure reliable network access to the Kimi token endpoint.","Keep system clocks synchronized (NTP) to avoid premature expiry."],"tags":["auth","oauth","kimi","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"}