disunday 1.0.0

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 (83) hide show
  1. package/dist/ai-tool-to-genai.js +208 -0
  2. package/dist/ai-tool-to-genai.test.js +267 -0
  3. package/dist/channel-management.js +96 -0
  4. package/dist/cli.js +1674 -0
  5. package/dist/commands/abort.js +89 -0
  6. package/dist/commands/add-project.js +117 -0
  7. package/dist/commands/agent.js +250 -0
  8. package/dist/commands/ask-question.js +219 -0
  9. package/dist/commands/compact.js +126 -0
  10. package/dist/commands/context-menu.js +171 -0
  11. package/dist/commands/context.js +89 -0
  12. package/dist/commands/cost.js +93 -0
  13. package/dist/commands/create-new-project.js +111 -0
  14. package/dist/commands/diff.js +77 -0
  15. package/dist/commands/export.js +100 -0
  16. package/dist/commands/files.js +73 -0
  17. package/dist/commands/fork.js +199 -0
  18. package/dist/commands/help.js +54 -0
  19. package/dist/commands/login.js +488 -0
  20. package/dist/commands/merge-worktree.js +165 -0
  21. package/dist/commands/model.js +325 -0
  22. package/dist/commands/permissions.js +140 -0
  23. package/dist/commands/ping.js +13 -0
  24. package/dist/commands/queue.js +133 -0
  25. package/dist/commands/remove-project.js +119 -0
  26. package/dist/commands/rename.js +70 -0
  27. package/dist/commands/restart-opencode-server.js +77 -0
  28. package/dist/commands/resume.js +276 -0
  29. package/dist/commands/run-config.js +79 -0
  30. package/dist/commands/run.js +240 -0
  31. package/dist/commands/schedule.js +170 -0
  32. package/dist/commands/session-info.js +58 -0
  33. package/dist/commands/session.js +191 -0
  34. package/dist/commands/settings.js +84 -0
  35. package/dist/commands/share.js +89 -0
  36. package/dist/commands/status.js +79 -0
  37. package/dist/commands/sync.js +119 -0
  38. package/dist/commands/theme.js +53 -0
  39. package/dist/commands/types.js +2 -0
  40. package/dist/commands/undo-redo.js +170 -0
  41. package/dist/commands/user-command.js +135 -0
  42. package/dist/commands/verbosity.js +59 -0
  43. package/dist/commands/worktree-settings.js +50 -0
  44. package/dist/commands/worktree.js +288 -0
  45. package/dist/config.js +139 -0
  46. package/dist/database.js +585 -0
  47. package/dist/discord-bot.js +700 -0
  48. package/dist/discord-utils.js +336 -0
  49. package/dist/discord-utils.test.js +20 -0
  50. package/dist/errors.js +193 -0
  51. package/dist/escape-backticks.test.js +429 -0
  52. package/dist/format-tables.js +96 -0
  53. package/dist/format-tables.test.js +418 -0
  54. package/dist/genai-worker-wrapper.js +109 -0
  55. package/dist/genai-worker.js +299 -0
  56. package/dist/genai.js +230 -0
  57. package/dist/image-utils.js +107 -0
  58. package/dist/interaction-handler.js +289 -0
  59. package/dist/limit-heading-depth.js +25 -0
  60. package/dist/limit-heading-depth.test.js +105 -0
  61. package/dist/logger.js +111 -0
  62. package/dist/markdown.js +323 -0
  63. package/dist/markdown.test.js +269 -0
  64. package/dist/message-formatting.js +447 -0
  65. package/dist/message-formatting.test.js +73 -0
  66. package/dist/openai-realtime.js +226 -0
  67. package/dist/opencode.js +224 -0
  68. package/dist/reaction-handler.js +128 -0
  69. package/dist/scheduler.js +93 -0
  70. package/dist/security.js +200 -0
  71. package/dist/session-handler.js +1436 -0
  72. package/dist/system-message.js +138 -0
  73. package/dist/tools.js +354 -0
  74. package/dist/unnest-code-blocks.js +117 -0
  75. package/dist/unnest-code-blocks.test.js +432 -0
  76. package/dist/utils.js +95 -0
  77. package/dist/voice-handler.js +569 -0
  78. package/dist/voice.js +344 -0
  79. package/dist/worker-types.js +4 -0
  80. package/dist/worktree-utils.js +134 -0
  81. package/dist/xml.js +90 -0
  82. package/dist/xml.test.js +32 -0
  83. package/package.json +84 -0
