kimaki 0.4.22 → 0.4.24

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.
@@ -0,0 +1,750 @@
1
+ import { ChannelType, Events, ThreadAutoArchiveDuration, } from 'discord.js';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { getDatabase } from './database.js';
6
+ import { initializeOpencodeForDirectory } from './opencode.js';
7
+ import { sendThreadMessage, resolveTextChannel, getKimakiMetadata, SILENT_MESSAGE_FLAGS, } from './discord-utils.js';
8
+ import { handleForkCommand, handleForkSelectMenu } from './fork.js';
9
+ import { handleModelCommand, handleProviderSelectMenu, handleModelSelectMenu, } from './model-command.js';
10
+ import { formatPart } from './message-formatting.js';
11
+ import { createProjectChannels } from './channel-management.js';
12
+ import { handleOpencodeSession, parseSlashCommand, abortControllers, pendingPermissions, } from './session-handler.js';
13
+ import { extractTagsArrays } from './xml.js';
14
+ import { createLogger } from './logger.js';
15
+ const discordLogger = createLogger('DISCORD');
16
+ const interactionLogger = createLogger('INTERACTION');
17
+ export function registerInteractionHandler({ discordClient, appId, }) {
18
+ interactionLogger.log('[REGISTER] Interaction handler registered');
19
+ discordClient.on(Events.InteractionCreate, async (interaction) => {
20
+ try {
21
+ interactionLogger.log(`[INTERACTION] Received: ${interaction.type} - ${interaction.isChatInputCommand() ? interaction.commandName : interaction.isAutocomplete() ? `autocomplete:${interaction.commandName}` : 'other'}`);
22
+ if (interaction.isAutocomplete()) {
23
+ if (interaction.commandName === 'resume') {
24
+ const focusedValue = interaction.options.getFocused();
25
+ let projectDirectory;
26
+ if (interaction.channel) {
27
+ const textChannel = await resolveTextChannel(interaction.channel);
28
+ if (textChannel) {
29
+ const { projectDirectory: directory, channelAppId } = getKimakiMetadata(textChannel);
30
+ if (channelAppId && channelAppId !== appId) {
31
+ await interaction.respond([]);
32
+ return;
33
+ }
34
+ projectDirectory = directory;
35
+ }
36
+ }
37
+ if (!projectDirectory) {
38
+ await interaction.respond([]);
39
+ return;
40
+ }
41
+ try {
42
+ const getClient = await initializeOpencodeForDirectory(projectDirectory);
43
+ const sessionsResponse = await getClient().session.list();
44
+ if (!sessionsResponse.data) {
45
+ await interaction.respond([]);
46
+ return;
47
+ }
48
+ const existingSessionIds = new Set(getDatabase()
49
+ .prepare('SELECT session_id FROM thread_sessions')
50
+ .all().map((row) => row.session_id));
51
+ const sessions = sessionsResponse.data
52
+ .filter((session) => !existingSessionIds.has(session.id))
53
+ .filter((session) => session.title
54
+ .toLowerCase()
55
+ .includes(focusedValue.toLowerCase()))
56
+ .slice(0, 25)
57
+ .map((session) => {
58
+ const dateStr = new Date(session.time.updated).toLocaleString();
59
+ const suffix = ` (${dateStr})`;
60
+ const maxTitleLength = 100 - suffix.length;
61
+ let title = session.title;
62
+ if (title.length > maxTitleLength) {
63
+ title = title.slice(0, Math.max(0, maxTitleLength - 1)) + '…';
64
+ }
65
+ return {
66
+ name: `${title}${suffix}`,
67
+ value: session.id,
68
+ };
69
+ });
70
+ await interaction.respond(sessions);
71
+ }
72
+ catch (error) {
73
+ interactionLogger.error('[AUTOCOMPLETE] Error fetching sessions:', error);
74
+ await interaction.respond([]);
75
+ }
76
+ }
77
+ else if (interaction.commandName === 'session') {
78
+ const focusedOption = interaction.options.getFocused(true);
79
+ if (focusedOption.name === 'files') {
80
+ const focusedValue = focusedOption.value;
81
+ const parts = focusedValue.split(',');
82
+ const previousFiles = parts
83
+ .slice(0, -1)
84
+ .map((f) => f.trim())
85
+ .filter((f) => f);
86
+ const currentQuery = (parts[parts.length - 1] || '').trim();
87
+ let projectDirectory;
88
+ if (interaction.channel) {
89
+ const textChannel = await resolveTextChannel(interaction.channel);
90
+ if (textChannel) {
91
+ const { projectDirectory: directory, channelAppId } = getKimakiMetadata(textChannel);
92
+ if (channelAppId && channelAppId !== appId) {
93
+ await interaction.respond([]);
94
+ return;
95
+ }
96
+ projectDirectory = directory;
97
+ }
98
+ }
99
+ if (!projectDirectory) {
100
+ await interaction.respond([]);
101
+ return;
102
+ }
103
+ try {
104
+ const getClient = await initializeOpencodeForDirectory(projectDirectory);
105
+ const response = await getClient().find.files({
106
+ query: {
107
+ query: currentQuery || '',
108
+ },
109
+ });
110
+ const files = response.data || [];
111
+ const prefix = previousFiles.length > 0
112
+ ? previousFiles.join(', ') + ', '
113
+ : '';
114
+ const choices = files
115
+ .map((file) => {
116
+ const fullValue = prefix + file;
117
+ const allFiles = [...previousFiles, file];
118
+ const allBasenames = allFiles.map((f) => f.split('/').pop() || f);
119
+ let displayName = allBasenames.join(', ');
120
+ if (displayName.length > 100) {
121
+ displayName = '…' + displayName.slice(-97);
122
+ }
123
+ return {
124
+ name: displayName,
125
+ value: fullValue,
126
+ };
127
+ })
128
+ .filter((choice) => choice.value.length <= 100)
129
+ .slice(0, 25);
130
+ await interaction.respond(choices);
131
+ }
132
+ catch (error) {
133
+ interactionLogger.error('[AUTOCOMPLETE] Error fetching files:', error);
134
+ await interaction.respond([]);
135
+ }
136
+ }
137
+ }
138
+ else if (interaction.commandName === 'add-project') {
139
+ const focusedValue = interaction.options.getFocused();
140
+ try {
141
+ const currentDir = process.cwd();
142
+ const getClient = await initializeOpencodeForDirectory(currentDir);
143
+ const projectsResponse = await getClient().project.list({});
144
+ if (!projectsResponse.data) {
145
+ await interaction.respond([]);
146
+ return;
147
+ }
148
+ const db = getDatabase();
149
+ const existingDirs = db
150
+ .prepare('SELECT DISTINCT directory FROM channel_directories WHERE channel_type = ?')
151
+ .all('text');
152
+ const existingDirSet = new Set(existingDirs.map((row) => row.directory));
153
+ const availableProjects = projectsResponse.data.filter((project) => !existingDirSet.has(project.worktree));
154
+ const projects = availableProjects
155
+ .filter((project) => {
156
+ const baseName = path.basename(project.worktree);
157
+ const searchText = `${baseName} ${project.worktree}`.toLowerCase();
158
+ return searchText.includes(focusedValue.toLowerCase());
159
+ })
160
+ .sort((a, b) => {
161
+ const aTime = a.time.initialized || a.time.created;
162
+ const bTime = b.time.initialized || b.time.created;
163
+ return bTime - aTime;
164
+ })
165
+ .slice(0, 25)
166
+ .map((project) => {
167
+ const name = `${path.basename(project.worktree)} (${project.worktree})`;
168
+ return {
169
+ name: name.length > 100 ? name.slice(0, 99) + '…' : name,
170
+ value: project.id,
171
+ };
172
+ });
173
+ await interaction.respond(projects);
174
+ }
175
+ catch (error) {
176
+ interactionLogger.error('[AUTOCOMPLETE] Error fetching projects:', error);
177
+ await interaction.respond([]);
178
+ }
179
+ }
180
+ }
181
+ if (interaction.isChatInputCommand()) {
182
+ const command = interaction;
183
+ interactionLogger.log(`[COMMAND] Processing: ${command.commandName}`);
184
+ if (command.commandName === 'session') {
185
+ await command.deferReply({ ephemeral: false });
186
+ const prompt = command.options.getString('prompt', true);
187
+ const filesString = command.options.getString('files') || '';
188
+ const channel = command.channel;
189
+ if (!channel || channel.type !== ChannelType.GuildText) {
190
+ await command.editReply('This command can only be used in text channels');
191
+ return;
192
+ }
193
+ const textChannel = channel;
194
+ let projectDirectory;
195
+ let channelAppId;
196
+ if (textChannel.topic) {
197
+ const extracted = extractTagsArrays({
198
+ xml: textChannel.topic,
199
+ tags: ['kimaki.directory', 'kimaki.app'],
200
+ });
201
+ projectDirectory = extracted['kimaki.directory']?.[0]?.trim();
202
+ channelAppId = extracted['kimaki.app']?.[0]?.trim();
203
+ }
204
+ if (channelAppId && channelAppId !== appId) {
205
+ await command.editReply('This channel is not configured for this bot');
206
+ return;
207
+ }
208
+ if (!projectDirectory) {
209
+ await command.editReply('This channel is not configured with a project directory');
210
+ return;
211
+ }
212
+ if (!fs.existsSync(projectDirectory)) {
213
+ await command.editReply(`Directory does not exist: ${projectDirectory}`);
214
+ return;
215
+ }
216
+ try {
217
+ const getClient = await initializeOpencodeForDirectory(projectDirectory);
218
+ const files = filesString
219
+ .split(',')
220
+ .map((f) => f.trim())
221
+ .filter((f) => f);
222
+ let fullPrompt = prompt;
223
+ if (files.length > 0) {
224
+ fullPrompt = `${prompt}\n\n@${files.join(' @')}`;
225
+ }
226
+ const starterMessage = await textChannel.send({
227
+ content: `🚀 **Starting OpenCode session**\n📝 ${prompt.slice(0, 200)}${prompt.length > 200 ? '…' : ''}${files.length > 0 ? `\n📎 Files: ${files.join(', ')}` : ''}`,
228
+ flags: SILENT_MESSAGE_FLAGS,
229
+ });
230
+ const thread = await starterMessage.startThread({
231
+ name: prompt.slice(0, 100),
232
+ autoArchiveDuration: 1440,
233
+ reason: 'OpenCode session',
234
+ });
235
+ await command.editReply(`Created new session in ${thread.toString()}`);
236
+ const parsedCommand = parseSlashCommand(fullPrompt);
237
+ await handleOpencodeSession({
238
+ prompt: fullPrompt,
239
+ thread,
240
+ projectDirectory,
241
+ parsedCommand,
242
+ channelId: textChannel.id,
243
+ });
244
+ }
245
+ catch (error) {
246
+ interactionLogger.error('[SESSION] Error:', error);
247
+ await command.editReply(`Failed to create session: ${error instanceof Error ? error.message : 'Unknown error'}`);
248
+ }
249
+ }
250
+ else if (command.commandName === 'resume') {
251
+ await command.deferReply({ ephemeral: false });
252
+ const sessionId = command.options.getString('session', true);
253
+ const channel = command.channel;
254
+ if (!channel || channel.type !== ChannelType.GuildText) {
255
+ await command.editReply('This command can only be used in text channels');
256
+ return;
257
+ }
258
+ const textChannel = channel;
259
+ let projectDirectory;
260
+ let channelAppId;
261
+ if (textChannel.topic) {
262
+ const extracted = extractTagsArrays({
263
+ xml: textChannel.topic,
264
+ tags: ['kimaki.directory', 'kimaki.app'],
265
+ });
266
+ projectDirectory = extracted['kimaki.directory']?.[0]?.trim();
267
+ channelAppId = extracted['kimaki.app']?.[0]?.trim();
268
+ }
269
+ if (channelAppId && channelAppId !== appId) {
270
+ await command.editReply('This channel is not configured for this bot');
271
+ return;
272
+ }
273
+ if (!projectDirectory) {
274
+ await command.editReply('This channel is not configured with a project directory');
275
+ return;
276
+ }
277
+ if (!fs.existsSync(projectDirectory)) {
278
+ await command.editReply(`Directory does not exist: ${projectDirectory}`);
279
+ return;
280
+ }
281
+ try {
282
+ const getClient = await initializeOpencodeForDirectory(projectDirectory);
283
+ const sessionResponse = await getClient().session.get({
284
+ path: { id: sessionId },
285
+ });
286
+ if (!sessionResponse.data) {
287
+ await command.editReply('Session not found');
288
+ return;
289
+ }
290
+ const sessionTitle = sessionResponse.data.title;
291
+ const thread = await textChannel.threads.create({
292
+ name: `Resume: ${sessionTitle}`.slice(0, 100),
293
+ autoArchiveDuration: ThreadAutoArchiveDuration.OneDay,
294
+ reason: `Resuming session ${sessionId}`,
295
+ });
296
+ getDatabase()
297
+ .prepare('INSERT OR REPLACE INTO thread_sessions (thread_id, session_id) VALUES (?, ?)')
298
+ .run(thread.id, sessionId);
299
+ interactionLogger.log(`[RESUME] Created thread ${thread.id} for session ${sessionId}`);
300
+ const messagesResponse = await getClient().session.messages({
301
+ path: { id: sessionId },
302
+ });
303
+ if (!messagesResponse.data) {
304
+ throw new Error('Failed to fetch session messages');
305
+ }
306
+ const messages = messagesResponse.data;
307
+ await command.editReply(`Resumed session "${sessionTitle}" in ${thread.toString()}`);
308
+ await sendThreadMessage(thread, `📂 **Resumed session:** ${sessionTitle}\n📅 **Created:** ${new Date(sessionResponse.data.time.created).toLocaleString()}\n\n*Loading ${messages.length} messages...*`);
309
+ const allAssistantParts = [];
310
+ for (const message of messages) {
311
+ if (message.info.role === 'assistant') {
312
+ for (const part of message.parts) {
313
+ const content = formatPart(part);
314
+ if (content.trim()) {
315
+ allAssistantParts.push({ id: part.id, content });
316
+ }
317
+ }
318
+ }
319
+ }
320
+ const partsToRender = allAssistantParts.slice(-30);
321
+ const skippedCount = allAssistantParts.length - partsToRender.length;
322
+ if (skippedCount > 0) {
323
+ await sendThreadMessage(thread, `*Skipped ${skippedCount} older assistant parts...*`);
324
+ }
325
+ if (partsToRender.length > 0) {
326
+ const combinedContent = partsToRender
327
+ .map((p) => p.content)
328
+ .join('\n');
329
+ const discordMessage = await sendThreadMessage(thread, combinedContent);
330
+ const stmt = getDatabase().prepare('INSERT OR REPLACE INTO part_messages (part_id, message_id, thread_id) VALUES (?, ?, ?)');
331
+ const transaction = getDatabase().transaction((parts) => {
332
+ for (const part of parts) {
333
+ stmt.run(part.id, discordMessage.id, thread.id);
334
+ }
335
+ });
336
+ transaction(partsToRender);
337
+ }
338
+ const messageCount = messages.length;
339
+ await sendThreadMessage(thread, `✅ **Session resumed!** Loaded ${messageCount} messages.\n\nYou can now continue the conversation by sending messages in this thread.`);
340
+ }
341
+ catch (error) {
342
+ interactionLogger.error('[RESUME] Error:', error);
343
+ await command.editReply(`Failed to resume session: ${error instanceof Error ? error.message : 'Unknown error'}`);
344
+ }
345
+ }
346
+ else if (command.commandName === 'add-project') {
347
+ await command.deferReply({ ephemeral: false });
348
+ const projectId = command.options.getString('project', true);
349
+ const guild = command.guild;
350
+ if (!guild) {
351
+ await command.editReply('This command can only be used in a guild');
352
+ return;
353
+ }
354
+ try {
355
+ const currentDir = process.cwd();
356
+ const getClient = await initializeOpencodeForDirectory(currentDir);
357
+ const projectsResponse = await getClient().project.list({});
358
+ if (!projectsResponse.data) {
359
+ await command.editReply('Failed to fetch projects');
360
+ return;
361
+ }
362
+ const project = projectsResponse.data.find((p) => p.id === projectId);
363
+ if (!project) {
364
+ await command.editReply('Project not found');
365
+ return;
366
+ }
367
+ const directory = project.worktree;
368
+ if (!fs.existsSync(directory)) {
369
+ await command.editReply(`Directory does not exist: ${directory}`);
370
+ return;
371
+ }
372
+ const db = getDatabase();
373
+ const existingChannel = db
374
+ .prepare('SELECT channel_id FROM channel_directories WHERE directory = ? AND channel_type = ?')
375
+ .get(directory, 'text');
376
+ if (existingChannel) {
377
+ await command.editReply(`A channel already exists for this directory: <#${existingChannel.channel_id}>`);
378
+ return;
379
+ }
380
+ const { textChannelId, voiceChannelId, channelName } = await createProjectChannels({
381
+ guild,
382
+ projectDirectory: directory,
383
+ appId,
384
+ });
385
+ await command.editReply(`✅ Created channels for project:\n📝 Text: <#${textChannelId}>\n🔊 Voice: <#${voiceChannelId}>\n📁 Directory: \`${directory}\``);
386
+ discordLogger.log(`Created channels for project ${channelName} at ${directory}`);
387
+ }
388
+ catch (error) {
389
+ interactionLogger.error('[ADD-PROJECT] Error:', error);
390
+ await command.editReply(`Failed to create channels: ${error instanceof Error ? error.message : 'Unknown error'}`);
391
+ }
392
+ }
393
+ else if (command.commandName === 'create-new-project') {
394
+ await command.deferReply({ ephemeral: false });
395
+ const projectName = command.options.getString('name', true);
396
+ const guild = command.guild;
397
+ const channel = command.channel;
398
+ if (!guild) {
399
+ await command.editReply('This command can only be used in a guild');
400
+ return;
401
+ }
402
+ if (!channel || channel.type !== ChannelType.GuildText) {
403
+ await command.editReply('This command can only be used in a text channel');
404
+ return;
405
+ }
406
+ const sanitizedName = projectName
407
+ .toLowerCase()
408
+ .replace(/[^a-z0-9-]/g, '-')
409
+ .replace(/-+/g, '-')
410
+ .replace(/^-|-$/g, '')
411
+ .slice(0, 100);
412
+ if (!sanitizedName) {
413
+ await command.editReply('Invalid project name');
414
+ return;
415
+ }
416
+ const kimakiDir = path.join(os.homedir(), 'kimaki');
417
+ const projectDirectory = path.join(kimakiDir, sanitizedName);
418
+ try {
419
+ if (!fs.existsSync(kimakiDir)) {
420
+ fs.mkdirSync(kimakiDir, { recursive: true });
421
+ discordLogger.log(`Created kimaki directory: ${kimakiDir}`);
422
+ }
423
+ if (fs.existsSync(projectDirectory)) {
424
+ await command.editReply(`Project directory already exists: ${projectDirectory}`);
425
+ return;
426
+ }
427
+ fs.mkdirSync(projectDirectory, { recursive: true });
428
+ discordLogger.log(`Created project directory: ${projectDirectory}`);
429
+ const { execSync } = await import('node:child_process');
430
+ execSync('git init', { cwd: projectDirectory, stdio: 'pipe' });
431
+ discordLogger.log(`Initialized git in: ${projectDirectory}`);
432
+ const { textChannelId, voiceChannelId, channelName } = await createProjectChannels({
433
+ guild,
434
+ projectDirectory,
435
+ appId,
436
+ });
437
+ const textChannel = await guild.channels.fetch(textChannelId);
438
+ await command.editReply(`✅ Created new project **${sanitizedName}**\n📁 Directory: \`${projectDirectory}\`\n📝 Text: <#${textChannelId}>\n🔊 Voice: <#${voiceChannelId}>\n\n_Starting session..._`);
439
+ const starterMessage = await textChannel.send({
440
+ content: `🚀 **New project initialized**\n📁 \`${projectDirectory}\``,
441
+ flags: SILENT_MESSAGE_FLAGS,
442
+ });
443
+ const thread = await starterMessage.startThread({
444
+ name: `Init: ${sanitizedName}`,
445
+ autoArchiveDuration: 1440,
446
+ reason: 'New project session',
447
+ });
448
+ await handleOpencodeSession({
449
+ prompt: 'The project was just initialized. Say hi and ask what the user wants to build.',
450
+ thread,
451
+ projectDirectory,
452
+ channelId: textChannel.id,
453
+ });
454
+ discordLogger.log(`Created new project ${channelName} at ${projectDirectory}`);
455
+ }
456
+ catch (error) {
457
+ interactionLogger.error('[ADD-NEW-PROJECT] Error:', error);
458
+ await command.editReply(`Failed to create new project: ${error instanceof Error ? error.message : 'Unknown error'}`);
459
+ }
460
+ }
461
+ else if (command.commandName === 'accept' ||
462
+ command.commandName === 'accept-always') {
463
+ const scope = command.commandName === 'accept-always' ? 'always' : 'once';
464
+ const channel = command.channel;
465
+ if (!channel) {
466
+ await command.reply({
467
+ content: 'This command can only be used in a channel',
468
+ ephemeral: true,
469
+ flags: SILENT_MESSAGE_FLAGS,
470
+ });
471
+ return;
472
+ }
473
+ const isThread = [
474
+ ChannelType.PublicThread,
475
+ ChannelType.PrivateThread,
476
+ ChannelType.AnnouncementThread,
477
+ ].includes(channel.type);
478
+ if (!isThread) {
479
+ await command.reply({
480
+ content: 'This command can only be used in a thread with an active session',
481
+ ephemeral: true,
482
+ flags: SILENT_MESSAGE_FLAGS,
483
+ });
484
+ return;
485
+ }
486
+ const pending = pendingPermissions.get(channel.id);
487
+ if (!pending) {
488
+ await command.reply({
489
+ content: 'No pending permission request in this thread',
490
+ ephemeral: true,
491
+ flags: SILENT_MESSAGE_FLAGS,
492
+ });
493
+ return;
494
+ }
495
+ try {
496
+ const getClient = await initializeOpencodeForDirectory(pending.directory);
497
+ await getClient().postSessionIdPermissionsPermissionId({
498
+ path: {
499
+ id: pending.permission.sessionID,
500
+ permissionID: pending.permission.id,
501
+ },
502
+ body: {
503
+ response: scope,
504
+ },
505
+ });
506
+ pendingPermissions.delete(channel.id);
507
+ const msg = scope === 'always'
508
+ ? `✅ Permission **accepted** (auto-approve similar requests)`
509
+ : `✅ Permission **accepted**`;
510
+ await command.reply({ content: msg, flags: SILENT_MESSAGE_FLAGS });
511
+ discordLogger.log(`Permission ${pending.permission.id} accepted with scope: ${scope}`);
512
+ }
513
+ catch (error) {
514
+ interactionLogger.error('[ACCEPT] Error:', error);
515
+ await command.reply({
516
+ content: `Failed to accept permission: ${error instanceof Error ? error.message : 'Unknown error'}`,
517
+ ephemeral: true,
518
+ flags: SILENT_MESSAGE_FLAGS,
519
+ });
520
+ }
521
+ }
522
+ else if (command.commandName === 'reject') {
523
+ const channel = command.channel;
524
+ if (!channel) {
525
+ await command.reply({
526
+ content: 'This command can only be used in a channel',
527
+ ephemeral: true,
528
+ flags: SILENT_MESSAGE_FLAGS,
529
+ });
530
+ return;
531
+ }
532
+ const isThread = [
533
+ ChannelType.PublicThread,
534
+ ChannelType.PrivateThread,
535
+ ChannelType.AnnouncementThread,
536
+ ].includes(channel.type);
537
+ if (!isThread) {
538
+ await command.reply({
539
+ content: 'This command can only be used in a thread with an active session',
540
+ ephemeral: true,
541
+ flags: SILENT_MESSAGE_FLAGS,
542
+ });
543
+ return;
544
+ }
545
+ const pending = pendingPermissions.get(channel.id);
546
+ if (!pending) {
547
+ await command.reply({
548
+ content: 'No pending permission request in this thread',
549
+ ephemeral: true,
550
+ flags: SILENT_MESSAGE_FLAGS,
551
+ });
552
+ return;
553
+ }
554
+ try {
555
+ const getClient = await initializeOpencodeForDirectory(pending.directory);
556
+ await getClient().postSessionIdPermissionsPermissionId({
557
+ path: {
558
+ id: pending.permission.sessionID,
559
+ permissionID: pending.permission.id,
560
+ },
561
+ body: {
562
+ response: 'reject',
563
+ },
564
+ });
565
+ pendingPermissions.delete(channel.id);
566
+ await command.reply({ content: `❌ Permission **rejected**`, flags: SILENT_MESSAGE_FLAGS });
567
+ discordLogger.log(`Permission ${pending.permission.id} rejected`);
568
+ }
569
+ catch (error) {
570
+ interactionLogger.error('[REJECT] Error:', error);
571
+ await command.reply({
572
+ content: `Failed to reject permission: ${error instanceof Error ? error.message : 'Unknown error'}`,
573
+ ephemeral: true,
574
+ flags: SILENT_MESSAGE_FLAGS,
575
+ });
576
+ }
577
+ }
578
+ else if (command.commandName === 'abort') {
579
+ const channel = command.channel;
580
+ if (!channel) {
581
+ await command.reply({
582
+ content: 'This command can only be used in a channel',
583
+ ephemeral: true,
584
+ flags: SILENT_MESSAGE_FLAGS,
585
+ });
586
+ return;
587
+ }
588
+ const isThread = [
589
+ ChannelType.PublicThread,
590
+ ChannelType.PrivateThread,
591
+ ChannelType.AnnouncementThread,
592
+ ].includes(channel.type);
593
+ if (!isThread) {
594
+ await command.reply({
595
+ content: 'This command can only be used in a thread with an active session',
596
+ ephemeral: true,
597
+ flags: SILENT_MESSAGE_FLAGS,
598
+ });
599
+ return;
600
+ }
601
+ const textChannel = await resolveTextChannel(channel);
602
+ const { projectDirectory: directory } = getKimakiMetadata(textChannel);
603
+ if (!directory) {
604
+ await command.reply({
605
+ content: 'Could not determine project directory for this channel',
606
+ ephemeral: true,
607
+ flags: SILENT_MESSAGE_FLAGS,
608
+ });
609
+ return;
610
+ }
611
+ const row = getDatabase()
612
+ .prepare('SELECT session_id FROM thread_sessions WHERE thread_id = ?')
613
+ .get(channel.id);
614
+ if (!row?.session_id) {
615
+ await command.reply({
616
+ content: 'No active session in this thread',
617
+ ephemeral: true,
618
+ flags: SILENT_MESSAGE_FLAGS,
619
+ });
620
+ return;
621
+ }
622
+ const sessionId = row.session_id;
623
+ try {
624
+ const existingController = abortControllers.get(sessionId);
625
+ if (existingController) {
626
+ existingController.abort(new Error('User requested abort'));
627
+ abortControllers.delete(sessionId);
628
+ }
629
+ const getClient = await initializeOpencodeForDirectory(directory);
630
+ await getClient().session.abort({
631
+ path: { id: sessionId },
632
+ });
633
+ await command.reply({ content: `🛑 Request **aborted**`, flags: SILENT_MESSAGE_FLAGS });
634
+ discordLogger.log(`Session ${sessionId} aborted by user`);
635
+ }
636
+ catch (error) {
637
+ interactionLogger.error('[ABORT] Error:', error);
638
+ await command.reply({
639
+ content: `Failed to abort: ${error instanceof Error ? error.message : 'Unknown error'}`,
640
+ ephemeral: true,
641
+ flags: SILENT_MESSAGE_FLAGS,
642
+ });
643
+ }
644
+ }
645
+ else if (command.commandName === 'share') {
646
+ const channel = command.channel;
647
+ if (!channel) {
648
+ await command.reply({
649
+ content: 'This command can only be used in a channel',
650
+ ephemeral: true,
651
+ flags: SILENT_MESSAGE_FLAGS,
652
+ });
653
+ return;
654
+ }
655
+ const isThread = [
656
+ ChannelType.PublicThread,
657
+ ChannelType.PrivateThread,
658
+ ChannelType.AnnouncementThread,
659
+ ].includes(channel.type);
660
+ if (!isThread) {
661
+ await command.reply({
662
+ content: 'This command can only be used in a thread with an active session',
663
+ ephemeral: true,
664
+ flags: SILENT_MESSAGE_FLAGS,
665
+ });
666
+ return;
667
+ }
668
+ const textChannel = await resolveTextChannel(channel);
669
+ const { projectDirectory: directory } = getKimakiMetadata(textChannel);
670
+ if (!directory) {
671
+ await command.reply({
672
+ content: 'Could not determine project directory for this channel',
673
+ ephemeral: true,
674
+ flags: SILENT_MESSAGE_FLAGS,
675
+ });
676
+ return;
677
+ }
678
+ const row = getDatabase()
679
+ .prepare('SELECT session_id FROM thread_sessions WHERE thread_id = ?')
680
+ .get(channel.id);
681
+ if (!row?.session_id) {
682
+ await command.reply({
683
+ content: 'No active session in this thread',
684
+ ephemeral: true,
685
+ flags: SILENT_MESSAGE_FLAGS,
686
+ });
687
+ return;
688
+ }
689
+ const sessionId = row.session_id;
690
+ try {
691
+ const getClient = await initializeOpencodeForDirectory(directory);
692
+ const response = await getClient().session.share({
693
+ path: { id: sessionId },
694
+ });
695
+ if (!response.data?.share?.url) {
696
+ await command.reply({
697
+ content: 'Failed to generate share URL',
698
+ ephemeral: true,
699
+ flags: SILENT_MESSAGE_FLAGS,
700
+ });
701
+ return;
702
+ }
703
+ await command.reply({ content: `🔗 **Session shared:** ${response.data.share.url}`, flags: SILENT_MESSAGE_FLAGS });
704
+ discordLogger.log(`Session ${sessionId} shared: ${response.data.share.url}`);
705
+ }
706
+ catch (error) {
707
+ interactionLogger.error('[SHARE] Error:', error);
708
+ await command.reply({
709
+ content: `Failed to share session: ${error instanceof Error ? error.message : 'Unknown error'}`,
710
+ ephemeral: true,
711
+ flags: SILENT_MESSAGE_FLAGS,
712
+ });
713
+ }
714
+ }
715
+ else if (command.commandName === 'fork') {
716
+ await handleForkCommand(command);
717
+ }
718
+ else if (command.commandName === 'model') {
719
+ await handleModelCommand({ interaction: command, appId });
720
+ }
721
+ }
722
+ if (interaction.isStringSelectMenu()) {
723
+ if (interaction.customId.startsWith('fork_select:')) {
724
+ await handleForkSelectMenu(interaction);
725
+ }
726
+ else if (interaction.customId.startsWith('model_provider:')) {
727
+ await handleProviderSelectMenu(interaction);
728
+ }
729
+ else if (interaction.customId.startsWith('model_select:')) {
730
+ await handleModelSelectMenu(interaction);
731
+ }
732
+ }
733
+ }
734
+ catch (error) {
735
+ interactionLogger.error('[INTERACTION] Error handling interaction:', error);
736
+ // Try to respond to the interaction if possible
737
+ try {
738
+ if (interaction.isRepliable() && !interaction.replied && !interaction.deferred) {
739
+ await interaction.reply({
740
+ content: 'An error occurred processing this command.',
741
+ ephemeral: true,
742
+ });
743
+ }
744
+ }
745
+ catch (replyError) {
746
+ interactionLogger.error('[INTERACTION] Failed to send error reply:', replyError);
747
+ }
748
+ }
749
+ });
750
+ }