open-index/open-npm huggingface dataset:
npm package: @orient-bot/agents
Description: AI agent services for the Orient
Latest version: 1.1.0

# @orient-bot/agents

AI agent services for the Orient.

## Overview

This package provides:

- **AgentService** - Core agent orchestration and message processing
- **ToolCallingService** - Tool execution and loop management
- **AgentRegistry** - Dynamic agent configuration and context resolution
- **ProgressiveResponder** - Streaming response handling

## Installation

```bash
pnpm add @orient-bot/agents
```

## Usage

```typescript
import { AgentService, ToolCallingService, AgentRegistry } from '@orient-bot/agents';

// Initialize the agent service
const agentService = new AgentService({
  anthropicApiKey: process.env.ANTHROPIC_API_KEY,
  // ...
});

// Process a message
const response = await agentService.processMessage(
  'What issues are in progress?',
  userId,
  channelId
);
```

## Migration Status

This package contains services migrated from `src/services/`:

- `agentService.ts` - Core agent service
- `whatsappAgentService.ts` - WhatsApp-specific agent
- `toolCallingService.ts` - Tool execution
- `agentRegistry.ts` - Agent configuration
- `agentContextLoader.ts` - Context loading
- `toolDiscovery.ts` - Tool discovery
- `toolRegistry.ts` - Tool registration
- `progressiveResponder.ts` - Streaming responses
- `contextService.ts` - Context management
npm package: @orient-bot/api-gateway
Description: REST API gateway for Orient - webhooks, scheduler, and health monitoring
Latest version: 1.1.0

# @orient-bot/api-gateway

REST API gateway for the Orient.

## Features

- **Scheduler Service**: Cron-based message scheduling
- **Webhook Forwarding**: Route incoming webhooks to handlers
- **Health Monitoring**: Service health checks and metrics
- **Notification Dispatch**: Send messages across platforms

## Installation

```bash
pnpm add @orient-bot/api-gateway
```

## Usage

```typescript
import { createApiServer, SchedulerService } from '@orient-bot/api-gateway';
import { loadConfig } from '@orient-bot/core';

const config = loadConfig();
const server = createApiServer(config);

// Start scheduler
const scheduler = new SchedulerService(config);
await scheduler.start();

// Start API server
server.listen(4098);
```

## API Endpoints

| Endpoint         | Method    | Description               |
| ---------------- | --------- | ------------------------- |
| `/health`        | GET       | System health status      |
| `/api/schedules` | GET, POST | Manage scheduled messages |
| `/api/webhooks`  | GET, POST | Manage webhook forwards   |
| `/webhook/*`     | POST      | Incoming webhook handler  |

## Scheduled Messages

```json
{
  "name": "Daily standup reminder",
  "cronExpression": "30 9 * * 1-5",
  "targetType": "slack",
  "targetId": "#standup",
  "message": "Time for standup! 🚀"
}
```

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Start server (development)
pnpm dev

# Start server (production)
pnpm start
```

## Docker

This package includes a per-package Dockerfile for containerized deployment:

```bash
# Build the Docker image
docker build -t orienter-api-gateway -f packages/api-gateway/Dockerfile .

# Run the container
docker run -d \
  --name api-gateway \
  -p 4100:4100 \
  orienter-api-gateway
```

For full stack deployment:

```bash
docker compose -f docker/docker-compose.v2.yml --profile api up -d
```
npm package: @orient-bot/apps
Description: Mini-apps system for the Orient
Latest version: 1.1.0

# @orient-bot/apps

Mini-apps system for the Orient.

## Overview

This package provides the infrastructure for creating, managing, and running mini-applications within the Orient ecosystem.

Features:

- **AppsService** - Core app management (create, list, update, delete)
- **AppGeneratorService** - AI-powered app generation from prompts
- **AppGitService** - Git worktree management for app development
- **AppRuntimeService** - Runtime for executing apps
- **MiniappEditService** - In-browser app editing via OpenCode
- **SkillsService** - Skill management for agents

## Installation

```bash
pnpm add @orient-bot/apps
```

## Usage

```typescript
import { AppConfig, AppManifest, GeneratedApp } from '@orient-bot/apps';

