# Partner API SDK Reference

This document provides comprehensive reference documentation for the
`@lilith/partner-api-sdk` TypeScript SDK for third-party integrations.

## Overview

The Lilith Partner API SDK enables third-party developers to integrate Lilith's
AI wisdom capabilities into their applications. It provides access to chat,
content, and text-to-speech features through a simplified API interface.

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

## Installation

```bash
# npm
npm install @lilith/partner-api-sdk

# yarn
yarn add @lilith/partner-api-sdk

# pnpm
pnpm add @lilith/partner-api-sdk
```

## Quick Start

```typescript
import { LilithPartnerClient } from '@lilith/partner-api-sdk';

// Initialize client with API key
const client = new LilithPartnerClient({
  apiKey: 'lilith_live_your_api_key_here',
});

// Send a chat message
const response = await client.chat({
  message: 'What is mindfulness?',
  persona: 'zen_master',
});

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

---

## Partner Tiers

| Tier             | Rate Limit (RPM) | Rate Limit (Daily) | Features                            |
| ---------------- | ---------------- | ------------------ | ----------------------------------- |
| **Starter**      | 60               | 1,000              | Chat, Content access                |
| **Professional** | 300              | 10,000             | + TTS, Webhooks, Analytics          |
| **Enterprise**   | 1,000            | Unlimited          | + Custom personas, Priority support |

---

## LilithPartnerClient Class

The main client class for Partner API interactions.

### Constructor

```typescript
new LilithPartnerClient(config: LilithPartnerSDKConfig)
```

| Parameter        | Type     | Required | Default                                  | Description          |
| ---------------- | -------- | -------- | ---------------------------------------- | -------------------- |
| `config.apiKey`  | `string` | Yes      | -                                        | Partner API key      |
| `config.baseURL` | `string` | No       | `https://api.lilith.example.com/partner` | API base URL         |
| `config.timeout` | `number` | No       | `30000`                                  | Request timeout (ms) |

**Example**:

```typescript
const client = new LilithPartnerClient({
  apiKey: 'lilith_live_abc123',
  baseURL: 'https://api.lilith.ai/partner',
  timeout: 60000,
});
```

---

## Partner Account Management

### `registerPartner(request)`

Register a new partner account.

```typescript
async registerPartner(request: PartnerRegistrationRequest): Promise<PartnerRegistrationResponse>
```

**Request Parameters**:

| Field                  | Type                                          | Required | Description           |
| ---------------------- | --------------------------------------------- | -------- | --------------------- |
| `organization_name`    | `string`                                      | Yes      | Organization name     |
| `contact_email`        | `string`                                      | Yes      | Primary contact email |
| `contact_name`         | `string`                                      | Yes      | Contact person name   |
| `website_url`          | `string`                                      | No       | Organization website  |
| `use_case_description` | `string`                                      | No       | Integration use case  |
| `estimated_usage`      | `object`                                      | No       | Estimated API usage   |
| `tier_request`         | `'starter' \| 'professional' \| 'enterprise'` | No       | Requested tier        |

**Response**:

| Field                     | Type       | Description                                      |
| ------------------------- | ---------- | ------------------------------------------------ |
| `partner_id`              | `string`   | Assigned partner ID                              |
| `status`                  | `string`   | `'pending_approval' \| 'approved' \| 'rejected'` |
| `tier`                    | `string`   | Assigned tier                                    |
| `estimated_approval_time` | `string`   | Expected approval timeframe                      |
| `next_steps`              | `string[]` | Required next steps                              |

**Example**:

```typescript
const registration = await client.registerPartner({
  organization_name: 'Mindful Apps Inc.',
  contact_email: 'dev@mindfulapps.com',
  contact_name: 'Jane Developer',
  website_url: 'https://mindfulapps.com',
  use_case_description: 'Integrating wisdom features into meditation app',
  tier_request: 'professional',
});

console.log(`Partner ID: ${registration.partner_id}`);
console.log(`Status: ${registration.status}`);
```

---

### `approvePartner(partnerId, request)`

Approve a partner account (admin only).

```typescript
async approvePartner(
  partnerId: string,
  request: PartnerApprovalRequest
): Promise<PartnerApprovalResponse>
```

**Request Parameters**:

| Field         | Type     | Required | Description             |
| ------------- | -------- | -------- | ----------------------- |
| `approved_by` | `string` | Yes      | Approver identifier     |
| `tier`        | `string` | No       | Override requested tier |
| `notes`       | `string` | No       | Approval notes          |

---

## API Key Management

