npm package: @orchard9ai/companion-world-sdk
Description: TypeScript SDK for Companion World API
Author: Orchard9
Latest version: 1.1.0

# Companion World SDK

Official TypeScript SDK for the Companion World API - create and manage AI-powered virtual worlds with autonomous agents.

## Installation

```bash
npm install @orchard9ai/companion-world-sdk
```

## Quick Start

```typescript
import { CompanionWorldClient } from '@orchard9ai/companion-world-sdk';

// Initialize the client
const client = new CompanionWorldClient({
  baseURL: 'https://agents.orchard9.ai/api/companion-world',
  apiKey: 'your-jwt-token',
  organizationId: 'your-org-id' // optional
});

// Create a world
const { world } = await client.initializeWorld({
  name: 'My AI World',
  config: {
    startTime: '2024-01-01T00:00:00Z',
    tickInterval: 15,
    timezone: 'America/Los_Angeles',
    planningHorizonMonths: 6
  }
});

// Generate population
const { job } = await client.generatePopulation(world.id, {
  count: 1000,
  batch_size: 50,
  config: {
    gender_distribution: { F: 1.0, M: 0.0 } // 100% female
  }
});

// Monitor progress
const stats = await client.getWorldStats(world.id);
console.log(`Total agents: ${stats.totalAgents}`);
console.log(`Pending: ${stats.pendingAgents}`);
```

## Key Features

- 🌍 **World Management** - Create and manage virtual worlds
- 👥 **Population Generation** - Generate diverse AI agents at scale
- 📍 **Location System** - Add cities and locations to your world
- 📊 **Real-time Monitoring** - Track population generation progress
- 🎭 **Agent Personalities** - Each agent has unique traits and behaviors

## API Reference

### World Management

```typescript
// Initialize a new world
await client.initializeWorld({
  name: string,
  config: {
    startTime: string,        // ISO date
    tickInterval: number,     // minutes
    timezone: string,         // IANA timezone
    planningHorizonMonths: number
  }
});

// Get world details
await client.getWorld(worldId: string);

// List all worlds
await client.listWorlds({ page?: number, limit?: number });
```

### Population Generation

```typescript
// Start population generation
await client.generatePopulation(worldId: string, {
  count: number,
  batch_size: number,
  config?: {
    age_distribution?: Record<string, number>,
    gender_distribution?: Record<string, number>
  }
});

// Check job status
await client.getPopulationJob(worldId: string, jobId: string);

// List all jobs
await client.listPopulationJobs(worldId: string);
```

### Agent Management

```typescript
// List agents
await client.listAgents(worldId: string, {
  page?: number,
  limit?: number,
  gender?: string,
  location_id?: string
});

// Get agent details
await client.getAgent(worldId: string, agentId: string);
```

### Helper Methods

```typescript
// Get comprehensive world statistics
const stats = await client.getWorldStats(worldId: string);
// Returns: {
//   world: World,
//   totalAgents: number,
//   activeJobs: number,
//   completedJobs: number,
//   pendingAgents: number,
//   populationProgress: Array<{
//     id: string,
//     status: string,
//     total: number,
//     completed: number,
//     progress: number
//   }>
// }
```

## Examples

### Monitor Population Generation

```typescript
async function monitorPopulation(worldId: string) {
  const stats = await client.getWorldStats(worldId);
  
  console.log(`World: ${stats.world.world_name}`);
  console.log(`Total Agents: ${stats.totalAgents}`);
  console.log(`Agents Being Generated: ${stats.pendingAgents}`);
  
  stats.populationProgress.forEach(job => {
    console.log(`Job ${job.id}: ${job.completed}/${job.total} (${job.progress.toFixed(1)}%)`);
  });
}

// Poll every 5 seconds
setInterval(() => monitorPopulation(worldId), 5000);
```

### Create World with Cities

```typescript
// Create world
const { world, locationId } = await client.initializeWorld({
  name: 'Urban World',
  config: {
    startTime: '2024-01-01T00:00:00Z',
    tickInterval: 15,
    timezone: 'America/Los_Angeles',
    planningHorizonMonths: 6
  }
});

// Add cities
await client.createLocationsBatch(world.id, {
  locations: [
    {
      name: 'San Francisco',
      type: 'GEOGRAPHIC',
      subtype: 'CITY',
      timezone: 'America/Los_Angeles',
      coordinates: {
        latitude: 37.7749,
        longitude: -122.4194
      }
    },
    {
      name: 'Los Angeles',
      type: 'GEOGRAPHIC', 
      subtype: 'CITY',
      timezone: 'America/Los_Angeles',
      coordinates: {
        latitude: 34.0522,
        longitude: -118.2437
      }
    }
  ],
  connect_nearby: true,
  max_connections: 5,
  connection_radius_km: 100
});
```

## Error Handling

```typescript
try {
  const world = await client.getWorld(worldId);
} catch (error) {
  if (error.response?.status === 404) {
    console.error('World not found');
  } else if (error.response?.status === 403) {
    console.error('Insufficient permissions');
  } else {
    console.error('Unexpected error:', error.message);
  }
}
```

## License

MIT