npm package: @layercode/ai-sdk
Description: Layercode AI SDK - ChatTransport for Vercel AI SDK
Author: Layercode
Latest version: 0.0.1

# @layercode/ai-sdk

ChatTransport implementation for the [Vercel AI SDK](https://sdk.vercel.ai/) that connects to [Layercode](https://layercode.com) agents via WebSocket.

## Installation

```bash
npm install @layercode/ai-sdk ai
```

## Usage

```typescript
import { useChat } from "ai/react";
import { LayercodeTransport } from "@layercode/ai-sdk";

const transport = new LayercodeTransport({
  agentId: "your-agent-id",
  authorizeSessionEndpoint: "/api/layercode/authorize",
  onStatusChange: (status) => {
    console.log("Connection status:", status);
  },
  onConnect: ({ conversationId }) => {
    console.log("Connected with conversation:", conversationId);
  },
  onError: (error) => {
    console.error("Transport error:", error);
  },
});

function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    transport,
  });

  return (
    <div>
      {messages.map((message) => (
        <div key={message.id}>
          <strong>{message.role}:</strong> {message.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}
```

## Configuration

### LayercodeTransportOptions

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `agentId` | `string` | Yes | Your Layercode agent ID |
| `authorizeSessionEndpoint` | `string` | Yes | Endpoint to authorize WebSocket sessions |
| `metadata` | `Record<string, unknown>` | No | Custom metadata to send with the session |
| `conversationId` | `string \| null` | No | Existing conversation ID to resume |
| `onStatusChange` | `(status: LayercodeStatus) => void` | No | Callback when connection status changes |
| `onConnect` | `(info: { conversationId: string \| null }) => void` | No | Callback when connected |
| `onDisconnect` | `() => void` | No | Callback when disconnected |
| `onError` | `(error: Error) => void` | No | Callback when an error occurs |

### LayercodeStatus

The connection status can be one of:
- `"disconnected"` - Not connected
- `"connecting"` - Connection in progress
- `"connected"` - Connected and ready
- `"error"` - Connection error occurred

## Server-side Authorization Endpoint

You need to create an API endpoint that authorizes WebSocket sessions. Example using Next.js:

```typescript
// app/api/layercode/authorize/route.ts
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const body = await request.json();

  const response = await fetch(
    "https://api.layercode.com/v1/agents/web/authorize_session",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.LAYERCODE_API_KEY}`,
      },
      body: JSON.stringify({
        agent_id: body.agent_id,
        metadata: body.metadata,
        conversation_id: body.conversation_id,
      }),
    }
  );

  const data = await response.json();
  return NextResponse.json(data);
}
```

## Methods

### `disconnect()`

Manually disconnect from the WebSocket.

```typescript
transport.disconnect();
```

### `getConversationId()`

Get the current conversation ID.

```typescript
const conversationId = transport.getConversationId();
```

### `getStatus()`

Get the current connection status.

```typescript
const status = transport.getStatus();
```

### `reconnectToStream()`

Attempt to reconnect to an interrupted stream.

```typescript
const stream = await transport.reconnectToStream();
```

## License

MIT