# TypeScript SDK Reference

This document provides comprehensive reference documentation for the
`@lilith/sdk-ts` TypeScript SDK.

## Overview

The Lilith TypeScript SDK provides a comprehensive client library for
interacting with the Lilith AI Wisdom Platform. It supports browsers, Node.js
18+, and edge runtime environments.

**Package**: `@lilith/sdk-ts` **Version**: 1.0.0 **Module Type**: ESM

## Installation

```bash
# npm
npm install @lilith/sdk-ts

# yarn
yarn add @lilith/sdk-ts

# pnpm
pnpm add @lilith/sdk-ts
```

## Quick Start

```typescript
import { APIClient, SeamlessAuthClient } from '@lilith/sdk-ts';

// Initialize API client
const api = new APIClient({
  baseUrl: 'https://api.lilith.ai',
  token: 'your-jwt-token',
});

// Or use authentication client
const auth = new SeamlessAuthClient({
  baseUrl: 'https://api.lilith.ai',
  platform: 'web',
});

await auth.signIn({ email: 'user@example.com', password: 'password' });
```

---

## APIClient Class

The main client class for interacting with Lilith platform APIs.

### Constructor

```typescript
new APIClient(options: APIClientOptions)
```

| Parameter           | Type           | Required | Description                 |
| ------------------- | -------------- | -------- | --------------------------- |
| `options.baseUrl`   | `string`       | Yes      | Base URL of the Lilith API  |
| `options.token`     | `string`       | No       | JWT authentication token    |
| `options.fetchImpl` | `typeof fetch` | No       | Custom fetch implementation |

**Example**:

```typescript
const api = new APIClient({
  baseUrl: 'https://api.lilith.ai',
  token: 'eyJhbGciOiJIUzI1NiIs...',
});
```

---

### Chat Methods

#### `chat(request)`

Send a non-streaming chat message to an AI persona.

```typescript
async chat(request: ChatRequest): Promise<ChatResponse>
```

**Parameters**:

| Field             | Type                         | Required | Description              |
| ----------------- | ---------------------------- | -------- | ------------------------ |
| `conversation_id` | `string`                     | No       | Existing conversation ID |
| `persona`         | `string`                     | Yes      | AI persona identifier    |
| `input.text`      | `string`                     | No       | Text message content     |
| `input.audio`     | `string`                     | No       | Base64-encoded audio     |
| `mode`            | `'text' \| 'voice'`          | Yes      | Interaction mode         |
| `options.cite`    | `boolean`                    | No       | Include citations        |
| `options.depth`   | `'practical' \| 'scholarly'` | No       | Response depth           |
| `options.stream`  | `boolean`                    | No       | Enable streaming         |

**Returns**: `ChatResponse`

| Field             | Type          | Description               |
| ----------------- | ------------- | ------------------------- |
| `message_id`      | `string`      | Unique message identifier |
| `conversation_id` | `string`      | Conversation identifier   |
| `text`            | `string`      | Response text content     |
| `citations`       | `Citation[]`  | Source citations          |
| `audio_url`       | `string`      | Audio response URL        |
| `metrics`         | `ChatMetrics` | Performance metrics       |

**Example**:

```typescript
const response = await api.chat({
  persona: 'zen_master',
  input: { text: 'How do I find inner peace?' },
  mode: 'text',
  options: { cite: true, depth: 'practical' },
});

console.log(response.text);
console.log(response.citations);
```

---

#### `streamChat(request)`

Send a streaming chat message with real-time response tokens.

```typescript
async *streamChat(request: ChatRequest): AsyncGenerator<ChatEvent>
```

**Parameters**: Same as `chat()` with `options.stream: true`

**Yields**: `ChatEvent`

| Event Type  | Data                  | Description               |
| ----------- | --------------------- | ------------------------- |
| `token`     | `{ text: string }`    | Individual response token |
| `citations` | `Citation[]`          | Citation data             |
| `audio`     | `{ url: string }`     | Audio metadata            |
| `done`      | `null`                | Stream completion         |
| `error`     | `{ message: string }` | Error information         |

**Example**:

```typescript
const stream = api.streamChat({
  persona: 'stoic_mentor',
  input: { text: 'Teach me about resilience' },
  mode: 'text',
  options: { stream: true },
});

for await (const event of stream) {
  switch (event.event) {
    case 'token':
      process.stdout.write(event.data?.text ?? '');
      break;
    case 'citations':
      console.log('Sources:', event.data);
      break;
    case 'done':
      console.log('\nComplete');
      break;
    case 'error':
      console.error('Error:', event.data);
      break;
  }
}
```

