npm package: @meldscience/message-bus
Description: Message bus for coordinating conversations between participants
Author: Adam Avenir
Latest version: 0.3.1

# @meldscience/message-bus

A lightweight message bus for coordinating conversations between participants in Discord threads.

## Installation

```bash
npm install @meldscience/message-bus
```

## Core Concepts

### Messages

Messages are the fundamental unit of communication. Each message has:

```typescript
interface Message {
  id: string;                 // Unique message identifier
  from: string;              // Sender ID (e.g. Discord user ID)
  to: string[];              // Target participants (for @mentions)
  channelId: string;         // Discord channel or thread ID
  content: {
    type: 'text' | 'thought' | 'action';
    data: string | ActionData;
  };
  metadata?: {
    protocolId: string;      // Active protocol
    threadId?: string;       // For threaded conversations
    [key: string]: unknown;  // Protocol-specific metadata
  };
  timestamp: number;         // Unix timestamp
}
```

### Protocols

Protocols define how messages are handled in specific conversation contexts. Each protocol:
- Has a unique ID and metadata
- Can process incoming messages
- Can maintain thread-specific state
- Receives lifecycle events (initialization, cleanup)

```typescript
class MyProtocol extends BaseProtocol {
  constructor() {
    super(
      'my-protocol',         // Unique ID
      'My Protocol',         // Display name
      'Protocol description' // Description
    );
  }

  async onMessage(msg: Message): Promise<Message | null> {
    // Process message
    return msg;
  }
}
```

### Message Bus

The message bus:
- Routes messages between participants
- Manages protocol registration
- Handles thread lifecycle
- Maintains thread state

```typescript
const messageBus = new MessageBus(discordClient);

// Register protocols
await messageBus.registerProtocol(new QandAProtocol({
  id: 'qanda',
  allowedQuestioners: ['user1', 'user2'],
  toolPermissions: { /* ... */ }
}));

// Create thread with protocol
const threadId = await messageBus.createThread(channelId, 'qanda');

// Route message
await messageBus.routeMessage({
  id: 'msg1',
  from: 'user1',
  to: ['claude1'],
  channelId: threadId,
  content: {
    type: 'text',
    data: 'Hello Claude!'
  },
  timestamp: Date.now()
});
```

## Built-in Protocols

### Q&A Protocol

Manages question-and-answer interactions:
- Controls who can ask questions
- Manages tool permissions
- Routes questions to appropriate participants

```typescript
const qandaProtocol = new QandAProtocol({
  id: 'qanda',
  name: 'Q&A Protocol',
  description: 'Question and answer coordination',
  allowedQuestioners: ['user1', 'user2'],
  toolPermissions: {
    'role1': ['tool1', 'tool2']
  }
});
```

### Meeting Protocol

Coordinates meetings in Discord threads:
- Parses meeting goals from initial message
- Manages participant roles
- Tracks meeting state

```typescript
const meetingProtocol = new MeetingProtocol();
```

## Events

The message bus emits events for key operations:

```typescript
messageBus.on('message', (msg: Message) => {
  // Handle message event
});

messageBus.on('threadCreate', ({ threadId, protocolId }) => {
  // Handle thread creation
});

messageBus.on('error', (error: Error) => {
  // Handle errors
});
```

## Integration with mcp-discord

When integrating with mcp-discord, ensure:

1. Messages include required fields:
   - `id`: Unique message identifier
   - `timestamp`: Unix timestamp
   - `metadata.protocolId`: Active protocol ID

2. Protocol configuration uses the new constructor format:
   ```typescript
   new QandAProtocol({
     id: 'protocol-id',      // Required
     name: 'Protocol Name',  // Optional
     description: '...',     // Optional
     // Protocol-specific config...
   });
   ```

3. Use thread state management instead of config:
   ```typescript
   // Set thread state
   await messageBus.setThreadState(threadId, {
     // Thread-specific state...
   });

   // Get thread state
   const state = await messageBus.getThreadState(threadId);
   ```

4. Implement event handlers for better state management:
   ```typescript
   messageBus.on('message', handleMessage);
   messageBus.on('threadCreate', handleThreadCreate);
   messageBus.on('error', handleError);
   ```

## License

MIT