### `createAPIKey(partnerId, request)`

Generate a new API key for an approved partner.

```typescript
async createAPIKey(
  partnerId: string,
  request: APIKeyRequest
): Promise<APIKeyResponse>
```

**Request Parameters**:

| Field         | Type                        | Required | Description                |
| ------------- | --------------------------- | -------- | -------------------------- |
| `name`        | `string`                    | Yes      | Key name                   |
| `description` | `string`                    | No       | Key description            |
| `scopes`      | `string[]`                  | No       | Permission scopes          |
| `environment` | `'production' \| 'staging'` | No       | Target environment         |
| `expires_at`  | `string \| null`            | No       | Expiration date (ISO 8601) |

**Response**:

| Field         | Type             | Description                   |
| ------------- | ---------------- | ----------------------------- |
| `key_id`      | `string`         | Key identifier                |
| `api_key`     | `string`         | The API key (shown only once) |
| `name`        | `string`         | Key name                      |
| `scopes`      | `string[]`       | Granted scopes                |
| `environment` | `string`         | Environment                   |
| `rate_limits` | `RateLimits`     | Rate limit configuration      |
| `expires_at`  | `string \| null` | Expiration date               |
| `created_at`  | `string`         | Creation timestamp            |

**Example**:

```typescript
const apiKey = await client.createAPIKey('partner_123', {
  name: 'Production Key',
  description: 'Main production API key',
  scopes: ['chat', 'content', 'tts'],
  environment: 'production',
  expires_at: null, // No expiration
});

// IMPORTANT: Store this securely - shown only once
console.log(`API Key: ${apiKey.api_key}`);
```

---

### `listAPIKeys(partnerId)`

List all API keys for a partner.

```typescript
async listAPIKeys(partnerId: string): Promise<{
  partner_id: string;
  api_keys: APIKeyInfo[];
  total_keys: number;
}>
```

**APIKeyInfo Fields**:

| Field         | Type                     | Description                    |
| ------------- | ------------------------ | ------------------------------ |
| `id`          | `string`                 | Key identifier                 |
| `name`        | `string`                 | Key name                       |
| `description` | `string`                 | Key description                |
| `scopes`      | `string[]`               | Permission scopes              |
| `environment` | `string`                 | Environment                    |
| `status`      | `'active' \| 'disabled'` | Key status                     |
| `api_key`     | `string`                 | Masked key (`lilith_live_***`) |
| `usage_stats` | `UsageStats`             | Usage statistics               |
| `expires_at`  | `string \| null`         | Expiration date                |
| `created_at`  | `string`                 | Creation timestamp             |

---

## Core API Endpoints

### `chat(request)`

Send a chat message and receive an AI response.

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

**Request Parameters**:

| Field     | Type     | Required | Description                 |
| --------- | -------- | -------- | --------------------------- |
| `message` | `string` | Yes      | User message                |
| `persona` | `string` | Yes      | AI persona                  |
| `user_id` | `string` | No       | User identifier for context |

**Available Personas**:

- `zen_master` - Zen Buddhist perspective
- `stoic_mentor` - Stoic philosophy approach
- `sufi_guide` - Sufi mysticism guidance

**Response**:

| Field                 | Type     | Description      |
| --------------------- | -------- | ---------------- |
| `response`            | `string` | AI response text |
| `persona`             | `string` | Used persona     |
| `citations`           | `array`  | Source citations |
| `processing_time_ms`  | `number` | Processing time  |
| `partner_api_version` | `string` | API version      |

**Example**:

```typescript
const response = await client.chat({
  message: 'How can I cultivate patience?',
  persona: 'stoic_mentor',
  user_id: 'user_abc123',
});

console.log(`${response.persona}: ${response.response}`);
console.log(`Processing time: ${response.processing_time_ms}ms`);
```

---

### `getContent(query?)`

Retrieve content from the wisdom library.

```typescript
async getContent(query?: Record<string, string>): Promise<ContentResponse>
```

**Query Parameters**:

| Parameter   | Type     | Description         |
| ----------- | -------- | ------------------- |
| `type`      | `string` | Content type filter |
| `tradition` | `string` | Tradition filter    |
| `limit`     | `string` | Results limit       |
| `offset`    | `string` | Pagination offset   |

**Response**:

| Field                 | Type            | Description           |
| --------------------- | --------------- | --------------------- |
| `content`             | `ContentItem[]` | Content items         |
| `total_count`         | `number`        | Total available items |
| `partner_api_version` | `string`        | API version           |

**ContentItem**:

| Field              | Type     | Description   |
| ------------------ | -------- | ------------- |
| `id`               | `string` | Content ID    |
| `title`            | `string` | Content title |
| `type`             | `string` | Content type  |
| `duration_minutes` | `number` | Duration      |

**Example**:

```typescript
const content = await client.getContent({
  type: 'meditation',
  tradition: 'buddhism',
  limit: '10',
});

for (const item of content.content) {
  console.log(`${item.title} (${item.duration_minutes} min)`);
}
```

---

### `synthesizeSpeech(request)`

Convert text to speech.

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

**Request Parameters**:

| Field      | Type                       | Required | Description        |
| ---------- | -------------------------- | -------- | ------------------ |
| `text`     | `string`                   | Yes      | Text to synthesize |
| `voice_id` | `string`                   | No       | Voice identifier   |
| `format`   | `'opus' \| 'mp3' \| 'wav'` | No       | Audio format       |

**Response**:

| Field                 | Type     | Description    |
| --------------------- | -------- | -------------- |
| `audio_url`           | `string` | Audio file URL |
| `duration_sec`        | `number` | Audio duration |
| `format`              | `string` | Audio format   |
| `voice_id`            | `string` | Used voice     |
| `partner_api_version` | `string` | API version    |

**Example**:

```typescript
const audio = await client.synthesizeSpeech({
  text: 'Welcome to your meditation practice. Find a comfortable position.',
  voice_id: 'calm_female_01',
  format: 'mp3',
});

console.log(`Audio URL: ${audio.audio_url}`);
console.log(`Duration: ${audio.duration_sec} seconds`);
```

---

## Analytics & Reporting

### `getAnalytics(partnerId, options?)`

Get usage analytics for a partner.

```typescript
async getAnalytics(
  partnerId: string,
  options?: {
    timeframe?: 'day' | 'week' | 'month';
    includeDetails?: boolean;
  }
): Promise<PartnerAnalytics>
```

**Response**:

| Field               | Type     | Description                    |
| ------------------- | -------- | ------------------------------ |
| `partner_id`        | `string` | Partner ID                     |
| `timeframe`         | `string` | Analytics timeframe            |
| `generated_at`      | `string` | Report generation time         |
| `summary`           | `object` | Usage summary                  |
| `usage_by_endpoint` | `object` | Per-endpoint usage             |
| `quota_utilization` | `object` | Quota usage                    |
| `detailed_usage`    | `array`  | Per-key details (if requested) |

**Summary Fields**:

| Field                      | Type     | Description        |
| -------------------------- | -------- | ------------------ |
| `total_requests`           | `number` | Total API requests |
| `active_api_keys`          | `number` | Active keys count  |
| `rate_limit_hits`          | `number` | Rate limit events  |
| `average_response_time_ms` | `number` | Average latency    |
| `error_rate`               | `number` | Error percentage   |

**Example**:

```typescript
const analytics = await client.getAnalytics('partner_123', {
  timeframe: 'week',
  includeDetails: true,
});

console.log(`Total requests: ${analytics.summary.total_requests}`);
console.log(`Error rate: ${analytics.summary.error_rate}%`);
console.log(`Quota used: ${analytics.quota_utilization.daily.percentage}%`);
```

---

### `getEndpointMetrics(timeframe?)`

Get endpoint usage metrics (admin only).

```typescript
async getEndpointMetrics(timeframe?: string): Promise<{
  timeframe: string;
  generated_at: string;
  endpoint_metrics: Array<{
    endpoint: string;
    requests_count: number;
    average_latency_ms: number;
    error_rate: number;
    unique_partners: number;
  }>;
}>
```

---

## Webhook Management

### `createWebhook(partnerId, request)`

Create a webhook subscription.

```typescript
async createWebhook(
  partnerId: string,
  request: WebhookSubscriptionRequest
): Promise<WebhookSubscriptionResponse>
```

**Request Parameters**:

| Field         | Type       | Required | Description              |
| ------------- | ---------- | -------- | ------------------------ |
| `url`         | `string`   | Yes      | Webhook endpoint URL     |
| `events`      | `string[]` | Yes      | Events to subscribe to   |
| `secret`      | `string`   | No       | Webhook signing secret   |
| `description` | `string`   | No       | Subscription description |
| `active`      | `boolean`  | No       | Enable immediately       |

**Available Events**:

- `chat.completed` - Chat response generated
- `tts.generated` - TTS audio created
- `content.accessed` - Content retrieved
- `rate_limit.hit` - Rate limit reached
- `key.disabled` - API key disabled