// App configuration
const appConfig: AppConfig = {
  name: 'my-app',
  description: 'A sample mini-app',
  author: 'user@example.com',
};
```

## Migration Status

This package contains services migrated from `src/services/`:

- `appsService.ts` - App CRUD operations
- `appGeneratorService.ts` - AI app generation
- `appGitService.ts` - Git worktree management
- `appRuntimeService.ts` - App execution
- `miniappEditService.ts` - In-browser editing
- `miniappEditDatabase.ts` - Edit session database
- `skillsService.ts` - Skill management
npm package: @orient-bot/bot-slack
Description: Slack bot service for Orient
Latest version: 1.1.0

# @orient-bot/bot-slack

Slack bot service for the Orient.

## Features

- **Slack Bolt Integration**: Event-driven Slack app framework
- **Socket Mode**: No public URL required
- **Mention Handling**: Respond to @mentions in channels
- **DM Handling**: Direct message conversations
- **Dual-Mode Posting**: Post as bot or as user

## Installation

```bash
pnpm add @orient-bot/bot-slack
```

## Usage

```typescript
import { SlackBotService } from '@orient-bot/bot-slack';
import { loadConfig } from '@orient-bot/core';

const config = loadConfig();
const bot = new SlackBotService(config);

await bot.start();
```

## Configuration

```json
{
  "integrations": {
    "slack": {
      "bot": {
        "token": "${SLACK_BOT_TOKEN}",
        "signingSecret": "${SLACK_SIGNING_SECRET}",
        "appToken": "${SLACK_APP_TOKEN}"
      },
      "standupChannel": "#standup",
      "defaultMode": "bot"
    }
  }
}
```

## Message Flow

```
1. Event received (Slack Bolt)
        │
        ▼
2. Route by event type (mention, DM, command)
        │
        ▼
3. Check permission (channel-based)
        │
        ├── ignored: Drop message
        ├── read_only: Store only
        └── read_write: Process with AI
                │
                ▼
4. Process with OpenCode
        │
        ▼
5. Post response (bot or user token)
```

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Start bot (development)
pnpm dev

# Start bot (production)
pnpm start
```

## Docker

This package includes a per-package Dockerfile for containerized deployment:

```bash
# Build the Docker image
docker build -t orienter-bot-slack -f packages/bot-slack/Dockerfile .

# Run the container
docker run -d \
  --name slack-bot \
  -e SLACK_BOT_TOKEN=xoxb-... \
  -e SLACK_SIGNING_SECRET=... \
  -e SLACK_APP_TOKEN=xapp-... \
  orienter-bot-slack
```

For full stack deployment with Slack profile:

```bash
docker compose -f docker/docker-compose.v2.yml --profile slack up -d
```
npm package: @orient-bot/bot-whatsapp
Description: WhatsApp bot service for Orient
Latest version: 1.1.0

# @orient-bot/bot-whatsapp

WhatsApp bot service for the Orient.

## Features

- **Baileys Integration**: WhatsApp Web multi-device protocol
- **Message Handling**: Text, media, and poll message processing
- **QR Code Pairing**: Web interface for device pairing
- **Health Monitoring**: Connection health checks with auto-reconnect

## Installation

```bash
pnpm add @orient-bot/bot-whatsapp
```

## Usage

```typescript
import { WhatsAppBotService } from '@orient-bot/bot-whatsapp';
import { loadConfig } from '@orient-bot/core';

const config = loadConfig();
const bot = new WhatsAppBotService(config);

await bot.start();
```

## Configuration

```json
{
  "whatsapp": {
    "personal": {
      "enabled": true,
      "adminPhone": "972501234567",
      "sessionPath": "./data/whatsapp-auth",
      "autoReconnect": true,
      "messageRateLimit": 10,
      "allowedGroupIds": []
    }
  }
}
```

## Message Flow

