File size: 26,008 Bytes
9332ccf | 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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
useCallback,
useMemo,
useEffect,
useState,
createElement,
} from 'react';
import { type PartListUnion } from '@google/genai';
import process from 'node:process';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import type {
Config,
ExtensionsStartingEvent,
ExtensionsStoppingEvent,
ToolCallConfirmationDetails,
AgentDefinition,
} from '@google/gemini-cli-core';
import {
GitService,
Logger,
logSlashCommand,
makeSlashCommandEvent,
SlashCommandStatus,
ToolConfirmationOutcome,
Storage,
IdeClient,
coreEvents,
addMCPStatusChangeListener,
removeMCPStatusChangeListener,
MCPDiscoveryState,
CoreToolCallStatus,
} from '@google/gemini-cli-core';
import { useSessionStats } from '../contexts/SessionContext.js';
import type {
Message,
HistoryItemWithoutId,
SlashCommandProcessorResult,
HistoryItem,
ConfirmationRequest,
IndividualToolCallDisplay,
} from '../types.js';
import { MessageType } from '../types.js';
import type { LoadedSettings } from '../../config/settings.js';
import { type CommandContext, type SlashCommand } from '../commands/types.js';
import { CommandService } from '../../services/CommandService.js';
import { BuiltinCommandLoader } from '../../services/BuiltinCommandLoader.js';
import { FileCommandLoader } from '../../services/FileCommandLoader.js';
import { McpPromptLoader } from '../../services/McpPromptLoader.js';
import { SkillCommandLoader } from '../../services/SkillCommandLoader.js';
import { parseSlashCommand } from '../../utils/commands.js';
import {
type ExtensionUpdateAction,
type ExtensionUpdateStatus,
} from '../state/extensions.js';
import {
LogoutConfirmationDialog,
LogoutChoice,
} from '../components/LogoutConfirmationDialog.js';
import { runExitCleanup } from '../../utils/cleanup.js';
interface SlashCommandProcessorActions {
openAuthDialog: () => void;
openThemeDialog: () => void;
openEditorDialog: () => void;
openPrivacyNotice: () => void;
openSettingsDialog: () => void;
openSessionBrowser: () => void;
openModelDialog: () => void;
openVoiceModelDialog: () => void;
openAgentConfigDialog: (
name: string,
displayName: string,
definition: AgentDefinition,
) => void;
openPermissionsDialog: (props?: { targetDirectory?: string }) => void;
quit: (messages: HistoryItem[]) => void;
setDebugMessage: (message: string) => void;
toggleCorgiMode: () => void;
toggleVoiceMode: () => void;
toggleDebugProfiler: () => void;
dispatchExtensionStateUpdate: (action: ExtensionUpdateAction) => void;
addConfirmUpdateExtensionRequest: (request: ConfirmationRequest) => void;
toggleBackgroundTasks: () => void;
toggleShortcutsHelp: () => void;
setText: (text: string) => void;
}
/**
* Hook to define and process slash commands (e.g., /help, /clear).
*/
export const useSlashCommandProcessor = (
config: Config | null,
settings: LoadedSettings,
addItem: UseHistoryManagerReturn['addItem'],
clearItems: UseHistoryManagerReturn['clearItems'],
loadHistory: UseHistoryManagerReturn['loadHistory'],
refreshStatic: () => void,
toggleVimEnabled: () => Promise<boolean>,
setIsProcessing: (isProcessing: boolean) => void,
actions: SlashCommandProcessorActions,
extensionsUpdateState: Map<string, ExtensionUpdateStatus>,
isConfigInitialized: boolean,
setBannerVisible: (visible: boolean) => void,
setCustomDialog: (dialog: React.ReactNode | null) => void,
) => {
const session = useSessionStats();
const [commands, setCommands] = useState<readonly SlashCommand[] | undefined>(
undefined,
);
const [reloadTrigger, setReloadTrigger] = useState(0);
const reloadCommands = useCallback(() => {
setReloadTrigger((v) => v + 1);
}, []);
const [confirmationRequest, setConfirmationRequest] = useState<null | {
prompt: React.ReactNode;
onConfirm: (confirmed: boolean) => void;
}>(null);
const [sessionShellAllowlist, setSessionShellAllowlist] = useState(
new Set<string>(),
);
const gitService = useMemo(() => {
if (!config?.getProjectRoot()) {
return;
}
return new GitService(config.getProjectRoot(), config.storage);
}, [config]);
const logger = useMemo(() => {
const l = new Logger(
config?.getSessionId() || '',
config?.storage ?? new Storage(process.cwd()),
);
// The logger's initialize is async, but we can create the instance
// synchronously. Commands that use it will await its initialization.
return l;
}, [config]);
const [pendingItem, setPendingItem] = useState<HistoryItemWithoutId | null>(
null,
);
const pendingHistoryItems = useMemo(() => {
const items: HistoryItemWithoutId[] = [];
if (pendingItem != null) {
items.push(pendingItem);
}
return items;
}, [pendingItem]);
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,
selectedAuthType: message.selectedAuthType,
gcpProject: message.gcpProject,
ideClient: message.ideClient,
};
} else if (message.type === MessageType.HELP) {
historyItemContent = {
type: 'help',
timestamp: message.timestamp,
};
} else if (message.type === MessageType.STATS) {
historyItemContent = {
type: 'stats',
duration: message.duration,
};
} else if (message.type === MessageType.MODEL_STATS) {
historyItemContent = {
type: 'model_stats',
};
} else if (message.type === MessageType.TOOL_STATS) {
historyItemContent = {
type: 'tool_stats',
};
} else if (message.type === MessageType.QUIT) {
historyItemContent = {
type: 'quit',
duration: message.duration,
};
} else if (message.type === MessageType.COMPRESSION) {
historyItemContent = {
type: 'compression',
compression: message.compression,
};
} else {
historyItemContent = {
type: message.type,
text: message.content,
};
}
addItem(historyItemContent, message.timestamp.getTime());
},
[addItem],
);
const commandContext = useMemo(
(): CommandContext => ({
services: {
agentContext: config,
settings,
git: gitService,
logger,
},
ui: {
addItem,
clear: () => {
clearItems();
refreshStatic();
setBannerVisible(false);
},
loadHistory: (history, postLoadInput) => {
loadHistory(history);
refreshStatic();
if (postLoadInput !== undefined) {
actions.setText(postLoadInput);
}
},
setDebugMessage: actions.setDebugMessage,
pendingItem,
setPendingItem,
toggleCorgiMode: actions.toggleCorgiMode,
toggleVoiceMode: actions.toggleVoiceMode,
toggleDebugProfiler: actions.toggleDebugProfiler,
toggleVimEnabled,
reloadCommands,
openAgentConfigDialog: actions.openAgentConfigDialog,
extensionsUpdateState,
dispatchExtensionStateUpdate: actions.dispatchExtensionStateUpdate,
addConfirmUpdateExtensionRequest:
actions.addConfirmUpdateExtensionRequest,
setConfirmationRequest,
removeComponent: () => setCustomDialog(null),
toggleBackgroundTasks: actions.toggleBackgroundTasks,
toggleShortcutsHelp: actions.toggleShortcutsHelp,
},
session: {
stats: session.stats,
sessionShellAllowlist,
},
}),
[
config,
settings,
gitService,
logger,
loadHistory,
addItem,
clearItems,
refreshStatic,
session.stats,
actions,
pendingItem,
setPendingItem,
setConfirmationRequest,
toggleVimEnabled,
sessionShellAllowlist,
reloadCommands,
extensionsUpdateState,
setBannerVisible,
setCustomDialog,
],
);
useEffect(() => {
if (!config) {
return;
}
const listener = () => {
reloadCommands();
};
let isActive = true;
let activeIdeClient: IdeClient | undefined;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
const ideClient = await IdeClient.getInstance();
if (!isActive) {
return;
}
activeIdeClient = ideClient;
ideClient.addStatusChangeListener(listener);
})();
// Listen for MCP server status changes (e.g. connection, discovery completion)
// to reload slash commands (since they may include MCP prompts).
addMCPStatusChangeListener(listener);
// TODO: Ideally this would happen more directly inside the ExtensionLoader,
// but the CommandService today is not conducive to that since it isn't a
// long lived service but instead gets fully re-created based on reload
// events within this hook.
const extensionEventListener = (
_event: ExtensionsStartingEvent | ExtensionsStoppingEvent,
) => {
// We only care once at least one extension has completed
// starting/stopping
reloadCommands();
};
coreEvents.on('extensionsStarting', extensionEventListener);
coreEvents.on('extensionsStopping', extensionEventListener);
return () => {
isActive = false;
activeIdeClient?.removeStatusChangeListener(listener);
removeMCPStatusChangeListener(listener);
coreEvents.off('extensionsStarting', extensionEventListener);
coreEvents.off('extensionsStopping', extensionEventListener);
};
}, [config, reloadCommands]);
useEffect(() => {
const controller = new AbortController();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
const commandService = await CommandService.create(
[
new BuiltinCommandLoader(config),
new SkillCommandLoader(config),
new McpPromptLoader(config),
new FileCommandLoader(config),
],
controller.signal,
);
if (controller.signal.aborted) {
return;
}
setCommands(commandService.getCommands());
})();
return () => {
controller.abort();
};
}, [config, reloadTrigger, isConfigInitialized]);
const handleSlashCommand = useCallback(
async (
rawQuery: PartListUnion,
oneTimeShellAllowlist?: Set<string>,
overwriteConfirmed?: boolean,
addToHistory: boolean = true,
): Promise<SlashCommandProcessorResult | false> => {
if (!commands) {
return false;
}
if (typeof rawQuery !== 'string') {
return false;
}
const trimmed = rawQuery.trim();
if (!trimmed.startsWith('/') && !trimmed.startsWith('?')) {
return false;
}
const {
commandToExecute,
args,
canonicalPath: resolvedCommandPath,
} = parseSlashCommand(trimmed, commands);
// If the input doesn't match any known command, check if MCP servers
// are still loading (the command might come from an MCP server).
// Otherwise, treat it as regular text input (e.g. file paths like
// /home/user/file.txt) and let it be sent to the model.
if (!commandToExecute) {
const isMcpLoading =
config?.getMcpClientManager()?.getDiscoveryState() ===
MCPDiscoveryState.IN_PROGRESS;
if (isMcpLoading) {
setIsProcessing(true);
if (addToHistory) {
addItem({ type: MessageType.USER, text: trimmed }, Date.now());
}
addMessage({
type: MessageType.ERROR,
content: `Unknown command: ${trimmed}. Command might have been from an MCP server but MCP servers are not done loading.`,
timestamp: new Date(),
});
setIsProcessing(false);
return { type: 'handled' };
}
return false;
}
setIsProcessing(true);
if (addToHistory) {
const userMessageTimestamp = Date.now();
addItem(
{ type: MessageType.USER, text: trimmed },
userMessageTimestamp,
);
}
let hasError = false;
const subcommand =
resolvedCommandPath.length > 1
? resolvedCommandPath.slice(1).join(' ')
: undefined;
try {
if (commandToExecute) {
if (commandToExecute.action) {
const fullCommandContext: CommandContext = {
...commandContext,
invocation: {
raw: trimmed,
name: commandToExecute.name,
args,
},
overwriteConfirmed,
};
// If a one-time list is provided for a "Proceed" action, temporarily
// augment the session allowlist for this single execution.
if (oneTimeShellAllowlist && oneTimeShellAllowlist.size > 0) {
fullCommandContext.session = {
...fullCommandContext.session,
sessionShellAllowlist: new Set([
...fullCommandContext.session.sessionShellAllowlist,
...oneTimeShellAllowlist,
]),
};
}
const result = await commandToExecute.action(
fullCommandContext,
args,
);
if (result) {
switch (result.type) {
case 'tool':
return {
type: 'schedule_tool',
toolName: result.toolName,
toolArgs: result.toolArgs,
postSubmitPrompt: result.postSubmitPrompt,
};
case 'message':
addItem(
{
type:
result.messageType === 'error'
? MessageType.ERROR
: MessageType.INFO,
text: result.content,
},
Date.now(),
);
return { type: 'handled' };
case 'logout':
// Show logout confirmation dialog with Login/Exit options
setCustomDialog(
createElement(LogoutConfirmationDialog, {
onSelect: async (choice: LogoutChoice) => {
setCustomDialog(null);
if (choice === LogoutChoice.LOGIN) {
actions.openAuthDialog();
} else {
await runExitCleanup();
process.exit(0);
}
},
}),
);
return { type: 'handled' };
case 'dialog':
switch (result.dialog) {
case 'auth':
actions.openAuthDialog();
return { type: 'handled' };
case 'theme':
actions.openThemeDialog();
return { type: 'handled' };
case 'editor':
actions.openEditorDialog();
return { type: 'handled' };
case 'privacy':
actions.openPrivacyNotice();
return { type: 'handled' };
case 'sessionBrowser':
actions.openSessionBrowser();
return { type: 'handled' };
case 'settings':
actions.openSettingsDialog();
return { type: 'handled' };
case 'model':
actions.openModelDialog();
return { type: 'handled' };
case 'voice-model':
actions.openVoiceModelDialog();
return { type: 'handled' };
case 'agentConfig': {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const props = result.props as Record<string, unknown>;
if (
!props ||
// eslint-disable-next-line no-restricted-syntax
typeof props['name'] !== 'string' ||
// eslint-disable-next-line no-restricted-syntax
typeof props['displayName'] !== 'string' ||
!props['definition']
) {
throw new Error(
'Received invalid properties for agentConfig dialog action.',
);
}
actions.openAgentConfigDialog(
props['name'],
props['displayName'],
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
props['definition'] as AgentDefinition,
);
return { type: 'handled' };
}
case 'permissions':
actions.openPermissionsDialog(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
result.props as { targetDirectory?: string },
);
return { type: 'handled' };
case 'help':
return { type: 'handled' };
default: {
const unhandled: never = result.dialog;
throw new Error(
`Unhandled slash command result: ${unhandled}`,
);
}
}
case 'load_history': {
config?.getGeminiClient()?.setHistory(result.clientHistory);
fullCommandContext.ui.clear();
result.history.forEach((item, index) => {
fullCommandContext.ui.addItem(item, index);
});
return { type: 'handled' };
}
case 'quit':
if (result.deleteSession) {
try {
const chatRecordingService = config
?.getGeminiClient()
?.getChatRecordingService();
if (chatRecordingService) {
await chatRecordingService.deleteCurrentSessionAsync();
}
} catch {
// Don't let deletion errors prevent exit.
}
}
actions.quit(result.messages);
return { type: 'handled' };
case 'submit_prompt':
return {
type: 'submit_prompt',
content: result.content,
};
case 'confirm_shell_commands': {
const callId = `expansion-${Date.now()}`;
const { outcome, approvedCommands } = await new Promise<{
outcome: ToolConfirmationOutcome;
approvedCommands?: string[];
}>((resolve) => {
const confirmationDetails: ToolCallConfirmationDetails = {
type: 'exec',
title: `Confirm Shell Expansion`,
command: result.commandsToConfirm[0] || '',
rootCommand: result.commandsToConfirm[0] || '',
rootCommands: result.commandsToConfirm,
commands: result.commandsToConfirm,
onConfirm: async (resolvedOutcome) => {
// Close the pending tool display by resolving
resolve({
outcome: resolvedOutcome,
approvedCommands:
resolvedOutcome === ToolConfirmationOutcome.Cancel
? []
: result.commandsToConfirm,
});
},
};
const toolDisplay: IndividualToolCallDisplay = {
callId,
name: 'Expansion',
description: 'Command expansion needs shell access',
status: CoreToolCallStatus.AwaitingApproval,
isClientInitiated: true,
resultDisplay: undefined,
confirmationDetails,
};
setPendingItem({
type: 'tool_group',
tools: [toolDisplay],
});
});
setPendingItem(null);
if (
outcome === ToolConfirmationOutcome.Cancel ||
!approvedCommands ||
approvedCommands.length === 0
) {
addItem(
{
type: MessageType.INFO,
text: 'Slash command shell execution declined.',
},
Date.now(),
);
return { type: 'handled' };
}
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
setSessionShellAllowlist(
(prev) => new Set([...prev, ...approvedCommands]),
);
}
return await handleSlashCommand(
result.originalInvocation.raw,
// Pass the approved commands as a one-time grant for this execution.
new Set(approvedCommands),
undefined,
false, // Do not add to history again
);
}
case 'confirm_action': {
const { confirmed } = await new Promise<{
confirmed: boolean;
}>((resolve) => {
setConfirmationRequest({
prompt: result.prompt,
onConfirm: (resolvedConfirmed) => {
setConfirmationRequest(null);
resolve({ confirmed: resolvedConfirmed });
},
});
});
if (!confirmed) {
addItem(
{
type: MessageType.INFO,
text: 'Operation cancelled.',
},
Date.now(),
);
return { type: 'handled' };
}
return await handleSlashCommand(
result.originalInvocation.raw,
undefined,
true,
);
}
case 'custom_dialog': {
setCustomDialog(result.component);
return { type: 'handled' };
}
default: {
const unhandled: never = result;
throw new Error(
`Unhandled slash command result: ${unhandled}`,
);
}
}
}
return { type: 'handled' };
} else if (commandToExecute.subCommands) {
const helpText = `Command '/${commandToExecute.name}' requires a subcommand. Available:\n${commandToExecute.subCommands
.map((sc) => ` - ${sc.name}: ${sc.description || ''}`)
.join('\n')}`;
addMessage({
type: MessageType.INFO,
content: helpText,
timestamp: new Date(),
});
return { type: 'handled' };
}
}
return { type: 'handled' };
} catch (e: unknown) {
hasError = true;
if (config) {
const event = makeSlashCommandEvent({
command: resolvedCommandPath[0],
subcommand,
status: SlashCommandStatus.ERROR,
extension_id: commandToExecute?.extensionId,
});
logSlashCommand(config, event);
}
addItem(
{
type: MessageType.ERROR,
text: e instanceof Error ? e.message : String(e),
},
Date.now(),
);
return { type: 'handled' };
} finally {
if (config && resolvedCommandPath[0] && !hasError) {
const event = makeSlashCommandEvent({
command: resolvedCommandPath[0],
subcommand,
status: SlashCommandStatus.SUCCESS,
extension_id: commandToExecute?.extensionId,
});
logSlashCommand(config, event);
}
setIsProcessing(false);
}
},
[
config,
addItem,
actions,
commands,
commandContext,
addMessage,
setSessionShellAllowlist,
setIsProcessing,
setConfirmationRequest,
setCustomDialog,
],
);
return {
handleSlashCommand,
slashCommands: commands,
pendingHistoryItems,
commandContext,
confirmationRequest,
};
};
|