**Response**:

| Field             | Type       | Description        |
| ----------------- | ---------- | ------------------ |
| `subscription_id` | `string`   | Subscription ID    |
| `url`             | `string`   | Webhook URL        |
| `events`          | `string[]` | Subscribed events  |
| `secret`          | `string`   | Signing secret     |
| `active`          | `boolean`  | Active status      |
| `created_at`      | `string`   | Creation timestamp |

**Example**:

```typescript
const webhook = await client.createWebhook('partner_123', {
  url: 'https://myapp.com/webhooks/lilith',
  events: ['chat.completed', 'rate_limit.hit'],
  description: 'Production webhook',
});

// Store the secret for signature verification
console.log(`Webhook secret: ${webhook.secret}`);
```

---

## Developer Portal

### `getDocumentation()`

Get API documentation (OpenAPI spec).

```typescript
async getDocumentation(): Promise<unknown>
```

---

### `getTiers()`

Get partner tier information.

```typescript
async getTiers(): Promise<TierInfo>
```

**Response**:

| Field               | Type          | Description            |
| ------------------- | ------------- | ---------------------- |
| `starter`           | `TierDetails` | Starter tier info      |
| `professional`      | `TierDetails` | Professional tier info |
| `enterprise`        | `TierDetails` | Enterprise tier info   |
| `current_offerings` | `string[]`    | Available features     |

**TierDetails**:

| Field         | Type         | Description       |
| ------------- | ------------ | ----------------- |
| `name`        | `string`     | Tier name         |
| `description` | `string`     | Tier description  |
| `rate_limits` | `RateLimits` | Rate limit config |
| `features`    | `string[]`   | Included features |
| `price`       | `string`     | Pricing info      |

---

### `checkHealth()`

Check API health status.

```typescript
async checkHealth(): Promise<HealthStatus>
```

**Response**:

| Field     | Type                       | Description  |
| --------- | -------------------------- | ------------ |
| `status`  | `'healthy' \| 'unhealthy'` | API status   |
| `service` | `string`                   | Service name |

---

## Error Handling

### PartnerAPIClientError Class

Custom error class for Partner API errors.

```typescript
class PartnerAPIClientError extends Error {
  constructor(
    message: string,
    public statusCode: number,
    public errorCode: string,
    public details?: PartnerAPIError
  )
}
```

**Properties**:

| Property     | Type              | Description           |
| ------------ | ----------------- | --------------------- |
| `message`    | `string`          | Error message         |
| `statusCode` | `number`          | HTTP status code      |
| `errorCode`  | `string`          | Error code            |
| `details`    | `PartnerAPIError` | Additional error info |

**Methods**:

| Method               | Returns               | Description                     |
| -------------------- | --------------------- | ------------------------------- |
| `isRateLimitError()` | `boolean`             | Check if rate limit error       |
| `isAuthError()`      | `boolean`             | Check if authentication error   |
| `isScopeError()`     | `boolean`             | Check if scope/permission error |
| `getRetryAfter()`    | `number \| undefined` | Get retry delay (seconds)       |

### Error Codes

| Code                          | HTTP Status | Description              |
| ----------------------------- | ----------- | ------------------------ |
| `partner.invalid_api_key`     | 401         | Invalid API key          |
| `partner.missing_api_key`     | 401         | No API key provided      |
| `partner.key_expired`         | 401         | API key expired          |
| `partner.key_disabled`        | 401         | API key disabled         |
| `partner.insufficient_scope`  | 403         | Missing required scope   |
| `partner.rate_limit_exceeded` | 429         | Rate limit exceeded      |
| `partner.quota_exceeded`      | 429         | Daily quota exceeded     |
| `network_error`               | 0           | Network connection error |

### Error Handling Example

```typescript
import {
  LilithPartnerClient,
  PartnerAPIClientError,
} from '@lilith/partner-api-sdk';

const client = new LilithPartnerClient({
  apiKey: 'lilith_live_abc123',
});

try {
  const response = await client.chat({
    message: 'Hello',
    persona: 'zen_master',
  });
} catch (error) {
  if (error instanceof PartnerAPIClientError) {
    if (error.isRateLimitError()) {
      const retryAfter = error.getRetryAfter() || 60;
      console.log(`Rate limited. Retry in ${retryAfter} seconds`);
      await sleep(retryAfter * 1000);
      // Retry request
    } else if (error.isAuthError()) {
      console.error('Authentication failed. Check your API key.');
    } else if (error.isScopeError()) {
      console.error('Insufficient permissions for this operation.');
    } else {
      console.error(`API Error [${error.errorCode}]: ${error.message}`);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}
```

