-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.ts
More file actions
901 lines (787 loc) · 32 KB
/
index.ts
File metadata and controls
901 lines (787 loc) · 32 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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
#!/usr/bin/env -S deno run --allow-all
/**
* Claude Code Discord Bot - Main Entry Point
*
* This file bootstraps the Discord bot with Claude Code integration.
* Most command handlers are now extracted to core modules for maintainability.
*
* @module index
*/
import {
createDiscordBot,
type BotConfig,
type InteractionContext,
type CommandHandlers,
type ButtonHandlers,
type BotDependencies,
type MessageContent,
SessionThreadManager,
} from "./discord/index.ts";
import type { TextChannel } from "npm:discord.js@14.14.1";
import { getGitInfo } from "./git/index.ts";
import { createClaudeSender, expandableContent, sendToClaudeCode, convertToClaudeMessages, type DiscordSender, type ClaudeMessage, type SessionThreadCallbacks } from "./claude/index.ts";
import { buildQuestionMessages, parseAskUserButtonId, parseAskUserConfirmId, type AskUserQuestionInput } from "./claude/index.ts";
import { buildPermissionEmbed, parsePermissionButtonId, type PermissionRequestCallback } from "./claude/index.ts";
import { claudeCommands, enhancedClaudeCommands } from "./claude/index.ts";
import { additionalClaudeCommands } from "./claude/additional-index.ts";
import { initModels } from "./claude/enhanced-client.ts";
import { advancedSettingsCommands, DEFAULT_SETTINGS, unifiedSettingsCommands, UNIFIED_DEFAULT_SETTINGS } from "./settings/index.ts";
import { gitCommands } from "./git/index.ts";
import { shellCommands } from "./shell/index.ts";
import { utilsCommands } from "./util/index.ts";
import { systemCommands } from "./system/index.ts";
import { helpCommand } from "./help/index.ts";
import { agentCommand } from "./agent/index.ts";
import { cleanupPaginationStates } from "./discord/index.ts";
import { runVersionCheck, startPeriodicUpdateCheck, BOT_VERSION } from "./util/version-check.ts";
// Core modules - now handle most of the heavy lifting
import {
parseArgs,
createMessageHistory,
createBotManagers,
setupPeriodicCleanup,
createBotSettings,
createAllHandlers,
getAllCommands,
cleanSessionId,
createButtonHandlers,
createAllCommandHandlers,
type BotManagers,
type AllHandlers,
type MessageHistoryOps,
} from "./core/index.ts";
// Re-export for backward compatibility
export { getGitInfo, executeGitCommand } from "./git/index.ts";
export { sendToClaudeCode } from "./claude/index.ts";
// ================================
// Bot Creation
// ================================
/**
* Create Claude Code Discord Bot with all handlers and integrations.
*/
export async function createClaudeCodeBot(config: BotConfig) {
const { discordToken, applicationId, workDir, repoName, branchName, categoryName, defaultMentionUserId } = config;
// Determine category name (use repository name if not specified)
const actualCategoryName = categoryName || repoName;
// Claude Code session management (closures needed for handler state)
let claudeController: AbortController | null = null;
let claudeSessionId: string | undefined;
// Message history for navigation
const messageHistoryOps: MessageHistoryOps = createMessageHistory(50);
// Create all managers using bot-factory
const managers: BotManagers = createBotManagers({
config: {
discordToken,
applicationId,
workDir,
categoryName: actualCategoryName,
userId: defaultMentionUserId,
},
crashHandlerOptions: {
maxRetries: 3,
retryDelay: 5000,
enableAutoRestart: true,
logCrashes: true,
notifyOnCrash: true,
// deno-lint-ignore require-await
onCrashNotification: async (report) => {
console.warn(`Process crash: ${report.processType} ${report.processId || ''} - ${report.error.message}`);
},
},
});
const { shellManager, worktreeBotManager, crashHandler, healthMonitor, claudeSessionManager } = managers;
// Initialize dynamic model fetching (uses ANTHROPIC_API_KEY if available)
initModels();
// Setup periodic cleanup tasks
const cleanupInterval = setupPeriodicCleanup(managers, 3600000, [
cleanupPaginationStates,
() => { sessionThreadManager.cleanup(); },
]);
// Initialize bot settings
const settingsOps = createBotSettings(defaultMentionUserId, DEFAULT_SETTINGS, UNIFIED_DEFAULT_SETTINGS);
const currentSettings = settingsOps.getSettings();
const botSettings = currentSettings.legacy;
// Bot instance placeholder
// deno-lint-ignore no-explicit-any prefer-const
let bot: any;
let claudeSender: ((messages: ClaudeMessage[]) => Promise<void>) | null = null;
// Session thread manager — maps each Claude session to a dedicated Discord thread
const sessionThreadManager = new SessionThreadManager();
// Session thread callbacks — used by claude/command.ts for /claude-thread and /resume.
// The callbacks are closures over `bot` (late-bound) and `sessionThreadManager`.
const sessionThreadCallbacks: SessionThreadCallbacks = {
async createThreadSender(prompt: string, sessionId?: string, threadName?: string) {
const channel = bot?.getChannel() as TextChannel | null;
if (!channel) throw new Error('Bot channel not ready');
// If a session ID was provided, check for an existing thread to reuse
if (sessionId) {
const existingThread = sessionThreadManager.getThread(sessionId);
if (existingThread) {
if (existingThread.archived) {
await existingThread.setArchived(false);
}
sessionThreadManager.recordActivity(sessionId);
const threadSender = createClaudeSender(createChannelSenderAdapter(existingThread));
return { sender: threadSender, threadSessionKey: sessionId, threadChannelId: existingThread.id };
}
}
// Generate a placeholder key until the real SDK session ID arrives
const placeholderKey = `pending_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
// Create a thread in the main channel
const thread = await sessionThreadManager.createSessionThread(channel, placeholderKey, prompt, threadName);
// Post a summary embed in the main channel pointing to the thread
await sendMessageContent(channel, {
embeds: [{
color: 0x5865F2,
title: '🧵 New Claude Session',
description: `A new session thread has been created.\n\n**Prompt:** \`${prompt.substring(0, 200)}${prompt.length > 200 ? '...' : ''}\``,
fields: [
{ name: 'Thread', value: `<#${thread.id}>`, inline: true },
],
timestamp: true,
}],
});
const threadSender = createClaudeSender(createChannelSenderAdapter(thread));
return { sender: threadSender, threadSessionKey: placeholderKey, threadChannelId: thread.id };
},
async getThreadSender(sessionId: string) {
const existingThread = sessionThreadManager.getThread(sessionId);
if (!existingThread) return undefined;
if (existingThread.archived) {
await existingThread.setArchived(false);
}
sessionThreadManager.recordActivity(sessionId);
const threadSender = createClaudeSender(createChannelSenderAdapter(existingThread));
return { sender: threadSender, threadSessionKey: sessionId };
},
updateSessionId(oldKey: string, newSessionId: string) {
sessionThreadManager.updateSessionId(oldKey, newSessionId);
},
};
// Late-bound AskUserQuestion handler — set after bot is created.
// When Claude needs clarification mid-session, this sends buttons to Discord
// and waits for the user's click.
// Uses an object wrapper so TypeScript doesn't narrow the closure to `never`.
const askUserState: { handler: ((input: AskUserQuestionInput) => Promise<Record<string, string>>) | null } = { handler: null };
// Late-bound PermissionRequest handler — set after bot is created.
// When Claude wants to use a tool that isn't pre-approved, this shows
// Allow/Deny buttons in Discord and returns the user's decision.
const permReqState: { handler: PermissionRequestCallback | null } = { handler: null };
// Create sendClaudeMessages function that uses the sender when available
const sendClaudeMessages = async (messages: ClaudeMessage[]) => {
if (claudeSender) {
await claudeSender(messages);
}
};
// Create onAskUser wrapper — delegates to askUserState.handler once bot is ready
const onAskUser = async (input: AskUserQuestionInput): Promise<Record<string, string>> => {
if (!askUserState.handler) {
throw new Error('AskUserQuestion handler not initialized — bot not ready');
}
return await askUserState.handler(input);
};
// Create onPermissionRequest wrapper — delegates to permReqState.handler once bot is ready
const onPermissionRequest: PermissionRequestCallback = async (toolName, toolInput) => {
if (!permReqState.handler) {
console.warn('[PermissionRequest] Handler not initialized — auto-denying');
return false;
}
return await permReqState.handler(toolName, toolInput);
};
// Create all handlers using the registry (centralized handler creation)
const allHandlers: AllHandlers = createAllHandlers(
{
workDir,
repoName,
branchName,
categoryName: actualCategoryName,
discordToken,
applicationId,
defaultMentionUserId,
shellManager,
worktreeBotManager,
crashHandler,
healthMonitor,
claudeSessionManager,
sendClaudeMessages,
onAskUser,
onPermissionRequest,
onBotSettingsUpdate: (settings) => {
botSettings.mentionEnabled = settings.mentionEnabled;
botSettings.mentionUserId = settings.mentionUserId;
if (bot) {
bot.updateBotSettings(settings);
}
},
sessionThreads: sessionThreadCallbacks,
},
{
getController: () => claudeController,
setController: (controller) => { claudeController = controller; },
getSessionId: () => claudeSessionId,
setSessionId: (sessionId) => { claudeSessionId = sessionId; },
},
settingsOps
);
// Create command handlers using the wrapper factory
const handlers: CommandHandlers = createAllCommandHandlers({
handlers: allHandlers,
messageHistory: messageHistoryOps,
getClaudeController: () => claudeController,
getClaudeSessionId: () => claudeSessionId,
crashHandler,
healthMonitor,
botSettings,
cleanupInterval,
});
// Create button handlers using the button handler factory
const buttonHandlers: ButtonHandlers = createButtonHandlers(
{
messageHistory: messageHistoryOps,
handlers: allHandlers,
getClaudeSessionId: () => claudeSessionId,
sendClaudeMessages,
workDir,
},
expandableContent
);
// Channel monitoring for auto-responding to bot/webhook messages
const monitorChannelId = Deno.env.get("MONITOR_CHANNEL_ID");
const monitorBotIds = Deno.env.get("MONITOR_BOT_IDS")?.split(",").map(s => s.trim()).filter(Boolean);
// Create dependencies object for Discord bot
const dependencies: BotDependencies = {
commands: getAllCommands(),
cleanSessionId,
botSettings,
onContinueSession: async (ctx) => {
await allHandlers.claude.onContinue(ctx);
},
...(monitorChannelId && monitorBotIds?.length && {
monitorConfig: {
channelId: monitorChannelId,
botIds: monitorBotIds,
onAlertMessage: async (content: string, thread: TextChannel) => {
const prompt = [
"A monitoring alert notification was just received. Investigate this alert.",
"Identify the alert, check severity, gather diagnostics, analyze the root cause, and report findings.",
"If a config change is needed, describe what should change. If it's a transient issue, report findings.",
"",
"Alert content:",
content,
].join("\n");
// Create a sender bound to the alert thread, not the bot's main channel
const threadSender = createClaudeSender(createChannelSenderAdapter(thread));
const controller = new AbortController();
await sendToClaudeCode(
workDir,
prompt,
controller,
undefined,
undefined,
(jsonData) => {
const claudeMessages = convertToClaudeMessages(jsonData);
if (claudeMessages.length > 0) {
threadSender(claudeMessages).catch(() => {});
}
},
false,
);
},
},
}),
};
// Create Discord bot
bot = await createDiscordBot(config, handlers, buttonHandlers, dependencies, crashHandler);
// Create Discord sender for Claude messages
claudeSender = createClaudeSender(createDiscordSenderAdapter(bot));
// Helper: resolve the target channel for the currently active session.
// If there's an active session thread, use that; otherwise fall back to main channel.
const getActiveSessionChannel = () => {
// Try to find the thread for the current session
if (claudeSessionId) {
const thread = sessionThreadManager.getThread(claudeSessionId);
if (thread) return thread;
}
// Also check for any pending (placeholder-keyed) threads
const allThreads = sessionThreadManager.getAllSessionThreads();
for (const meta of allThreads) {
if (meta.sessionId.startsWith('pending_')) {
const thread = sessionThreadManager.getThread(meta.sessionId);
if (thread) return thread;
}
}
return bot.getChannel();
};
// Initialize AskUserQuestion handler — sends questions to Discord, waits for button clicks
askUserState.handler = createAskUserDiscordHandler(bot, getActiveSessionChannel);
// Initialize PermissionRequest handler — shows Allow/Deny buttons for unapproved tools
permReqState.handler = createPermissionRequestHandler(bot, getActiveSessionChannel);
// Check for updates (non-blocking)
runVersionCheck().then(async ({ updateAvailable, embed }) => {
if (updateAvailable && embed) {
const channel = bot.getChannel();
if (channel) {
const { EmbedBuilder } = await import("npm:discord.js@14.14.1");
const discordEmbed = new EmbedBuilder()
.setColor(embed.color)
.setTitle(embed.title)
.setDescription(embed.description)
.setTimestamp();
embed.fields.forEach(f => discordEmbed.addFields(f));
await channel.send({ embeds: [discordEmbed] });
}
}
}).catch(() => { /* version check is best-effort */ });
// Start periodic update checks (every 12 hours)
startPeriodicUpdateCheck(async (result) => {
try {
const channel = bot.getChannel();
if (channel) {
const { EmbedBuilder } = await import("npm:discord.js@14.14.1");
const embed = new EmbedBuilder()
.setColor(0xFFA500)
.setTitle("🔄 Update Available")
.setDescription(`A newer version is available. You are running **v${BOT_VERSION}** (\`${result.localCommit}\`).`)
.addFields(
{ name: "Latest Commit", value: `\`${result.remoteCommit}\``, inline: true },
{
name: "How to Update",
value: Deno.env.get("DOCKER_CONTAINER")
? "```\ndocker compose pull && docker compose up -d\n```"
: "```\ngit pull origin main && deno task start\n```",
inline: false
}
)
.setTimestamp();
await channel.send({ embeds: [embed] });
}
} catch {
// Periodic notification is best-effort
}
});
// Setup signal handlers for graceful shutdown
setupSignalHandlers({
managers,
allHandlers,
getClaudeController: () => claudeController,
claudeSender,
actualCategoryName,
repoName,
branchName,
cleanupInterval,
// deno-lint-ignore no-explicit-any
bot: bot as any,
});
return bot;
}
// ================================
// Helper Functions
// ================================
/**
* Build a Discord.js payload from a MessageContent object and send it to a channel.
*/
// deno-lint-ignore no-explicit-any
async function sendMessageContent(channel: any, content: MessageContent): Promise<void> {
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = await import("npm:discord.js@14.14.1");
// deno-lint-ignore no-explicit-any
const payload: any = {};
if (content.content) payload.content = content.content;
if (content.embeds) {
payload.embeds = content.embeds.map(e => {
const embed = new EmbedBuilder();
if (e.color !== undefined) embed.setColor(e.color);
if (e.title) embed.setTitle(e.title);
if (e.description) embed.setDescription(e.description);
if (e.fields) e.fields.forEach(f => embed.addFields(f));
if (e.footer) embed.setFooter(e.footer);
if (e.timestamp) embed.setTimestamp();
return embed;
});
}
if (content.components) {
payload.components = content.components.map(row => {
// deno-lint-ignore no-explicit-any
const actionRow = new ActionRowBuilder<any>();
row.components.forEach(comp => {
const button = new ButtonBuilder()
.setCustomId(comp.customId)
.setLabel(comp.label);
switch (comp.style) {
case 'primary': button.setStyle(ButtonStyle.Primary); break;
case 'secondary': button.setStyle(ButtonStyle.Secondary); break;
case 'success': button.setStyle(ButtonStyle.Success); break;
case 'danger': button.setStyle(ButtonStyle.Danger); break;
case 'link': button.setStyle(ButtonStyle.Link); break;
}
actionRow.addComponents(button);
});
return actionRow;
});
}
await channel.send(payload);
}
/**
* Create Discord sender adapter from bot instance.
*/
// deno-lint-ignore no-explicit-any
function createDiscordSenderAdapter(bot: any): DiscordSender {
return {
async sendMessage(content) {
const channel = bot.getChannel();
if (channel) {
await sendMessageContent(channel, content);
}
}
};
}
/**
* Create Discord sender adapter that sends to a specific channel (e.g., a thread).
*/
// deno-lint-ignore no-explicit-any
function createChannelSenderAdapter(channel: any): DiscordSender {
return {
async sendMessage(content) {
await sendMessageContent(channel, content);
}
};
}
/**
* Create the AskUserQuestion handler that uses the Discord channel.
*
* When Claude calls the AskUserQuestion tool:
* 1. Builds embeds with option buttons for each question
* 2. Sends them to the bot's channel (or session thread if available)
* 3. Waits up to 5 minutes for button clicks
* 4. Returns answers to the SDK so Claude can continue
*/
// deno-lint-ignore no-explicit-any
function createAskUserDiscordHandler(bot: any, getTargetChannel?: () => any): (input: AskUserQuestionInput) => Promise<Record<string, string>> {
return async (input: AskUserQuestionInput): Promise<Record<string, string>> => {
const channel = getTargetChannel?.() ?? bot.getChannel();
if (!channel) {
throw new Error('Discord channel not available');
}
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType } = await import("npm:discord.js@14.14.1");
const answers: Record<string, string> = {};
for (let qi = 0; qi < input.questions.length; qi++) {
const q = input.questions[qi];
// Build embed
const embed = new EmbedBuilder()
.setColor(0xff9900)
.setTitle(`❓ Claude needs your input — ${q.header}`)
.setDescription(q.question)
.setFooter({ text: q.multiSelect ? 'Select option(s), then click ✅ Confirm — Claude is waiting' : 'Click an option to answer — Claude is waiting' })
.setTimestamp();
for (let oi = 0; oi < q.options.length; oi++) {
embed.addFields({ name: `${oi + 1}. ${q.options[oi].label}`, value: q.options[oi].description, inline: true });
}
// Build buttons
const row = new ActionRowBuilder();
for (let oi = 0; oi < q.options.length; oi++) {
row.addComponents(
new ButtonBuilder()
.setCustomId(`ask-user:${qi}:${oi}`)
.setLabel(q.options[oi].label)
.setStyle(ButtonStyle.Primary)
);
}
if (q.multiSelect) {
row.addComponents(
new ButtonBuilder()
.setCustomId(`ask-user-confirm:${qi}`)
.setLabel('✅ Confirm')
.setStyle(ButtonStyle.Success)
);
}
// Send the question message
const questionMsg = await channel.send({ embeds: [embed], components: [row] });
// Collect response
if (q.multiSelect) {
// Multi-select: collect multiple clicks, then wait for confirm
const selected: string[] = [];
const collector = questionMsg.createMessageComponentCollector({
componentType: ComponentType.Button,
});
await new Promise<void>((resolve, reject) => {
// deno-lint-ignore no-explicit-any
collector.on('collect', async (i: any) => {
const parsed = parseAskUserButtonId(i.customId);
if (parsed && parsed.questionIndex === qi) {
const label = q.options[parsed.optionIndex].label;
if (!selected.includes(label)) {
selected.push(label);
}
await i.update({
embeds: [embed.setFooter({ text: `Selected: ${selected.join(', ')} — click ✅ Confirm when done` })],
components: [row],
});
} else if (parseAskUserConfirmId(i.customId)?.questionIndex === qi) {
answers[q.question] = selected.join(', ');
collector.stop('confirmed');
await i.update({
embeds: [embed.setColor(0x00ff00).setFooter({ text: `✅ Answered: ${selected.join(', ')}` })],
components: [],
});
resolve();
}
});
collector.on('end', (_: unknown, reason: string) => {
if (reason !== 'confirmed') {
reject(new Error(`Question "${q.header}" was cancelled`));
}
});
});
} else {
// Single-select: wait for one button click
// deno-lint-ignore no-explicit-any
const interaction: any = await questionMsg.awaitMessageComponent({
componentType: ComponentType.Button,
});
const parsed = parseAskUserButtonId(interaction.customId);
if (parsed && parsed.questionIndex === qi) {
const label = q.options[parsed.optionIndex].label;
answers[q.question] = label;
await interaction.update({
embeds: [embed.setColor(0x00ff00).setFooter({ text: `✅ Answered: ${label}` })],
components: [],
});
} else {
throw new Error(`Unexpected button ID: ${interaction.customId}`);
}
}
}
console.log('[AskUserQuestion] Collected answers:', JSON.stringify(answers));
return answers;
};
}
/**
* Create the PermissionRequest handler that uses the Discord channel.
*
* When Claude wants to use a tool that isn't pre-approved:
* 1. Builds an embed showing the tool name and input preview
* 2. Adds Allow / Deny buttons
* 3. Sends to the bot's channel
* 4. Waits for a button click (no timeout — user decides)
* 5. Returns true (allow) or false (deny)
*/
// deno-lint-ignore no-explicit-any
function createPermissionRequestHandler(bot: any, getTargetChannel?: () => any): PermissionRequestCallback {
// Simple incrementing nonce to disambiguate concurrent requests
let nonce = 0;
return async (toolName: string, toolInput: Record<string, unknown>): Promise<boolean> => {
const channel = getTargetChannel?.() ?? bot.getChannel();
if (!channel) {
console.warn('[PermissionRequest] No channel — auto-denying');
return false;
}
const reqNonce = String(++nonce);
const embedData = buildPermissionEmbed(toolName, toolInput);
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType } = await import("npm:discord.js@14.14.1");
const embed = new EmbedBuilder()
.setColor(embedData.color)
.setTitle(embedData.title)
.setDescription(embedData.description)
.setFooter({ text: embedData.footer.text })
.setTimestamp();
for (const field of embedData.fields) {
embed.addFields({ name: field.name, value: field.value, inline: field.inline });
}
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId(`perm-req:${reqNonce}:allow`)
.setLabel('✅ Allow')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`perm-req:${reqNonce}:deny`)
.setLabel('❌ Deny')
.setStyle(ButtonStyle.Danger),
);
const msg = await channel.send({ embeds: [embed], components: [row] });
// Wait for exactly one button click — no timeout
// deno-lint-ignore no-explicit-any
const interaction: any = await msg.awaitMessageComponent({
componentType: ComponentType.Button,
});
const parsed = parsePermissionButtonId(interaction.customId);
const allowed = parsed?.allowed ?? false;
// Update the embed to reflect the decision
embed.setColor(allowed ? 0x00ff00 : 0xff4444)
.setFooter({ text: allowed ? `✅ Allowed by user` : `❌ Denied by user` });
await interaction.update({
embeds: [embed],
components: [], // Remove buttons after decision
});
console.log(`[PermissionRequest] Tool "${toolName}" — ${allowed ? 'ALLOWED' : 'DENIED'} by user`);
return allowed;
};
}
/**
* Setup signal handlers for graceful shutdown.
*/
function setupSignalHandlers(ctx: {
managers: BotManagers;
allHandlers: AllHandlers;
getClaudeController: () => AbortController | null;
claudeSender: ((messages: ClaudeMessage[]) => Promise<void>) | null;
actualCategoryName: string;
repoName: string;
branchName: string;
cleanupInterval: number;
// deno-lint-ignore no-explicit-any
bot: any;
}) {
const { managers, allHandlers, getClaudeController, claudeSender, actualCategoryName, repoName, branchName, cleanupInterval, bot } = ctx;
const { crashHandler, healthMonitor } = managers;
const { shell: shellHandlers, git: gitHandlers } = allHandlers;
const handleSignal = async (signal: string) => {
console.log(`\n${signal} signal received. Stopping bot...`);
try {
// Stop all processes
shellHandlers.killAllProcesses();
gitHandlers.killAllWorktreeBots();
// Cancel Claude Code session
const claudeController = getClaudeController();
if (claudeController) {
claudeController.abort();
}
// Send shutdown message
if (claudeSender) {
await claudeSender([{
type: 'system',
content: '',
metadata: {
subtype: 'shutdown',
signal,
categoryName: actualCategoryName,
repoName,
branchName
}
}]);
}
// Cleanup
healthMonitor.stopAll();
crashHandler.cleanup();
cleanupPaginationStates();
clearInterval(cleanupInterval);
setTimeout(() => {
bot.client.destroy();
Deno.exit(0);
}, 1000);
} catch (error) {
console.error('Error during shutdown:', error);
Deno.exit(1);
}
};
// Cross-platform signal handling
const platform = Deno.build.os;
try {
Deno.addSignalListener("SIGINT", () => handleSignal("SIGINT"));
if (platform === "windows") {
try {
Deno.addSignalListener("SIGBREAK", () => handleSignal("SIGBREAK"));
} catch (winError) {
const message = winError instanceof Error ? winError.message : String(winError);
console.warn('Could not register SIGBREAK handler:', message);
}
} else {
try {
Deno.addSignalListener("SIGTERM", () => handleSignal("SIGTERM"));
} catch (unixError) {
const message = unixError instanceof Error ? unixError.message : String(unixError);
console.warn('Could not register SIGTERM handler:', message);
}
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn('Signal handler registration error:', message);
}
}
// ================================
// .env Auto-Load
// ================================
/**
* Load environment variables from .env file if it exists.
* This enables zero-config startup when .env is present.
*/
async function loadEnvFile(): Promise<void> {
try {
const envPath = `${Deno.cwd()}/.env`;
const stat = await Deno.stat(envPath).catch(() => null);
if (!stat?.isFile) return;
const content = await Deno.readTextFile(envPath);
const lines = content.split('\n');
for (const line of lines) {
const trimmed = line.trim();
// Skip comments and empty lines
if (!trimmed || trimmed.startsWith('#')) continue;
// Parse KEY=VALUE format
const eqIndex = trimmed.indexOf('=');
if (eqIndex === -1) continue;
const key = trimmed.substring(0, eqIndex).trim();
let value = trimmed.substring(eqIndex + 1).trim();
// Remove surrounding quotes if present
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
// Only set if not already defined (env vars take precedence)
if (!Deno.env.get(key) && key && value) {
Deno.env.set(key, value);
}
}
console.log('✓ Loaded configuration from .env file');
} catch (error) {
// Silently ignore .env loading errors
const message = error instanceof Error ? error.message : String(error);
console.warn(`Note: Could not load .env file: ${message}`);
}
}
// ================================
// Main Execution
// ================================
if (import.meta.main) {
try {
// Auto-load .env file (if present)
await loadEnvFile();
// Get environment variables and command line arguments
const discordToken = Deno.env.get("DISCORD_TOKEN");
const applicationId = Deno.env.get("APPLICATION_ID");
const envCategoryName = Deno.env.get("CATEGORY_NAME");
const envMentionUserId = Deno.env.get("USER_ID") || Deno.env.get("DEFAULT_MENTION_USER_ID");
const envWorkDir = Deno.env.get("WORK_DIR");
if (!discordToken || !applicationId) {
console.error("╔═══════════════════════════════════════════════════════════╗");
console.error("║ Error: Missing required configuration ║");
console.error("╠═══════════════════════════════════════════════════════════╣");
console.error("║ DISCORD_TOKEN and APPLICATION_ID are required. ║");
console.error("║ ║");
console.error("║ Options: ║");
console.error("║ 1. Create a .env file with these variables ║");
console.error("║ 2. Set environment variables before running ║");
console.error("║ 3. Run setup script: ./setup.sh or .\\setup.ps1 ║");
console.error("╚═══════════════════════════════════════════════════════════╝");
Deno.exit(1);
}
// Parse command line arguments
const args = parseArgs(Deno.args);
const categoryName = args.category || envCategoryName;
const defaultMentionUserId = args.userId || envMentionUserId;
const workDir = envWorkDir || Deno.cwd();
// Get Git information
const gitInfo = await getGitInfo();
// Create and start bot
await createClaudeCodeBot({
discordToken,
applicationId,
workDir,
repoName: gitInfo.repo,
branchName: gitInfo.branch,
categoryName,
defaultMentionUserId,
});
console.log("✓ Bot has started. Press Ctrl+C to stop.");
} catch (error) {
console.error("Failed to start bot:", error);
Deno.exit(1);
}
}