```
1. Message received (Baileys)
        │
        ▼
2. Parse and validate message
        │
        ▼
3. Check permission (read_only, read_write, ignored)
        │
        ├── ignored: Drop message
        ├── read_only: Store only
        └── read_write: Process with AI
                │
                ▼
4. Route to handler (text, media, poll)
        │
        ▼
5. Process with OpenCode (if AI)
        │
        ▼
6. Send response
```

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Start bot (development)
pnpm dev

# Start bot (production)
pnpm start
```

## Docker

This package includes a per-package Dockerfile for containerized deployment:

```bash
# Build the Docker image
docker build -t orienter-bot-whatsapp -f packages/bot-whatsapp/Dockerfile .

# Run the container
docker run -d \
  --name whatsapp-bot \
  -v $(pwd)/data:/app/data \
  -v $(pwd)/logs:/app/logs \
  -p 4097:4097 \
  -p 4098:4098 \
  orienter-bot-whatsapp
```

For full stack deployment, use docker-compose:

```bash
docker compose -f docker/docker-compose.v2.yml up -d bot-whatsapp
```
npm package: @orient-bot/core
Description: Shared utilities, types, and configuration for Orient
Latest version: 1.1.0

# @orient-bot/core

Shared utilities, types, and configuration for the Orient.

## Features

- **Configuration**: Zod-validated configuration with environment variable substitution
- **Logger**: Structured logging with Winston, log rotation, and sensitive data redaction
- **Types**: Common type definitions used across all packages
- **Utils**: Utility functions for common operations

## Installation

```bash
pnpm add @orient-bot/core
```

## Usage

### Configuration

```typescript
import { loadConfig, getConfig } from '@orient-bot/core';

// Load configuration from file and environment
const config = loadConfig();

// Access configuration values
console.log(config.organization.name);
console.log(config.integrations.jira.host);
```

### Logger

```typescript
import { createServiceLogger, logger } from '@orient-bot/core';

// Use the main logger
logger.info('Application started');

// Create a service-specific logger
const serviceLog = createServiceLogger('my-service');
serviceLog.info('Service initialized');

// Track operations with timing
const op = serviceLog.startOperation('fetchData');
try {
  await fetchData();
  op.success('Data fetched');
} catch (error) {
  op.failure(error);
}
```

### Types

```typescript
import type { JiraIssue, ChatPermission, WhatsAppMessage } from '@orient-bot/core';

const issue: JiraIssue = {
  id: '10001',
  key: 'PROJ-123',
  summary: 'Example issue',
  // ...
};
```

### Utils

```typescript
import { sleep, retryWithBackoff, formatDuration, isProduction } from '@orient-bot/core';

// Wait for a duration
await sleep(1000);

// Retry with exponential backoff
const result = await retryWithBackoff(
  () => fetchWithRetry(),
  3, // max retries
  1000 // initial delay
);

// Format duration
console.log(formatDuration(125000)); // "2m 5s"

// Environment checks
if (isProduction()) {
  // Production-specific code
}
```

## Configuration File

The config loader looks for configuration in this order:

1. `.mcp.config.local.json`
2. `.mcp.config.json`
3. `mcp-config.json`
4. `config.json`
5. `config/app.json`

Environment variables can be substituted using `${VAR_NAME}` syntax:

```json
{
  "integrations": {
    "jira": {
      "apiToken": "${JIRA_API_TOKEN}"
    }
  }
}
```

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Type check
pnpm typecheck
```
npm package: @orient-bot/dashboard
Description: Dashboard frontend for Orient
Latest version: 1.1.0

# @orient-bot/dashboard

Dashboard package for the Orient.

## Features

- **Dashboard API Server**: Express-based API for dashboard data
- **Health Monitoring**: System health checks and status
- **Stats Aggregation**: Message and usage statistics
- **Chat Management**: Configure chat permissions
- **Schedule Management**: Manage scheduled messages

## Installation

```bash
pnpm add @orient-bot/dashboard
```

## Usage

### Starting the Server

```typescript
import { startDashboardServer } from '@orient-bot/dashboard';

await startDashboardServer({
  port: 3001,
  staticPath: './public',
});
```

### Using the Router

```typescript
import express from 'express';
import { createDashboardRouter } from '@orient-bot/dashboard/server';

const app = express();
app.use('/dashboard/api', createDashboardRouter());
```

