kimaki 0.4.24 → 0.4.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.
Files changed (86) hide show
  1. package/bin.js +6 -1
  2. package/dist/acp-client.test.js +149 -0
  3. package/dist/ai-tool-to-genai.js +3 -0
  4. package/dist/channel-management.js +14 -9
  5. package/dist/cli.js +148 -17
  6. package/dist/commands/abort.js +78 -0
  7. package/dist/commands/add-project.js +98 -0
  8. package/dist/commands/agent.js +152 -0
  9. package/dist/commands/ask-question.js +183 -0
  10. package/dist/commands/create-new-project.js +78 -0
  11. package/dist/commands/fork.js +186 -0
  12. package/dist/commands/model.js +313 -0
  13. package/dist/commands/permissions.js +126 -0
  14. package/dist/commands/queue.js +129 -0
  15. package/dist/commands/resume.js +145 -0
  16. package/dist/commands/session.js +142 -0
  17. package/dist/commands/share.js +80 -0
  18. package/dist/commands/types.js +2 -0
  19. package/dist/commands/undo-redo.js +161 -0
  20. package/dist/commands/user-command.js +145 -0
  21. package/dist/database.js +54 -0
  22. package/dist/discord-bot.js +35 -32
  23. package/dist/discord-utils.js +81 -15
  24. package/dist/format-tables.js +3 -0
  25. package/dist/genai-worker-wrapper.js +3 -0
  26. package/dist/genai-worker.js +3 -0
  27. package/dist/genai.js +3 -0
  28. package/dist/interaction-handler.js +89 -695
  29. package/dist/logger.js +46 -5
  30. package/dist/markdown.js +107 -0
  31. package/dist/markdown.test.js +31 -1
  32. package/dist/message-formatting.js +113 -28
  33. package/dist/message-formatting.test.js +73 -0
  34. package/dist/opencode.js +73 -16
  35. package/dist/session-handler.js +176 -63
  36. package/dist/system-message.js +7 -38
  37. package/dist/tools.js +3 -0
  38. package/dist/utils.js +3 -0
  39. package/dist/voice-handler.js +21 -8
  40. package/dist/voice.js +31 -12
  41. package/dist/worker-types.js +3 -0
  42. package/dist/xml.js +3 -0
  43. package/package.json +3 -3
  44. package/src/__snapshots__/compact-session-context-no-system.md +35 -0
  45. package/src/__snapshots__/compact-session-context.md +47 -0
  46. package/src/ai-tool-to-genai.ts +4 -0
  47. package/src/channel-management.ts +24 -8
  48. package/src/cli.ts +163 -18
  49. package/src/commands/abort.ts +94 -0
  50. package/src/commands/add-project.ts +139 -0
  51. package/src/commands/agent.ts +201 -0
  52. package/src/commands/ask-question.ts +276 -0
  53. package/src/commands/create-new-project.ts +111 -0
  54. package/src/{fork.ts → commands/fork.ts} +40 -7
  55. package/src/{model-command.ts → commands/model.ts} +31 -9
  56. package/src/commands/permissions.ts +146 -0
  57. package/src/commands/queue.ts +181 -0
  58. package/src/commands/resume.ts +230 -0
  59. package/src/commands/session.ts +184 -0
  60. package/src/commands/share.ts +96 -0
  61. package/src/commands/types.ts +25 -0
  62. package/src/commands/undo-redo.ts +213 -0
  63. package/src/commands/user-command.ts +178 -0
  64. package/src/database.ts +65 -0
  65. package/src/discord-bot.ts +40 -33
  66. package/src/discord-utils.ts +88 -14
  67. package/src/format-tables.ts +4 -0
  68. package/src/genai-worker-wrapper.ts +4 -0
  69. package/src/genai-worker.ts +4 -0
  70. package/src/genai.ts +4 -0
  71. package/src/interaction-handler.ts +111 -924
  72. package/src/logger.ts +51 -10
  73. package/src/markdown.test.ts +45 -1
  74. package/src/markdown.ts +136 -0
  75. package/src/message-formatting.test.ts +81 -0
  76. package/src/message-formatting.ts +143 -30
  77. package/src/opencode.ts +84 -21
  78. package/src/session-handler.ts +248 -91
  79. package/src/system-message.ts +8 -38
  80. package/src/tools.ts +4 -0
  81. package/src/utils.ts +4 -0
  82. package/src/voice-handler.ts +24 -9
  83. package/src/voice.ts +36 -13
  84. package/src/worker-types.ts +4 -0
  85. package/src/xml.ts +4 -0
  86. package/README.md +0 -48
