npm package: @kyraak/sdk
Description: Build conversational AI agents with maximum flexibility - Open Source TypeScript SDK for Kyraak
Author: Prayag Dave
Latest version: 1.0.0-beta.1

# @kyraak/sdk

**Build conversational AI agents with maximum flexibility.**

Open-source TypeScript SDK for Kyraak Platform. MIT License.

## Philosophy

We believe developers should have **full creative freedom**. This SDK is designed to **get out of your way**:

- ✅ **Use what you need** - Pick helpers or go raw
- ✅ **Zero magic** - Everything is explicit
- ✅ **Escape hatches** - Direct platform API access always available
- ✅ **No lock-in** - SDK is optional, extend freely
- ✅ **Open source** - MIT License, fork and customize

## Installation

```bash
npm install @kyraak/sdk
```

## Quick Start

### Level 1: Function-based (Simplest)

Perfect for simple agents:

```typescript
import { createAgent } from '@kyraak/sdk';

export default createAgent({
  metadata: {
    name: 'Fitness Coach',
    description: 'Your personal fitness companion'
  },
  
  async onMessage({ content, user }, context) {
    // Use AI helper
    const reply = await context.ai.chat({
      message: content,
      system: 'You are a friendly fitness coach'
    });
    
    return reply;
  }
});
```

### Level 2: Class-based (More Structure)

Better for complex agents with state:

```typescript
import { Agent, type IncomingMessage } from '@kyraak/sdk';

export default class FitnessCoach extends Agent {
  metadata = {
    name: 'Fitness Coach',
    description: 'Your personal fitness companion'
  };

  async onMessage({ content, user }: IncomingMessage) {
    // Access memory (per-user state)
    const goals = await this.memory.get('fitness_goals') || [];
    
    // Use AI with conversation history
    const history = await this.getHistory();
    const reply = await this.ai.chatWithHistory(
      content,
      history,
      `You are a fitness coach. User's goals: ${goals.join(', ')}`
    );
    
    // Send response
    return reply;
  }

  async onUserSubscribe(user: User) {
    await this.send('Welcome! Let\'s set your fitness goals.');
  }
}
```

### Level 3: Raw Access (Maximum Power)

Full control over platform APIs:

```typescript
import { createTelegramClient, type AgentContext } from '@kyraak/sdk';

export async function handler(req: any, context: AgentContext) {
  // Create raw Telegram client
  const telegram = createTelegramClient(process.env.BOT_TOKEN!);
  
  // Use Telegram-specific features
  await telegram.sendMessage(context.userId, 'Choose your plan:', {
    parse_mode: 'HTML',
    reply_markup: {
      inline_keyboard: [
        [
          { text: '🏃 Beginner', callback_data: 'plan:beginner' },
          { text: '💪 Advanced', callback_data: 'plan:advanced' }
        ],
        [
          { text: '🔥 Elite', callback_data: 'plan:elite' }
        ]
      ]
    }
  });
  
  // Access memory directly
  await context.memory.set(context.userId, 'onboarding_step', 2);
  
  // Call AI directly
  const insights = await context.ai.complete(
    'Analyze this workout data and give 3 insights: ...',
    { model: 'gpt-4', temperature: 0.3 }
  );
}
```

## Core Concepts

### AgentContext

Your agent receives a runtime context with everything it needs:

```typescript
interface AgentContext {
  // Agent info
  agentId: number;
  agentName: string;
  
  // Current request
  userId: string;
  platform: string;  // 'telegram' | 'discord' | 'slack' | 'whatsapp'
  
  // Built-in services
  memory: Memory;    // Per-user state storage
  ai: AI;            // LLM capabilities
  clients: {         // Raw platform APIs
    telegram?: TelegramClient;
    discord?: DiscordClient;
    slack?: SlackClient;
    whatsapp?: WhatsAppClient;
  };
  
  // Helper methods
  sendMessage(msg: OutgoingMessage): Promise<void>;
  getHistory(userId: string, limit?: number): Promise<Message[]>;
  
  // Environment & logging
  env: Record<string, string>;
  log: Logger;
}
```

### Memory API

Per-user key-value storage:

```typescript
// Raw access
await context.memory.set(userId, 'key', value);
const data = await context.memory.get(userId, 'key');

// Using helper (in Agent class)
await this.memory.set('goals', ['lose weight', 'gain muscle']);
const goals = await this.memory.get('goals');

// Advanced operations
await this.memory.increment('workout_count');
await this.memory.push('history', newEntry);
await this.memory.update('profile', { age: 30 });
```

### AI API

LLM capabilities:

```typescript
// Simple chat
const reply = await context.ai.chat({
  message: 'What should I eat?',
  system: 'You are a nutrition expert'
});

// With conversation history
const reply = await context.ai.chat({
  message: 'Tell me more',
  messages: history,  // Previous conversation
  model: 'gpt-4',
  temperature: 0.7
});

// Helpers (in Agent class)
const summary = await this.ai.summarize(longText, 100);
const sentiment = await this.ai.analyzeSentiment(message);
const data = await this.ai.extract(text, {
  name: 'person name',
  email: 'email address'
});
```

### Platform Clients

Direct access to platform APIs:

```typescript
// Telegram
const telegram = context.clients.telegram!;
await telegram.sendPhoto(chatId, photoUrl, { caption: 'Check this out!' });
await telegram.sendChatAction(chatId, 'typing');
await telegram.setMyCommands([
  { command: 'start', description: 'Start the bot' },
  { command: 'help', description: 'Get help' }
]);

