-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommandsHandler.js
More file actions
731 lines (652 loc) · 22 KB
/
CommandsHandler.js
File metadata and controls
731 lines (652 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
const fs = require('fs');
const path = require('path');
/**
* Commands Handler for Slash Commands Management
* Handles discovery, pagination, and execution of Claude Code slash commands
*/
class CommandsHandler {
constructor(bot, sessionManager) {
this.bot = bot;
this.sessionManager = sessionManager;
this.commandsCache = null;
this.cacheTimestamp = null;
this.CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
this.COMMANDS_PER_PAGE = 10;
}
/**
* Discover slash commands from both project and global directories
*/
async discoverCommands() {
// Check cache first
if (this.commandsCache && this.cacheTimestamp &&
Date.now() - this.cacheTimestamp < this.CACHE_DURATION) {
return this.commandsCache;
}
const commands = [];
// Add default Claude Code commands first
const defaultCommands = this.getDefaultClaudeCodeCommands();
commands.push(...defaultCommands);
const projectCommandsDir = path.join(process.cwd(), '.claude', 'commands');
const globalCommandsDir = path.join(process.env.HOME || process.env.USERPROFILE, '.claude', 'commands');
// Discover project commands
await this.discoverCommandsInDirectory(projectCommandsDir, commands, 'project');
// Discover global commands
await this.discoverCommandsInDirectory(globalCommandsDir, commands, 'global');
// Sort only custom commands (keep default commands at top)
const defaultCommandsCount = defaultCommands.length;
const customCommands = commands.slice(defaultCommandsCount);
customCommands.sort((a, b) => a.name.localeCompare(b.name));
// Reconstruct array with default commands first, then sorted custom commands
const finalCommands = [...defaultCommands, ...customCommands];
// Update cache
this.commandsCache = finalCommands;
this.cacheTimestamp = Date.now();
return finalCommands;
}
/**
* Get default Claude Code slash commands
*/
getDefaultClaudeCodeCommands() {
return [
{
name: 'add-dir',
scope: 'built-in',
slashCommand: '/add-dir',
description: 'Add additional working directories',
argumentHint: '[directory-path]',
allowedTools: [],
filePath: null
},
{
name: 'agents',
scope: 'built-in',
slashCommand: '/agents',
description: 'Manage custom AI subagents',
argumentHint: '[list|create|delete] [agent-name]',
allowedTools: [],
filePath: null
},
{
name: 'bug',
scope: 'built-in',
slashCommand: '/bug',
description: 'Report bugs to Anthropic',
argumentHint: '[bug-description]',
allowedTools: [],
filePath: null
},
{
name: 'clear',
scope: 'built-in',
slashCommand: '/clear',
description: 'Clear conversation history',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'compact',
scope: 'built-in',
slashCommand: '/compact',
description: 'Compact conversation with optional focus',
argumentHint: '[focus-topic]',
allowedTools: [],
filePath: null
},
{
name: 'config',
scope: 'built-in',
slashCommand: '/config',
description: 'View/modify configuration',
argumentHint: '[setting] [value]',
allowedTools: [],
filePath: null
},
{
name: 'cost',
scope: 'built-in',
slashCommand: '/cost',
description: 'Show token usage statistics',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'doctor',
scope: 'built-in',
slashCommand: '/doctor',
description: 'Check Claude Code installation health',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'help',
scope: 'built-in',
slashCommand: '/help',
description: 'Get usage help',
argumentHint: '[topic]',
allowedTools: [],
filePath: null
},
{
name: 'init',
scope: 'built-in',
slashCommand: '/init',
description: 'Initialize project with CLAUDE.md guide',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'login',
scope: 'built-in',
slashCommand: '/login',
description: 'Switch Anthropic accounts',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'logout',
scope: 'built-in',
slashCommand: '/logout',
description: 'Sign out from Anthropic account',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'mcp',
scope: 'built-in',
slashCommand: '/mcp',
description: 'Manage MCP server connections',
argumentHint: '[list|add|remove] [server-name]',
allowedTools: [],
filePath: null
},
{
name: 'memory',
scope: 'built-in',
slashCommand: '/memory',
description: 'Edit CLAUDE.md memory files',
argumentHint: '[global|local]',
allowedTools: [],
filePath: null
},
{
name: 'model',
scope: 'built-in',
slashCommand: '/model',
description: 'Select or change AI model',
argumentHint: '[model-name]',
allowedTools: [],
filePath: null
},
{
name: 'permissions',
scope: 'built-in',
slashCommand: '/permissions',
description: 'View or update permissions',
argumentHint: '[view|update]',
allowedTools: [],
filePath: null
},
{
name: 'pr_comments',
scope: 'built-in',
slashCommand: '/pr_comments',
description: 'View pull request comments',
argumentHint: '[pr-number]',
allowedTools: [],
filePath: null
},
{
name: 'review',
scope: 'built-in',
slashCommand: '/review',
description: 'Request code review',
argumentHint: '[file-path]',
allowedTools: [],
filePath: null
},
{
name: 'status',
scope: 'built-in',
slashCommand: '/status',
description: 'View account and system statuses',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'terminal-setup',
scope: 'built-in',
slashCommand: '/terminal-setup',
description: 'Install Shift+Enter key binding',
argumentHint: '',
allowedTools: [],
filePath: null
},
{
name: 'vim',
scope: 'built-in',
slashCommand: '/vim',
description: 'Enter vim mode for alternating modes',
argumentHint: '',
allowedTools: [],
filePath: null
}
];
}
/**
* Discover commands in a specific directory
*/
async discoverCommandsInDirectory(dir, commands, scope) {
if (!fs.existsSync(dir)) {
return;
}
const scanDirectory = (currentDir, prefix = '') => {
try {
const items = fs.readdirSync(currentDir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(currentDir, item.name);
if (item.isDirectory()) {
// Recursively scan subdirectories (for namespaced commands)
scanDirectory(fullPath, prefix ? `${prefix}:${item.name}` : item.name);
} else if (item.isFile() && item.name.endsWith('.md')) {
// Parse command file
const commandName = path.basename(item.name, '.md');
const displayName = prefix ? `${prefix}:${commandName}` : commandName;
try {
const content = fs.readFileSync(fullPath, 'utf8');
const command = this.parseCommandFile(content, displayName, scope, fullPath);
if (command) {
commands.push(command);
}
} catch (error) {
console.error(`[CommandsHandler] Error parsing command ${fullPath}:`, error);
}
}
}
} catch (error) {
console.error(`[CommandsHandler] Error scanning directory ${currentDir}:`, error);
}
};
scanDirectory(dir);
}
/**
* Parse command file and extract metadata
*/
parseCommandFile(content, name, scope, filePath) {
const command = {
name: name,
scope: scope,
filePath: filePath,
description: '',
argumentHint: '',
allowedTools: []
};
// Parse frontmatter if present
if (content.startsWith('---')) {
const frontmatterEnd = content.indexOf('---', 3);
if (frontmatterEnd !== -1) {
const frontmatter = content.substring(3, frontmatterEnd);
const lines = frontmatter.split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('description:')) {
command.description = trimmedLine.substring(12).trim();
} else if (trimmedLine.startsWith('argument-hint:')) {
command.argumentHint = trimmedLine.substring(14).trim();
} else if (trimmedLine.startsWith('allowed-tools:')) {
// Parse array format
const toolsString = trimmedLine.substring(14).trim();
if (toolsString.startsWith('[') && toolsString.endsWith(']')) {
command.allowedTools = toolsString.slice(1, -1).split(',').map(t => t.trim());
}
}
}
// Extract content after frontmatter
const mainContent = content.substring(frontmatterEnd + 3).trim();
if (!command.description && mainContent) {
// Use first line of content as description if no frontmatter description
const firstLine = mainContent.split('\n')[0].trim();
if (firstLine.startsWith('#')) {
command.description = firstLine.replace(/^#+\s*/, '');
}
}
}
} else {
// No frontmatter, try to extract from content
const lines = content.split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('#') && !command.description) {
command.description = trimmedLine.replace(/^#+\s*/, '');
break;
}
}
}
// Generate slash command
command.slashCommand = `/${name}`;
return command;
}
/**
* Show commands menu with pagination
*/
async showCommandsMenu(chatId, page = 0, messageId = null) {
try {
const commands = await this.discoverCommands();
const totalPages = Math.ceil(commands.length / this.COMMANDS_PER_PAGE);
if (commands.length === 0) {
const message = '⚡ **Commands**\n\n' +
'No slash commands found.\n\n' +
'💡 **Tip:** Add commands to `.claude/commands/` (project) or `~/.claude/commands/` (global)';
if (messageId) {
await this.bot.safeEditMessage(chatId, messageId, message);
} else {
await this.bot.safeSendMessage(chatId, message);
}
return;
}
const startIndex = page * this.COMMANDS_PER_PAGE;
const endIndex = Math.min(startIndex + this.COMMANDS_PER_PAGE, commands.length);
const pageCommands = commands.slice(startIndex, endIndex);
let message = `⚡ **Commands** (Page ${page + 1}/${totalPages})\n\n`;
message += 'Available slash commands:\n\n';
// Add numbered commands (1-10)
pageCommands.forEach((command, index) => {
const number = index + 1;
let scopeIcon;
if (command.scope === 'built-in') {
scopeIcon = '⚡';
} else if (command.scope === 'global') {
scopeIcon = '🌍';
} else {
scopeIcon = '📁';
}
message += `**${number}.** ${scopeIcon} \`${command.slashCommand}\`\n`;
if (command.description) {
message += ` ${command.description}\n`;
}
if (command.argumentHint) {
message += ` 💡 Usage: \`${command.slashCommand} ${command.argumentHint}\`\n`;
}
message += '\n';
});
message += '👆 **Tap a number (1-10) to execute the command**';
const keyboard = this.createCommandsKeyboard(page, totalPages, pageCommands.length);
if (messageId) {
await this.bot.safeEditMessage(chatId, messageId, message, { reply_markup: keyboard });
} else {
await this.bot.safeSendMessage(chatId, message, { reply_markup: keyboard });
}
} catch (error) {
console.error('[CommandsHandler] Error showing commands menu:', error);
const errorMessage = '❌ **Commands Error**\n\n' + 'Failed to load commands list.';
if (messageId) {
await this.bot.safeEditMessage(chatId, messageId, errorMessage);
} else {
await this.bot.safeSendMessage(chatId, errorMessage);
}
}
}
/**
* Create commands keyboard with numbered buttons and pagination
*/
createCommandsKeyboard(page = 0, totalPages = 1, commandsOnPage = 0) {
const keyboard = {
inline_keyboard: []
};
// Add numbered buttons (1-10) in rows of 5
if (commandsOnPage > 0) {
const maxButtons = Math.min(commandsOnPage, 10);
// First row (1-5)
const firstRow = [];
for (let i = 1; i <= Math.min(5, maxButtons); i++) {
firstRow.push({
text: i.toString(),
callback_data: `cmd:exec:${page}:${i - 1}`
});
}
keyboard.inline_keyboard.push(firstRow);
// Second row (6-10) if needed
if (maxButtons > 5) {
const secondRow = [];
for (let i = 6; i <= maxButtons; i++) {
secondRow.push({
text: i.toString(),
callback_data: `cmd:exec:${page}:${i - 1}`
});
}
keyboard.inline_keyboard.push(secondRow);
}
}
// Add pagination if needed
if (totalPages > 1) {
const paginationRow = [];
if (page > 0) {
paginationRow.push({
text: '◀️',
callback_data: `cmd:page:${page - 1}`
});
}
paginationRow.push({
text: `${page + 1}/${totalPages}`,
callback_data: 'noop'
});
if (page < totalPages - 1) {
paginationRow.push({
text: '▶️',
callback_data: `cmd:page:${page + 1}`
});
}
keyboard.inline_keyboard.push(paginationRow);
}
// Add close button
keyboard.inline_keyboard.push([
{ text: '❌ Close', callback_data: 'cmd:close' }
]);
return keyboard;
}
/**
* Execute a command by index
*/
async executeCommand(chatId, userId, page, commandIndex, messageId) {
try {
const commands = await this.discoverCommands();
const startIndex = page * this.COMMANDS_PER_PAGE;
const actualIndex = startIndex + commandIndex;
if (actualIndex >= commands.length) {
await this.bot.safeSendMessage(chatId, '❌ Command not found');
return;
}
const command = commands[actualIndex];
console.log(`[CommandsHandler] Executing command: ${command.slashCommand} for user ${userId}`);
// Check if session is currently processing (only if session exists in memory)
const userSession = this.sessionManager.userSessions.get(userId);
if (userSession) {
const isProcessing = userSession.processor && userSession.processor.isActive();
if (isProcessing) {
await this.bot.safeSendMessage(chatId,
'⏳ **Session Busy**\n\n' +
'Claude is currently processing a request. Please wait for it to complete before executing commands.'
);
return;
}
}
// If no session in memory, SessionManager will handle resuming/creating as needed
// Show argument input interface
await this.showArgumentInput(chatId, userId, command, messageId);
} catch (error) {
console.error('[CommandsHandler] Error executing command:', error);
await this.bot.safeSendMessage(chatId,
'❌ **Command Execution Error**\n\n' +
'Failed to execute the selected command.'
);
}
}
/**
* Show argument input interface
*/
async showArgumentInput(chatId, userId, command, messageId) {
try {
let scopeIcon;
if (command.scope === 'built-in') {
scopeIcon = '⚡';
} else if (command.scope === 'global') {
scopeIcon = '🌍';
} else {
scopeIcon = '📁';
}
let message = '⚡ **Execute Command**\n\n';
message += `${scopeIcon} \`${command.slashCommand}\`\n`;
if (command.description) {
message += `📝 ${command.description}\n`;
}
message += '\n';
if (command.argumentHint) {
message += `💡 **Expected arguments:** \`${command.argumentHint}\`\n\n`;
message += '📝 **Please type the arguments for this command, or send without arguments:**';
} else {
message += '✅ **This command requires no arguments.**\n\n';
message += '🚀 **Ready to execute!**';
}
const keyboard = {
inline_keyboard: [
[
{ text: '✅ Execute Without Arguments', callback_data: `cmd:run:${command.name}:noargs` },
{ text: '❌ Cancel', callback_data: 'cmd:close' }
]
]
};
// Store command for argument input
this.pendingCommands = this.pendingCommands || new Map();
this.pendingCommands.set(userId, {
command: command,
chatId: chatId,
messageId: messageId
});
if (messageId) {
await this.bot.safeEditMessage(chatId, messageId, message, { reply_markup: keyboard });
} else {
await this.bot.safeSendMessage(chatId, message, { reply_markup: keyboard });
}
} catch (error) {
console.error('[CommandsHandler] Error showing argument input:', error);
await this.bot.safeSendMessage(chatId,
'❌ **Argument Input Error**\n\n' +
'Failed to show argument input interface.'
);
}
}
/**
* Send command to Claude Code session
*/
async sendCommandToSession(chatId, userId, command, args = '') {
try {
// Format full command with arguments
const fullCommand = args.trim() ? `${command.slashCommand} ${args.trim()}` : command.slashCommand;
// Clear pending command
if (this.pendingCommands) {
this.pendingCommands.delete(userId);
}
await this.bot.safeSendMessage(chatId,
'⚡ **Executing Command**\n\n' +
`\`${fullCommand}\`\n\n` +
'🚀 Sending to Claude Code session...'
);
// Use main bot's processUserMessage method to handle it like a regular message
await this.bot.processUserMessage(fullCommand, userId, chatId);
} catch (error) {
console.error('[CommandsHandler] Error sending command to session:', error);
await this.bot.safeSendMessage(chatId,
'❌ **Command Send Error**\n\n' +
'Failed to send command to Claude session.'
);
}
}
/**
* Handle text message input for command arguments
*/
async handleTextMessage(msg) {
const userId = msg.from.id;
const chatId = msg.chat.id;
const text = msg.text;
// Check if user has a pending command
if (!this.pendingCommands || !this.pendingCommands.has(userId)) {
return false; // Not handling this message
}
const pendingCommand = this.pendingCommands.get(userId);
const { command } = pendingCommand;
console.log(`[CommandsHandler] Processing argument input for command: ${command.slashCommand}`);
// Send command with arguments
await this.sendCommandToSession(chatId, userId, command, text);
return true; // Message was handled
}
/**
* Handle commands callbacks
*/
async handleCommandsCallback(callbackData, chatId, messageId, userId) {
try {
if (callbackData.startsWith('cmd:page:')) {
const page = parseInt(callbackData.split(':')[2]);
await this.showCommandsMenu(chatId, page, messageId);
return true;
}
if (callbackData.startsWith('cmd:exec:')) {
const parts = callbackData.split(':');
const page = parseInt(parts[2]);
const commandIndex = parseInt(parts[3]);
await this.executeCommand(chatId, userId, page, commandIndex, messageId);
return true;
}
if (callbackData.startsWith('cmd:run:') && callbackData.endsWith(':noargs')) {
const commandName = callbackData.replace('cmd:run:', '').replace(':noargs', '');
// Find command by name
const commands = await this.discoverCommands();
const command = commands.find(cmd => cmd.name === commandName);
if (command) {
await this.sendCommandToSession(chatId, userId, command, '');
await this.bot.bot.deleteMessage(chatId, messageId);
} else {
await this.bot.safeEditMessage(chatId, messageId,
'❌ **Command Not Found**\n\nThe selected command could not be found.'
);
}
return true;
}
if (callbackData === 'cmd:close') {
await this.bot.bot.deleteMessage(chatId, messageId);
return true;
}
return false;
} catch (error) {
console.error('[CommandsHandler] Callback error:', error);
return false;
}
}
/**
* Clear commands cache (useful for refreshing)
*/
clearCache() {
this.commandsCache = null;
this.cacheTimestamp = null;
}
/**
* Get stats for debugging
*/
async getStats() {
const commands = await this.discoverCommands();
const projectCommands = commands.filter(c => c.scope === 'project').length;
const globalCommands = commands.filter(c => c.scope === 'global').length;
return {
totalCommands: commands.length,
projectCommands: projectCommands,
globalCommands: globalCommands,
cacheAge: this.cacheTimestamp ? Date.now() - this.cacheTimestamp : null
};
}
}
module.exports = CommandsHandler;