## API Endpoints

| Endpoint         | Method | Description             |
| ---------------- | ------ | ----------------------- |
| `/api/health`    | GET    | Health check            |
| `/api/stats`     | GET    | Platform statistics     |
| `/api/chats`     | GET    | List chats              |
| `/api/schedules` | GET    | List scheduled messages |

## Types

The package exports all types for dashboard data:

```typescript
import type {
  HealthStatus,
  PlatformStats,
  ChatConfig,
  ScheduledMessage,
  AuditLogEntry,
} from '@orient-bot/dashboard';
```

## Development

```bash
# Build
pnpm build

# Watch mode
pnpm dev

# Test
pnpm test
```
npm package: @orient-bot/database
Description: Database schemas, migrations, and clients for Orient
Latest version: 1.1.0

# @orient-bot/database

Database schemas, migrations, and clients for the Orient.

## Features

- **Drizzle ORM**: Type-safe database operations with PostgreSQL
- **Schema Definitions**: All tables defined using Drizzle schema
- **Connection Pooling**: Efficient database connections
- **Type Exports**: TypeScript types inferred from schema

## Installation

```bash
pnpm add @orient-bot/database
```

## Usage

### Basic Usage

```typescript
import { getDatabase, schema, eq } from '@orient-bot/database';

// Get database instance
const db = getDatabase();

// Query messages
const messages = await db
  .select()
  .from(schema.messages)
  .where(eq(schema.messages.phone, '1234567890'))
  .limit(10);

// Insert a new message
await db.insert(schema.messages).values({
  direction: 'incoming',
  jid: '1234567890@s.whatsapp.net',
  phone: '1234567890',
  text: 'Hello!',
  isGroup: false,
  timestamp: new Date(),
});
```

### Using Types

```typescript
import type { Message, NewMessage, ChatPermission } from '@orient-bot/database';

const newMessage: NewMessage = {
  direction: 'outgoing',
  jid: '1234567890@s.whatsapp.net',
  phone: '1234567890',
  text: 'Response',
  isGroup: false,
  timestamp: new Date(),
};
```

### Database Configuration

```typescript
import { getDatabase } from '@orient-bot/database';

const db = getDatabase({
  connectionString: process.env.DATABASE_URL,
  maxConnections: 10,
  idleTimeout: 30,
  connectTimeout: 5,
});
```

### Cleanup

```typescript
import { closeDatabase } from '@orient-bot/database';

// Close connection on app shutdown
process.on('SIGTERM', async () => {
  await closeDatabase();
  process.exit(0);
});
```

## Tables

### WhatsApp

- `messages` - Message history
- `groups` - Group metadata
- `chatPermissions` - Per-chat permissions
- `permissionAuditLog` - Permission change history

### Slack

- `slackMessages` - Slack message history
- `slackChannels` - Channel metadata
- `slackChannelPermissions` - Per-channel permissions
- `slackPermissionAuditLog` - Permission change history

### Shared

- `dashboardUsers` - Admin dashboard users
- `systemPrompts` - Custom system prompts per chat
- `scheduledMessages` - Cron-scheduled messages
- `webhookForwards` - Webhook forwarding rules

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Generate migrations
pnpm db:generate

# Run migrations
pnpm db:migrate

# Open Drizzle Studio
pnpm db:studio
```

## Environment Variables

- `DATABASE_URL` - PostgreSQL connection string
- `TEST_DATABASE_URL` - Test database connection (for E2E tests)
npm package: @orient-bot/database-services
Description: Database service implementations for Orient (messages, Slack, scheduler, webhooks)
Latest version: 1.1.0

# @orient-bot/database-services

Database service implementations for the Orient.

## Services

- **MessageDatabase**: WhatsApp message storage and retrieval (SQLite)
- **SlackDatabase**: Slack integration data (PostgreSQL via Drizzle)
- **SchedulerDatabase**: Scheduled message storage (PostgreSQL via Drizzle)
- **WebhookDatabase**: Webhook configuration storage (PostgreSQL via Drizzle)

## Usage

```typescript
import {
  MessageDatabase,
  createSlackDatabase,
  createSchedulerDatabase,
  createWebhookDatabase,
} from '@orient-bot/database-services';