// Or create standalone client
import { createTelegramClient } from '@kyraak/sdk';
const telegram = createTelegramClient(botToken);
await telegram.call('sendPoll', {
  chat_id: chatId,
  question: 'How do you feel?',
  options: ['Great', 'Good', 'Okay', 'Bad']
});
```

## Examples

### Stateful Conversation

```typescript
export default class Therapist extends Agent {
  async onMessage({ content }: IncomingMessage) {
    // Load conversation history
    const history = await this.getHistory(10);
    
    // Get user's emotional state from memory
    const mood = await this.memory.get('current_mood');
    
    // Build conversational AI
    const reply = await this.conversation()
      .system('You are a compassionate therapist')
      .history(history)
      .withTemperature(0.8)
      .send(content);
    
    return reply;
  }
}
```

### Proactive Messages (Scheduled Tasks)

```typescript
export default class WorkoutReminder extends Agent {
  // Define scheduled tasks
  schedule = {
    morning: {
      cron: '0 9 * * *',  // 9 AM daily
      handler: async (userId: string) => {
        const plan = await this.memory.get('workout_plan');
        await this.send(`Good morning! Today's workout: ${plan}`);
      }
    },
    weekly: {
      cron: '0 20 * * 0',  // 8 PM every Sunday
      handler: async (userId: string) => {
        const stats = await this.memory.get('weekly_stats');
        await this.send(`Week recap: You crushed ${stats.workouts} workouts! 🔥`);
      }
    }
  };
}
```

### Multi-Platform Support

```typescript
export default createAgent({
  async onMessage({ content, user }, context) {
    // Platform-agnostic response
    const reply = await context.ai.chat({ message: content });
    
    // Platform-specific features
    if (context.platform === 'telegram') {
      await context.clients.telegram!.sendMessage(user.id, reply, {
        reply_markup: TelegramBotClient.inlineKeyboard([[
          { text: 'Continue', callback_data: 'continue' }
        ]])
      });
    } else if (context.platform === 'discord') {
      await context.clients.discord!.sendMessage(user.id, {
        content: reply,
        embeds: [{ title: 'Fitness Tip', color: 0x00ff00 }]
      });
    } else {
      return reply;  // Fallback for other platforms
    }
  }
});
```

### Complex State Management

```typescript
export default class GoalTracker extends Agent {
  async onMessage({ content }: IncomingMessage) {
    // Check intent
    const intent = await this.ai.detectIntent(content, [
      'set_goal', 'check_progress', 'update_goal', 'delete_goal'
    ]);
    
    switch (intent) {
      case 'set_goal':
        const goal = await this.ai.extract(content, {
          name: 'goal name',
          target: 'target amount',
          deadline: 'deadline date'
        });
        await this.memory.push('goals', goal);
        return `Goal set: ${goal.name}`;
      
      case 'check_progress':
        const goals = await this.memory.get('goals') || [];
        return `You have ${goals.length} active goals.`;
      
      default:
        return await this.ai.chat(content);
    }
  }
}
```

## API Reference

### Core Types

- `User` - User information
- `Message` - Conversation message
- `IncomingMessage` - Message from user
- `OutgoingMessage` - Message to user
- `AgentMetadata` - Agent configuration
- `AgentContext` - Runtime context

### Platform Clients

- `TelegramBotClient` - Full Telegram Bot API
- `DiscordClient` - Discord API (coming soon)
- `SlackClient` - Slack API (coming soon)
- `WhatsAppClient` - WhatsApp API (coming soon)

### Helpers

- `MemoryStore` - Memory utilities
- `AIHelper` - AI utilities
- `AIConversation` - Conversation builder

### Base Classes

- `Agent` - Optional base class
- `createAgent()` - Function-based agent

## Philosophy: Why This Design?

Most SDKs force you into their abstractions. We don't.

**Traditional SDK:**
```typescript
// ❌ Forced into framework patterns
class MyAgent extends Framework {
  @Inject() memory: Memory;
  @Handler('message') handleMessage() { ... }
}
```

**Kyraak SDK:**
```typescript
// ✅ You decide how to structure code
export function handler(msg, context) {
  // Use helpers if you want
  const reply = await context.ai.chat({ message: msg.content });
  
  // Or go raw if you need
  await context.clients.telegram.call('sendAnimation', { ... });
  
  return reply;
}
```

**We give you:**
- 🎨 **Creative freedom** - Structure code your way
- 🔧 **Full power** - Access all platform features
- 🚀 **Easy start** - Helpers for common tasks
- ⚡ **Zero overhead** - Thin wrappers, no magic
- 🔓 **No lock-in** - Fork, extend, customize

## Contributing

This SDK is open source (MIT License). Contributions welcome!

```bash
# Clone repo
git clone https://github.com/prayagdave25/kyraak-platform
cd kyraak-platform/packages/sdk

# Install deps
npm install

# Build
npm run build

# Publish (maintainers only)
npm publish
```

## License

MIT License - See LICENSE file

## Links

- **Platform**: https://kyraak.app
- **Docs**: https://docs.kyraak.app
- **GitHub**: https://github.com/prayagdave25/kyraak-platform
- **Discord**: https://discord.gg/kyraak (coming soon)

---

Built with ❤️ by developers, for developers.