---

### Conversation Methods

#### `listConversations(cursor?, limit?)`

List user's conversations with pagination.

```typescript
async listConversations(cursor?: string, limit?: number): Promise<ConversationListResponse>
```

| Parameter | Type     | Default | Description       |
| --------- | -------- | ------- | ----------------- |
| `cursor`  | `string` | -       | Pagination cursor |
| `limit`   | `number` | 20      | Items per page    |

**Returns**: `ConversationListResponse`

| Field           | Type                    | Description       |
| --------------- | ----------------------- | ----------------- |
| `conversations` | `ConversationSummary[]` | Conversation list |
| `total`         | `number`                | Total count       |
| `nextCursor`    | `string`                | Next page cursor  |

---

#### `getConversation(conversationId)`

Get full conversation with messages.

```typescript
async getConversation(conversationId: string): Promise<Conversation>
```

**Returns**: `Conversation` with messages array.

---

#### `deleteConversation(conversationId)`

Delete a conversation.

```typescript
async deleteConversation(conversationId: string): Promise<void>
```

---

#### `resetConversation(conversationId)`

Reset conversation context while preserving history.

```typescript
async resetConversation(conversationId: string): Promise<void>
```

---

### Content Generation Methods

#### `generateLecture(request)`

Generate an AI-powered educational lecture.

```typescript
async generateLecture(request: LectureRequest): Promise<LectureResponse>
```

**Parameters**:

| Field               | Type       | Required | Description          |
| ------------------- | ---------- | -------- | -------------------- |
| `topic`             | `string`   | Yes      | Lecture topic        |
| `duration_min`      | `number`   | Yes      | Duration in minutes  |
| `tradition`         | `string[]` | No       | Spiritual traditions |
| `lang`              | `string`   | No       | Language code        |
| `voice`             | `string`   | No       | TTS voice ID         |
| `outline_level`     | `string`   | No       | Detail level         |
| `include_citations` | `boolean`  | No       | Include sources      |

---

#### `ttsSynthesize(request)`

Convert text to speech.

```typescript
async ttsSynthesize(request: TTSRequest): Promise<TTSResponse>
```

**Parameters**:

| Field    | Type     | Required | Description                   |
| -------- | -------- | -------- | ----------------------------- |
| `text`   | `string` | Yes      | Text to synthesize            |
| `voice`  | `string` | Yes      | Voice ID                      |
| `format` | `string` | No       | Audio format (mp3, opus, wav) |
| `speed`  | `number` | No       | Playback speed (0.5-2.0)      |
| `pitch`  | `number` | No       | Voice pitch (0.5-2.0)         |

---

#### `ingest(request)`

Ingest content into the knowledge base.

```typescript
async ingest(request: IngestRequest): Promise<IngestResponse>
```

---

### Agent Methods

#### `createAgent(request)`

Create a new AI agent.

```typescript
async createAgent(request: AgentCreateRequest): Promise<Agent>
```

**Parameters**:

| Field           | Type                                       | Required | Description           |
| --------------- | ------------------------------------------ | -------- | --------------------- |
| `name`          | `string`                                   | Yes      | Agent name            |
| `agent_type`    | `string`                                   | Yes      | Agent type identifier |
| `description`   | `string`                                   | No       | Agent description     |
| `capabilities`  | `string[]`                                 | No       | Agent capabilities    |
| `model`         | `string`                                   | No       | LLM model identifier  |
| `system_prompt` | `string`                                   | No       | System prompt         |
| `tools`         | `string[]`                                 | No       | Available tools       |
| `autonomyLevel` | `'autonomous' \| 'supervised' \| 'manual'` | No       | Autonomy level        |

**Example**:

```typescript
const agent = await api.createAgent({
  name: 'Meditation Guide',
  agent_type: 'wellness',
  description: 'Guides users through meditation practices',
  capabilities: ['guided_meditation', 'breathing_exercises'],
  autonomyLevel: 'supervised',
});
```

---

#### `listAgents(filters?)`

List agents with optional filters.

```typescript
async listAgents(filters?: AgentListFilters): Promise<AgentListResponse>
```

