@cmdop/bot 2026.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,36 @@
1
+ # @cmdop/bot — Changelog
2
+
3
+ ## 2026.3.0 — 2026-03-01
4
+
5
+ Initial release.
6
+
7
+ ### Features
8
+
9
+ - **`IntegrationHub`** — single entry point that wires channels, handlers, CMDOP client, and permissions together
10
+ - `create({ apiKey?, local?, defaultMachine?, adminUsers?, channelStartMode? })`
11
+ - `addTelegram()`, `addDiscord()`, `addSlack()` — lazy channel registration (platform deps optional)
12
+ - `start()` / `stop()` — concurrent channel lifecycle with per-channel error isolation
13
+ - `linkIdentities()` — cross-channel user identity linking
14
+ - `permissions`, `runningChannelIds`, `failedChannelIds`, `getChannelStatus()` — introspection
15
+
16
+ - **Telegram** (`grammy`) — text/MarkdownV2, token streaming with debounced edits, inline keyboards, throttler plugin
17
+
18
+ - **Discord** (`discord.js`) — slash commands (`/exec`, `/agent`, `/files`, `/help`), `deferReply` for long ops, rate-limit monitoring
19
+
20
+ - **Slack** (`@slack/bolt`) — Socket Mode, `Assistant` lifecycle (`threadStarted`, `userMessage`), Block Kit builders, native `chatStream`
21
+
22
+ - **Handlers**
23
+ - `TerminalHandler` — `/exec <command>` (requires `EXECUTE`)
24
+ - `AgentHandler` — `/agent <prompt>` (requires `EXECUTE`)
25
+ - `FilesHandler` — `/files [read] <path>` (requires `READ`)
26
+ - `HelpHandler` — `/help` (no permission required)
27
+
28
+ - **Permission system** — five levels `NONE / READ / EXECUTE / FILES / ADMIN`, `IdentityMap` for cross-channel identity, `InMemoryPermissionStore` (default) + `PermissionStoreProtocol` for custom backends
29
+
30
+ - **Streaming** — `TokenBuffer` (debounced flush, drain on shutdown), `SlackStream` (native `chatStream` wrapper)
31
+
32
+ - **Error hierarchy** — all errors extend `BotError` with `.code`, never exposes raw platform errors
33
+
34
+ - **`DemoChannel`** — in-process channel for local testing and CLI usage (`injectMessage()`)
35
+
36
+ - **`BaseChannel`** / **`BaseHandler`** — extension points for custom platform integrations
package/README.md ADDED
@@ -0,0 +1,284 @@
1
+ # @cmdop/bot
2
+
3
+ Multi-channel bot framework for [CMDOP](https://cmdop.com) — run `/exec`, `/agent`, and `/files` commands from Telegram, Discord, and Slack.
4
+
5
+ ```
6
+ pnpm add @cmdop/bot
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```ts
12
+ import { IntegrationHub } from '@cmdop/bot';
13
+
14
+ const hub = await IntegrationHub.create({
15
+ apiKey: process.env.CMDOP_API_KEY,
16
+ });
17
+
18
+ await hub.addTelegram({ token: process.env.TELEGRAM_TOKEN });
19
+ await hub.start();
20
+ ```
21
+
22
+ That's it. Your bot now responds to `/exec`, `/agent`, `/files`, and `/help`.
23
+
24
+ ---
25
+
26
+ ## Platform setup
27
+
28
+ ### Telegram
29
+
30
+ ```
31
+ pnpm add grammy @grammyjs/transformer-throttler
32
+ ```
33
+
34
+ ```ts
35
+ await hub.addTelegram({ token: 'YOUR_BOT_TOKEN' });
36
+ ```
37
+
38
+ Get a token from [@BotFather](https://t.me/BotFather).
39
+
40
+ ### Discord
41
+
42
+ ```
43
+ pnpm add discord.js @discordjs/rest @discordjs/builders
44
+ ```
45
+
46
+ ```ts
47
+ await hub.addDiscord({
48
+ token: 'YOUR_BOT_TOKEN',
49
+ clientId: 'YOUR_APPLICATION_ID',
50
+ guildId: 'OPTIONAL_GUILD_ID', // omit for global slash commands
51
+ });
52
+ ```
53
+
54
+ Get tokens from the [Discord Developer Portal](https://discord.com/developers/applications).
55
+
56
+ ### Slack
57
+
58
+ ```
59
+ pnpm add @slack/bolt @slack/web-api
60
+ ```
61
+
62
+ ```ts
63
+ await hub.addSlack({
64
+ token: 'xoxb-YOUR-BOT-TOKEN',
65
+ appToken: 'xapp-YOUR-APP-TOKEN',
66
+ });
67
+ ```
68
+
69
+ Requires Socket Mode enabled in your Slack app settings. See [examples/slack.ts](examples/slack.ts) for full setup.
70
+
71
+ ---
72
+
73
+ ## Commands
74
+
75
+ | Command | Usage | Required permission |
76
+ |---------|-------|-------------------|
77
+ | `/exec` | `/exec <shell command>` | `EXECUTE` |
78
+ | `/agent` | `/agent <prompt>` | `EXECUTE` |
79
+ | `/files` | `/files [read] <path>` | `READ` |
80
+ | `/help` | `/help` | none |
81
+
82
+ Commands use a `/` or `!` prefix. Example: `/exec ls -la`, `!agent list running processes`.
83
+
84
+ ---
85
+
86
+ ## Permissions
87
+
88
+ Users default to `NONE` (no access). Grant levels programmatically:
89
+
90
+ ```ts
91
+ const hub = await IntegrationHub.create({
92
+ adminUsers: ['telegram:123456789'], // always ADMIN
93
+ });
94
+
95
+ // Grant a specific user READ access
96
+ await hub.permissions.setLevel('telegram:987654321', 'READ');
97
+ ```
98
+
99
+ Permission levels (ordered, each includes all levels below):
100
+
101
+ | Level | Access |
102
+ |-------|--------|
103
+ | `NONE` | No commands (only `/help`) |
104
+ | `READ` | `/files` |
105
+ | `EXECUTE` | `/exec`, `/agent` |
106
+ | `FILES` | _(reserved for future write operations)_ |
107
+ | `ADMIN` | All commands |
108
+
109
+ ### Cross-channel identity
110
+
111
+ Link a Telegram user to their Discord account so permissions apply on both platforms:
112
+
113
+ ```ts
114
+ hub.linkIdentities('telegram', '12345', 'discord', '67890');
115
+
116
+ // Now granting EXECUTE to either ID applies to both
117
+ await hub.permissions.setLevel('telegram:12345', 'EXECUTE');
118
+ ```
119
+
120
+ ---
121
+
122
+ ## Hub options
123
+
124
+ ```ts
125
+ const hub = await IntegrationHub.create({
126
+ // CMDOP connection
127
+ apiKey: 'cmdop_live_xxx', // cloud; omit for local IPC
128
+ defaultMachine: 'my-server', // pre-select a machine
129
+
130
+ // Permissions
131
+ adminUsers: ['telegram:123'],
132
+ permissionStore: myRedisStore, // custom store (see PermissionStoreProtocol)
133
+
134
+ // Startup behaviour
135
+ channelStartMode: 'isolated', // 'isolated' (default) | 'strict'
136
+ // 'isolated' — a failing channel is logged; others continue
137
+ // 'strict' — any channel failure throws and aborts hub.start()
138
+
139
+ // Logging
140
+ logger: myLogger, // any { info, warn, error, debug } object
141
+ });
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Custom handlers
147
+
148
+ Register a handler for a new command:
149
+
150
+ ```ts
151
+ import { BaseHandler, ok, err, CommandArgsError } from '@cmdop/bot';
152
+ import type { CommandContext, HandlerResult, LoggerProtocol } from '@cmdop/bot';
153
+ import type { CMDOPClient } from '@cmdop/node';
154
+
155
+ class PingHandler extends BaseHandler {
156
+ readonly name = 'ping';
157
+ readonly description = 'Check if the bot is alive';
158
+ readonly usage = '/ping';
159
+ readonly requiredPermission = 'NONE' as const;
160
+
161
+ async handle(_ctx: CommandContext): Promise<HandlerResult> {
162
+ return ok({ type: 'text', text: 'pong 🏓' });
163
+ }
164
+ }
165
+
166
+ hub.registerHandler(new PingHandler(hub.cmdop, logger));
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Custom channels
172
+
173
+ Implement `ChannelProtocol` (or extend `BaseChannel`) to add any messaging platform:
174
+
175
+ ```ts
176
+ import { BaseChannel } from '@cmdop/bot';
177
+
178
+ class MyChannel extends BaseChannel {
179
+ constructor(permissions, dispatcher, logger) {
180
+ super('my-channel', 'My Platform', permissions, dispatcher, logger);
181
+ }
182
+
183
+ async start() {
184
+ // connect to platform, register event listeners
185
+ myPlatform.on('message', async (msg) => {
186
+ await this.processMessage({
187
+ id: msg.id,
188
+ userId: msg.authorId,
189
+ channelId: this.id,
190
+ text: msg.text,
191
+ timestamp: new Date(),
192
+ attachments: [],
193
+ });
194
+ });
195
+ }
196
+
197
+ async stop() { await myPlatform.disconnect(); }
198
+
199
+ async send(userId: string, message: OutgoingMessage) {
200
+ // format and send message to platform
201
+ }
202
+
203
+ onMessage(handler) { /* store handler for hub use */ }
204
+ }
205
+
206
+ hub.registerChannel(new MyChannel(hub.permissions, /* dispatcher */, logger));
207
+ ```
208
+
209
+ See [examples/custom-channel.ts](examples/custom-channel.ts) for a complete working example.
210
+
211
+ ---
212
+
213
+ ## Multi-channel hub
214
+
215
+ ```ts
216
+ const hub = await IntegrationHub.create({ apiKey: '...', channelStartMode: 'isolated' });
217
+
218
+ await hub.addTelegram({ token: process.env.TELEGRAM_TOKEN });
219
+ await hub.addDiscord({ token: process.env.DISCORD_TOKEN, clientId: process.env.DISCORD_CLIENT_ID });
220
+ await hub.addSlack({ token: process.env.SLACK_BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN });
221
+
222
+ await hub.start();
223
+
224
+ console.log(`Running: ${hub.runningChannelIds.join(', ')}`);
225
+ console.log(`Failed: ${hub.failedChannelIds.join(', ')}`);
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Graceful shutdown
231
+
232
+ ```ts
233
+ async function shutdown() {
234
+ await hub.stop(); // stops all channels, closes CMDOP client
235
+ process.exit(0);
236
+ }
237
+
238
+ process.once('SIGINT', shutdown);
239
+ process.once('SIGTERM', shutdown);
240
+ ```
241
+
242
+ ---
243
+
244
+ ## Error handling
245
+
246
+ All errors extend `BotError` and expose a `code` string:
247
+
248
+ | Class | Code | When |
249
+ |-------|------|------|
250
+ | `PermissionDeniedError` | `PERMISSION_DENIED` | User lacks required level |
251
+ | `CommandNotFoundError` | `COMMAND_NOT_FOUND` | Unknown command |
252
+ | `CommandArgsError` | `COMMAND_ARGS` | Invalid arguments |
253
+ | `CMDOPError` | `CMDOP_ERROR` | CMDOP client failure |
254
+ | `MachineNotFoundError` | `MACHINE_NOT_FOUND` | Machine hostname unknown |
255
+ | `MachineOfflineError` | `MACHINE_OFFLINE` | No active session on machine |
256
+ | `ConfigError` | `CONFIG_ERROR` | Missing / invalid configuration |
257
+
258
+ ---
259
+
260
+ ## Environment variables
261
+
262
+ | Variable | Description |
263
+ |----------|-------------|
264
+ | `CMDOP_API_KEY` | CMDOP cloud API key (omit for local IPC) |
265
+ | `CMDOP_MACHINE` | Default machine hostname |
266
+ | `BOT_LOG_LEVEL` | `debug` \| `info` \| `warn` \| `error` (default: `info`) |
267
+ | `BOT_MAX_OUTPUT` | Max characters returned by `/exec` (default: `4000`) |
268
+ | `TELEGRAM_TOKEN` | Telegram bot token |
269
+ | `DISCORD_TOKEN` | Discord bot token |
270
+ | `DISCORD_CLIENT_ID` | Discord application ID |
271
+ | `SLACK_BOT_TOKEN` | Slack bot OAuth token (`xoxb-...`) |
272
+ | `SLACK_APP_TOKEN` | Slack app-level token for Socket Mode (`xapp-...`) |
273
+
274
+ ---
275
+
276
+ ## Requirements
277
+
278
+ - Node.js ≥ 20
279
+ - `@cmdop/node` (peer dependency, installed automatically)
280
+ - Platform libraries are **optional peer dependencies** — install only what you use
281
+
282
+ ## License
283
+
284
+ MIT