// SQLite message database
const messageDb = new MessageDatabase('./data/messages.db');
await messageDb.initialize();

// PostgreSQL Drizzle-based databases
const slackDb = createSlackDatabase();
const schedulerDb = createSchedulerDatabase();
const webhookDb = createWebhookDatabase();
```

## Directory Structure

```
src/
├── index.ts              # Main exports
├── messageDatabase.ts    # WhatsApp message storage (SQLite)
├── slackDatabase.ts      # Slack integration data
├── schedulerDatabase.ts  # Scheduled messages
└── webhookDatabase.ts    # Webhook configurations
```
npm package: @orient-bot/integrations
Description: External service integrations for Orient (Google, etc.)
Latest version: 1.1.0

# @orient-bot/integrations

External service integrations for the Orient.

## Features

- **Google Integration**: Slides, Sheets, Gmail services

## Usage

```typescript
// Google
import { SlidesService, SheetsService, GmailService } from '@orient-bot/integrations/google';
```

## Directory Structure

```
src/
├── index.ts           # Main exports
└── google/
    ├── index.ts       # Google exports
    ├── slides.ts      # Google Slides service
    ├── sheets.ts      # Google Sheets service
    └── gmail.ts       # Gmail service
```
npm package: @orient-bot/mcp-servers
Description: MCP server implementations for the Orient
Latest version: 1.1.0

# @orient-bot/mcp-servers

MCP (Model Context Protocol) server implementations for the Orient.

## Overview

This package provides:

- **BaseServer** - Base class for MCP server implementations
- **CoreServer** - Core MCP server with standard tools
- **CodingServer** - MCP server for coding agents
- **AssistantServer** - MCP server for assistant agents
- **ToolExecutor** - Tool execution infrastructure
- **ToolFilter** - Tool filtering based on agent context

## Installation

```bash
pnpm add @orient-bot/mcp-servers
```

## Usage

```typescript
import { CoreServer, CodingServer } from '@orient-bot/mcp-servers';

// Create a core server
const coreServer = new CoreServer({
  port: 4099,
  // ...
});

await coreServer.start();
```

## Migration Status

This package contains servers migrated from `src/mcp-servers/`:

- `base-server.ts` - Base server class
- `core-server.ts` - Core server implementation
- `coding-server.ts` - Coding server implementation
- `assistant-server.ts` - Assistant server implementation
- `tool-executor.ts` - Tool execution
- `tool-filter.ts` - Tool filtering
npm package: @orient-bot/mcp-tools
Description: Portable MCP tools and registry for Orient
Latest version: 1.1.0

# @orient-bot/mcp-tools

Portable MCP tools and registry for the Orient.

## Features

- **Base Tool Class**: Abstract class for creating type-safe MCP tools
- **Tool Registry**: Central registry with search and discovery capabilities
- **Tool Context**: Context factory for service injection
- **Category Organization**: Tools organized by domain (messaging, docs, google, system, etc.)

## Installation

```bash
pnpm add @orient-bot/mcp-tools
```

## Usage

### Creating a Tool

```typescript
import { MCPTool, ToolContext } from '@orient-bot/mcp-tools';
import { z } from 'zod';

// Using the base class
class SendSlackDmTool extends MCPTool<{ userId: string; message: string }, { success: boolean }> {
  name = 'slack_send_dm';
  description = 'Send a Slack DM to a user';
  category = 'messaging' as const;
  inputSchema = z.object({
    userId: z.string().describe('Slack user ID'),
    message: z.string().describe('Message to send'),
  });
  keywords = ['slack', 'dm', 'message'];
  useCases = ['Send a direct message to a Slack user'];

  async execute(
    input: { userId: string; message: string },
    context: ToolContext
  ): Promise<{ success: boolean }> {
    // Implementation would use context.services?.slack
    return { success: true };
  }
}

// Using the factory function
import { createTool } from '@orient-bot/mcp-tools';