---

## Rate Limits

### Rate Limit Headers

Responses include rate limit information in headers:

| Header                  | Description                  |
| ----------------------- | ---------------------------- |
| `X-RateLimit-Limit`     | Maximum requests allowed     |
| `X-RateLimit-Remaining` | Remaining requests           |
| `X-RateLimit-Reset`     | Reset timestamp (Unix)       |
| `Retry-After`           | Seconds until retry (on 429) |

### Rate Limit by Tier

| Tier         | Per Minute | Per Hour | Per Day   | Concurrent |
| ------------ | ---------- | -------- | --------- | ---------- |
| Starter      | 60         | 500      | 1,000     | 5          |
| Professional | 300        | 5,000    | 10,000    | 25         |
| Enterprise   | 1,000      | 50,000   | Unlimited | 100        |

### Handling Rate Limits

```typescript
async function withRateLimitRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3
): Promise<T> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (error instanceof PartnerAPIClientError && error.isRateLimitError()) {
        const retryAfter = error.getRetryAfter() || Math.pow(2, attempt);
        if (attempt < maxRetries - 1) {
          console.log(`Rate limited. Retrying in ${retryAfter}s...`);
          await new Promise((r) => setTimeout(r, retryAfter * 1000));
        }
      } else {
        throw error;
      }
    }
  }
  throw new Error('Max retries exceeded');
}

// Usage
const response = await withRateLimitRetry(() =>
  client.chat({ message: 'Hello', persona: 'zen_master' })
);
```

---

## Type Definitions

### RateLimits

```typescript
interface RateLimits {
  requests_per_minute: number;
  requests_per_hour: number;
  requests_per_day: number;
  concurrent_requests: number;
}
```

### UsageStats

```typescript
interface UsageStats {
  total_requests: number;
  last_used: string | null;
  created_requests_today: number;
  reset_at: number;
}
```

### PartnerAPIError

```typescript
interface PartnerAPIError {
  code: string;
  message: string;
  retry_after?: number;
  limit_type?: string;
}
```

---

## Webhook Signature Verification

Verify webhook authenticity using the signing secret:

```typescript
import crypto from 'crypto';

function verifyWebhookSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

// Express middleware example
app.post('/webhooks/lilith', (req, res) => {
  const signature = req.headers['x-lilith-signature'] as string;
  const payload = JSON.stringify(req.body);

  if (!verifyWebhookSignature(payload, signature, WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook event
  const event = req.body;
  console.log(`Received event: ${event.type}`);

  res.status(200).send('OK');
});
```

---

## Best Practices

### API Key Security

```typescript
// DO: Use environment variables
const client = new LilithPartnerClient({
  apiKey: process.env.LILITH_API_KEY!,
});

// DON'T: Hardcode API keys
const client = new LilithPartnerClient({
  apiKey: 'lilith_live_abc123', // Never do this
});
```

### Connection Reuse

```typescript
// DO: Create a single client instance
const client = new LilithPartnerClient({
  apiKey: process.env.LILITH_API_KEY!,
});

export async function chat(message: string) {
  return client.chat({ message, persona: 'zen_master' });
}

// DON'T: Create new clients for each request
export async function chat(message: string) {
  const client = new LilithPartnerClient({
    // Wasteful
    apiKey: process.env.LILITH_API_KEY!,
  });
  return client.chat({ message, persona: 'zen_master' });
}
```

### Graceful Degradation

```typescript
async function getChatResponse(message: string): Promise<string> {
  try {
    const response = await client.chat({
      message,
      persona: 'zen_master',
    });
    return response.response;
  } catch (error) {
    if (error instanceof PartnerAPIClientError) {
      // Log error for monitoring
      console.error(`Partner API error: ${error.errorCode}`);

      // Return fallback response
      return 'I apologize, but I am unable to respond at this moment. Please try again later.';
    }
    throw error;
  }
}
```

---

## Related Documentation

- [TypeScript SDK Reference](./typescript-sdk.md) - Full platform SDK
- [Authentication Guide](./authentication.md) - Authentication flows
- [API Versioning](./api-versioning.md) - Version management
- [Error Codes](./error-codes.md) - Complete error reference

---

## Support

- **Partner Portal**: https://partners.lilith.ai
- **Technical Support**: partner-support@lilith.ai
- **Documentation**: https://docs.lilith.ai/partners
- **Status Page**: https://status.lilith.ai