@@ -1,739 +1,133 @@
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';
1
+ // Discord slash command and interaction handler.
2
+ // Processes all slash commands (/session, /resume, /fork, /model, /abort, etc.)
3
+ // and manages autocomplete, select menu interactions for the bot.
4
+ import { Events } from 'discord.js';
5
+ import { handleSessionCommand, handleSessionAutocomplete } from './commands/session.js';
6
+ import { handleResumeCommand, handleResumeAutocomplete } from './commands/resume.js';
7
+ import { handleAddProjectCommand, handleAddProjectAutocomplete } from './commands/add-project.js';
8
+ import { handleCreateNewProjectCommand } from './commands/create-new-project.js';
9
+ import { handleAcceptCommand, handleRejectCommand } from './commands/permissions.js';
10
+ import { handleAbortCommand } from './commands/abort.js';
11
+ import { handleShareCommand } from './commands/share.js';
12
+ import { handleForkCommand, handleForkSelectMenu } from './commands/fork.js';
13
+ import { handleModelCommand, handleProviderSelectMenu, handleModelSelectMenu } from './commands/model.js';
14
+ import { handleAgentCommand, handleAgentSelectMenu } from './commands/agent.js';
15
+ import { handleAskQuestionSelectMenu } from './commands/ask-question.js';
16
+ import { handleQueueCommand, handleClearQueueCommand } from './commands/queue.js';
17
+ import { handleUndoCommand, handleRedoCommand } from './commands/undo-redo.js';
18
+ import { handleUserCommand } from './commands/user-command.js';
14
19
  import { createLogger } from './logger.js';
15
- const discordLogger = createLogger('DISCORD');
16
20
  const interactionLogger = createLogger('INTERACTION');
17
21
  export function registerInteractionHandler({ discordClient, appId, }) {
18
22
  interactionLogger.log('[REGISTER] Interaction handler registered');
19
23
  discordClient.on(Events.InteractionCreate, async (interaction) => {
20
24
  try {
21
- interactionLogger.log(`[INTERACTION] Received: ${interaction.type} - ${interaction.isChatInputCommand() ? interaction.commandName : interaction.isAutocomplete() ? `autocomplete:${interaction.commandName}` : 'other'}`);
25
+ interactionLogger.log(`[INTERACTION] Received: ${interaction.type} - ${interaction.isChatInputCommand()
26
+ ? interaction.commandName
27
+ : interaction.isAutocomplete()
28
+ ? `autocomplete:${interaction.commandName}`
29
+ : 'other'}`);
22
30
  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');
31
+ switch (interaction.commandName) {
32
+ case 'session':
33
+ await handleSessionAutocomplete({ interaction, appId });
256
34
  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');
35
+ case 'resume':
36
+ await handleResumeAutocomplete({ interaction, appId });
271
37
  return;
272
- }
273
- if (!projectDirectory) {
274
- await command.editReply('This channel is not configured with a project directory');
38
+ case 'add-project':
39
+ await handleAddProjectAutocomplete({ interaction, appId });
275
40
  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');
41
+ default:
42
+ await interaction.respond([]);
352
43
  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
44
  }
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');
45
+ }
46
+ if (interaction.isChatInputCommand()) {
47
+ interactionLogger.log(`[COMMAND] Processing: ${interaction.commandName}`);
48
+ switch (interaction.commandName) {
49
+ case 'session':
50
+ await handleSessionCommand({ command: interaction, appId });
414
51
  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
- });
52
+ case 'resume':
53
+ await handleResumeCommand({ command: interaction, appId });
471
54
  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
- });
55
+ case 'add-project':
56
+ await handleAddProjectCommand({ command: interaction, appId });
484
57
  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
- });
58
+ case 'create-new-project':
59
+ await handleCreateNewProjectCommand({ command: interaction, appId });
493
60
  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
