npm package: @smartlabormanagement/smartee
Description: A standalone, dependency-free chat engine with streaming support for web and React Native
Author: Smart Labor Management
Latest version: 0.1.1

# @smartlabormanagement/smartee

A standalone, dependency-free AI chat engine with Server-Sent Events (SSE) streaming support for web and React Native applications.

## Features

- 🚀 Zero dependencies
- 📱 React Native compatible
- 🔄 Real-time SSE streaming for AI responses
- 🤖 Built for AI assistant conversations (like ChatGPT/Claude)
- 🛠️ Tool execution support
- 📡 Event-driven architecture
- 💬 Text chunk buffering for smooth display
- 🔌 Abort/cancel support
- 📦 TypeScript support
- 🌐 Works in both browser and Node.js environments

## Installation

```bash
npm install @smartlabormanagement/smartee
```

## Usage

### Basic Setup

```typescript
import { ChatEngine } from '@smartlabormanagement/smartee';

const chatEngine = new ChatEngine({
  apiUrl: 'https://api.example.com/v3',
  authToken: 'your-auth-token',
  debug: true,
  onAuthError: () => {
    // Handle authentication errors
    console.log('Authentication failed');
  },
});

// Create a conversation
const conversation = await chatEngine.createConversation('My Chat');

// Send a message
await chatEngine.sendMessage('Hello, AI assistant!');
```

### Handling Streaming Responses

```typescript
// Listen for streaming events
chatEngine.on('stream:start', (data) => {
  console.log('Stream started');
});

chatEngine.on('stream:userMessage', (message) => {
  console.log('User said:', message.content);
});

chatEngine.on('stream:assistantStart', (message) => {
  console.log('Assistant is typing...');
});

chatEngine.on('stream:textChunk', ({ messageId, text }) => {
  // Update your UI with the streaming text
  updateMessageInUI(messageId, text);
});

chatEngine.on('stream:complete', (data) => {
  console.log('Response complete');
});

chatEngine.on('stream:error', (error) => {
  console.error('Stream error:', error);
});
```

### Tool Execution

```typescript
// Listen for tool execution events
chatEngine.on('stream:toolUse', (data) => {
  console.log(`Tool ${data.name} invoked with:`, data.input);
});

chatEngine.on('stream:toolExecutionStart', (data) => {
  console.log(`Executing tool: ${data.toolName}`);
});

chatEngine.on('stream:toolExecutionComplete', (data) => {
  console.log(`Tool ${data.toolId} completed with result:`, data.result);
});

// Handle confirmation requests
chatEngine.on('stream:confirmationRequired', async (data) => {
  const userConfirmed = await showConfirmationDialog(data.confirmationData);

  await chatEngine.confirmToolExecution(data.confirmationData.id, userConfirmed);
});
```

### Aborting Streams

```typescript
// Start a message
const messagePromise = chatEngine.sendMessage('Tell me a long story...');

// Abort if needed
chatEngine.abort();

// The promise will reject with an abort error
try {
  await messagePromise;
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Stream was aborted');
  }
}
```

## API Reference

### ChatEngine

#### Constructor Options

```typescript
interface ChatEngineConfig {
  apiUrl: string; // Base API URL
  authToken?: string | (() => string | Promise<string>); // Auth token or getter
  conversationId?: string | number; // Initial conversation ID
  onAuthError?: () => void; // Called on auth errors
  debug?: boolean; // Enable debug logging
}
```

#### Methods

- `createConversation(title?: string): Promise<Conversation>` - Create a new conversation
- `sendMessage(content: string, conversationId?: string | number): Promise<void>` - Send a message and stream the response
- `confirmToolExecution(confirmationId: string, confirmed: boolean, conversationId?: string | number): Promise<any>` - Confirm or reject tool execution
- `abort(): void` - Abort the current stream
- `getMessages(): Message[]` - Get all messages in memory
- `clearMessages(): void` - Clear message history
- `getCurrentConversationId(): string | number | null` - Get current conversation ID
- `setCurrentConversationId(id: string | number): void` - Set current conversation ID
- `destroy(): void` - Clean up resources

#### Events

- `stream:start` - Stream started
- `stream:userMessage` - User message added
- `stream:assistantStart` - Assistant message started
- `stream:assistantContinuationStart` - Assistant continuing previous message
- `stream:textChunk` - Text chunk received
- `stream:toolUse` - Tool invoked
- `stream:toolExecutionStart` - Tool execution started
- `stream:toolExecutionComplete` - Tool execution completed
- `stream:confirmationRequired` - Confirmation needed for tool
- `stream:complete` - Stream completed successfully
- `stream:error` - Stream error occurred
- `stream:abort` - Stream was aborted

## Testing

### Run Tests

```bash
# Run mock server (in one terminal)
npm run test:mock

# Run tests (in another terminal)
npm test

# Or test in browser
npm run test:browser
```

### Using the Mock Server

The package includes a mock SSE server for testing:

```bash
npm run test:mock
```

This starts a server on `http://localhost:3000` that simulates AI chat streaming responses.

## React Native Support

The library uses only JavaScript standard APIs and has no DOM dependencies, making it fully compatible with React Native.

```typescript
// In React Native
import { ChatEngine } from '@smartlabormanagement/smartee';

// Use exactly the same as in web
const chatEngine = new ChatEngine({
  apiUrl: 'https://api.example.com/v3',
  authToken: await getAuthToken(),
});
```

## License

MIT