mastra-ai/mastra · error · ProviderAuthRequiredError

Failed to refresh the Kimi For Coding token.

Error message

Failed to refresh the Kimi For Coding token.

What it means

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.

Source

Thrown at mastracode/sdk/src/providers/kimi-coding.ts:39

function getAuthStorage(): AuthStorage {
  if (!authStorageInstance) authStorageInstance = new AuthStorage();
  return authStorageInstance;
}

export function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {
  return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {
    const store = options.credentialStore ?? getAuthStorage();
    store.reload();
    const credential = store.get(PROVIDER_ID);
    if (!credential || credential.type !== 'oauth') {
      throw new ProviderAuthRequiredError('Not logged in to Kimi For Coding.');
    }
    if (!isKimiCodingDeviceId(credential.deviceId)) {
      throw new ProviderAuthRequiredError('Kimi For Coding credentials are invalid. Please reconnect the account.');
    }
    const deviceHeaders = getKimiCodingDeviceHeaders(credential.deviceId);
    const token = await store.getApiKey(PROVIDER_ID);
    if (!token) throw new ProviderAuthRequiredError('Failed to refresh the Kimi For Coding token.');

    const headers = new Headers(input instanceof Request ? input.headers : undefined);
    if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
    for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);
    headers.delete('authorization');
    headers.delete('x-api-key');
    headers.set('Authorization', `Bearer ${token}`);
    return fetch(input, { ...init, headers });
  }) as typeof fetch;
}

export function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {
  return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {
    const headers = new Headers(input instanceof Request ? input.headers : undefined);
    if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
    headers.delete('authorization');
    headers.delete('x-api-key');
    headers.set('Authorization', `Bearer ${apiKey}`);

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Re-run the Kimi For Coding OAuth login to obtain fresh access and refresh tokens.
  2. Check network/proxy connectivity to the Kimi token endpoint, since refresh requires a live call.
  3. Verify the stored credential contains a refresh token, not just an expired access token.
  4. Check system clock accuracy if tokens appear prematurely expired.

Example fix

// before
const fetchWithAuth = buildKimiCodingOAuthFetch(); // refresh fails, throws
// after
try {
  return await fetchWithAuth(input, init);
} catch (e) {
  if (e instanceof ProviderAuthRequiredError) await kimiForCodingLogin(); // re-auth then retry
  throw e;
}
Defensive patterns

Strategy: retry

Validate before calling

const token = await store.getApiKey('kimi-for-coding');
if (!token) console.warn('Kimi token unavailable; re-login needed before requests');

Type guard

null

Try / catch

try {
  return await fetchWithAuth(input, init);
} catch (e) {
  if (e instanceof ProviderAuthRequiredError && /refresh/.test(e.message)) {
    await kimiForCodingLogin(); // obtain fresh tokens, then retry once
    return await fetchWithAuth(input, init);
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/c4e927586182a4a3. Report an issue: GitHub.