| Filter    | Type      | Description        |
| --------- | --------- | ------------------ |
| `type`    | `string`  | Agent type         |
| `status`  | `string`  | Agent status       |
| `enabled` | `boolean` | Enabled state      |
| `persona` | `string`  | Associated persona |

---

#### `getAgent(agentId)`

Get agent by ID.

```typescript
async getAgent(agentId: string): Promise<Agent>
```

---

#### `createAgentSession(request)`

Create an interactive agent session.

```typescript
async createAgentSession(request: AgentSessionCreateRequest): Promise<AgentSession>
```

**Parameters**:

| Field      | Type                      | Required | Description     |
| ---------- | ------------------------- | -------- | --------------- |
| `agent_id` | `string`                  | Yes      | Agent to use    |
| `user_id`  | `string`                  | Yes      | User identifier |
| `context`  | `Record<string, unknown>` | No       | Session context |

---

#### `getAgentSession(sessionId)`

Get session details.

```typescript
async getAgentSession(sessionId: string): Promise<AgentSession>
```

---

### Agent Memory Methods

#### `getAgentMemory(userId, memoryType?, includeStats?)`

Retrieve agent memory for a user.

```typescript
async getAgentMemory(
  userId: string,
  memoryType?: string,
  includeStats?: boolean
): Promise<AgentMemoryResponse>
```

---

#### `storeAgentMemory(userId, request)`

Store a memory entry.

```typescript
async storeAgentMemory(
  userId: string,
  request: AgentMemoryStoreRequest
): Promise<AgentMemoryStoreResponse>
```

---

#### `resetAgentMemory(userId, memoryType?)`

Clear agent memory.

```typescript
async resetAgentMemory(
  userId: string,
  memoryType?: string
): Promise<AgentMemoryResetResponse>
```

---

### Workflow Methods

#### `createWorkflow(request)`

Create a notification workflow.

```typescript
async createWorkflow(request: WorkflowCreateRequest): Promise<Workflow>
```

**Parameters**:

| Field               | Type                | Required | Description        |
| ------------------- | ------------------- | -------- | ------------------ |
| `agent_id`          | `string`            | Yes      | Assigned agent     |
| `user_id`           | `string`            | Yes      | Target user        |
| `notification_type` | `string`            | Yes      | Notification type  |
| `priority`          | `number`            | No       | Priority level     |
| `triggers`          | `WorkflowTrigger[]` | No       | Trigger conditions |

---

#### `listWorkflows(filters?)`

List workflows.

```typescript
async listWorkflows(filters?: WorkflowListFilters): Promise<WorkflowListResponse>
```

---

#### `executeWorkflow(workflowId, request?)`

Execute a workflow.

```typescript
async executeWorkflow(
  workflowId: string,
  request?: WorkflowExecuteRequest
): Promise<WorkflowExecutionResult>
```

---

### AI Agent Methods

#### `listAIAgents()`

List domain-specific AI agents.

```typescript
async listAIAgents(): Promise<AIAgentListResponse>
```

---

#### `getAIAgent(agentId)`

Get AI agent details.

```typescript
async getAIAgent(agentId: string): Promise<{ agent: DomainAgent }>
```

---

#### `getAIAgentsByRole(role)`

Find agents by role.

```typescript
async getAIAgentsByRole(role: string): Promise<AIAgentQueryResponse>
```

---

#### `getAIAgentsByCapability(capability)`

Find agents by capability.

```typescript
async getAIAgentsByCapability(capability: string): Promise<AIAgentQueryResponse>
```

---

#### `getAIAgentsByTool(toolName)`

Find agents by tool.

```typescript
async getAIAgentsByTool(toolName: string): Promise<AIAgentQueryResponse>
```

---

#### `createAIAgentTask(agentId, request)`

Create a task for an AI agent.

```typescript
async createAIAgentTask(
  agentId: string,
  request: AIAgentTaskRequest
): Promise<AIAgentTaskResponse>
```

---

### Admin Methods

> **Note**: Admin methods require elevated permissions.

#### User Management

```typescript
// Update user roles
async adminUpdateUserRoles(userId: string, roles: string[]): Promise<AdminUserRolesResponse>

// Get user audit logs
async adminGetUserAuditLogs(userId: string): Promise<AdminUserAuditLogsResponse>
```

#### Backup & Restore

