1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { useCallback, useMemo } from 'react';
import { type PartListUnion } from '@google/genai';
import open from 'open';
import process from 'node:process';
import { UseHistoryManagerReturn } from './useHistoryManager.js';
import { Config, MCPServerStatus, getMCPServerStatus } from '@gemini-cli/core';
import { Message, MessageType, HistoryItemWithoutId } from '../types.js';
import { createShowMemoryAction } from './useShowMemoryCommand.js';
import { GIT_COMMIT_INFO } from '../../generated/git-commit.js';
import { formatMemoryUsage } from '../utils/formatters.js';
import { getCliVersion } from '../../utils/version.js';
export interface SlashCommandActionReturn {
shouldScheduleTool?: boolean;
toolName?: string;
toolArgs?: Record<string, unknown>;
message?: string; // For simple messages or errors
}
export interface SlashCommand {
name: string;
altName?: string;
description?: string;
action: (
mainCommand: string,
subCommand?: string,
args?: string,
) => void | SlashCommandActionReturn; // Action can now return this object
}
/**
* Hook to define and process slash commands (e.g., /help, /clear).
*/
export const useSlashCommandProcessor = (
config: Config | null,
addItem: UseHistoryManagerReturn['addItem'],
clearItems: UseHistoryManagerReturn['clearItems'],
refreshStatic: () => void,
setShowHelp: React.Dispatch<React.SetStateAction<boolean>>,
onDebugMessage: (message: string) => void,
openThemeDialog: () => void,
performMemoryRefresh: () => Promise<void>,
toggleCorgiMode: () => void,
) => {
const addMessage = useCallback(
(message: Message) => {
// Convert Message to HistoryItemWithoutId
let historyItemContent: HistoryItemWithoutId;
if (message.type === MessageType.ABOUT) {
historyItemContent = {
type: 'about',
cliVersion: message.cliVersion,
osVersion: message.osVersion,
sandboxEnv: message.sandboxEnv,
modelVersion: message.modelVersion,
};
} else {
historyItemContent = {
type: message.type as
| MessageType.INFO
| MessageType.ERROR
| MessageType.USER,
text: message.content,
};
}
addItem(historyItemContent, message.timestamp.getTime());
},
[addItem],
);
const showMemoryAction = useCallback(async () => {
const actionFn = createShowMemoryAction(config, addMessage);
await actionFn();
}, [config, addMessage]);
const addMemoryAction = useCallback(
(
_mainCommand: string,
_subCommand?: string,
args?: string,
): SlashCommandActionReturn | void => {
if (!args || args.trim() === '') {
addMessage({
type: MessageType.ERROR,
content: 'Usage: /memory add <text to remember>',
timestamp: new Date(),
});
return;
}
// UI feedback for attempting to schedule
addMessage({
type: MessageType.INFO,
content: `Attempting to save to memory: "${args.trim()}"`,
timestamp: new Date(),
});
// Return info for scheduling the tool call
return {
shouldScheduleTool: true,
toolName: 'save_memory',
toolArgs: { fact: args.trim() },
};
},
[addMessage],
);
const slashCommands: SlashCommand[] = useMemo(
() => [
{
name: 'help',
altName: '?',
description: 'for help on gemini-cli',
action: (_mainCommand, _subCommand, _args) => {
onDebugMessage('Opening help.');
setShowHelp(true);
},
},
{
name: 'clear',
description: 'clear the screen',
action: (_mainCommand, _subCommand, _args) => {
onDebugMessage('Clearing terminal.');
clearItems();
console.clear();
refreshStatic();
},
},
{
name: 'theme',
description: 'change the theme',
action: (_mainCommand, _subCommand, _args) => {
openThemeDialog();
},
},
{
name: 'mcp',
description: 'list configured MCP servers and tools',
action: async (_mainCommand, _subCommand, _args) => {
const toolRegistry = await config?.getToolRegistry();
if (!toolRegistry) {
addMessage({
type: MessageType.ERROR,
content: 'Could not retrieve tool registry.',
timestamp: new Date(),
});
return;
}
const mcpServers = config?.getMcpServers() || {};
const serverNames = Object.keys(mcpServers);
if (serverNames.length === 0) {
addMessage({
type: MessageType.INFO,
content: 'No MCP servers configured.',
timestamp: new Date(),
});
return;
}
let message = 'Configured MCP servers and tools:\n\n';
for (const serverName of serverNames) {
const serverTools = toolRegistry.getToolsByServer(serverName);
const status = getMCPServerStatus(serverName);
// Add status indicator
let statusDot = '';
switch (status) {
case MCPServerStatus.CONNECTED:
statusDot = '🟢'; // Green dot for connected
break;
case MCPServerStatus.CONNECTING:
statusDot = '🟡'; // Yellow dot for connecting
break;
case MCPServerStatus.DISCONNECTED:
default:
statusDot = '🔴'; // Red dot for disconnected
break;
}
message += `${statusDot} ${serverName} (${serverTools.length} tools):\n`;
if (serverTools.length > 0) {
serverTools.forEach((tool) => {
message += ` - ${tool.name}\n`;
});
} else {
message += ' No tools available\n';
}
message += '\n';
}
addMessage({
type: MessageType.INFO,
content: message,
timestamp: new Date(),
});
},
},
{
name: 'memory',
description:
'manage memory. Usage: /memory <show|refresh|add> [text for add]',
action: (mainCommand, subCommand, args) => {
switch (subCommand) {
case 'show':
showMemoryAction();
return; // Explicitly return void
case 'refresh':
performMemoryRefresh();
return; // Explicitly return void
case 'add':
return addMemoryAction(mainCommand, subCommand, args); // Return the object
default:
addMessage({
type: MessageType.ERROR,
content: `Unknown /memory command: ${subCommand}. Available: show, refresh, add`,
timestamp: new Date(),
});
return; // Explicitly return void
}
},
},
{
name: 'tools',
description: 'list available Gemini CLI tools',
action: async (_mainCommand, _subCommand, _args) => {
const toolRegistry = await config?.getToolRegistry();
const tools = toolRegistry?.getAllTools();
if (!tools) {
addMessage({
type: MessageType.ERROR,
content: 'Could not retrieve tools.',
timestamp: new Date(),
});
return;
}
// Filter out MCP tools by checking if they have a serverName property
const geminiTools = tools.filter((tool) => !('serverName' in tool));
const geminiToolList = geminiTools.map((tool) => tool.name);
addMessage({
type: MessageType.INFO,
content: `Available Gemini CLI tools:\n\n${geminiToolList.join('\n')}`,
timestamp: new Date(),
});
},
},
{
name: 'corgi',
action: (_mainCommand, _subCommand, _args) => {
toggleCorgiMode();
},
},
{
name: 'about',
description: 'show version info',
action: (_mainCommand, _subCommand, _args) => {
const osVersion = process.platform;
let sandboxEnv = 'no sandbox';
if (process.env.SANDBOX && process.env.SANDBOX !== 'sandbox-exec') {
sandboxEnv = process.env.SANDBOX;
} else if (process.env.SANDBOX === 'sandbox-exec') {
sandboxEnv = `sandbox-exec (${process.env.SEATBELT_PROFILE || 'unknown'})`;
}
const modelVersion = config?.getModel() || 'Unknown';
const cliVersion = getCliVersion();
addMessage({
type: MessageType.ABOUT,
timestamp: new Date(),
cliVersion,
osVersion,
sandboxEnv,
modelVersion,
});
},
},
{
name: 'bug',
description: 'submit a bug report',
action: (_mainCommand, _subCommand, args) => {
let bugDescription = _subCommand || '';
if (args) {
bugDescription += ` ${args}`;
}
bugDescription = bugDescription.trim();
const osVersion = `${process.platform} ${process.version}`;
let sandboxEnv = 'no sandbox';
if (process.env.SANDBOX && process.env.SANDBOX !== 'sandbox-exec') {
sandboxEnv = process.env.SANDBOX.replace(/^gemini-(?:code-)?/, '');
} else if (process.env.SANDBOX === 'sandbox-exec') {
sandboxEnv = `sandbox-exec (${process.env.SEATBELT_PROFILE || 'unknown'})`;
}
const modelVersion = config?.getModel() || 'Unknown';
const memoryUsage = formatMemoryUsage(process.memoryUsage().rss);
const cliVersion = getCliVersion();
const diagnosticInfo = `
## Describe the bug
A clear and concise description of what the bug is.
## Additional context
Add any other context about the problem here.
## Diagnostic Information
* **CLI Version:** ${cliVersion}
* **Git Commit:** ${GIT_COMMIT_INFO}
* **Operating System:** ${osVersion}
* **Sandbox Environment:** ${sandboxEnv}
* **Model Version:** ${modelVersion}
* **Memory Usage:** ${memoryUsage}
`;
let bugReportUrl =
'https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.md';
if (bugDescription) {
const encodedArgs = encodeURIComponent(bugDescription);
bugReportUrl += `&title=${encodedArgs}`;
}
const encodedBody = encodeURIComponent(diagnosticInfo);
bugReportUrl += `&body=${encodedBody}`;
addMessage({
type: MessageType.INFO,
content: `To submit your bug report, please open the following URL in your browser:\n${bugReportUrl}`,
timestamp: new Date(),
});
(async () => {
try {
await open(bugReportUrl);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
addMessage({
type: MessageType.ERROR,
content: `Could not open URL in browser: ${errorMessage}`,
timestamp: new Date(),
});
}
})();
},
},
{
name: 'quit',
altName: 'exit',
description: 'exit the cli',
action: (_mainCommand, _subCommand, _args) => {
onDebugMessage('Quitting. Good-bye.');
process.exit(0);
},
},
],
[
onDebugMessage,
setShowHelp,
refreshStatic,
openThemeDialog,
clearItems,
performMemoryRefresh,
showMemoryAction,
addMemoryAction,
addMessage,
toggleCorgiMode,
config,
],
);
const handleSlashCommand = useCallback(
(rawQuery: PartListUnion): SlashCommandActionReturn | boolean => {
if (typeof rawQuery !== 'string') {
return false;
}
const trimmed = rawQuery.trim();
if (!trimmed.startsWith('/') && !trimmed.startsWith('?')) {
return false;
}
const userMessageTimestamp = Date.now();
addItem({ type: MessageType.USER, text: trimmed }, userMessageTimestamp);
let subCommand: string | undefined;
let args: string | undefined;
const commandToMatch = (() => {
if (trimmed.startsWith('?')) {
return 'help';
}
const parts = trimmed.substring(1).trim().split(/\s+/);
if (parts.length > 1) {
subCommand = parts[1];
}
if (parts.length > 2) {
args = parts.slice(2).join(' ');
}
return parts[0];
})();
const mainCommand = commandToMatch;
for (const cmd of slashCommands) {
if (mainCommand === cmd.name || mainCommand === cmd.altName) {
const actionResult = cmd.action(mainCommand, subCommand, args);
if (
typeof actionResult === 'object' &&
actionResult?.shouldScheduleTool
) {
return actionResult; // Return the object for useGeminiStream
}
return true; // Command was handled, but no tool to schedule
}
}
addMessage({
type: MessageType.ERROR,
content: `Unknown command: ${trimmed}`,
timestamp: new Date(),
});
return true; // Indicate command was processed (even if unknown)
},
[addItem, slashCommands, addMessage],
);
return { handleSlashCommand, slashCommands };
};
|