const myTool = createTool({
  name: 'my_tool',
  description: 'My custom tool',
  category: 'system',
  inputSchema: z.object({ message: z.string() }),
  keywords: ['custom'],
  useCases: ['Custom operations'],
  execute: async (input, context) => {
    return { message: input.message };
  },
});
```

### Using the Registry

```typescript
import { getToolRegistry, ToolRegistry } from '@orient-bot/mcp-tools';

const registry = getToolRegistry();

// Register a tool
registry.registerTool(myTool.toMetadata());

// Search for tools
const results = registry.searchTools('send message');

// Get tools by category
const messagingTools = registry.getToolsByCategory('messaging');

// Get all categories
const categories = registry.getAllCategories();
```

### Creating Tool Context

```typescript
import { createToolContext, loadConfig } from '@orient-bot/mcp-tools';
import { loadConfig } from '@orient-bot/core';

const config = loadConfig();
const context = createToolContext(config, {
  correlationId: 'unique-request-id',
});

// Use context with tools
const result = await myTool.run(input, context);
```

## Tool Categories

| Category    | Description                    |
| ----------- | ------------------------------ |
| `messaging` | Slack communication tools      |
| `whatsapp`  | WhatsApp messaging tools       |
| `docs`      | Google Docs/Slides tools       |
| `google`    | Google OAuth tools             |
| `system`    | System and configuration tools |

## Development

```bash
# Build
pnpm build

# Run tests
pnpm test

# Type check
pnpm typecheck
```
npm package: @orient-bot/test-utils
Description: Shared test utilities, mocks, and factories for Orient
Latest version: 1.0.0

# @orient-bot/test-utils

Shared test utilities for the Orient monorepo.

## Features

- **Mock Objects**: Pre-configured mocks for logger, config, database
- **Factory Functions**: Generate test data for JIRA, messages, etc.
- **Assertion Helpers**: Custom assertions for common patterns
- **Database Utilities**: Helpers for database tests

## Installation

```bash
pnpm add -D @orient-bot/test-utils
```

## Usage

### Mocks

```typescript
import { createMockLogger, createMockConfig } from '@orient-bot/test-utils';

describe('MyService', () => {
  it('should use logger', () => {
    const logger = createMockLogger();
    const config = createMockConfig();

    const service = new MyService(config, logger);
    service.doSomething();

    expect(logger.info).toHaveBeenCalled();
  });
});
```

### Factories

```typescript
import { createJiraIssue, createWhatsAppMessage } from '@orient-bot/test-utils';

describe('IssueProcessor', () => {
  it('should process issue', () => {
    const issue = createJiraIssue({
      key: 'TEST-1',
      fields: { summary: 'My test issue' },
    });

    expect(processIssue(issue)).toBeDefined();
  });
});

describe('MessageHandler', () => {
  it('should handle message', () => {
    const message = createWhatsAppMessage({ text: 'hello' });

    expect(handleMessage(message)).toBe('response');
  });
});
```

### Assertion Helpers

```typescript
import { expectAsyncError, expectHasKeys } from '@orient-bot/test-utils';

describe('ErrorHandling', () => {
  it('should throw on invalid input', async () => {
    await expectAsyncError(() => validateInput(null), 'Input is required');
  });

  it('should have required keys', () => {
    expectHasKeys(result, ['id', 'name', 'created']);
  });
});
```

### Database Helpers

```typescript
import { skipIfNoDatabase, createMockDatabase } from '@orient-bot/test-utils';

describe('Database operations', () => {
  beforeAll(() => {
    if (skipIfNoDatabase()) {
      console.log('Skipping database tests - no DATABASE_URL');
      return;
    }
  });

  it('should mock database', () => {
    const db = createMockDatabase();
    db.select.mockResolvedValueOnce([{ id: 1 }]);

    // Use mock database
  });
});
```

## Package Structure

```
src/
├── mocks/
│   ├── logger.ts    # Mock logger
│   └── config.ts    # Mock config
├── factories/
│   ├── jira.ts      # JIRA test data
│   └── messages.ts  # Message test data
├── helpers/
│   ├── assertions.ts # Custom assertions
│   └── database.ts   # Database helpers
└── index.ts          # Main exports
```