```typescript
// Create backup
async createBackup(request?: BackupRequest): Promise<BackupResponse>

// List backups
async listBackups(): Promise<BackupListResponse>

// Get backup status
async getBackupStatus(backupId: string): Promise<BackupResponse>

// Delete backup
async deleteBackup(backupId: string): Promise<void>

// Create restore operation
async createRestore(request: RestoreRequest): Promise<RestoreResponse>

// Get restore status
async getRestoreStatus(restoreId: string): Promise<RestoreResponse>
```

#### System Management

```typescript
// Get system health
async getSystemHealth(): Promise<SystemHealthResponse>

// Get system configuration
async getSystemConfig(): Promise<SystemConfigResponse>

// Set maintenance mode
async setMaintenanceMode(request: MaintenanceRequest): Promise<MaintenanceResponse>

// Get maintenance status
async getMaintenanceStatus(): Promise<MaintenanceResponse>
```

#### Autoscaling & GPU

```typescript
// Get autoscaling status
async getAutoscalingStatus(): Promise<AutoscalingStatusResponse>

// Execute scaling action
async executeScalingAction(request: ScalingActionRequest): Promise<ScalingActionResponse>

// Get GPU metrics
async getGPUMetrics(): Promise<GPUMetricsResponse>
```

---

## SeamlessAuthClient Class

Handles authentication across multiple platforms with seamless state
synchronization.

### Constructor

```typescript
new SeamlessAuthClient(options: SeamlessAuthClientOptions)
```

| Parameter             | Type                      | Required | Description         |
| --------------------- | ------------------------- | -------- | ------------------- |
| `options.baseUrl`     | `string`                  | Yes      | API base URL        |
| `options.coordinator` | `SeamlessAuthCoordinator` | No       | State coordinator   |
| `options.fetchImpl`   | `typeof fetch`            | No       | Custom fetch        |
| `options.platform`    | `SeamlessAuthPlatform`    | No       | Platform identifier |

**Platforms**: `'web' | 'mobile' | 'desktop' | 'sdk'`

---

### Authentication Methods

#### `signIn(credentials, options?)`

Authenticate a user.

```typescript
async signIn(
  credentials: SignInCredentials,
  options?: AuthOptions
): Promise<SeamlessAuthState>
```

**Credentials**:

| Field      | Type     | Required | Description                  |
| ---------- | -------- | -------- | ---------------------------- |
| `email`    | `string` | Yes      | User email                   |
| `password` | `string` | No       | Password (for password auth) |
| `mfaCode`  | `string` | No       | MFA verification code        |

**Example**:

```typescript
const state = await auth.signIn({
  email: 'user@example.com',
  password: 'securePassword123',
});

console.log('Logged in as:', state.user?.email);
```

---

#### `register(credentials, options?)`

Register a new user.

```typescript
async register(
  credentials: RegisterCredentials,
  options?: AuthOptions
): Promise<SeamlessAuthState>
```

**Credentials**:

| Field           | Type      | Required | Description      |
| --------------- | --------- | -------- | ---------------- |
| `email`         | `string`  | Yes      | User email       |
| `password`      | `string`  | Yes      | Password         |
| `displayName`   | `string`  | No       | Display name     |
| `acceptedTerms` | `boolean` | No       | Terms acceptance |

---

#### `signOut()`

Sign out and clear session.

```typescript
async signOut(): Promise<void>
```

---

#### `refresh()`

Refresh the authentication token.

```typescript
async refresh(): Promise<SeamlessAuthState>
```

---

#### `validate()`

Validate the current token.

```typescript
async validate(): Promise<TokenValidationResult>
```

**Returns**:

| Field       | Type       | Description          |
| ----------- | ---------- | -------------------- |
| `valid`     | `boolean`  | Token validity       |
| `userId`    | `string`   | User ID              |
| `expiresAt` | `string`   | Expiration timestamp |
| `scopes`    | `string[]` | Permission scopes    |

---

### Profile Methods

#### `getProfile()`

Get user profile.

```typescript
async getProfile(): Promise<UserProfile>
```

---

#### `updateProfile(updates)`

Update user profile.

```typescript
async updateProfile(updates: UpdateProfileRequest): Promise<UserProfile>
```

---

#### `deleteAccount()`

Delete user account.

```typescript
async deleteAccount(): Promise<void>
```

---

### Session Methods

#### `listSessions()`

List active sessions.

```typescript
async listSessions(): Promise<SessionInfo[]>
```

---

#### `revokeSession(sessionId)`

Revoke a session.

```typescript
async revokeSession(sessionId: string): Promise<void>
```

---

### Password Methods

