---
title: Keiko
---

Keiko (hereinafter the "Application") is a private Discord bot that serves as Naomi's personal AI assistant, providing intelligent conversational assistance powered by Anthropic's Claude AI with integrated web search capabilities.

## 1. User Documentation

This section is for those interacting with a live instance of the Application.

### 1.1. Getting Started

Keiko is available through Discord and can be interacted with in multiple ways:

- **Direct Messages (DM)**: Send a direct message to Keiko to start a private conversation
- **Guild/Server Messages**: Mention @Keiko in a server where the bot is present
- **Thread Messages**: Participate in threads created by Keiko

### 1.2. Access Requirements

- **Primary User**: Naomi (User ID: 465650873650118659) has full access to all features
- **Subscribers**: Other users require an active Discord entitlement (premium subscription) to interact with Keiko
- **Unauthorized Users**: Will receive a prompt to purchase a premium subscription

### 1.3. Available Commands

#### `/dm`
Reopens or initiates a direct message conversation with Keiko.

**Usage**: `/dm`

**Example**:
```
/dm
```

#### `/clear`
Clears the conversation history in the current channel or thread. This inserts a marker message that prevents Keiko from accessing previous messages in the conversation context.

**Usage**: `/clear`

**Example**:
```
/clear
```

### 1.4. Conversational Features

#### Message Handling
- Keiko maintains conversation context by reading the last 20 messages in the channel/thread
- Responses are automatically chunked into 2000-character segments for readability
- Keiko will show typing indicators while processing your request
- Multiple message chunks are delivered with a 2.5-second delay between them

#### Web Search Integration
- Keiko can search the web to provide up-to-date information
- Web search is automatically invoked when needed (up to 5 searches per request)
- Citations and sources are included in responses when available

#### Cost Display
- Each response includes token usage statistics
- Input and output token counts are displayed
- Estimated API costs are shown for transparency

### 1.5. Keiko's Personality

Keiko is designed with a calm, demure, and reserved personality. She conducts herself like a butler - always polite, respectful, and ready to serve. Her primary role is to provide clinical and unbiased information in response to requests, with an emphasis on including sources and links to confirm claims.

### 1.6. Getting Help