- });
61
+ case 'accept':
62
+ case 'accept-always':
63
+ await handleAcceptCommand({ command: interaction, appId });
530
64
  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
- });
65
+ case 'reject':
66
+ await handleRejectCommand({ command: interaction, appId });
543
67
  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
- });
68
+ case 'abort':
69
+ case 'stop':
70
+ await handleAbortCommand({ command: interaction, appId });
552
71
  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
- });
72
+ case 'share':
73
+ await handleShareCommand({ command: interaction, appId });
586
74
  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
- });
75
+ case 'fork':
76
+ await handleForkCommand(interaction);
599
77
  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
- });
78
+ case 'model':
79
+ await handleModelCommand({ interaction, appId });
609
80
  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
- });
81
+ case 'agent':
82
+ await handleAgentCommand({ interaction, appId });
620
83
  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
- });
84
+ case 'queue':
85
+ await handleQueueCommand({ command: interaction, appId });
653
86
  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
- });
87
+ case 'clear-queue':
88
+ await handleClearQueueCommand({ command: interaction, appId });
666
89
  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
- });
90
+ case 'undo':
91
+ await handleUndoCommand({ command: interaction, appId });
676
92
  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
- });
93
+ case 'redo':
94
+ await handleRedoCommand({ command: interaction, appId });
687
95
  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
96
  }
715
- else if (command.commandName === 'fork') {
716
- await handleForkCommand(command);
717
- }
718
- else if (command.commandName === 'model') {
719
- await handleModelCommand({ interaction: command, appId });
97
+ // Handle user-defined commands (ending with -cmd suffix)
98
+ if (interaction.commandName.endsWith('-cmd')) {
99
+ await handleUserCommand({ command: interaction, appId });
100
+ return;
720
101
  }
102
+ return;
721
103
  }
722
104
  if (interaction.isStringSelectMenu()) {
723
- if (interaction.customId.startsWith('fork_select:')) {
105
+ const customId = interaction.customId;
106
+ if (customId.startsWith('fork_select:')) {
724
107
  await handleForkSelectMenu(interaction);
108
+ return;
725
109
  }
726
- else if (interaction.customId.startsWith('model_provider:')) {
110
+ if (customId.startsWith('model_provider:')) {
727
111
  await handleProviderSelectMenu(interaction);
112
+ return;
728
113
  }
729
- else if (interaction.customId.startsWith('model_select:')) {
114
+ if (customId.startsWith('model_select:')) {
730
115
  await handleModelSelectMenu(interaction);
116
+ return;
117
+ }
118
+ if (customId.startsWith('agent_select:')) {
119
+ await handleAgentSelectMenu(interaction);
120
+ return;
121
+ }
122
+ if (customId.startsWith('ask_question:')) {
123
+ await handleAskQuestionSelectMenu(interaction);
124
+ return;
731
125
  }
126
+ return;
732
127
  }
733
128
  }
734
129
  catch (error) {
735
130
  interactionLogger.error('[INTERACTION] Error handling interaction:', error);
736
- // Try to respond to the interaction if possible
737
131
  try {
738
132
  if (interaction.isRepliable() && !interaction.replied && !interaction.deferred) {
739
133
  await interaction.reply({