npm package: @kaily-ai/chat-sdk
Description: Kaily Chat SDK — build AI chat experiences with Kaily.ai copilots
Author: Copilot Live Team
Latest version: 2.1.2

# @kaily-ai/chat-sdk

A TypeScript SDK for integrating [Kaily.ai](https://kaily.ai) copilot chat into your applications. Real-time messaging, streaming responses, thread management, custom tools, and more.

## Installation

```bash
npm install @kaily-ai/chat-sdk
```

## Quick Start

```typescript
import { CopilotPlatform } from '@kaily-ai/chat-sdk';

// 1. Initialize the SDK
const copilot = CopilotPlatform.getInstance({
  environment: 'production',
  surfaceClient: 'web',
});

// 2. Create a bot instance with your copilot app token
const bot = await copilot.createBotInstance('YOUR_APP_TOKEN');

// 3. Send a message
await bot.message(
  { text: 'Hello!' },
  {
    deltaListener: (res) => console.log('Streaming:', res.data.content),
    replyListener: (res) => console.log('Reply:', res.data),
    progressListener: (res) => console.log('Progress:', res.data.progress),
    toolMessageListener: (res) => console.log('Tool:', res.data),
  }
);
```

## SDK Initialization

```typescript
import { CopilotPlatform } from '@kaily-ai/chat-sdk';

// Single instance (default)
const copilot = CopilotPlatform.getInstance({
  environment: 'production',       // 'production' | 'uat' | 'sit'
  surfaceClient: 'web',            // Your client identifier
});

// Named instance (for multi-instance)
const copilot = CopilotPlatform.createInstance('my-widget', {
  environment: 'production',
  surfaceClient: 'web',
});
```

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `environment` | `'production' \| 'uat' \| 'sit'` | Recommended | Target environment |
| `surfaceClient` | `string` | Yes | Your client identifier |

## Multi-Instance Support

Run multiple independent widgets on the same page — each with its own socket, events, and state:

```typescript
const sales = CopilotPlatform.createInstance('sales', { environment: 'production', surfaceClient: 'web' });
const support = CopilotPlatform.createInstance('support', { environment: 'production', surfaceClient: 'web' });

const salesBot = await sales.createBotInstance('SALES_TOKEN');
const supportBot = await support.createBotInstance('SUPPORT_TOKEN');

// Retrieve later
const widget = CopilotPlatform.getInstanceById('sales');

// Cleanup
sales.destroy(); // other instances unaffected
```

`getInstance()` still works exactly as before for single-widget use cases.

## Messaging

```typescript
const result = await bot.message(
  {
    text: 'What is the status of my order?',
    thread_id: 'optional-thread-id',
  },
  {
    deltaListener: (res) => {
      // Real-time streaming chunks
      console.log(res.data.content);
    },
    replyListener: (res) => {
      // Final complete response
      console.log(res.data.messages);
    },
    progressListener: (res) => {
      // Progress updates (e.g., "Searching...")
      console.log(`${res.data.progress}%`, res.data.content);
    },
    toolMessageListener: (res) => {
      // Tool execution output
      console.log(res.data.content);
    },
  }
);
```

### Stop Generation

```typescript
await bot.stopMessage({ thread_id: 'thread-id' });
```

## Thread Management

```typescript
const threads = await bot.getThreads({ page: 1, limit: 20 });
const messages = await bot.getMessages({ threadId: 'thread-id' });
await bot.updateThread({ threadId: 'thread-id', title: 'New Title' });
await bot.deleteThread('thread-id');
await bot.deleteAllThreads({});
```

## Custom Tools

Register client-side tools that the AI can invoke during conversations:

```typescript
import { Tool } from '@kaily-ai/chat-sdk';

await bot.addTool({
  name: 'lookupOrder',
  description: 'Look up order status by order ID',
  timeout: 5000,
  parameters: {
    type: 'object',
    properties: {
      orderId: { type: 'string', description: 'The order ID' },
    },
    required: ['orderId'],
  },
  handler: async (params) => {
    const order = await fetchOrder(params.orderId);
    return { status: order.status, eta: order.eta };
  },
});

// Remove tools
await bot.removeTool('lookupOrder');
await bot.removeAllTools();
```

## User Management

```typescript
await bot.setUser({
  name: 'John Doe',
  email: 'john@example.com',
  phone: '+1234567890',
  additionalFields: { company: 'Acme Inc' },
});

await bot.unsetUser();
```

## Context

```typescript
await bot.setContext({
  currentPage: '/products',
  cartItems: 3,
});
```

## API Reference

### CopilotPlatform

| Method | Description |
|--------|-------------|
| `getInstance(options)` | Get or create default instance |
| `createInstance(id, options)` | Create a named, isolated instance |
| `getInstanceById(id)` | Retrieve existing instance by ID |
| `destroy()` | Destroy instance (sockets, events, registry) |
| `createBotInstance(token)` | Create bot instance |
| `getBot()` | Get current bot |
| `switchBot(token)` | Switch to different bot |

### CopilotBot

| Method | Description |
|--------|-------------|
| `message(message, listeners)` | Send message with streaming |
| `stopMessage(options)` | Stop generation |
| `getThreads(request)` | Get all threads |
| `getMessages(request)` | Get thread messages |
| `updateThread(request)` | Update thread |
| `deleteThread(threadId)` | Delete thread |
| `addTool(tools)` | Add custom tools |
| `removeTool(name)` | Remove tool |
| `setContext(context)` | Set conversation context |
| `setUser(request)` | Set user details |
| `unsetUser()` | Clear user |
| `feedback(request)` | Submit feedback |
| `captureData(request)` | Capture analytics |
| `destroy()` | Cleanup |

## Type Definitions

```typescript
type Environment = 'production' | 'uat' | 'sit';

interface MessageModel {
  text: string;
  path: string;
  thread_id?: string;
  files?: Array<any>;
  info?: { custom_data?: any };
}

interface Tool {
  name: string;
  description?: string;
  parameters?: object;
  timeout: number;
  handler: (params: Record<string, any>) => any | Promise<any>;
}
```

## License

MIT