npm package: @orchard9ai/api-client
Description: TypeScript client library for Companion World API - Agent Hub integration
Author: Orchard9 AI Team
Latest version: 1.0.0-20250710160819

# Companion World API Client

A TypeScript client library for the Companion World API, providing type-safe access to agent management endpoints.

## Features

- **Type-Safe**: Generated from OpenAPI specification with full TypeScript support
- **Comprehensive**: Covers all agent and media management endpoints
- **Flexible**: Support for filtering, pagination, and search
- **Lightweight**: Zero dependencies (uses native fetch)
- **Extensible**: Easy to customize with your own HTTP client

## Installation

```bash
npm install @orchard9ai/api-client
```

## Quick Start

```typescript
import { createCompanionWorldApiClient } from '@orchard9ai/api-client';

// Create client
const client = createCompanionWorldApiClient({
  baseUrl: 'http://localhost:13240',
  timeout: 10000
});

// List agents with filtering
const agents = await client.listAgents({
  search: 'Alice',
  gender: ['F'],
  status: ['active'],
  page: 1,
  pageSize: 20
});

console.log(`Found ${agents.pagination.total} agents`);
```

## API Reference

### Client Configuration

```typescript
interface CompanionWorldApiConfig {
  baseUrl: string;          // API base URL (e.g., 'http://localhost:13240')
  timeout?: number;         // Request timeout in milliseconds (default: no timeout)
  headers?: Record<string, string>; // Additional headers
}
```

### Agent Management

#### List Agents

```typescript
// Basic listing
const agents = await client.listAgents();

// With filtering and pagination
const filteredAgents = await client.listAgents({
  page: 1,
  pageSize: 50,
  search: 'John',
  gender: ['M', 'F'],
  status: ['active'],
  ageMin: 25,
  ageMax: 65,
  worlds: ['world-uuid-1', 'world-uuid-2']
});
```

#### Get Agent Details

```typescript
const agent = await client.getAgent('agent-uuid');
console.log(`${agent.name} is ${agent.age} years old`);
console.log(`Bio: ${agent.bio}`);
console.log(`Traits: ${agent.personalityTraits?.join(', ')}`);
```

### Media Management

#### List Agent Media

```typescript
const media = await client.getAgentMedia('agent-uuid', {
  page: 1,
  pageSize: 20
});

media.media.forEach(item => {
  console.log(`${item.title}: ${item.url}`);
});
```

#### Create Media

```typescript
const newMedia = await client.createAgentMedia('agent-uuid', {
  title: 'Profile Photo',
  type: 'image',
  url: 'https://example.com/photo.jpg',
  thumbnailUrl: 'https://example.com/photo-thumb.webp',
  size: 245760,
  metadata: {
    description: 'Professional headshot',
    tags: ['profile', 'professional'],
    technical_info: {
      resolution: '1920x1080',
      format: 'JPEG'
    }
  }
});
```

#### Update Media

```typescript
const updatedMedia = await client.updateAgentMedia('agent-uuid', 'media-uuid', {
  title: 'Updated Title',
  metadata: {
    description: 'Updated description',
    tags: ['updated', 'profile']
  }
});
```

#### Delete Media

```typescript
await client.deleteAgentMedia('agent-uuid', 'media-uuid');
```

## Helper Utilities

The library includes helper functions for common use cases:

```typescript
import { CompanionWorldHelpers } from '@orchard9ai/api-client';

const helpers = new CompanionWorldHelpers(client);

// Search agents by name
const searchResults = await helpers.searchAgentsByName('Alice');

// Get all agents in a specific world
const worldAgents = await helpers.getAgentsInWorld('world-uuid');

// Filter by demographics
const youngAdults = await helpers.getAgentsByDemographics({
  ageMin: 18,
  ageMax: 35,
  gender: ['F', 'M'],
  status: ['active']
});

// Get all media for an agent (handles pagination automatically)
const allMedia = await helpers.getAllAgentMedia('agent-uuid');
```

## Error Handling

The client throws `CompanionWorldApiError` for API errors:

```typescript
import { CompanionWorldApiError } from '@orchard9ai/api-client';

try {
  const agent = await client.getAgent('invalid-uuid');
} catch (error) {
  if (error instanceof CompanionWorldApiError) {
    console.error(`API Error ${error.status}:`, error.data);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Types

All types are exported for use in your application:

```typescript
import type {
  AgentListResponse,
  SimplifiedAgent,
  AgentDetails,
  AgentMedia,
  CreateAgentMediaRequest,
  UpdateAgentMediaRequest,
  PaginationInfo,
  MediaMetadata
} from '@orchard9ai/api-client';
```

## Custom HTTP Client

You can provide your own HTTP client implementation:

```typescript
import axios from 'axios';
import { CompanionWorldApiClient, HttpClient } from '@orchard9ai/api-client';

class AxiosHttpClient implements HttpClient {
  constructor(private axios = axios.create()) {}
  
  async get<T>(url: string): Promise<T> {
    const response = await this.axios.get(url);
    return response.data;
  }
  
  async post<T>(url: string, data?: any): Promise<T> {
    const response = await this.axios.post(url, data);
    return response.data;
  }
  
  async put<T>(url: string, data?: any): Promise<T> {
    const response = await this.axios.put(url, data);
    return response.data;
  }
  
  async delete<T>(url: string): Promise<T> {
    const response = await this.axios.delete(url);
    return response.data;
  }
}

const client = new CompanionWorldApiClient(config, new AxiosHttpClient());
```

## Requirements

- Node.js 18+ (for native fetch support)
- TypeScript 4.9+ (if using TypeScript)

## License

MIT