> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch16-model-providers-and-failover/16.2-authprofile-and-credential-management.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 16.2 Auth Profile and Credential Management

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~400,000 tokens, Output \~32,000 tokens (Chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

LLM API calls require authentication credentials. OpenClaw manages authentication information for all providers through the **Auth Profile** mechanism — including API Keys, OAuth Tokens, and special Copilot Tokens. Multiple Profiles can provide redundant credentials for the same provider, enabling automatic rotation and fault isolation.

## 16.2.1 Auth Profile Mechanism (`src/agents/auth-profiles.ts`)

The Auth Profile subsystem code is organized in the `src/agents/auth-profiles/` directory, aggregated and exported through `auth-profiles.ts`:

```
src/agents/auth-profiles/
    ├── constants.ts   ← Special Profile ID constants
    ├── display.ts     ← Profile display labels
    ├── doctor.ts      ← Diagnostic hints
    ├── oauth.ts       ← OAuth Token parsing
    ├── order.ts       ← Profile ordering
    ├── paths.ts       ← Storage paths
    ├── profiles.ts    ← Profile CRUD operations
    ├── repair.ts      ← Profile ID repair
    ├── store.ts       ← Persistent storage
    ├── types.ts       ← Type definitions
    └── usage.ts       ← Usage statistics and cooldown
```

### Storage Structure

Auth Profiles are stored in the `auth-profiles.json` file under the Agent directory. The `AuthProfileStore` type defines the storage structure:

```typescript
// src/agents/auth-profiles/types.ts (conceptual model)
export type AuthProfileStore = {
  profiles: Record<string, AuthProfileCredential>;
  usageStats?: Record<string, ProfileUsageStats>;
  profileOrder?: Record<string, string[]>;  // Provider → Profile ID list
};
```

Each Profile contains credentials and metadata:

```typescript
export type AuthProfileCredential =
  | ApiKeyCredential
  | OAuthCredential
  | TokenCredential;

export type ApiKeyCredential = {
  type: "api-key";
  provider: string;
  apiKey: string;
  label?: string;
};

export type OAuthCredential = {
  type: "oauth";
  provider: string;
  accessToken: string;
  refreshToken?: string;
  expiresAt?: number;
  label?: string;
};
```

## 16.2.2 OAuth Authentication Flow

OpenClaw supports OAuth authentication for multiple providers, allowing users to use their own subscription accounts (such as Claude Pro/Max, ChatGPT Plus) rather than direct API Keys.

The basic steps of the OAuth flow:

1. **Initiate Authorization** — User starts the OAuth flow via the `openclaw auth` command
2. **Browser Authorization** — System opens a browser, user logs in and authorizes on the provider's website
3. **Receive Callback** — Local HTTP server receives the callback and obtains the authorization code
4. **Token Exchange** — Exchange the code for access token and refresh token
5. **Store Profile** — Store the Token as an Auth Profile

On each LLM call, the `resolveApiKeyForProfile` function checks if the Token has expired and automatically refreshes it using the refresh token if necessary.

## 16.2.3 API Key Authentication

API Key is the simplest authentication method. Users set the API Key through configuration files or the `openclaw auth` command:

```yaml
# Configuration example (conceptual)
agents:
  defaults:
    model:
      primary: "anthropic/claude-sonnet-4-20250514"
```

API Keys can be obtained from multiple sources:

* `api-key` type Profiles in the Auth Profile Store
* Environment variables (such as `ANTHROPIC_API_KEY`)
* System Keychain (macOS)

The retrieval priority is: **Profile Store > Environment Variables > Keychain**.

## 16.2.4 Profile Rotation and Cooldown

When an Auth Profile fails due to rate limiting or other errors, the system doesn't immediately give up. Instead, it marks the Profile as **cooldown** state and attempts the next available Profile.

### Cooldown Check

```typescript
// src/agents/auth-profiles/usage.ts
export function isProfileInCooldown(store: AuthProfileStore, profileId: string): boolean {
  const stats = store.usageStats?.[profileId];
  if (!stats) return false;
  const unusableUntil = resolveProfileUnusableUntil(stats);
  return unusableUntil ? Date.now() < unusableUntil : false;
}
```

A Profile is in cooldown state when its `cooldownUntil` or `disabledUntil` timestamp is greater than the current time.

### Cooldown Duration Calculation

Cooldown duration uses an **exponential backoff** strategy:

```typescript
// src/agents/auth-profiles/usage.ts
export function calculateAuthProfileCooldownMs(errorCount: number): number {
  const normalized = Math.max(1, errorCount);
  return Math.min(
    60 * 60 * 1000,              // Upper limit: 1 hour
    60 * 1000 * 5 ** Math.min(normalized - 1, 3),
  );
}
```

| Consecutive Failures | Cooldown Duration        |
| -------------------- | ------------------------ |
| 1                    | 1 minute                 |
| 2                    | 5 minutes                |
| 3                    | 25 minutes               |
| 4+                   | 60 minutes (upper limit) |

> **Sidebar**: **Exponential backoff** is a classic strategy in distributed systems. When an operation fails, the wait time grows exponentially (rather than linearly) to avoid repeatedly sending requests when the problem hasn't been resolved (called the "thundering herd effect"). OpenClaw uses powers of 5 (5^0=1, 5^1=5, 5^2=25), which is more aggressive than the common powers of 2, because API rate limits typically require longer recovery times.

### Failure Marking

```typescript
// src/agents/auth-profiles/usage.ts (simplified)
export async function markAuthProfileFailure(params: {
  store: AuthProfileStore;
  profileId: string;
  reason: AuthProfileFailureReason;
  cfg?: OpenClawConfig;
  agentDir?: string;
}): Promise<void> {
  const stats = store.usageStats?.[profileId] ?? {};
  const errorCount = (stats.errorCount ?? 0) + 1;
  const cooldownMs = calculateAuthProfileCooldownMs(errorCount);

  store.usageStats[profileId] = {
    ...stats,
    errorCount,
    lastError: Date.now(),
    lastErrorReason: params.reason,
    cooldownUntil: Date.now() + cooldownMs,
  };
  // Persist to disk
  saveAuthProfileStore(store, params.agentDir);
}
```

### Success Reset

When a Profile is successfully used, the error counter is reset:

```typescript
// src/agents/auth-profiles/usage.ts
export async function markAuthProfileUsed(params: {
  store: AuthProfileStore;
  profileId: string;
  agentDir?: string;
}): Promise<void> {
  store.usageStats[profileId] = {
    lastUsed: Date.now(),
    errorCount: 0,           // Reset error count
    cooldownUntil: undefined, // Clear cooldown
    disabledUntil: undefined,
    disabledReason: undefined,
  };
}
```

This means a single successful use completely clears the Profile's "record" — even if it had failed consecutively multiple times before.

### Profile Ordering

The system determines the attempt order of Profiles through `resolveAuthProfileOrder`. It prioritizes the order specified in the configuration, followed by sorting by the most recent successful use time. Profiles in cooldown are not removed from the ordering (they may still be selected and then skipped), but are filtered out by `isProfileInCooldown` during actual rotation.

## 16.2.5 GitHub Copilot Token Authentication

GitHub Copilot uses a special authentication flow — it requires first exchanging a GitHub Personal Access Token (PAT) for a short-lived Copilot API Token:

```typescript
// src/agents/pi-embedded-runner/run.ts (simplified)
if (model.provider === "github-copilot") {
  const { resolveCopilotApiToken } = await import("../../providers/github-copilot-token.js");
  const copilotToken = await resolveCopilotApiToken({
    githubToken: apiKeyInfo.apiKey,  // PAT
  });
  authStorage.setRuntimeApiKey(model.provider, copilotToken.token);  // Short-lived Token
}
```

GitHub Copilot's authentication chain:

```
GitHub PAT (long-lived)
    │
    ├── POST https://api.github.com/copilot_internal/v2/token
    │
    ▼
Copilot API Token (short-lived, ~30 minutes)
    │
    ├── Call Copilot Chat API
    │
    ▼
LLM Response
```

The `resolveCopilotApiToken` function handles Token caching and automatic refresh, avoiding the need to fetch a new Token on every LLM call.

***

## Section Summary

1. **Auth Profile** is OpenClaw's unified credential management abstraction, supporting three types: API Key, OAuth Token, and special Token.
2. **OAuth authentication** allows users to use subscription accounts (Claude Pro/Max, ChatGPT Plus) rather than direct API Keys, with the system automatically handling Token refresh.
3. **Profile rotation** automatically switches to the next available Profile when credentials fail, and **exponential backoff cooldown** avoids repeatedly using known-failed credentials.
4. Cooldown duration increases from 1 minute to 60 minutes, and a single successful use completely resets the cooldown state.
5. **GitHub Copilot** uses a two-stage Token exchange mechanism, exchanging PAT for a short-lived API Token, handled by a dedicated function for caching and refresh.