If you encounter any issues or need support:
- Visit the community server: [chat.nhcarrigan.com](https://chat.nhcarrigan.com)
- Open an issue on the GitHub repository
- Contact via email: contact@nhcarrigan.com

## 2. Technical Documentation

This section is for those interested in running their own instance of the Application.

### 2.1. Prerequisites

Before setting up Keiko, ensure you have the following:

- **Node.js**: Latest LTS version recommended
- **npm**: Package manager (comes with Node.js)
- **Discord Bot**: A registered Discord application with bot token
- **Anthropic API Key**: Access to Claude AI API
- **1Password CLI** (optional): For secure environment variable management

### 2.2. Technology Stack

- **Runtime**: Node.js with ES Modules
- **Language**: TypeScript 5.9.3
- **Discord Framework**: discord.js v14.23.2
- **AI Integration**: @anthropic-ai/sdk v0.65.0
- **Web Server**: Fastify v5.6.1
- **Logging**: @nhcarrigan/logger v1.1.1
- **Analytics**: @nhcarrigan/discord-analytics v0.0.6

### 2.3. Installation

1. **Clone the repository**:
```bash
git clone <repository-url>
cd keiko
```

2. **Install dependencies**:
```bash
npm install
```

3. **Configure environment variables**:

Create a `prod.env` file in the root directory with the following variables:

```env
DISCORD_TOKEN=your_discord_bot_token
AI_TOKEN=your_anthropic_api_key
LOG_TOKEN=your_logging_token (optional)
```

Alternatively, you can set these as system environment variables.

### 2.4. Configuration

#### Discord Bot Setup

1. Create a Discord application at [Discord Developer Portal](https://discord.com/developers/applications)
2. Enable the following Gateway Intents:
   - DirectMessages
   - MessageContent
   - GuildMessages
   - Guilds
3. Generate a bot token and add it to your environment configuration
4. Invite the bot to your server with appropriate permissions

#### AI Configuration

The AI model configuration is set in the codebase (src/modules/makeAiRequest.ts:29):
- **Model**: claude-sonnet-4-5-20250929
- **Max Tokens**: 3000
- **Temperature**: 1
- **Web Search**: Enabled (max 5 uses per request)

#### Personality Customization

Edit `src/config/personality.ts` to customise Keiko's personality and behaviour.

#### User Authorization

Update `src/utils/isNaomi.ts:15` to configure authorised user IDs and SKU IDs for subscription management.

### 2.5. Building the Application

Compile TypeScript to JavaScript:

```bash
npm run build
```

This will:
- Remove the existing `prod` directory
- Compile TypeScript files to the `prod` directory

### 2.6. Running the Application

#### With 1Password CLI:
```bash
npm start
```

This uses 1Password CLI to inject environment variables from `prod.env`.

#### Without 1Password CLI:
```bash
node prod/index.js
```

Ensure environment variables are set in your system before running.

### 2.7. Development

#### Linting

Run ESLint to check code quality:

```bash
npm run lint
```

#### Testing

Currently, tests are not implemented:

```bash
npm test
```

### 2.8. Project Structure

```
keiko/
├── src/
│   ├── commands/          # Slash command definitions
│   │   ├── clear.ts       # Clear history command
│   │   └── dm.ts          # DM command
│   ├── config/            # Configuration files
│   │   └── personality.ts # AI personality definition
│   ├── events/            # Discord event handlers
│   │   ├── handleDmMessage.ts
│   │   ├── handleGuildMessage.ts
│   │   ├── handleThreadMessage.ts
│   │   └── onMessage.ts
│   ├── modules/           # Core business logic
│   │   ├── clear.ts       # Clear command logic
│   │   ├── dm.ts          # DM command logic
│   │   ├── makeAiRequest.ts    # AI request handler
│   │   └── sendAiResponse.ts   # Response chunking
│   ├── server/            # Web server
│   │   └── serve.ts       # Fastify health check server
│   ├── utils/             # Utility functions
│   │   ├── ai.ts          # Anthropic client
│   │   ├── calculateCost.ts
│   │   ├── isNaomi.ts     # Authorization
│   │   ├── logger.ts
│   │   ├── replyToError.ts
│   │   └── sleep.ts
│   └── index.ts           # Main entry point
├── prod/                  # Compiled JavaScript (generated)
├── package.json
├── tsconfig.json
├── prod.env              # Environment variables
└── LICENSE.md
```

### 2.9. Monitoring and Health Checks

Keiko runs a Fastify web server on port 3333 that provides:
- Health check endpoint at `GET /`
- Basic bot information page
- Uptime monitoring capability

### 2.10. Error Handling

The application includes:
- Global unhandled rejection handler
- Global uncaught exception handler
- User-facing error messages with support links
- Comprehensive logging via @nhcarrigan/logger

### 2.11. Analytics

Discord analytics are tracked for:
- Direct messages
- Guild messages
- Thread messages
- Token usage and API costs per interaction

### 2.12. Deployment

**Recommended Environment**:
- Linux server (tested on Arch Linux 6.17.5-arch1-1)
- Node.js runtime
- Process manager (e.g., PM2, systemd)

**Deployment Steps**:

1. Clone and configure the repository
2. Build the application
3. Set up environment variables
4. Run with a process manager for reliability
5. Configure monitoring for the health check endpoint (port 3333)

## 3. Legal Documentation

This section is for expansions to our legal policies specific to the Application.

### 3.1. License

This software is licensed under [Naomi's Public Licence](https://docs.nhcarrigan.com/#/license).

Copyright held by Naomi Carrigan.

### 3.2. Privacy and Data Handling

#### Data Collection

Keiko collects and processes the following data:
- Discord user IDs for authorisation
- Message content for conversation context (last 20 messages)
- Discord entitlement information for subscription management
- Analytics data (message counts, token usage, API costs)

#### Data Retention

- **Conversation History**: Stored temporarily in memory during active sessions
- **Message Context**: Fetched on-demand from Discord's API (last 20 messages)
- **No Persistent Storage**: Keiko does not maintain a traditional database

#### Third-Party Services

Keiko integrates with:
- **Discord**: For bot functionality and message delivery
- **Anthropic**: For AI-powered responses (Claude AI)
- **Web Search Services**: For retrieving up-to-date information

User messages and conversation context are sent to these services for processing.

### 3.3. Terms of Use

#### Authorized Use

- Keiko is a private assistant primarily designed for Naomi's personal use
- Subscription-based access is available for authorised users
- Unauthorized access attempts will be rejected

#### Service Availability

- The Application is provided "as is" without warranties
- Service availability is not guaranteed
- Features and functionality may change without notice

#### Acceptable Use

Users must:
- Comply with Discord's Terms of Service
- Use the bot for lawful purposes only
- Respect the bot's intended functionality
- Not attempt to abuse, exploit, or reverse engineer the service

### 3.4. API Usage and Costs

- AI interactions incur costs via the Anthropic API
- Token usage and costs are displayed transparently to users
- Excessive usage may be rate-limited or restricted

## 4. Contributing Documentation

This section is for documentation related to contributing to the Application's codebase.

### 4.1. How to Contribute

We welcome contributions to Keiko! Here's how you can help:

1. **Fork the repository** on GitHub
2. **Create a feature branch** for your changes
3. **Make your changes** following our coding standards
4. **Test your changes** thoroughly
5. **Submit a Pull Request** with a clear description of your changes

### 4.2. Contributing Guidelines

Please review our comprehensive contributing guidelines:

[Contributing Guidelines](https://docs.nhcarrigan.com/#/contributing)

### 4.3. Code of Conduct

Before interacting with our community, please read our Code of Conduct:

[Code of Conduct](https://docs.nhcarrigan.com/#/coc)

### 4.4. Development Setup

1. **Clone the repository**:
```bash
git clone <repository-url>
cd keiko
```

2. **Install dependencies**:
```bash
npm install
```

3. **Set up environment variables** (see Technical Documentation section)

4. **Run the linter**:
```bash
npm run lint
```

5. **Build the project**:
```bash
npm run build
```

### 4.5. Coding Standards

- **Language**: TypeScript
- **Module System**: ES Modules
- **Linting**: ESLint with @nhcarrigan/eslint-config
- **Type Checking**: Strict TypeScript configuration
- **Code Style**: Follow existing patterns in the codebase

### 4.6. Pull Request Guidelines

When submitting a Pull Request:

- **Clear Description**: Explain what your changes do and why
- **Reference Issues**: Link to any related issues
- **Test Your Changes**: Ensure the bot builds and runs correctly
- **Follow Conventions**: Match the existing code style
- **Small, Focused Changes**: Keep PRs focused on a single feature or fix

### 4.7. Areas for Contribution

Potential areas where contributions are welcome:

- **Testing**: Implement unit and integration tests
- **Documentation**: Improve or expand documentation
- **Features**: Add new commands or capabilities
- **Bug Fixes**: Fix reported issues
- **Performance**: Optimise existing functionality
- **Error Handling**: Improve error messages and handling

### 4.8. Reporting Issues

If you find a bug or have a feature request:

1. **Check existing issues** to avoid duplicates
2. **Create a detailed issue** with:
   - Clear title
   - Description of the problem or feature
   - Steps to reproduce (for bugs)
   - Expected vs actual behaviour
   - Environment details (if applicable)

### 4.9. Getting Help

Need help contributing?

- Join our community: [chat.nhcarrigan.com](https://chat.nhcarrigan.com)
- Email: contact@nhcarrigan.com
- Check the documentation: [docs.nhcarrigan.com](https://docs.nhcarrigan.com)

### 4.10. Recognition

Contributors will be:
- Acknowledged in Pull Request comments
- Listed in project contributors (if applicable)
- Appreciated for their time and effort!

## Appendix

### A.1. Key File References

- **Main Entry Point**: src/index.ts:1
- **AI Request Handler**: src/modules/makeAiRequest.ts:29
- **Authorization Logic**: src/utils/isNaomi.ts:15
- **Personality Configuration**: src/config/personality.ts:11
- **Message Router**: src/events/onMessage.ts:1

### A.2. Important Constants

- **Bot ID**: 1425897287065800785
- **Naomi's User ID**: 465650873650118659
- **SKU ID**: 1425905043244060762
- **Health Check Port**: 3333
- **Max Context Messages**: 20
- **Max AI Tokens**: 3000
- **Message Chunk Size**: 2000 characters
- **Chunk Delay**: 2.5 seconds

### A.3. External Resources

- **Community**: https://chat.nhcarrigan.com
- **Documentation**: https://docs.nhcarrigan.com
- **License**: https://docs.nhcarrigan.com/#/license
- **Contributing**: https://docs.nhcarrigan.com/#/contributing
- **Code of Conduct**: https://docs.nhcarrigan.com/#/coc
- **Contact Email**: contact@nhcarrigan.com
