> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chucky.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# ChuckyClient

> JavaScript/TypeScript SDK client reference

# ChuckyClient

The main client class for interacting with Chucky. Matches the official Claude Agent SDK V2 interface.

## Installation

```bash theme={null}
npm install @chucky.cloud/sdk
```

## Import

```typescript theme={null}
import { ChuckyClient, createClient, getAssistantText } from '@chucky.cloud/sdk';
```

## Constructor

```typescript theme={null}
const client = new ChuckyClient(options: ClientOptions);
```

### ClientOptions

| Property            | Type      | Required | Default                           | Description              |
| ------------------- | --------- | -------- | --------------------------------- | ------------------------ |
| `token`             | `string`  | Yes      | -                                 | JWT authentication token |
| `baseUrl`           | `string`  | No       | `'wss://conjure.chucky.cloud/ws'` | WebSocket server URL     |
| `debug`             | `boolean` | No       | `false`                           | Enable debug logging     |
| `timeout`           | `number`  | No       | `60000`                           | Connection timeout (ms)  |
| `keepAliveInterval` | `number`  | No       | `300000`                          | Keep-alive interval (ms) |

### Example

```typescript theme={null}
const client = new ChuckyClient({
  token: 'your-jwt-token',
  debug: true,
});
```

## Methods

### prompt()

Send a one-shot prompt (stateless). Creates a session, sends the message, and returns the result.

```typescript theme={null}
async prompt(message: string, options?: SessionOptions): Promise<SDKResultMessage>
```

#### Example

```typescript theme={null}
const result = await client.prompt(
  'What is 2 + 2?',
  { model: 'claude-sonnet-4-5-20250929' }
);

if (result.subtype === 'success') {
  console.log(result.result); // "4"
  console.log(result.total_cost_usd); // 0.0001
}
```

***

### createSession()

Create a new conversation session. Returns the session immediately; connection happens on first `send()`.

```typescript theme={null}
createSession(options?: SessionOptions): Session
```

#### SessionOptions

| Property       | Type           | Description                |
| -------------- | -------------- | -------------------------- |
| `model`        | `string`       | Claude model to use        |
| `systemPrompt` | `string`       | System prompt              |
| `tools`        | `Tool[]`       | Available tools            |
| `mcpServers`   | `McpServer[]`  | MCP servers                |
| `maxTurns`     | `number`       | Max conversation turns     |
| `maxBudgetUsd` | `number`       | Budget limit               |
| `outputFormat` | `OutputFormat` | Structured output format   |
| `sessionId`    | `string`       | Resume existing session    |
| `forkSession`  | `string`       | Fork from session ID       |
| `continue`     | `boolean`      | Continue from last message |

#### Example

```typescript theme={null}
const session = client.createSession({
  model: 'claude-sonnet-4-5-20250929',
  systemPrompt: 'You are a helpful assistant.',
});

await session.send('Hello!');
for await (const msg of session.stream()) {
  if (msg.type === 'assistant') {
    console.log(getAssistantText(msg));
  }
}

session.close();
```

***

### resumeSession()

Resume an existing session by ID.

```typescript theme={null}
resumeSession(
  sessionId: string,
  options?: Omit<SessionOptions, 'sessionId'>
): Session
```

#### Example

```typescript theme={null}
const session = client.resumeSession('session-123');

await session.send('What did we discuss before?');
for await (const msg of session.stream()) {
  // handle messages
}
```

***

### close()

Close all active sessions.

```typescript theme={null}
close(): void
```

#### Example

```typescript theme={null}
// Clean up when done
client.close();
```

***

### on()

Register event handlers.

```typescript theme={null}
on(handlers: ClientEventHandlers): this
```

#### ClientEventHandlers

| Handler        | Parameters          | Description            |
| -------------- | ------------------- | ---------------------- |
| `onConnect`    | `()`                | WebSocket connected    |
| `onDisconnect` | `(reason: string)`  | WebSocket disconnected |
| `onReconnect`  | `(attempt: number)` | Reconnection attempt   |
| `onError`      | `(error: Error)`    | Error occurred         |

## Factory Function

### createClient()

Alternative factory function for creating clients.

```typescript theme={null}
function createClient(options: ClientOptions): ChuckyClient
```

#### Example

```typescript theme={null}
const client = createClient({ token: 'your-token' });
```

## Helper Functions

### getAssistantText()

Extract text content from an assistant message.

```typescript theme={null}
import { getAssistantText } from '@chucky.cloud/sdk';

const text = getAssistantText(msg);
```

### getResultText()

Extract the result text from a result message.

```typescript theme={null}
import { getResultText } from '@chucky.cloud/sdk';

const text = getResultText(msg);
```

## Complete Example

```typescript theme={null}
import { ChuckyClient, tool, getAssistantText } from '@chucky.cloud/sdk';

// Create client
const client = new ChuckyClient({
  token: process.env.CHUCKY_TOKEN,
  debug: true,
});

// Define a tool
const calculatorTool = tool(
  'calculate',
  'Perform math calculations',
  {
    type: 'object',
    properties: {
      expression: { type: 'string' },
    },
    required: ['expression'],
  },
  async ({ expression }) => {
    const result = eval(expression); // Use a proper math lib in production
    return { content: [{ type: 'text', text: String(result) }] };
  }
);

// Create a session with tools
const session = client.createSession({
  model: 'claude-sonnet-4-5-20250929',
  systemPrompt: 'You are a math tutor.',
  tools: [calculatorTool],
});

// Send message and stream response
await session.send('What is 15% of 230?');
for await (const msg of session.stream()) {
  if (msg.type === 'assistant') {
    const text = getAssistantText(msg);
    if (text) process.stdout.write(text);
  }
  if (msg.type === 'result' && msg.subtype === 'success') {
    console.log('\nCost:', msg.total_cost_usd);
  }
}

// Multi-turn conversation
await session.send('Explain how you calculated that');
for await (const msg of session.stream()) {
  if (msg.type === 'assistant') {
    console.log(getAssistantText(msg));
  }
}

// Clean up
session.close();
client.close();
```