@@ -0,0 +1,89 @@
1
+ // /abort command - Abort the current OpenCode request in this thread.
2
+ import { ChannelType } from 'discord.js';
3
+ import { getDatabase } from '../database.js';
4
+ import { initializeOpencodeForDirectory } from '../opencode.js';
5
+ import { resolveTextChannel, getDisundayMetadata, SILENT_MESSAGE_FLAGS } from '../discord-utils.js';
6
+ import { abortControllers } from '../session-handler.js';
7
+ import { createLogger, LogPrefix } from '../logger.js';
8
+ import * as errore from 'errore';
9
+ const logger = createLogger(LogPrefix.ABORT);
10
+ export async function handleAbortCommand({ command }) {
11
+ const channel = command.channel;
12
+ if (!channel) {
13
+ await command.reply({
14
+ content: 'This command can only be used in a channel',
15
+ ephemeral: true,
16
+ flags: SILENT_MESSAGE_FLAGS,
17
+ });
18
+ return;
19
+ }
20
+ const isThread = [
21
+ ChannelType.PublicThread,
22
+ ChannelType.PrivateThread,
23
+ ChannelType.AnnouncementThread,
24
+ ].includes(channel.type);
25
+ if (!isThread) {
26
+ await command.reply({
27
+ content: 'This command can only be used in a thread with an active session',
28
+ ephemeral: true,
29
+ flags: SILENT_MESSAGE_FLAGS,
30
+ });
31
+ return;
32
+ }
33
+ const textChannel = await resolveTextChannel(channel);
34
+ const { projectDirectory: directory } = getDisundayMetadata(textChannel);
35
+ if (!directory) {
36
+ await command.reply({
37
+ content: 'Could not determine project directory for this channel',
38
+ ephemeral: true,
39
+ flags: SILENT_MESSAGE_FLAGS,
40
+ });
41
+ return;
42
+ }
43
+ const row = getDatabase()
44
+ .prepare('SELECT session_id FROM thread_sessions WHERE thread_id = ?')
45
+ .get(channel.id);
46
+ if (!row?.session_id) {
47
+ await command.reply({
48
+ content: 'No active session in this thread',
49
+ ephemeral: true,
50
+ flags: SILENT_MESSAGE_FLAGS,
51
+ });
52
+ return;
53
+ }
54
+ const sessionId = row.session_id;
55
+ const existingController = abortControllers.get(sessionId);
56
+ if (existingController) {
57
+ logger.log(`[ABORT] reason=user-requested sessionId=${sessionId} channelId=${channel.id} - user ran /abort command`);
58
+ existingController.abort(new Error('User requested abort'));
59
+ abortControllers.delete(sessionId);
60
+ }
61
+ const getClient = await initializeOpencodeForDirectory(directory);
62
+ if (getClient instanceof Error) {
63
+ await command.reply({
64
+ content: `Failed to abort: ${getClient.message}`,
65
+ ephemeral: true,
66
+ flags: SILENT_MESSAGE_FLAGS,
67
+ });
68
+ return;
69
+ }
70
+ try {
71
+ logger.log(`[ABORT-API] reason=user-requested sessionId=${sessionId} channelId=${channel.id} - sending API abort from /abort command`);
72
+ await getClient().session.abort({
73
+ path: { id: sessionId },
74
+ });
75
+ await command.reply({
76
+ content: `🛑 Request **aborted**`,
77
+ flags: SILENT_MESSAGE_FLAGS,
78
+ });
79
+ logger.log(`Session ${sessionId} aborted by user`);
80
+ }
81
+ catch (error) {
82
+ logger.error('[ABORT] Error:', error);
83
+ await command.reply({
84
+ content: `Failed to abort: ${error instanceof Error ? error.message : 'Unknown error'}`,
85
+ ephemeral: true,
86
+ flags: SILENT_MESSAGE_FLAGS,
87
+ });
88
+ }
89
+ }
@@ -0,0 +1,117 @@
1
+ // /add-project command - Create Discord channels for an existing OpenCode project.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getDatabase } from '../database.js';
5
+ import { initializeOpencodeForDirectory } from '../opencode.js';
6
+ import { createProjectChannels } from '../channel-management.js';
7
+ import { createLogger, LogPrefix } from '../logger.js';
8
+ import { abbreviatePath } from '../utils.js';
9
+ import * as errore from 'errore';
10
+ const logger = createLogger(LogPrefix.ADD_PROJECT);
11
+ export async function handleAddProjectCommand({ command, appId }) {
12
+ await command.deferReply({ ephemeral: false });
13
+ const projectId = command.options.getString('project', true);
14
+ const guild = command.guild;
15
+ if (!guild) {
16
+ await command.editReply('This command can only be used in a guild');
17
+ return;
18
+ }
19
+ try {
20
+ const currentDir = process.cwd();
21
+ const getClient = await initializeOpencodeForDirectory(currentDir);
22
+ if (getClient instanceof Error) {
23
+ await command.editReply(getClient.message);
24
+ return;
25
+ }
26
+ const projectsResponse = await getClient().project.list({});
27
+ if (!projectsResponse.data) {
28
+ await command.editReply('Failed to fetch projects');
29
+ return;
30
+ }
31
+ const project = projectsResponse.data.find((p) => p.id === projectId);
32
+ if (!project) {
33
+ await command.editReply('Project not found');
34
+ return;
35
+ }
36
+ const directory = project.worktree;
37
+ if (!fs.existsSync(directory)) {
38
+ await command.editReply(`Directory does not exist: ${directory}`);
39
+ return;
40
+ }
41
+ const db = getDatabase();
42
+ const existingChannel = db
43
+ .prepare('SELECT channel_id FROM channel_directories WHERE directory = ? AND channel_type = ?')
44
+ .get(directory, 'text');
45
+ if (existingChannel) {
46
+ await command.editReply(`A channel already exists for this directory: <#${existingChannel.channel_id}>`);
47
+ return;
48
+ }
49
+ const { textChannelId, voiceChannelId, channelName } = await createProjectChannels({
50
+ guild,
51
+ projectDirectory: directory,
52
+ appId,
53
+ botName: command.client.user?.username,
54
+ });
55
+ const voiceInfo = voiceChannelId ? `\n🔊 Voice: <#${voiceChannelId}>` : '';
56
+ await command.editReply(`✅ Created channels for project:\n📝 Text: <#${textChannelId}>${voiceInfo}\n📁 Directory: \`${directory}\``);
57
+ logger.log(`Created channels for project ${channelName} at ${directory}`);
58
+ }
59
+ catch (error) {
60
+ logger.error('[ADD-PROJECT] Error:', error);
61
+ await command.editReply(`Failed to create channels: ${error instanceof Error ? error.message : 'Unknown error'}`);
62
+ }
63
+ }
64
+ export async function handleAddProjectAutocomplete({ interaction, appId, }) {
65
+ const focusedValue = interaction.options.getFocused();
66
+ try {
67
+ const currentDir = process.cwd();
68
+ const getClient = await initializeOpencodeForDirectory(currentDir);
69
+ if (getClient instanceof Error) {
70
+ await interaction.respond([]);
71
+ return;
72
+ }
73
+ const projectsResponse = await getClient().project.list({});
74
+ if (!projectsResponse.data) {
75
+ await interaction.respond([]);
76
+ return;
77
+ }
78
+ const db = getDatabase();
79
+ const existingDirs = db
80
+ .prepare('SELECT DISTINCT directory FROM channel_directories WHERE channel_type = ?')
81
+ .all('text');
82
+ const existingDirSet = new Set(existingDirs.map((row) => row.directory));
83
+ const availableProjects = projectsResponse.data.filter((project) => {
84
+ if (existingDirSet.has(project.worktree)) {
85
+ return false;
86
+ }
87
+ if (path.basename(project.worktree).startsWith('opencode-test-')) {
88
+ return false;
89
+ }
90
+ return true;
91
+ });
92
+ const projects = availableProjects
93
+ .filter((project) => {
94
+ const baseName = path.basename(project.worktree);
95
+ const searchText = `${baseName} ${project.worktree}`.toLowerCase();
96
+ return searchText.includes(focusedValue.toLowerCase());
97
+ })
98
+ .sort((a, b) => {
99
+ const aTime = a.time.initialized || a.time.created;
100
+ const bTime = b.time.initialized || b.time.created;
101
+ return bTime - aTime;
102
+ })
103
+ .slice(0, 25)
104
+ .map((project) => {
105
+ const name = `${path.basename(project.worktree)} (${abbreviatePath(project.worktree)})`;
106
+ return {
107
+ name: name.length > 100 ? name.slice(0, 99) + '…' : name,
108
+ value: project.id,
109
+ };
110
+ });
111
+ await interaction.respond(projects);
112
+ }
113
+ catch (error) {
114
+ logger.error('[AUTOCOMPLETE] Error fetching projects:', error);
115
+ await interaction.respond([]);
116
+ }
117
+ }
@@ -0,0 +1,250 @@
1
+ // /agent command - Set the preferred agent for this channel or session.
2
+ // Also provides quick agent commands like /plan-agent, /build-agent that switch instantly.
3
+ import { ChatInputCommandInteraction, StringSelectMenuInteraction, StringSelectMenuBuilder, ActionRowBuilder, ChannelType, } from 'discord.js';
4
+ import crypto from 'node:crypto';
5
+ import { getDatabase, setChannelAgent, setSessionAgent, clearSessionModel, runModelMigrations } from '../database.js';
6
+ import { initializeOpencodeForDirectory } from '../opencode.js';
7
+ import { resolveTextChannel, getDisundayMetadata } from '../discord-utils.js';
8
+ import { createLogger, LogPrefix } from '../logger.js';
9
+ import * as errore from 'errore';
10
+ const agentLogger = createLogger(LogPrefix.AGENT);
11
+ const pendingAgentContexts = new Map();
12
+ /**
13
+ * Sanitize an agent name to be a valid Discord command name component.
14
+ * Lowercase, alphanumeric and hyphens only.
15
+ */
16
+ export function sanitizeAgentName(name) {
17
+ return name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
18
+ }
19
+ /**
20
+ * Resolve the context for an agent command (directory, channel, session).
21
+ * Returns null if the command cannot be executed in this context.
22
+ */
23
+ export async function resolveAgentCommandContext({ interaction, appId, }) {
24
+ const channel = interaction.channel;
25
+ if (!channel) {
26
+ await interaction.editReply({ content: 'This command can only be used in a channel' });
27
+ return null;
28
+ }
29
+ const isThread = [
30
+ ChannelType.PublicThread,
31
+ ChannelType.PrivateThread,
32
+ ChannelType.AnnouncementThread,
33
+ ].includes(channel.type);
34
+ let projectDirectory;
35
+ let channelAppId;
36
+ let targetChannelId;
37
+ let sessionId;
38
+ if (isThread) {
39
+ const thread = channel;
40
+ const textChannel = await resolveTextChannel(thread);
41
+ const metadata = getDisundayMetadata(textChannel);
42
+ projectDirectory = metadata.projectDirectory;
43
+ channelAppId = metadata.channelAppId;
44
+ targetChannelId = textChannel?.id || channel.id;
45
+ const row = getDatabase()
46
+ .prepare('SELECT session_id FROM thread_sessions WHERE thread_id = ?')
47
+ .get(thread.id);
48
+ sessionId = row?.session_id;
49
+ }
50
+ else if (channel.type === ChannelType.GuildText) {
51
+ const textChannel = channel;
52
+ const metadata = getDisundayMetadata(textChannel);
53
+ projectDirectory = metadata.projectDirectory;
54
+ channelAppId = metadata.channelAppId;
55
+ targetChannelId = channel.id;
56
+ }
57
+ else {
58
+ await interaction.editReply({
59
+ content: 'This command can only be used in text channels or threads',
60
+ });
61
+ return null;
62
+ }
63
+ if (channelAppId && channelAppId !== appId) {
64
+ await interaction.editReply({ content: 'This channel is not configured for this bot' });
65
+ return null;
66
+ }
67
+ if (!projectDirectory) {
68
+ await interaction.editReply({
69
+ content: 'This channel is not configured with a project directory',
70
+ });
71
+ return null;
72
+ }
73
+ return {
74
+ dir: projectDirectory,
75
+ channelId: targetChannelId,
76
+ sessionId,
77
+ isThread,
78
+ };
79
+ }
80
+ /**
81
+ * Set the agent preference for a context (session or channel).
82
+ * When switching agents for a session, clears session model preference
83
+ * so the new agent's model takes effect (agent model > channel model).
84
+ */
85
+ export function setAgentForContext({ context, agentName, }) {
86
+ if (context.isThread && context.sessionId) {
87
+ setSessionAgent(context.sessionId, agentName);
88
+ // Clear session model so the new agent's model takes effect
89
+ clearSessionModel(context.sessionId);
90
+ agentLogger.log(`Set agent ${agentName} for session ${context.sessionId} (cleared session model)`);
91
+ }
92
+ else {
93
+ setChannelAgent(context.channelId, agentName);
94
+ agentLogger.log(`Set agent ${agentName} for channel ${context.channelId}`);
95
+ }
96
+ }
97
+ export async function handleAgentCommand({ interaction, appId, }) {
98
+ await interaction.deferReply({ ephemeral: true });
99
+ runModelMigrations();
100
+ const context = await resolveAgentCommandContext({ interaction, appId });
101
+ if (!context) {
102
+ return;
103
+ }
104
+ try {
105
+ const getClient = await initializeOpencodeForDirectory(context.dir);
106
+ if (getClient instanceof Error) {
107
+ await interaction.editReply({ content: getClient.message });
108
+ return;
109
+ }
110
+ const agentsResponse = await getClient().app.agents({
111
+ query: { directory: context.dir },
112
+ });
113
+ if (!agentsResponse.data || agentsResponse.data.length === 0) {
114
+ await interaction.editReply({ content: 'No agents available' });
115
+ return;
116
+ }
117
+ const agents = agentsResponse.data
118
+ .filter((agent) => {
119
+ const hidden = agent.hidden;
120
+ return (agent.mode === 'primary' || agent.mode === 'all') && !hidden;
121
+ })
122
+ .slice(0, 25);
123
+ if (agents.length === 0) {
124
+ await interaction.editReply({ content: 'No primary agents available' });
125
+ return;
126
+ }
127
+ const contextHash = crypto.randomBytes(8).toString('hex');
128
+ pendingAgentContexts.set(contextHash, context);
129
+ const options = agents.map((agent) => ({
130
+ label: agent.name.slice(0, 100),
131
+ value: agent.name,
132
+ description: (agent.description || `${agent.mode} agent`).slice(0, 100),
133
+ }));
134
+ const selectMenu = new StringSelectMenuBuilder()
135
+ .setCustomId(`agent_select:${contextHash}`)
136
+ .setPlaceholder('Select an agent')
137
+ .addOptions(options);
138
+ const actionRow = new ActionRowBuilder().addComponents(selectMenu);
139
+ await interaction.editReply({
140
+ content: '**Set Agent Preference**\nSelect an agent:',
141
+ components: [actionRow],
142
+ });
143
+ }
144
+ catch (error) {
145
+ agentLogger.error('Error loading agents:', error);
146
+ await interaction.editReply({
147
+ content: `Failed to load agents: ${error instanceof Error ? error.message : 'Unknown error'}`,
148
+ });
149
+ }
150
+ }
151
+ export async function handleAgentSelectMenu(interaction) {
152
+ const customId = interaction.customId;
153
+ if (!customId.startsWith('agent_select:')) {
154
+ return;
155
+ }
156
+ await interaction.deferUpdate();
157
+ const contextHash = customId.replace('agent_select:', '');
158
+ const context = pendingAgentContexts.get(contextHash);
159
+ if (!context) {
160
+ await interaction.editReply({
161
+ content: 'Selection expired. Please run /agent again.',
162
+ components: [],
163
+ });
164
+ return;
165
+ }
166
+ const selectedAgent = interaction.values[0];
167
+ if (!selectedAgent) {
168
+ await interaction.editReply({
169
+ content: 'No agent selected',
170
+ components: [],
171
+ });
172
+ return;
173
+ }
174
+ try {
175
+ setAgentForContext({ context, agentName: selectedAgent });
176
+ if (context.isThread && context.sessionId) {
177
+ await interaction.editReply({
178
+ content: `Agent preference set for this session: **${selectedAgent}**`,
179
+ components: [],
180
+ });
181
+ }
182
+ else {
183
+ await interaction.editReply({
184
+ content: `Agent preference set for this channel: **${selectedAgent}**\nAll new sessions in this channel will use this agent.`,
185
+ components: [],
186
+ });
187
+ }
188
+ pendingAgentContexts.delete(contextHash);
189
+ }
190
+ catch (error) {
191
+ agentLogger.error('Error saving agent preference:', error);
192
+ await interaction.editReply({
193
+ content: `Failed to save agent preference: ${error instanceof Error ? error.message : 'Unknown error'}`,
194
+ components: [],
195
+ });
196
+ }
197
+ }
198
+ /**
199
+ * Handle quick agent commands like /plan-agent, /build-agent.
200
+ * These instantly switch to the specified agent without showing a dropdown.
201
+ */
202
+ export async function handleQuickAgentCommand({ command, appId, }) {
203
+ await command.deferReply({ ephemeral: true });
204
+ runModelMigrations();
205
+ // Extract agent name from command: "plan-agent" → "plan"
206
+ const sanitizedAgentName = command.commandName.replace(/-agent$/, '');
207
+ const context = await resolveAgentCommandContext({ interaction: command, appId });
208
+ if (!context) {
209
+ return;
210
+ }
211
+ try {
212
+ const getClient = await initializeOpencodeForDirectory(context.dir);
213
+ if (getClient instanceof Error) {
214
+ await command.editReply({ content: getClient.message });
215
+ return;
216
+ }
217
+ const agentsResponse = await getClient().app.agents({
218
+ query: { directory: context.dir },
219
+ });
220
+ if (!agentsResponse.data || agentsResponse.data.length === 0) {
221
+ await command.editReply({ content: 'No agents available in this project' });
222
+ return;
223
+ }
224
+ // Find the agent matching the sanitized command name
225
+ const matchingAgent = agentsResponse.data.find((a) => sanitizeAgentName(a.name) === sanitizedAgentName);
226
+ if (!matchingAgent) {
227
+ await command.editReply({
228
+ content: `Agent not found. Available agents: ${agentsResponse.data.map((a) => a.name).join(', ')}`,
229
+ });
230
+ return;
231
+ }
232
+ setAgentForContext({ context, agentName: matchingAgent.name });
233
+ if (context.isThread && context.sessionId) {
234
+ await command.editReply({
235
+ content: `Switched to **${matchingAgent.name}** agent for this session`,
236
+ });
237
+ }
238
+ else {
239
+ await command.editReply({
240
+ content: `Switched to **${matchingAgent.name}** agent for this channel\nAll new sessions will use this agent.`,
241
+ });
242
+ }
243
+ }
244
+ catch (error) {
245
+ agentLogger.error('Error in quick agent command:', error);
246
+ await command.editReply({
247
+ content: `Failed to switch agent: ${error instanceof Error ? error.message : 'Unknown error'}`,
248
+ });
249
+ }
250
+ }
@@ -0,0 +1,219 @@
1
+ // AskUserQuestion tool handler - Shows Discord dropdowns for AI questions.
2
+ // When the AI uses the AskUserQuestion tool, this module renders dropdowns
3
+ // for each question and collects user responses.
4
+ import { StringSelectMenuBuilder, StringSelectMenuInteraction, ActionRowBuilder, } from 'discord.js';
5
+ import crypto from 'node:crypto';
6
+ import { sendThreadMessage, NOTIFY_MESSAGE_FLAGS } from '../discord-utils.js';
7
+ import { getOpencodeClientV2 } from '../opencode.js';
8
+ import { createLogger, LogPrefix } from '../logger.js';
9
+ const logger = createLogger(LogPrefix.ASK_QUESTION);
10
+ // Store pending question contexts by hash
11
+ export const pendingQuestionContexts = new Map();
12
+ /**
13
+ * Show dropdown menus for question tool input.
14
+ * Sends one message per question with the dropdown directly under the question text.
15
+ */
16
+ export async function showAskUserQuestionDropdowns({ thread, sessionId, directory, requestId, input, }) {
17
+ const contextHash = crypto.randomBytes(8).toString('hex');
18
+ const context = {
19
+ sessionId,
20
+ directory,
21
+ thread,
22
+ requestId,
23
+ questions: input.questions,
24
+ answers: {},
25
+ totalQuestions: input.questions.length,
26
+ answeredCount: 0,
27
+ contextHash,
28
+ };
29
+ pendingQuestionContexts.set(contextHash, context);
30
+ // Send one message per question with its dropdown directly underneath
31
+ for (let i = 0; i < input.questions.length; i++) {
32
+ const q = input.questions[i];
33
+ // Map options to Discord select menu options
34
+ // Discord max: 25 options per select menu
35
+ const options = [
36
+ ...q.options.slice(0, 24).map((opt, optIdx) => ({
37
+ label: opt.label.slice(0, 100),
38
+ value: `${optIdx}`,
39
+ description: opt.description.slice(0, 100),
40
+ })),
41
+ {
42
+ label: 'Other',
43
+ value: 'other',
44
+ description: 'Provide a custom answer in chat',
45
+ },
46
+ ];
47
+ const placeholder = options.find((x) => x.label)?.label || 'Select an option';
48
+ const selectMenu = new StringSelectMenuBuilder()
49
+ .setCustomId(`ask_question:${contextHash}:${i}`)
50
+ .setPlaceholder(placeholder)
51
+ .addOptions(options);
52
+ // Enable multi-select if the question supports it
53
+ if (q.multiple) {
54
+ selectMenu.setMinValues(1);
55
+ selectMenu.setMaxValues(options.length);
56
+ }
57
+ const actionRow = new ActionRowBuilder().addComponents(selectMenu);
58
+ await thread.send({
59
+ content: `**${q.header}**\n${q.question}`,
60
+ components: [actionRow],
61
+ flags: NOTIFY_MESSAGE_FLAGS,
62
+ });
63
+ }
64
+ logger.log(`Showed ${input.questions.length} question dropdown(s) for session ${sessionId}`);
65
+ }
66
+ /**
67
+ * Handle dropdown selection for AskUserQuestion.
68
+ */
69
+ export async function handleAskQuestionSelectMenu(interaction) {
70
+ const customId = interaction.customId;
71
+ if (!customId.startsWith('ask_question:')) {
72
+ return;
73
+ }
74
+ const parts = customId.split(':');
75
+ const contextHash = parts[1];
76
+ const questionIndex = parseInt(parts[2], 10);
77
+ if (!contextHash) {
78
+ await interaction.reply({
79
+ content: 'Invalid selection.',
80
+ ephemeral: true,
81
+ });
82
+ return;
83
+ }
84
+ const context = pendingQuestionContexts.get(contextHash);
85
+ if (!context) {
86
+ await interaction.reply({
87
+ content: 'This question has expired. Please ask the AI again.',
88
+ ephemeral: true,
89
+ });
90
+ return;
91
+ }
92
+ await interaction.deferUpdate();
93
+ const selectedValues = interaction.values;
94
+ const question = context.questions[questionIndex];
95
+ if (!question) {
96
+ logger.error(`Question index ${questionIndex} not found in context`);
97
+ return;
98
+ }
99
+ // Check if "other" was selected
100
+ if (selectedValues.includes('other')) {
101
+ // User wants to provide custom answer
102
+ // For now, mark as "Other" - they can type in chat
103
+ context.answers[questionIndex] = ['Other (please type your answer in chat)'];
104
+ }
105
+ else {
106
+ // Map value indices back to option labels
107
+ context.answers[questionIndex] = selectedValues.map((v) => {
108
+ const optIdx = parseInt(v, 10);
109
+ return question.options[optIdx]?.label || `Option ${optIdx + 1}`;
110
+ });
111
+ }
112
+ context.answeredCount++;
113
+ // Update this question's message: show answer and remove dropdown
114
+ const answeredText = context.answers[questionIndex].join(', ');
115
+ await interaction.editReply({
116
+ content: `**${question.header}**\n${question.question}\n✓ _${answeredText}_`,
117
+ components: [], // Remove the dropdown
118
+ });
119
+ // Check if all questions are answered
120
+ if (context.answeredCount >= context.totalQuestions) {
121
+ // All questions answered - send result back to session
122
+ await submitQuestionAnswers(context);
123
+ pendingQuestionContexts.delete(contextHash);
124
+ }
125
+ }
126
+ /**
127
+ * Submit all collected answers back to the OpenCode session.
128
+ * Uses the question.reply API to provide answers to the waiting tool.
129
+ */
130
+ async function submitQuestionAnswers(context) {
131
+ try {
132
+ const clientV2 = getOpencodeClientV2(context.directory);
133
+ if (!clientV2) {
134
+ throw new Error('OpenCode server not found for directory');
135
+ }
136
+ // Build answers array: each element is an array of selected labels for that question
137
+ const answers = context.questions.map((_, i) => {
138
+ return context.answers[i] || [];
139
+ });
140
+ await clientV2.question.reply({
141
+ requestID: context.requestId,
142
+ answers,
143
+ });
144
+ logger.log(`Submitted answers for question ${context.requestId} in session ${context.sessionId}`);
145
+ }
146
+ catch (error) {
147
+ logger.error('Failed to submit answers:', error);
148
+ await sendThreadMessage(context.thread, `✗ Failed to submit answers: ${error instanceof Error ? error.message : 'Unknown error'}`);
149
+ }
150
+ }
151
+ /**
152
+ * Check if a tool part is an AskUserQuestion tool.
153
+ * Returns the parsed input if valid, null otherwise.
154
+ */
155
+ export function parseAskUserQuestionTool(part) {
156
+ if (part.type !== 'tool') {
157
+ return null;
158
+ }
159
+ // Check for the tool name (case-insensitive)
160
+ const toolName = part.tool?.toLowerCase();
161
+ if (toolName !== 'question') {
162
+ return null;
163
+ }
164
+ const input = part.state?.input;
165
+ if (!input?.questions || !Array.isArray(input.questions) || input.questions.length === 0) {
166
+ return null;
167
+ }
168
+ // Validate structure
169
+ for (const q of input.questions) {
170
+ if (typeof q.question !== 'string' ||
171
+ typeof q.header !== 'string' ||
172
+ !Array.isArray(q.options) ||
173
+ q.options.length < 2) {
174
+ return null;
175
+ }
176
+ }
177
+ return input;
178
+ }
179
+ /**
180
+ * Cancel a pending question for a thread (e.g., when user sends a new message).
181
+ * Sends the user's message as the answer to OpenCode so the model sees their actual response.
182
+ */
183
+ export async function cancelPendingQuestion(threadId, userMessage) {
184
+ // Find pending question for this thread
185
+ let contextHash;
186
+ let context;
187
+ for (const [hash, ctx] of pendingQuestionContexts) {
188
+ if (ctx.thread.id === threadId) {
189
+ contextHash = hash;
190
+ context = ctx;
191
+ break;
192
+ }
193
+ }
194
+ if (!contextHash || !context) {
195
+ return false;
196
+ }
197
+ try {
198
+ const clientV2 = getOpencodeClientV2(context.directory);
199
+ if (!clientV2) {
200
+ throw new Error('OpenCode server not found for directory');
201
+ }
202
+ // Use user's message as answer if provided, otherwise mark as "Other"
203
+ const customAnswer = userMessage || 'Other';
204
+ const answers = context.questions.map((_, i) => {
205
+ return context.answers[i] || [customAnswer];
206
+ });
207
+ await clientV2.question.reply({
208
+ requestID: context.requestId,
209
+ answers,
210
+ });
211
+ logger.log(`Answered question ${context.requestId} with user message`);
212
+ }
213
+ catch (error) {
214
+ logger.error('Failed to answer question:', error);
215
+ }
216
+ // Clean up regardless of whether the API call succeeded
217
+ pendingQuestionContexts.delete(contextHash);
218
+ return true;
219
+ }