kimaki 0.4.52 → 0.4.53

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.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // Main CLI entrypoint for the Kimaki Discord bot.
3
3
  // Handles interactive setup, Discord OAuth, slash command registration,
4
4
  // project channel creation, and launching the bot with opencode integration.
5
- import { cac } from 'cac';
5
+ import { cac } from '@xmorse/cac';
6
6
  import { intro, outro, text, password, note, cancel, isCancel, confirm, log, multiselect, spinner, } from '@clack/prompts';
7
7
  import { deduplicateByKey, generateBotInstallUrl, abbreviatePath } from './utils.js';
8
8
  import { getChannelsWithDescriptions, createDiscordClient, getDatabase, getChannelDirectory, startDiscordBot, initializeOpencodeForDirectory, ensureKimakiCategory, createProjectChannels, } from './discord-bot.js';
@@ -204,12 +204,8 @@ async function registerCommands({ token, appId, userCommands = [], agents = [],
204
204
  .setDescription('Merge the worktree branch into the default branch')
205
205
  .toJSON(),
206
206
  new SlashCommandBuilder()
207
- .setName('enable-worktrees')
208
- .setDescription('Enable automatic git worktree creation for new sessions in this channel')
209
- .toJSON(),
210
- new SlashCommandBuilder()
211
- .setName('disable-worktrees')
212
- .setDescription('Disable automatic git worktree creation for new sessions in this channel')
207
+ .setName('toggle-worktrees')
208
+ .setDescription('Toggle automatic git worktree creation for new sessions in this channel')
213
209
  .toJSON(),
214
210
  new SlashCommandBuilder()
215
211
  .setName('add-project')
@@ -267,6 +263,10 @@ async function registerCommands({ token, appId, userCommands = [], agents = [],
267
263
  .setName('model')
268
264
  .setDescription('Set the preferred model for this channel or session')
269
265
  .toJSON(),
266
+ new SlashCommandBuilder()
267
+ .setName('login')
268
+ .setDescription('Authenticate with an AI provider (OAuth or API key). Use this instead of /connect')
269
+ .toJSON(),
270
270
  new SlashCommandBuilder()
271
271
  .setName('agent')
272
272
  .setDescription('Set the preferred agent for this channel or session')
@@ -303,6 +303,10 @@ async function registerCommands({ token, appId, userCommands = [], agents = [],
303
303
  return option;
304
304
  })
305
305
  .toJSON(),
306
+ new SlashCommandBuilder()
307
+ .setName('restart-opencode-server')
308
+ .setDescription('Restart the opencode server for this channel only (fixes state/auth/plugins)')
309
+ .toJSON(),
306
310
  ];
307
311
  // Add user-defined commands with -cmd suffix
308
312
  for (const cmd of userCommands) {
@@ -1382,5 +1386,33 @@ cli
1382
1386
  process.exit(EXIT_NO_RESTART);
1383
1387
  }
1384
1388
  });
1389
+ cli
1390
+ .command('tunnel', 'Expose a local port via tunnel')
1391
+ .option('-p, --port <port>', 'Local port to expose (required)')
1392
+ .option('-t, --tunnel-id [id]', 'Tunnel ID (random if omitted)')
1393
+ .option('-h, --host [host]', 'Local host (default: localhost)')
1394
+ .option('-s, --server [url]', 'Tunnel server URL')
1395
+ .action(async (options) => {
1396
+ const { runTunnel, parseCommandFromArgv, CLI_NAME } = await import('traforo/run-tunnel');
1397
+ if (!options.port) {
1398
+ cliLogger.error('Error: --port is required');
1399
+ cliLogger.error(`\nUsage: kimaki tunnel -p <port> [-- command]`);
1400
+ process.exit(EXIT_NO_RESTART);
1401
+ }
1402
+ const port = parseInt(options.port, 10);
1403
+ if (isNaN(port) || port < 1 || port > 65535) {
1404
+ cliLogger.error(`Error: Invalid port number: ${options.port}`);
1405
+ process.exit(EXIT_NO_RESTART);
1406
+ }
1407
+ // Parse command after -- from argv
1408
+ const { command } = parseCommandFromArgv(process.argv);
1409
+ await runTunnel({
1410
+ port,
1411
+ tunnelId: options.tunnelId,
1412
+ localHost: options.host,
1413
+ serverUrl: options.server,
1414
+ command: command.length > 0 ? command : undefined,
1415
+ });
1416
+ });
1385
1417
  cli.help();
1386
1418
  cli.parse();
@@ -79,15 +79,15 @@ export async function resolveAgentCommandContext({ interaction, appId, }) {
79
79
  }
80
80
  /**
81
81
  * Set the agent preference for a context (session or channel).
82
- * When switching agents for a session, also clears the session model preference
83
- * so the new agent's model takes effect.
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
84
  */
85
85
  export function setAgentForContext({ context, agentName, }) {
86
86
  if (context.isThread && context.sessionId) {
87
87
  setSessionAgent(context.sessionId, agentName);
88
88
  // Clear session model so the new agent's model takes effect
89
89
  clearSessionModel(context.sessionId);
90
- agentLogger.log(`Set agent ${agentName} for session ${context.sessionId} (cleared model preference)`);
90
+ agentLogger.log(`Set agent ${agentName} for session ${context.sessionId} (cleared session model)`);
91
91
  }
92
92
  else {
93
93
  setChannelAgent(context.channelId, agentName);
@@ -0,0 +1,488 @@
1
+ // /login command - Authenticate with AI providers (OAuth or API key).
2
+ // Supports GitHub Copilot (device flow), OpenAI Codex (device flow), and API keys.
3
+ import { ChatInputCommandInteraction, StringSelectMenuInteraction, StringSelectMenuBuilder, ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ModalSubmitInteraction, ChannelType, } from 'discord.js';
4
+ import crypto from 'node:crypto';
5
+ import { initializeOpencodeForDirectory } from '../opencode.js';
6
+ import { resolveTextChannel, getKimakiMetadata } from '../discord-utils.js';
7
+ import { createLogger, LogPrefix } from '../logger.js';
8
+ const loginLogger = createLogger(LogPrefix.LOGIN);
9
+ // Store context by hash to avoid customId length limits (Discord max: 100 chars)
10
+ const pendingLoginContexts = new Map();
11
+ /**
12
+ * Handle the /login slash command.
13
+ * Shows a select menu with available providers.
14
+ */
15
+ export async function handleLoginCommand({ interaction, appId, }) {
16
+ loginLogger.log('[LOGIN] handleLoginCommand called');
17
+ // Defer reply immediately to avoid 3-second timeout
18
+ await interaction.deferReply({ ephemeral: true });
19
+ loginLogger.log('[LOGIN] Deferred reply');
20
+ const channel = interaction.channel;
21
+ if (!channel) {
22
+ await interaction.editReply({
23
+ content: 'This command can only be used in a channel',
24
+ });
25
+ return;
26
+ }
27
+ // Determine if we're in a thread or text channel
28
+ const isThread = [
29
+ ChannelType.PublicThread,
30
+ ChannelType.PrivateThread,
31
+ ChannelType.AnnouncementThread,
32
+ ].includes(channel.type);
33
+ let projectDirectory;
34
+ let channelAppId;
35
+ let targetChannelId;
36
+ if (isThread) {
37
+ const thread = channel;
38
+ const textChannel = await resolveTextChannel(thread);
39
+ const metadata = getKimakiMetadata(textChannel);
40
+ projectDirectory = metadata.projectDirectory;
41
+ channelAppId = metadata.channelAppId;
42
+ targetChannelId = textChannel?.id || channel.id;
43
+ }
44
+ else if (channel.type === ChannelType.GuildText) {
45
+ const textChannel = channel;
46
+ const metadata = getKimakiMetadata(textChannel);
47
+ projectDirectory = metadata.projectDirectory;
48
+ channelAppId = metadata.channelAppId;
49
+ targetChannelId = channel.id;
50
+ }
51
+ else {
52
+ await interaction.editReply({
53
+ content: 'This command can only be used in text channels or threads',
54
+ });
55
+ return;
56
+ }
57
+ if (channelAppId && channelAppId !== appId) {
58
+ await interaction.editReply({
59
+ content: 'This channel is not configured for this bot',
60
+ });
61
+ return;
62
+ }
63
+ if (!projectDirectory) {
64
+ await interaction.editReply({
65
+ content: 'This channel is not configured with a project directory',
66
+ });
67
+ return;
68
+ }
69
+ try {
70
+ const getClient = await initializeOpencodeForDirectory(projectDirectory);
71
+ if (getClient instanceof Error) {
72
+ await interaction.editReply({ content: getClient.message });
73
+ return;
74
+ }
75
+ const providersResponse = await getClient().provider.list({
76
+ query: { directory: projectDirectory },
77
+ });
78
+ if (!providersResponse.data) {
79
+ await interaction.editReply({
80
+ content: 'Failed to fetch providers',
81
+ });
82
+ return;
83
+ }
84
+ const { all: allProviders, connected } = providersResponse.data;
85
+ if (allProviders.length === 0) {
86
+ await interaction.editReply({
87
+ content: 'No providers available.',
88
+ });
89
+ return;
90
+ }
91
+ // Store context with a short hash key to avoid customId length limits
92
+ const context = {
93
+ dir: projectDirectory,
94
+ channelId: targetChannelId,
95
+ };
96
+ const contextHash = crypto.randomBytes(8).toString('hex');
97
+ pendingLoginContexts.set(contextHash, context);
98
+ const options = allProviders.slice(0, 25).map((provider) => {
99
+ const isConnected = connected.includes(provider.id);
100
+ return {
101
+ label: `${provider.name}${isConnected ? ' ✓' : ''}`.slice(0, 100),
102
+ value: provider.id,
103
+ description: isConnected ? 'Connected - select to re-authenticate' : 'Not connected',
104
+ };
105
+ });
106
+ const selectMenu = new StringSelectMenuBuilder()
107
+ .setCustomId(`login_provider:${contextHash}`)
108
+ .setPlaceholder('Select a provider to authenticate')
109
+ .addOptions(options);
110
+ const actionRow = new ActionRowBuilder().addComponents(selectMenu);
111
+ await interaction.editReply({
112
+ content: '**Authenticate with Provider**\nSelect a provider:',
113
+ components: [actionRow],
114
+ });
115
+ }
116
+ catch (error) {
117
+ loginLogger.error('Error loading providers:', error);
118
+ await interaction.editReply({
119
+ content: `Failed to load providers: ${error instanceof Error ? error.message : 'Unknown error'}`,
120
+ });
121
+ }
122
+ }
123
+ /**
124
+ * Handle the provider select menu interaction.
125
+ * Shows a second select menu with auth methods for the chosen provider.
126
+ */
127
+ export async function handleLoginProviderSelectMenu(interaction) {
128
+ const customId = interaction.customId;
129
+ if (!customId.startsWith('login_provider:')) {
130
+ return;
131
+ }
132
+ const contextHash = customId.replace('login_provider:', '');
133
+ const context = pendingLoginContexts.get(contextHash);
134
+ if (!context) {
135
+ await interaction.deferUpdate();
136
+ await interaction.editReply({
137
+ content: 'Selection expired. Please run /login again.',
138
+ components: [],
139
+ });
140
+ return;
141
+ }
142
+ const selectedProviderId = interaction.values[0];
143
+ if (!selectedProviderId) {
144
+ await interaction.deferUpdate();
145
+ await interaction.editReply({
146
+ content: 'No provider selected',
147
+ components: [],
148
+ });
149
+ return;
150
+ }
151
+ try {
152
+ const getClient = await initializeOpencodeForDirectory(context.dir);
153
+ if (getClient instanceof Error) {
154
+ await interaction.deferUpdate();
155
+ await interaction.editReply({
156
+ content: getClient.message,
157
+ components: [],
158
+ });
159
+ return;
160
+ }
161
+ // Get provider info for display
162
+ const providersResponse = await getClient().provider.list({
163
+ query: { directory: context.dir },
164
+ });
165
+ const provider = providersResponse.data?.all.find((p) => p.id === selectedProviderId);
166
+ const providerName = provider?.name || selectedProviderId;
167
+ // Get auth methods for all providers
168
+ const authMethodsResponse = await getClient().provider.auth({
169
+ query: { directory: context.dir },
170
+ });
171
+ if (!authMethodsResponse.data) {
172
+ await interaction.deferUpdate();
173
+ await interaction.editReply({
174
+ content: 'Failed to fetch authentication methods',
175
+ components: [],
176
+ });
177
+ return;
178
+ }
179
+ // Get methods for this specific provider, default to API key if none defined
180
+ const methods = authMethodsResponse.data[selectedProviderId] || [
181
+ { type: 'api', label: 'API Key' },
182
+ ];
183
+ if (methods.length === 0) {
184
+ await interaction.deferUpdate();
185
+ await interaction.editReply({
186
+ content: `No authentication methods available for ${providerName}`,
187
+ components: [],
188
+ });
189
+ return;
190
+ }
191
+ // Update context with provider info
192
+ context.providerId = selectedProviderId;
193
+ context.providerName = providerName;
194
+ pendingLoginContexts.set(contextHash, context);
195
+ // If only one method and it's API, show modal directly (no defer)
196
+ if (methods.length === 1 && methods[0].type === 'api') {
197
+ const method = methods[0];
198
+ context.methodIndex = 0;
199
+ context.methodType = method.type;
200
+ context.methodLabel = method.label;
201
+ pendingLoginContexts.set(contextHash, context);
202
+ await showApiKeyModal(interaction, contextHash, providerName);
203
+ return;
204
+ }
205
+ // For OAuth or multiple methods, defer and continue
206
+ await interaction.deferUpdate();
207
+ // If only one method and it's OAuth, start flow directly
208
+ if (methods.length === 1) {
209
+ const method = methods[0];
210
+ context.methodIndex = 0;
211
+ context.methodType = method.type;
212
+ context.methodLabel = method.label;
213
+ pendingLoginContexts.set(contextHash, context);
214
+ await startOAuthFlow(interaction, context, contextHash);
215
+ return;
216
+ }
217
+ // Multiple methods - show selection menu
218
+ const options = methods.slice(0, 25).map((method, index) => ({
219
+ label: method.label.slice(0, 100),
220
+ value: String(index),
221
+ description: method.type === 'oauth' ? 'OAuth authentication' : 'Enter API key manually',
222
+ }));
223
+ const selectMenu = new StringSelectMenuBuilder()
224
+ .setCustomId(`login_method:${contextHash}`)
225
+ .setPlaceholder('Select authentication method')
226
+ .addOptions(options);
227
+ const actionRow = new ActionRowBuilder().addComponents(selectMenu);
228
+ await interaction.editReply({
229
+ content: `**Authenticate with ${providerName}**\nSelect authentication method:`,
230
+ components: [actionRow],
231
+ });
232
+ }
233
+ catch (error) {
234
+ loginLogger.error('Error loading auth methods:', error);
235
+ if (!interaction.deferred && !interaction.replied) {
236
+ await interaction.deferUpdate();
237
+ }
238
+ await interaction.editReply({
239
+ content: `Failed to load auth methods: ${error instanceof Error ? error.message : 'Unknown error'}`,
240
+ components: [],
241
+ });
242
+ }
243
+ }
244
+ /**
245
+ * Handle the auth method select menu interaction.
246
+ * Starts OAuth flow or shows API key modal.
247
+ */
248
+ export async function handleLoginMethodSelectMenu(interaction) {
249
+ const customId = interaction.customId;
250
+ if (!customId.startsWith('login_method:')) {
251
+ return;
252
+ }
253
+ const contextHash = customId.replace('login_method:', '');
254
+ const context = pendingLoginContexts.get(contextHash);
255
+ if (!context || !context.providerId || !context.providerName) {
256
+ await interaction.deferUpdate();
257
+ await interaction.editReply({
258
+ content: 'Selection expired. Please run /login again.',
259
+ components: [],
260
+ });
261
+ return;
262
+ }
263
+ const selectedMethodIndex = parseInt(interaction.values[0] || '0', 10);
264
+ try {
265
+ const getClient = await initializeOpencodeForDirectory(context.dir);
266
+ if (getClient instanceof Error) {
267
+ await interaction.deferUpdate();
268
+ await interaction.editReply({
269
+ content: getClient.message,
270
+ components: [],
271
+ });
272
+ return;
273
+ }
274
+ // Get auth methods again to get the selected one
275
+ const authMethodsResponse = await getClient().provider.auth({
276
+ query: { directory: context.dir },
277
+ });
278
+ const methods = authMethodsResponse.data?.[context.providerId] || [
279
+ { type: 'api', label: 'API Key' },
280
+ ];
281
+ const selectedMethod = methods[selectedMethodIndex];
282
+ if (!selectedMethod) {
283
+ await interaction.deferUpdate();
284
+ await interaction.editReply({
285
+ content: 'Invalid method selected',
286
+ components: [],
287
+ });
288
+ return;
289
+ }
290
+ // Update context
291
+ context.methodIndex = selectedMethodIndex;
292
+ context.methodType = selectedMethod.type;
293
+ context.methodLabel = selectedMethod.label;
294
+ pendingLoginContexts.set(contextHash, context);
295
+ if (selectedMethod.type === 'api') {
296
+ // Show API key modal (don't defer for modals)
297
+ await showApiKeyModal(interaction, contextHash, context.providerName);
298
+ }
299
+ else {
300
+ // Start OAuth flow
301
+ await interaction.deferUpdate();
302
+ await startOAuthFlow(interaction, context, contextHash);
303
+ }
304
+ }
305
+ catch (error) {
306
+ loginLogger.error('Error processing auth method:', error);
307
+ try {
308
+ if (!interaction.deferred && !interaction.replied) {
309
+ await interaction.deferUpdate();
310
+ }
311
+ await interaction.editReply({
312
+ content: `Failed to process auth method: ${error instanceof Error ? error.message : 'Unknown error'}`,
313
+ components: [],
314
+ });
315
+ }
316
+ catch {
317
+ // Ignore follow-up errors
318
+ }
319
+ }
320
+ }
321
+ /**
322
+ * Show API key input modal.
323
+ */
324
+ async function showApiKeyModal(interaction, contextHash, providerName) {
325
+ const modal = new ModalBuilder()
326
+ .setCustomId(`login_apikey:${contextHash}`)
327
+ .setTitle(`${providerName} API Key`.slice(0, 45));
328
+ const apiKeyInput = new TextInputBuilder()
329
+ .setCustomId('apikey')
330
+ .setLabel('API Key')
331
+ .setPlaceholder('sk-...')
332
+ .setStyle(TextInputStyle.Short)
333
+ .setRequired(true);
334
+ const actionRow = new ActionRowBuilder().addComponents(apiKeyInput);
335
+ modal.addComponents(actionRow);
336
+ await interaction.showModal(modal);
337
+ }
338
+ /**
339
+ * Start OAuth authorization flow.
340
+ */
341
+ async function startOAuthFlow(interaction, context, contextHash) {
342
+ if (!context.providerId || context.methodIndex === undefined) {
343
+ await interaction.editReply({
344
+ content: 'Invalid context for OAuth flow',
345
+ components: [],
346
+ });
347
+ return;
348
+ }
349
+ try {
350
+ const getClient = await initializeOpencodeForDirectory(context.dir);
351
+ if (getClient instanceof Error) {
352
+ await interaction.editReply({
353
+ content: getClient.message,
354
+ components: [],
355
+ });
356
+ return;
357
+ }
358
+ await interaction.editReply({
359
+ content: `**Authenticating with ${context.providerName}**\nStarting authorization...`,
360
+ components: [],
361
+ });
362
+ // Start OAuth authorization
363
+ const authorizeResponse = await getClient().provider.oauth.authorize({
364
+ path: { id: context.providerId },
365
+ body: { method: context.methodIndex },
366
+ query: { directory: context.dir },
367
+ });
368
+ if (!authorizeResponse.data) {
369
+ const errorData = authorizeResponse.error;
370
+ await interaction.editReply({
371
+ content: `Failed to start authorization: ${errorData?.data?.message || 'Unknown error'}`,
372
+ components: [],
373
+ });
374
+ return;
375
+ }
376
+ const { url, method, instructions } = authorizeResponse.data;
377
+ // Show authorization URL and instructions
378
+ let message = `**Authenticating with ${context.providerName}**\n\n`;
379
+ message += `Open this URL to authorize:\n${url}\n\n`;
380
+ if (instructions) {
381
+ // Extract code from instructions like "Enter code: ABC-123"
382
+ const codeMatch = instructions.match(/code[:\s]+([A-Z0-9-]+)/i);
383
+ if (codeMatch) {
384
+ message += `**Code:** \`${codeMatch[1]}\`\n\n`;
385
+ }
386
+ else {
387
+ message += `${instructions}\n\n`;
388
+ }
389
+ }
390
+ if (method === 'auto') {
391
+ message += '_Waiting for authorization to complete..._';
392
+ }
393
+ await interaction.editReply({
394
+ content: message,
395
+ components: [],
396
+ });
397
+ if (method === 'auto') {
398
+ // Poll for completion (device flow)
399
+ const callbackResponse = await getClient().provider.oauth.callback({
400
+ path: { id: context.providerId },
401
+ body: { method: context.methodIndex },
402
+ query: { directory: context.dir },
403
+ });
404
+ if (callbackResponse.error) {
405
+ const errorData = callbackResponse.error;
406
+ await interaction.editReply({
407
+ content: `**Authentication Failed**\n${errorData?.data?.message || 'Authorization was not completed'}`,
408
+ components: [],
409
+ });
410
+ return;
411
+ }
412
+ // Dispose to refresh provider state so new credentials are recognized
413
+ await getClient().instance.dispose({ query: { directory: context.dir } });
414
+ await interaction.editReply({
415
+ content: `✅ **Successfully authenticated with ${context.providerName}!**\n\nYou can now use models from this provider.`,
416
+ components: [],
417
+ });
418
+ }
419
+ // For 'code' method, we would need to prompt for code input
420
+ // But Discord modals can't be shown after deferUpdate, so we'd need a different flow
421
+ // For now, most providers use 'auto' (device flow) which works well for Discord
422
+ // Clean up context
423
+ pendingLoginContexts.delete(contextHash);
424
+ }
425
+ catch (error) {
426
+ loginLogger.error('OAuth flow error:', error);
427
+ await interaction.editReply({
428
+ content: `**Authentication Failed**\n${error instanceof Error ? error.message : 'Unknown error'}`,
429
+ components: [],
430
+ });
431
+ }
432
+ }
433
+ /**
434
+ * Handle API key modal submission.
435
+ */
436
+ export async function handleApiKeyModalSubmit(interaction) {
437
+ const customId = interaction.customId;
438
+ if (!customId.startsWith('login_apikey:')) {
439
+ return;
440
+ }
441
+ await interaction.deferReply({ ephemeral: true });
442
+ const contextHash = customId.replace('login_apikey:', '');
443
+ const context = pendingLoginContexts.get(contextHash);
444
+ if (!context || !context.providerId || !context.providerName) {
445
+ await interaction.editReply({
446
+ content: 'Session expired. Please run /login again.',
447
+ });
448
+ return;
449
+ }
450
+ const apiKey = interaction.fields.getTextInputValue('apikey');
451
+ if (!apiKey?.trim()) {
452
+ await interaction.editReply({
453
+ content: 'API key is required.',
454
+ });
455
+ return;
456
+ }
457
+ try {
458
+ const getClient = await initializeOpencodeForDirectory(context.dir);
459
+ if (getClient instanceof Error) {
460
+ await interaction.editReply({
461
+ content: getClient.message,
462
+ });
463
+ return;
464
+ }
465
+ // Set the API key
466
+ await getClient().auth.set({
467
+ path: { id: context.providerId },
468
+ body: {
469
+ type: 'api',
470
+ key: apiKey.trim(),
471
+ },
472
+ query: { directory: context.dir },
473
+ });
474
+ // Dispose to refresh provider state so new credentials are recognized
475
+ await getClient().instance.dispose({ query: { directory: context.dir } });
476
+ await interaction.editReply({
477
+ content: `✅ **Successfully authenticated with ${context.providerName}!**\n\nYou can now use models from this provider.`,
478
+ });
479
+ // Clean up context
480
+ pendingLoginContexts.delete(contextHash);
481
+ }
482
+ catch (error) {
483
+ loginLogger.error('API key save error:', error);
484
+ await interaction.editReply({
485
+ content: `**Failed to save API key**\n${error instanceof Error ? error.message : 'Unknown error'}`,
486
+ });
487
+ }
488
+ }
@@ -1,15 +1,57 @@
1
1
  // /model command - Set the preferred model for this channel or session.
2
2
  import { ChatInputCommandInteraction, StringSelectMenuInteraction, StringSelectMenuBuilder, ActionRowBuilder, ChannelType, } from 'discord.js';
3
3
  import crypto from 'node:crypto';
4
- import { getDatabase, setChannelModel, setSessionModel, runModelMigrations } from '../database.js';
4
+ import { getDatabase, setChannelModel, setSessionModel, runModelMigrations, getChannelModel, getSessionModel, getSessionAgent, getChannelAgent, } from '../database.js';
5
5
  import { initializeOpencodeForDirectory } from '../opencode.js';
6
6
  import { resolveTextChannel, getKimakiMetadata } from '../discord-utils.js';
7
- import { abortAndRetrySession } from '../session-handler.js';
7
+ import { abortAndRetrySession, getDefaultModel } from '../session-handler.js';
8
8
  import { createLogger, LogPrefix } from '../logger.js';
9
9
  import * as errore from 'errore';
10
10
  const modelLogger = createLogger(LogPrefix.MODEL);
11
11
  // Store context by hash to avoid customId length limits (Discord max: 100 chars)
12
12
  const pendingModelContexts = new Map();
13
+ /**
14
+ * Get the current model info for a channel/session, including where it comes from.
15
+ * Priority: session > agent > channel > opencode default
16
+ */
17
+ async function getCurrentModelInfo({ sessionId, channelId, getClient, }) {
18
+ if (getClient instanceof Error) {
19
+ return { type: 'none' };
20
+ }
21
+ // 1. Check session model preference
22
+ if (sessionId) {
23
+ const sessionModel = getSessionModel(sessionId);
24
+ if (sessionModel) {
25
+ return { type: 'session', model: sessionModel };
26
+ }
27
+ }
28
+ // 2. Check agent's configured model
29
+ const agentPreference = sessionId
30
+ ? getSessionAgent(sessionId) || getChannelAgent(channelId)
31
+ : getChannelAgent(channelId);
32
+ if (agentPreference) {
33
+ const agentsResponse = await getClient().app.agents({});
34
+ if (agentsResponse.data) {
35
+ const agent = agentsResponse.data.find((a) => a.name === agentPreference);
36
+ if (agent?.model) {
37
+ const model = `${agent.model.providerID}/${agent.model.modelID}`;
38
+ return { type: 'agent', model, agentName: agentPreference };
39
+ }
40
+ }
41
+ }
42
+ // 3. Check channel model preference
43
+ const channelModel = getChannelModel(channelId);
44
+ if (channelModel) {
45
+ return { type: 'channel', model: channelModel };
46
+ }
47
+ // 4. Get opencode default (config > recent > provider default)
48
+ const defaultModel = await getDefaultModel({ getClient });
49
+ if (defaultModel) {
50
+ const model = `${defaultModel.providerID}/${defaultModel.modelID}`;
51
+ return { type: defaultModel.source, model };
52
+ }
53
+ return { type: 'none' };
54
+ }
13
55
  /**
14
56
  * Handle the /model slash command.
15
57
  * Shows a select menu with available providers.
@@ -98,10 +140,32 @@ export async function handleModelCommand({ interaction, appId, }) {
98
140
  });
99
141
  if (availableProviders.length === 0) {
100
142
  await interaction.editReply({
101
- content: 'No providers with credentials found. Use `/connect` in OpenCode TUI to add provider credentials.',
143
+ content: 'No providers with credentials found. Use `/login` to connect a provider and add credentials.',
102
144
  });
103
145
  return;
104
146
  }
147
+ // Get current model info to display
148
+ const currentModelInfo = await getCurrentModelInfo({
149
+ sessionId,
150
+ channelId: targetChannelId,
151
+ getClient,
152
+ });
153
+ const currentModelText = (() => {
154
+ switch (currentModelInfo.type) {
155
+ case 'session':
156
+ return `**Current (session override):** \`${currentModelInfo.model}\``;
157
+ case 'agent':
158
+ return `**Current (agent "${currentModelInfo.agentName}"):** \`${currentModelInfo.model}\``;
159
+ case 'channel':
160
+ return `**Current (channel override):** \`${currentModelInfo.model}\``;
161
+ case 'opencode-config':
162
+ case 'opencode-recent':
163
+ case 'opencode-provider-default':
164
+ return `**Current (opencode default):** \`${currentModelInfo.model}\``;
165
+ case 'none':
166
+ return '**Current:** none';
167
+ }
168
+ })();
105
169
  // Store context with a short hash key to avoid customId length limits
106
170
  const context = {
107
171
  dir: projectDirectory,
@@ -126,7 +190,7 @@ export async function handleModelCommand({ interaction, appId, }) {
126
190
  .addOptions(options);
127
191
  const actionRow = new ActionRowBuilder().addComponents(selectMenu);
128
192
  await interaction.editReply({
129
- content: '**Set Model Preference**\nSelect a provider:',
193
+ content: `**Set Model Preference**\n${currentModelText}\nSelect a provider:`,
130
194
  components: [actionRow],
131
195
  });
132
196
  }