thedotmack/claude-mem · critical · Error

Invalid API key: check your API key configuration in ~/.clau

Error message

Invalid API key: check your API key configuration in ~/.claude-mem/settings.json or ~/.claude-mem/.env

What it means

Thrown by ClaudeProvider when the SDK's response text literally contains the substring 'Invalid API key'. The provider treats this in-band text as a hard auth failure because the SDK sometimes returns a 200 with an error body rather than a proper non-2xx. It points the user at the two key configuration locations.

Source

Thrown at src/services/worker/ClaudeProvider.ts:382

            });
          }

          const discoveryTokens = (session.cumulativeInputTokens + session.cumulativeOutputTokens) - tokensBeforeResponse;

          const originalTimestamp = session.earliestPendingTimestamp;

          if (responseSize > 0) {
            const truncatedResponse = responseSize > 100
              ? textContent.substring(0, 100) + '...'
              : textContent;
            logger.dataOut('SDK', `Response received (${responseSize} chars)`, {
              sessionId: session.sessionDbId,
              promptNumber: session.lastPromptNumber
            }, truncatedResponse);
          }

          if (typeof textContent === 'string' && textContent.includes('Invalid API key')) {
            throw new Error('Invalid API key: check your API key configuration in ~/.claude-mem/settings.json or ~/.claude-mem/.env');
          }

          await processAgentResponse(
            textContent,
            session,
            this.dbManager,
            this.sessionManager,
            worker,
            discoveryTokens,
            originalTimestamp,
            'SDK',
            cwdTracker.lastCwd,
            modelId,
            activeResponseContext.current
          );
        }

        if (message.type === 'result') {

View on GitHub (pinned to d768ba3643)

Solutions

  1. Check ~/.claude-mem/settings.json and ~/.claude-mem/.env for the API key and update it to a valid, active key.
  2. Confirm the key is not expired/revoked and has credit/permission for the configured model.
  3. Remove leading/trailing whitespace or quotes around the key value.
  4. Verify the env var name the provider reads (e.g. ANTHROPIC_API_KEY) is exported in the worker process.
  5. If behind a proxy, ensure the proxy forwards the Authorization header and isn't injecting its own error body.

Example fix

# before: ANTHROPIC_API_KEY=sk-ant-...EXPIRED...
# after:  ANTHROPIC_API_KEY=sk-ant-...VALID...  (in ~/.claude-mem/.env or settings.json)
Defensive patterns

Strategy: validation

Validate before calling

import { readFileSync, existsSync } from 'fs';
function resolveApiKey(env: NodeJS.ProcessEnv = process.env): string {
  const fromEnv = (env.ANTHROPIC_API_KEY ?? '').trim();
  if (fromEnv) return fromEnv;
  const envPath = process.env.HOME + '/.claude-mem/.env';
  if (existsSync(envPath)) {
    const kv = Object.fromEntries(readFileSync(envPath, 'utf-8').split('\n').filter(Boolean).map(l => l.split('=')));
    if (kv.ANTHROPIC_API_KEY) return kv.ANTHROPIC_API_KEY.trim();
  }
  throw new Error('ANTHROPIC_API_KEY missing; configure ~/.claude-mem/.env before starting the worker');
}

Try / catch

try { resolveApiKey(); /* before worker start */ }
catch (e) { logger.error('CONFIG', (e as Error).message); process.exit(1); }
// and around the SDK loop:
try { /* run sdk loop */ }
catch (e) {
  if (e instanceof Error && e.message.startsWith('Invalid API key')) {
    logger.error('AUTH', e.message); stopWorkerForOperatorIntervention(); return;
  }
  throw e;
}

Prevention

When it happens

Trigger: Inside the SDK message loop, after receiving assistant textContent: if typeof textContent === 'string' && textContent.includes('Invalid API key'), throw. The substring match is intentionally broad, so any response containing that phrase triggers it.

Common situations: ANTHROPIC_API_KEY (or the configured key) is missing, expired, revoked, copied with extra whitespace, or for the wrong workspace; the key has insufficient permissions/credits; or a proxy/gateway returns an 'Invalid API key' body. Common after rotating keys, in CI without the secret, or when a key from another provider is set.

Understand the failure class

Related errors


AI-assisted analysis of thedotmack/claude-mem@d768ba3643 (2026-08-12). Data as JSON: /api/errors/73bf8cc383e68b92. Report an issue: GitHub.