npm package: @jovyan/client
Description: Client library for Jovyan AI Copilot - Jupyter notebook integration
Latest version: 0.4.9

# Jovyan AI Client

Client library for interacting with the Jovyan AI Copilot for Jupyter notebooks.

## Installation

```bash
npm install @jovyan/client
# or
yarn add @jovyan/client
```

## Usage

### Browser/Frontend

```typescript
import { JovyanClient } from '@jovyan/client';

const client = new JovyanClient('wss://your-jovyan-server.com');

// Connect to the server
await client.connect();

// Start a session
const sessionId = await client.startSession('user123');

// Generate code
await client.generateCodeStream({
  currentCell: {
    cell_type: 'code',
    source: '',
    outputs: [],
    metadata: {}
  },
  previousCells: [],
  nextCells: [],
  prompt: "Create a histogram of this dataset",
  language: "python",
  stream: true
}, (chunk) => {
  console.log('Received chunk:', chunk);
});
```

### Suggest Next Action

```typescript
import { JovyanClient } from '@jovyan/client;

const client = new JovyanClient('wss://your-jovyan-server.com');

// Connect to the server
await client.connect();

// Start a session
const sessionId = await client.startSession('user123');

// Suggest next action
const nextActions = await client.suggestNextAction({
  currentCell: {
    cell_type: 'code',
    source: '',
    outputs: [],
    metadata: {}
  },
  previousCells: [],
  nextCells: []
});

// Use the suggested actions
console.log(nextActions);
```

### Node.js

```typescript
import { JovyanClient } from '@jovyan/client';

// Same API as browser version
// ...
```

### Stream User Messages

```typescript
import { JovyanClient } from '@jovyan/client';

const client = new JovyanClient('wss://your-jovyan-server.com');

// Connect to the server
await client.connect();

// Start a session
const sessionId = await client.startSession('user123');

// Stream user messages
await client.sendUserMessageStream('How do I create a scatter plot?', {
  currentCell: {
    cell_type: 'code',
    source: '',
    outputs: [],
    metadata: {}
  },
  previousCells: [],
  nextCells: [],
  todoList: [],
  chatHistory: []
}, (chunk) => {
  console.log('Received chunk:', chunk);
});
```

### Stream Continue Requests

```typescript
import { JovyanClient } from '@jovyan/client';

const client = new JovyanClient('wss://your-jovyan-server.com');

// Connect to the server
await client.connect();

// Start a session
const sessionId = await client.startSession('user123');

// Stream continue requests
await client.requestContinueStream({
  currentCell: {
    cell_type: 'code',
    source: '',
    outputs: [],
    metadata: {}
  },
  previousCells: [],
  nextCells: [],
  todoList: []
}, (chunk) => {
  console.log('Received chunk:', chunk);
}, (updatedItems) => {
  console.log('Updated todo items:', updatedItems);
});
```

### Integrate Tool and Handle Tool Execution

To integrate a tool and handle its execution in the context of `sendUserMessageStream`, you need to follow these steps:

1. **Define the Tool**: Create a tool definition that includes the tool's name, description, and execution logic.
2. **Include the Tool in the Context**: Pass the tool in the context when calling `sendUserMessageStream`.
3. **Handle Tool Execution**: The `sendUserMessageStream` method will handle the tool execution and stream the user message chunks.

#### Example

```typescript
import { JovyanClient } from '@jovyan/client';
import { Tool } from '@jovyan/client';

// Define a tool
const myTool: Tool = {
  name: 'MyTool',
  description: 'A custom tool for demonstration purposes',
  handleMessage: async (message, resultCallback) => {
    // Tool execution logic
    if (message.type === 'agent:tool_use_chunk') {
      // Process the chunk
      console.log('Processing chunk:', message.payload);
    } else if (message.type === 'agent:tool_use_complete') {
      // Complete the tool execution
      resultCallback({
        type: 'agent:tool_use_result',
        payload: {
          toolCall: {
            result: 'Tool executed successfully',
            toolCallId: message.payload.toolCall.toolCallId
          }
        }
      });
    }
  }
};

// Integrate with JovyanClient
const client = new JovyanClient('wss://your-jovyan-server.com');

// Connect to the server
await client.connect();

// Start a session
const sessionId = await client.startSession('user123');

// Stream user messages and handle tool execution
await client.sendUserMessageStream('How do I create a scatter plot?', {
  currentCell: {
    cell_type: 'code',
    source: '',
    outputs: [],
    metadata: {}
  },
  previousCells: [],
  nextCells: [],
  todoList: [],
  chatHistory: [],
  tools: [myTool] // Include the tool in the context
}, (chunk) => {
  console.log('Received chunk:', chunk);
});
```

In this example, we define a custom tool named `MyTool` and include it in the context when calling `sendUserMessageStream`. The `sendUserMessageStream` method will handle the tool execution and stream the user message chunks.

## API Reference

### `JovyanClient`

The main client class for interacting with the Jovyan AI server.

#### Constructor

```typescript
constructor(url: string)
```

- `url`: WebSocket URL of the Jovyan AI server

#### Methods

##### `connect(): Promise<void>`
Establishes a WebSocket connection to the server.

##### `startSession(userId: string): Promise<string>`
Starts a new session and returns the session ID.

##### `generateCodeStream(params: GenerateCodeParams, onChunk: (chunk: string) => void): Promise<void>`
Streams code generation chunks based on the provided parameters.

##### `suggestNextAction(params: { currentCell: CellData; previousCells: CellData[]; nextCells: CellData[] }): Promise<string[]>`
Suggests the next actions based on the provided parameters.

##### `sendUserMessageStream(message: string, context: { currentCell: CellData; previousCells: CellData[]; nextCells: CellData[]; todoList: TodoItem[]; chatHistory: ChatMessage[] }, onChunk: (chunk: string) => void): Promise<void>`
Streams user message chunks based on the provided parameters.

##### `requestContinueStream(context: { currentCell: CellData; previousCells: CellData[]; nextCells: CellData[]; todoList: TodoItem[] }, onChunk: (chunk: string) => void, onUpdateTodo: (items: TodoItem[]) => void): Promise<void>`
Streams continuation response chunks and updates todo items based on the provided parameters.

##### `close(): void`
Closes the WebSocket connection.

## Types

The package exports TypeScript types for all messages and parameters:

```typescript
import { CellData, GenerateCodeMessage } from '@jovyan/client';
```

## Error Handling

The client handles various error scenarios:
- Connection errors
- Server errors
- Invalid message formats

All errors are properly typed and include descriptive messages.

## License

ISC