#### `changePassword(request)`

Change password.

```typescript
async changePassword(request: PasswordChangeRequest): Promise<void>
```

---

#### `requestPasswordReset(email)`

Request password reset.

```typescript
async requestPasswordReset(email: string): Promise<void>
```

---

#### `confirmPasswordReset(token, newPassword)`

Confirm password reset.

```typescript
async confirmPasswordReset(token: string, newPassword: string): Promise<void>
```

---

### OAuth Methods

#### `getOAuthProviders()`

Get available OAuth providers.

```typescript
async getOAuthProviders(): Promise<OAuthProvider[]>
```

---

#### `getOAuthAuthorizationUrl(provider, redirectUri?)`

Get OAuth authorization URL.

```typescript
async getOAuthAuthorizationUrl(
  provider: OAuthProviderType,
  redirectUri?: string
): Promise<OAuthAuthorizationUrl>
```

**Providers**: `'google' | 'github' | 'apple' | 'facebook'`

---

#### `completeOAuthSignIn(provider, code, state?)`

Complete OAuth flow.

```typescript
async completeOAuthSignIn(
  provider: OAuthProviderType,
  code: string,
  state?: string
): Promise<OAuthCallbackResult>
```

---

### WebAuthn Methods

#### `registerWebAuthnCredential(request)`

Register a WebAuthn credential (passkey).

```typescript
async registerWebAuthnCredential(
  request: WebAuthnRegisterRequest
): Promise<WebAuthnCredential>
```

---

#### `authenticateWithWebAuthn(request)`

Authenticate with WebAuthn.

```typescript
async authenticateWithWebAuthn(
  request: WebAuthnAuthenticateRequest
): Promise<SeamlessAuthState>
```

---

### Two-Factor Authentication

#### `enable2FA()`

Enable 2FA and get setup data.

```typescript
async enable2FA(): Promise<TwoFactorEnableResponse>
```

**Returns**:

| Field          | Type       | Description      |
| -------------- | ---------- | ---------------- |
| `secret`       | `string`   | TOTP secret      |
| `qr_code`      | `string`   | QR code data URL |
| `backup_codes` | `string[]` | Recovery codes   |

---

#### `verify2FA(code)`

Verify 2FA setup.

```typescript
async verify2FA(code: string): Promise<TwoFactorVerifyResponse>
```

---

#### `disable2FA(password)`

Disable 2FA.

```typescript
async disable2FA(password: string): Promise<TwoFactorDisableResponse>
```

---

#### `toggleMFA(enable?)`

Toggle MFA status.

```typescript
async toggleMFA(enable?: boolean): Promise<MFAToggleResponse>
```

---

### State Management

#### `getState()`

Get current authentication state.

```typescript
getState(): SeamlessAuthState
```

**Returns**:

| Field           | Type                  | Description           |
| --------------- | --------------------- | --------------------- |
| `user`          | `AuthUser \| null`    | Current user          |
| `session`       | `AuthSession \| null` | Current session       |
| `token`         | `string \| null`      | JWT token             |
| `lastOrigin`    | `string \| null`      | Last update origin    |
| `lastUpdatedAt` | `string \| null`      | Last update timestamp |

---

#### `onStateChange(handler)`

Subscribe to state changes.

```typescript
onStateChange(handler: (state: SeamlessAuthState) => void): () => void
```

**Example**:

```typescript
const unsubscribe = auth.onStateChange((state) => {
  if (state.user) {
    console.log('User logged in:', state.user.email);
  } else {
    console.log('User logged out');
  }
});

// Later: cleanup
unsubscribe();
```

---

## Type Definitions

### Chat Types

```typescript
interface ChatRequest {
  conversation_id?: string;
  persona: string;
  input: {
    text?: string | null;
    audio?: string | null; // base64
  };
  mode: 'text' | 'voice';
  options?: {
    cite?: boolean;
    depth?: 'practical' | 'scholarly';
    stream?: boolean;
  };
}

interface ChatResponse {
  message_id: string;
  conversation_id: string;
  text?: string;
  citations?: Citation[];
  audio_url?: string | null;
  metrics?: {
    tokens_in?: number;
    tokens_out?: number;
    latency_ms?: number;
    model_inference_ms?: number;
  };
}

interface Citation {
  source_uri: string;
  span?: { start: number; end: number };
  license?: string;
  confidence?: number;
}
```

### Agent Types

