npm package: @pivoty/viken-core
Description: Core client library for Viken AI coding assistant
Author: Viken Team
Latest version: 0.0.1

# @viken/core

<p align="center">
  <img src="https://raw.githubusercontent.com/viken/viken-js/main/assets/logo.png" alt="Viken Logo" width="200" />
</p>

<p align="center">
  <strong>TypeScript/JavaScript client for Viken AI coding assistant</strong>
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/@viken/core"><img src="https://img.shields.io/npm/v/@viken/core.svg?style=flat-square" alt="npm version" /></a>
  <a href="https://www.npmjs.com/package/@viken/core"><img src="https://img.shields.io/npm/dm/@viken/core.svg?style=flat-square" alt="npm downloads" /></a>
  <a href="https://github.com/viken/viken-js/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@viken/core.svg?style=flat-square" alt="license" /></a>
  <a href="https://github.com/viken/viken-js/actions"><img src="https://img.shields.io/github/actions/workflow/status/viken/viken-js/ci.yml?branch=main&style=flat-square" alt="build status" /></a>
  <a href="https://codecov.io/gh/viken/viken-js"><img src="https://img.shields.io/codecov/c/github/viken/viken-js?style=flat-square" alt="coverage" /></a>
  <a href="https://bundlephobia.com/package/@viken/core"><img src="https://img.shields.io/bundlephobia/minzip/@viken/core?style=flat-square" alt="bundle size" /></a>
</p>

<p align="center">
  <a href="https://viken.dev/docs">Documentation</a> •
  <a href="https://viken.dev/docs/getting-started">Getting Started</a> •
  <a href="https://viken.dev/docs/api">API Reference</a> •
  <a href="https://github.com/viken/viken-js/tree/main/examples">Examples</a>
</p>

---

@viken/core is the official TypeScript/JavaScript client library for interacting with the Viken AI coding assistant API. It provides real-time streaming, task notifications, and a powerful event system for building AI-powered development tools.

## Features

- 🚀 **Real-time streaming** - Stream AI responses as they're generated
- 🔔 **Task notifications** - Get notified when tasks are completed
- 🔄 **Auto-reconnection** - Automatic WebSocket reconnection with exponential backoff
- 📦 **Multiple transports** - WebSocket, TCP, and Unix socket support
- 🔐 **JWT authentication** - Secure API access with token-based auth
- 📝 **Full TypeScript support** - Complete type definitions included
- 🌐 **Browser & Node.js** - Works in both environments

## Installation

```bash
npm install @viken/core
# or
yarn add @viken/core
# or
pnpm add @viken/core
```

## Quick Start

```typescript
import { VikenClient } from '@viken/core';

// Create a client instance
const client = new VikenClient({
  host: 'localhost',
  port: 7456,
  auth: {
    token: 'your-jwt-token'
  }
});

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

// Create a session
const session = await client.createSession({
  provider: {
    type: 'openai',
    apiKey: 'your-api-key',
    model: 'gpt-4'
  }
});

// Send a message with streaming
const stream = await client.sendMessage(session.id, {
  content: 'Create a React counter component',
  stream: true
});

// Handle streaming updates
stream.on('delta', (delta) => {
  console.log('AI:', delta);
});

stream.on('tool', (tool) => {
  console.log('Tool execution:', tool.name, tool.parameters);
});

stream.on('complete', (message) => {
  console.log('Message complete:', message);
});

// Listen for task notifications
client.on('notification', (notification) => {
  if (notification.type === 'task.completed') {
    console.log('Task completed:', notification.task.summary);
    console.log('Files changed:', notification.task.fileChanges);
  }
});
```

## API Reference

### VikenClient

The main client class for interacting with the Viken API.

#### Constructor Options

```typescript
interface VikenClientOptions {
  host?: string;        // Default: 'localhost'
  port?: number;        // Default: 7456
  transport?: 'websocket' | 'tcp' | 'unix';  // Default: 'websocket'
  auth?: AuthOptions;   // JWT authentication options
  reconnect?: boolean;  // Default: true
  reconnectInterval?: number;  // Default: 1000ms
  reconnectMaxAttempts?: number;  // Default: 10
}
```

#### Methods

- `connect(): Promise<void>` - Connect to the Viken server
- `disconnect(): Promise<void>` - Disconnect from the server
- `createSession(options: CreateSessionOptions): Promise<Session>` - Create a new chat session
- `getSession(id: string): Promise<Session>` - Get a session by ID
- `listSessions(options?: SessionListOptions): Promise<Session[]>` - List all sessions
- `updateSession(id: string, options: UpdateSessionOptions): Promise<Session>` - Update a session
- `deleteSession(id: string): Promise<void>` - Delete a session
- `sendMessage(sessionId: string, options: SendMessageOptions): Promise<Message | MessageStream>` - Send a message
- `listMessages(sessionId: string, options?: MessageListOptions): Promise<Message[]>` - List messages in a session

#### Events

The client extends EventEmitter and emits the following events:

- `connection.opened` - WebSocket connection established
- `connection.closed` - Connection closed
- `connection.error` - Connection error occurred
- `connection.reconnecting` - Attempting to reconnect
- `connection.reconnected` - Successfully reconnected
- `notification` - Server notification received
- `error` - General error occurred

### Types

See the [types directory](./src/types) for all available TypeScript types.

## Advanced Usage

### Custom Transport

```typescript
import { VikenClient, TCPTransport } from '@viken/core';

const client = new VikenClient({
  transport: new TCPTransport({
    host: '192.168.1.100',
    port: 7456
  })
});
```

### Error Handling

```typescript
try {
  await client.connect();
} catch (error) {
  if (error.code === 'ECONNREFUSED') {
    console.error('Viken server is not running');
  } else if (error.code === 'AUTHENTICATION_ERROR') {
    console.error('Invalid authentication token');
  }
}

// Global error handler
client.on('error', (error) => {
  console.error('Client error:', error);
});
```

### Task Notifications

```typescript
// Listen for all task lifecycle events
client.on('notification', (notification) => {
  switch (notification.type) {
    case 'task.detected':
      console.log('New task:', notification.task.summary);
      break;
    
    case 'task.progress':
      console.log(`Task ${notification.taskId}: ${notification.progress}%`);
      break;
    
    case 'task.completed':
      console.log('Task completed:', notification.task);
      // Show notification to user
      showNotification({
        title: 'Task Completed',
        body: notification.task.summary,
        actions: notification.task.fileChanges.map(f => f.path)
      });
      break;
  }
});
```

## Contributing

See the main [Viken repository](https://github.com/viken/viken) for contribution guidelines.

## License

MIT