```typescript
interface Agent {
  id: string;
  name: string;
  type: string;
  description?: string;
  capabilities?: string[];
  role?: string;
  status?: 'active' | 'inactive' | 'training' | 'error' | 'maintenance';
  model?: string;
  system_prompt?: string;
  tools?: string[];
  autonomyLevel?: string;
  createdAt?: string;
  updatedAt?: string;
  config?: Record<string, unknown>;
  statistics?: {
    tasksCompleted?: number;
    avgResponseTime?: number;
    successRate?: number;
  };
}

interface AgentSession {
  session_id: string;
  user_id: string;
  agent_id: string;
  status: 'active' | 'paused' | 'completed' | 'error';
  context?: Record<string, unknown>;
  messages?: Array<{
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp: string;
  }>;
  createdAt: string;
  lastActivityAt: string;
}
```

### Authentication Types

```typescript
interface UserProfile {
  id: string;
  email: string;
  username?: string;
  fullName?: string;
  avatarUrl?: string;
  roles: string[];
  mfaEnabled: boolean;
  isVerified: boolean;
  createdAt: string;
  updatedAt: string;
  preferences?: Record<string, unknown>;
}

interface SessionInfo {
  sessionId: string;
  deviceId: string;
  platform: string;
  lastActivityAt: string;
  createdAt: string;
  isCurrent: boolean;
}
```

---

## Error Handling

The SDK throws standard JavaScript `Error` objects with descriptive messages:

```typescript
try {
  const response = await api.chat({
    persona: 'zen_master',
    input: { text: 'Hello' },
    mode: 'text',
  });
} catch (error) {
  if (error instanceof Error) {
    // Parse HTTP status from message format: "401 Unauthorized: ..."
    const statusMatch = error.message.match(/^(\d{3})/);
    const status = statusMatch ? parseInt(statusMatch[1]) : 0;

    switch (status) {
      case 401:
        console.log('Authentication required');
        break;
      case 429:
        console.log('Rate limit exceeded');
        break;
      case 500:
        console.log('Server error');
        break;
      default:
        console.log('Error:', error.message);
    }
  }
}
```

---

## Platform Support

### Browser Compatibility

| Browser | Minimum Version |
| ------- | --------------- |
| Chrome  | 90+             |
| Firefox | 88+             |
| Safari  | 14+             |
| Edge    | 90+             |

### Node.js

- Node.js 18.0+ (native fetch required)
- Compatible with CommonJS and ES modules

### Edge Runtimes

- Cloudflare Workers
- Vercel Edge Functions
- Deno Deploy

---

## Environment Variables

```bash
# API Configuration
LILITH_API_BASE_URL=https://api.lilith.ai
LILITH_API_TIMEOUT=30000

# Debug Mode
LILITH_DEBUG=true
```

---

## Best Practices

### Token Management

```typescript
// Store tokens securely
const api = new APIClient({
  baseUrl: process.env.LILITH_API_BASE_URL!,
  token: secureTokenStorage.get(),
});

// Refresh tokens before expiration
auth.onStateChange((state) => {
  if (state.token) {
    secureTokenStorage.set(state.token);
  }
});
```

### Streaming Best Practices

```typescript
// Handle streaming with proper cleanup
const controller = new AbortController();

try {
  const stream = api.streamChat({
    persona: 'guide',
    input: { text: 'Long meditation' },
    mode: 'text',
    options: { stream: true },
  });

  for await (const event of stream) {
    if (controller.signal.aborted) break;
    // Process event
  }
} catch (error) {
  if (!controller.signal.aborted) {
    console.error('Stream error:', error);
  }
}
```

### Error Recovery

```typescript
// Implement retry logic
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
  let lastError: Error;

  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error as Error;
      if (error.message.includes('429')) {
        await new Promise((r) => setTimeout(r, Math.pow(2, i) * 1000));
      } else {
        throw error;
      }
    }
  }

  throw lastError!;
}
```

---

## Related Documentation

- [Authentication Guide](./authentication.md) - Authentication flows and
  security
- [API Versioning](./api-versioning.md) - Version management and migration
- [Error Codes](./error-codes.md) - Complete error reference
- [Partner API SDK](./partner-api-sdk.md) - Third-party integration SDK

---

## Support

- **GitHub Issues**: [Report bugs](https://github.com/lilith/platform/issues)
- **Documentation**: https://docs.lilith.ai
- **Email**: sdk-support@lilith.ai
