chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 11:58:09 +08:00
commit c48e26cdd0
2909 changed files with 1591131 additions and 0 deletions
+597
View File
@@ -0,0 +1,597 @@
# CLI commands
Gemini CLI supports several built-in commands to help you manage your session,
customize the interface, and control its behavior. These commands are prefixed
with a forward slash (`/`), an at symbol (`@`), or an exclamation mark (`!`).
## Slash commands (`/`)
Slash commands provide meta-level control over the CLI itself.
### Built-in Commands
### `/about`
- **Description:** Show version info. Share this information when filing issues.
### `/agents`
- **Description:** Manage local and remote subagents.
- **Sub-commands:**
- **`list`**:
- **Description:** Lists all discovered agents, including built-in, local,
and remote agents.
- **Usage:** `/agents list`
- **`reload`** (alias: `refresh`):
- **Description:** Rescans agent directories (`~/.gemini/agents` and
`.gemini/agents`) and reloads the registry.
- **Usage:** `/agents reload`
- **`enable`**:
- **Description:** Enables a specific subagent.
- **Usage:** `/agents enable <agent-name>`
- **`disable`**:
- **Description:** Disables a specific subagent.
- **Usage:** `/agents disable <agent-name>`
- **`config`**:
- **Description:** Opens a configuration dialog for the specified agent to
adjust its model, temperature, or execution limits.
- **Usage:** `/agents config <agent-name>`
### `/auth`
- **Description:** Open a dialog that lets you change the authentication method.
### `/bug`
- **Description:** File an issue about Gemini CLI. By default, the issue is
filed within the GitHub repository for Gemini CLI. The string you enter after
`/bug` will become the headline for the bug being filed. The default `/bug`
behavior can be modified using the `advanced.bugCommand` setting in your
`.gemini/settings.json` files.
### `/chat`
- **Description:** Alias for `/resume`. Both commands now expose the same
session browser action and checkpoint subcommands.
- **Menu layout when typing `/chat` (or `/resume`)**:
- `-- auto --`
- `list` (selecting this opens the auto-saved session browser)
- `-- checkpoints --`
- `list`, `save`, `resume`, `delete`, `share` (manual tagged checkpoints)
- Unique prefixes (for example `/cha` or `/resu`) resolve to the same grouped
menu.
- **Sub-commands:**
- **`debug`**
- **Description:** Export the most recent API request as a JSON payload.
- **`delete <tag>`**
- **Description:** Deletes a saved conversation checkpoint.
- **Equivalent:** `/resume delete <tag>`
- **`list`**
- **Description:** Lists available tags for manually saved checkpoints.
- **Note:** This command only lists chats saved within the current project.
Because chat history is project-scoped, chats saved in other project
directories will not be displayed.
- **Equivalent:** `/resume list`
- **`resume <tag>`**
- **Description:** Resumes a conversation from a previous save.
- **Note:** You can only resume chats that were saved within the current
project. To resume a chat from a different project, you must run the
Gemini CLI from that project's directory.
- **Equivalent:** `/resume resume <tag>`
- **`save <tag>`**
- **Description:** Saves the current conversation history. You must add a
`<tag>` for identifying the conversation state.
- **Details on checkpoint location:** The default locations for saved chat
checkpoints are:
- Linux/macOS: `~/.gemini/tmp/<project_hash>/`
- Windows: `C:\Users\<YourUsername>\.gemini\tmp\<project_hash>\`
- **Behavior:** Chats are saved into a project-specific directory,
determined by where you run the CLI. Consequently, saved chats are only
accessible when working within that same project.
- **Note:** These checkpoints are for manually saving and resuming
conversation states. For automatic checkpoints created before file
modifications, see the
[Checkpointing documentation](../cli/checkpointing.md).
- **Equivalent:** `/resume save <tag>`
- **`share [filename]`**
- **Description:** Writes the current conversation to a provided Markdown or
JSON file. If no filename is provided, then the CLI will generate one.
- **Usage:** `/chat share file.md` or `/chat share file.json`.
- **Equivalent:** `/resume share [filename]`
### `/clear`
- **Description:** Clear the terminal screen, including the visible session
history and scrollback within the CLI. The underlying session data (for
history recall) might be preserved depending on the exact implementation, but
the visual display is cleared.
- **Keyboard shortcut:** Press **Ctrl+L** at any time to perform a clear action.
### `/commands`
- **Description:** Manage custom slash commands loaded from `.toml` files.
- **Sub-commands:**
- **`list`**:
- **Description:** List available custom command `.toml` files from all
sources (user-level `~/.gemini/commands/`, project-level
`<project>/.gemini/commands/`, and active extensions).
- **Usage:** `/commands list`
- **`reload`**:
- **Description:** Reload custom command definitions from all sources
(user-level `~/.gemini/commands/`, project-level
`<project>/.gemini/commands/`, MCP prompts, and extensions). Use this to
pick up new or modified `.toml` files without restarting the CLI.
- **Usage:** `/commands reload`
### `/compress`
- **Description:** Replace the entire chat context with a summary. This saves on
tokens used for future tasks while retaining a high level summary of what has
happened.
### `/copy`
- **Description:** Copies the last output produced by Gemini CLI to your
clipboard, for easy sharing or reuse.
- **Behavior:**
- Local sessions use system clipboard tools (pbcopy/xclip/clip).
- Remote sessions (SSH/WSL) use OSC 52 and require terminal support.
- **Note:** This command requires platform-specific clipboard tools to be
installed.
- On Linux, it requires `xclip` or `xsel`. You can typically install them
using your system's package manager.
- On macOS, it requires `pbcopy`, and on Windows, it requires `clip`. These
tools are typically pre-installed on their respective systems.
### `/directory` (or `/dir`)
- **Description:** Manage workspace directories for multi-directory support.
- **Sub-commands:**
- **`add`**:
- **Description:** Add a directory to the workspace. The path can be
absolute or relative to the current working directory. Moreover, the
reference from home directory is supported as well.
- **Usage:** `/directory add <path1>,<path2>`
- **Note:** Disabled in restrictive sandbox profiles. If you're using that,
use `--include-directories` when starting the session instead.
- **`show`**:
- **Description:** Display all directories added by `/directory add` and
`--include-directories`.
- **Usage:** `/directory show`
### `/docs`
- **Description:** Open Gemini CLI documentation in your browser.
### `/editor`
- **Description:** Open a dialog for selecting supported editors.
### `/extensions`
- **Description:** Manage extensions. See
[Gemini CLI Extensions](../extensions/index.md).
- **Sub-commands:**
- **`config`**:
- **Description:** Configure extension settings.
- **`disable`**:
- **Description:** Disable an extension.
- **`enable`**:
- **Description:** Enable an extension.
- **`explore`**:
- **Description:** Open extensions page in your browser.
- **`install`**:
- **Description:** Install an extension from a git repo or local path.
- **`link`**:
- **Description:** Link an extension from a local path.
- **`list`**:
- **Description:** List active extensions.
- **`restart`**:
- **Description:** Restart all extensions.
- **`uninstall`**:
- **Description:** Uninstall an extension.
- **`update`**:
- **Description:** Update extensions. Usage: update <extension-names>|--all
### `/help` (or `/?`)
- **Description:** Display help information about Gemini CLI, including
available commands and their usage.
### `/hooks`
- **Description:** Manage hooks, which allow you to intercept and customize
Gemini CLI behavior at specific lifecycle events.
- **Sub-commands:**
- **`disable-all`**:
- **Description:** Disable all enabled hooks.
- **`disable <hook-name>`**:
- **Description:** Disable a hook by name.
- **`enable-all`**:
- **Description:** Enable all disabled hooks.
- **`enable <hook-name>`**:
- **Description:** Enable a hook by name.
- **`list`** (or `show`, `panel`):
- **Description:** Display all registered hooks with their status.
### `/ide`
- **Description:** Manage IDE integration.
- **Sub-commands:**
- **`disable`**:
- **Description:** Disable IDE integration.
- **`enable`**:
- **Description:** Enable IDE integration.
- **`install`**:
- **Description:** Install required IDE companion.
- **`status`**:
- **Description:** Check status of IDE integration.
### `/init`
- **Description:** To help users easily create a `GEMINI.md` file, this command
analyzes the current directory and generates a tailored context file, making
it simpler for them to provide project-specific instructions to the Gemini
agent.
### `/mcp`
- **Description:** Manage configured Model Context Protocol (MCP) servers.
- **Sub-commands:**
- **`auth`**:
- **Description:** Authenticate with an OAuth-enabled MCP server.
- **Usage:** `/mcp auth <server-name>`
- **Details:** If `<server-name>` is provided, it initiates the OAuth flow
for that server. If no server name is provided, it lists all configured
servers that support OAuth authentication.
- **`desc`**
- **Description:** List configured MCP servers and tools with descriptions.
- **`disable`**
- **Description:** Disable an MCP server.
- **`enable`**
- **Description:** Enable a disabled MCP server.
- **`list`** or **`ls`**:
- **Description:** List configured MCP servers and tools. This is the
default action if no subcommand is specified.
- **`reload`**:
- **Description:** Reloads all MCP servers and re-discovers their available
tools.
- **`schema`**:
- **Description:** List configured MCP servers and tools with descriptions
and schemas.
### `/memory`
- **Description:** Manage the AI's instructional context (hierarchical memory
loaded from `GEMINI.md` files).
- **Sub-commands:**
- **`list`**:
- **Description:** Lists the paths of the GEMINI.md files in use for
hierarchical memory.
- **`refresh`**:
- **Description:** Reload the hierarchical instructional memory from all
`GEMINI.md` files found in the configured locations (global,
project/ancestors, and sub-directories). This command updates the model
with the latest `GEMINI.md` content.
- **`show`**:
- **Description:** Display the full, concatenated content of the current
hierarchical memory that has been loaded from all `GEMINI.md` files. This
lets you inspect the instructional context being provided to the Gemini
model.
- **Note:** For more details on how `GEMINI.md` files contribute to
hierarchical memory, see the
[CLI Configuration documentation](./configuration.md).
### `/model`
- **Description:** Manage model configuration.
- **Sub-commands:**
- **`manage`**:
- **Description:** Opens a dialog to configure the model.
- **`set`**:
- **Description:** Set the model to use.
- **Usage:** `/model set <model-name> [--persist]`
### `/permissions`
- **Description:** Manage folder trust settings and other permissions.
- **Sub-commands:**
- **`trust`**:
- **Description:** Manage folder trust settings.
- **Usage:** `/permissions trust [<directory-path>]`
### `/plan`
- **Description:** Switch to Plan Mode (read-only) and view the current plan if
one has been generated.
- **Note:** This feature is enabled by default. It can be disabled via the
`general.plan.enabled` setting in your configuration.
- **Sub-commands:**
- **`copy`**:
- **Description:** Copy the currently approved plan to your clipboard.
### `/policies`
- **Description:** Manage policies.
- **Sub-commands:**
- **`list`**:
- **Description:** List all active policies grouped by mode.
### `/privacy`
- **Description:** Display the Privacy Notice and allow users to select whether
they consent to the collection of their data for service improvement purposes.
### `/quit` (or `/exit`)
- **Description:** Exit Gemini CLI.
- **Flags:**
- **`--delete`** _(optional)_: Exit and permanently delete the current
session's history and temporary files (chat recording, tool outputs). Useful
for privacy or one-off tasks where you don't want to leave any traces.
- **Usage:** `/quit --delete` or `/exit --delete`
### `/restore`
- **Description:** Restores the project files to the state they were in just
before a tool was executed. This is particularly useful for undoing file edits
made by a tool. If run without a tool call ID, it will list available
checkpoints to restore from.
- **Usage:** `/restore [tool_call_id]`
- **Note:** Only available if checkpointing is configured via
[settings](./configuration.md). See
[Checkpointing documentation](../cli/checkpointing.md) for more details.
### `/rewind`
- **Description:** Navigates backward through the conversation history, letting
you review past interactions and potentially revert both chat state and file
changes.
- **Usage:** Press **Esc** twice as a shortcut.
- **Features:**
- **Select Interaction:** Preview user prompts and file changes.
- **Action Selection:** Choose to rewind history only, revert code changes
only, or both.
### `/resume`
- **Description:** Browse and resume previous conversation sessions, and manage
manual chat checkpoints.
- **Features:**
- **Auto sessions:** Run `/resume` to open the interactive session browser for
automatically saved conversations.
- **Chat checkpoints:** Use checkpoint subcommands directly (`/resume save`,
`/resume resume`, etc.).
- **Management:** Delete unwanted sessions directly from the browser
- **Resume:** Select any session to resume and continue the conversation
- **Search:** Use `/` to search through conversation content across all
sessions
- **Session Browser:** Interactive interface showing all saved sessions with
timestamps, message counts, and first user message for context
- **Sorting:** Sort sessions by date or message count
- **Note:** All conversations are automatically saved as you chat - no manual
saving required. See [Session Management](../cli/session-management.md) for
complete details.
- **Alias:** `/chat` provides the same behavior and subcommands.
- **Sub-commands:**
- **`list`**
- **Description:** Lists available tags for manual chat checkpoints.
- **`save <tag>`**
- **Description:** Saves the current conversation as a tagged checkpoint.
- **`resume <tag>`** (alias: `load`)
- **Description:** Loads a previously saved tagged checkpoint.
- **`delete <tag>`**
- **Description:** Deletes a tagged checkpoint.
- **`share [filename]`**
- **Description:** Exports the current conversation to Markdown or JSON.
- **`debug`**
- **Description:** Export the most recent API request as JSON payload
(nightly builds).
- **Compatibility alias:** `/resume checkpoints ...` is still accepted for the
same checkpoint commands.
### `/settings`
- **Description:** Open the settings editor to view and modify Gemini CLI
settings.
- **Details:** This command provides a user-friendly interface for changing
settings that control the behavior and appearance of Gemini CLI. It is
equivalent to manually editing the `.gemini/settings.json` file, but with
validation and guidance to prevent errors. See the
[settings documentation](../cli/settings.md) for a full list of available
settings.
- **Usage:** Simply run `/settings` and the editor will open. You can then
browse or search for specific settings, view their current values, and modify
them as desired. Changes to some settings are applied immediately, while
others require a restart.
### `/shells` (or `/bashes`)
- **Description:** Toggle the background shells view. This lets you view and
manage long-running processes that you've sent to the background.
### `/setup-github`
- **Description:** Set up GitHub Actions to triage issues and review PRs with
Gemini.
### `/skills`
- **Description:** Manage Agent Skills, which provide on-demand expertise and
specialized workflows.
- **Sub-commands:**
- **`disable <name>`**:
- **Description:** Disable a specific skill by name.
- **Usage:** `/skills disable <name>`
- **`enable <name>`**:
- **Description:** Enable a specific skill by name.
- **Usage:** `/skills enable <name>`
- **`list`**:
- **Description:** List all discovered skills and their current status
(enabled/disabled).
- **`reload`**:
- **Description:** Refresh the list of discovered skills from all tiers
(workspace, user, and extensions).
### `/stats`
- **Description:** Display detailed statistics for the current Gemini CLI
session.
- **Sub-commands:**
- **`session`**:
- **Description:** Show session-specific usage statistics, including
duration, tool calls, and performance metrics. This is the default view.
- **`model`**:
- **Description:** Show model-specific usage statistics, including token
counts and quota information.
- **`tools`**:
- **Description:** Show tool-specific usage statistics.
### `/terminal-setup`
- **Description:** Configure terminal keybindings for multiline input (VS Code,
Cursor, Windsurf).
### `/theme`
- **Description:** Open a dialog that lets you change the visual theme of Gemini
CLI.
### `/tools`
- **Description:** Display a list of tools that are currently available within
Gemini CLI.
- **Usage:** `/tools [desc]`
- **Sub-commands:**
- **`desc`** or **`descriptions`**:
- **Description:** Show detailed descriptions of each tool, including each
tool's name with its full description as provided to the model.
- **`nodesc`** or **`nodescriptions`**:
- **Description:** Hide tool descriptions, showing only the tool names.
### `/upgrade`
- **Description:** Open the Gemini Code Assist upgrade page in your browser.
This lets you upgrade your tier for higher usage limits.
- **Note:** This command is only available when logged in with Google.
### `/vim`
- **Description:** Toggle vim mode on or off. When vim mode is enabled, the
input area supports vim-style navigation and editing commands in both NORMAL
and INSERT modes.
- **Features:**
- **Count support:** Prefix commands with numbers (for example, `3h`, `5w`,
`10G`)
- **Editing commands:** Delete with `x`, change with `c`, insert with `i`,
`a`, `o`, `O`; complex operations like `dd`, `cc`, `dw`, `cw`
- **INSERT mode:** Standard text input with escape to return to NORMAL mode
- **NORMAL mode:** Navigate with `h`, `j`, `k`, `l`; jump by words with `w`,
`b`, `e`; go to line start/end with `0`, `$`, `^`; go to specific lines with
`G` (or `gg` for first line)
- **Persistent setting:** Vim mode preference is saved to
`~/.gemini/settings.json` and restored between sessions
- **Repeat last command:** Use `.` to repeat the last editing operation
- **Status indicator:** When enabled, shows `[NORMAL]` or `[INSERT]` in the
footer
### Custom commands
Custom commands allow you to create personalized shortcuts for your most-used
prompts. For detailed instructions on how to create, manage, and use them, see
the dedicated [Custom Commands documentation](../cli/custom-commands.md).
## Input prompt shortcuts
These shortcuts apply directly to the input prompt for text manipulation.
- **Undo:**
- **Keyboard shortcut:** Press **Ctrl+z** (Windows), **Cmd+z** (macOS), or
**Alt+z** (Linux/WSL) to undo the last action in the input prompt.
- **Redo:**
- **Keyboard shortcut:** Press **Shift+Cmd+Z** (macOS), or **Shift+Alt+Z**
(Linux/WSL) to redo the last undone action in the input prompt.
## At commands (`@`)
At commands are used to include the content of files or directories as part of
your prompt to Gemini. These commands include git-aware filtering.
- **`@<path_to_file_or_directory>`**
- **Description:** Inject the content of the specified file or files into your
current prompt. This is useful for asking questions about specific code,
text, or collections of files.
- **Examples:**
- `@path/to/your/file.txt Explain this text.`
- `@src/my_project/ Summarize the code in this directory.`
- `What is this file about? @README.md`
- **Details:**
- If a path to a single file is provided, the content of that file is read.
- If a path to a directory is provided, the command attempts to read the
content of files within that directory and any subdirectories.
- Spaces in paths should be escaped with a backslash (for example,
`@My\ Documents/file.txt`).
- The command uses the `read_many_files` tool internally. The content is
fetched and then inserted into your query before being sent to the Gemini
model.
- **Git-aware filtering:** By default, git-ignored files (like
`node_modules/`, `dist/`, `.env`, `.git/`) are excluded. This behavior can
be changed via the `context.fileFiltering` settings.
- **File types:** The command is intended for text-based files. While it
might attempt to read any file, binary files or very large files might be
skipped or truncated by the underlying `read_many_files` tool to ensure
performance and relevance. The tool indicates if files were skipped.
- **Output:** The CLI will show a tool call message indicating that
`read_many_files` was used, along with a message detailing the status and
the path(s) that were processed.
- **`@` (Lone at symbol)**
- **Description:** If you type a lone `@` symbol without a path, the query is
passed as-is to the Gemini model. This might be useful if you are
specifically talking _about_ the `@` symbol in your prompt.
### Error handling for `@` commands
- If the path specified after `@` is not found or is invalid, an error message
will be displayed, and the query might not be sent to the Gemini model, or it
will be sent without the file content.
- If the `read_many_files` tool encounters an error (for example, permission
issues), this will also be reported.
## Shell mode and passthrough commands (`!`)
The `!` prefix lets you interact with your system's shell directly from within
Gemini CLI.
- **`!<shell_command>`**
- **Description:** Execute the given `<shell_command>` using `bash` on
Linux/macOS or `powershell.exe -NoProfile -Command` on Windows (unless you
override `ComSpec`). Any output or errors from the command are displayed in
the terminal.
- **Examples:**
- `!ls -la` (executes `ls -la` and returns to Gemini CLI)
- `!git status` (executes `git status` and returns to Gemini CLI)
- **`!` (Toggle shell mode)**
- **Description:** Typing `!` on its own toggles shell mode.
- **Entering shell mode:**
- When active, shell mode uses a different coloring and a "Shell Mode
Indicator".
- While in shell mode, text you type is interpreted directly as a shell
command.
- **Exiting shell mode:**
- When exited, the UI reverts to its standard appearance and normal Gemini
CLI behavior resumes.
- **Caution for all `!` usage:** Commands you execute in shell mode have the
same permissions and impact as if you ran them directly in your terminal.
- **Environment variable:** When a command is executed via `!` or in shell mode,
the `GEMINI_CLI=1` environment variable is set in the subprocess's
environment. This allows scripts or tools to detect if they are being run from
within Gemini CLI.
File diff suppressed because it is too large Load Diff
+360
View File
@@ -0,0 +1,360 @@
# Gemini CLI keyboard shortcuts
Gemini CLI ships with a set of default keyboard shortcuts for editing input,
navigating history, and controlling the UI. Use this reference to learn the
available combinations.
<!-- KEYBINDINGS-AUTOGEN:START -->
#### Basic Controls
| Command | Action | Keys |
| --------------- | --------------------------------------------------------------- | ------------------- |
| `basic.confirm` | Confirm the current selection or choice. | `Enter` |
| `basic.cancel` | Dismiss dialogs or cancel the current focus. | `Esc`<br />`Ctrl+[` |
| `basic.quit` | Cancel the current request or quit the CLI when input is empty. | `Ctrl+C` |
| `basic.exit` | Exit the CLI when the input buffer is empty. | `Ctrl+D` |
#### Cursor Movement
| Command | Action | Keys |
| ------------------ | ------------------------------------------- | ------------------------------------------ |
| `cursor.home` | Move the cursor to the start of the line. | `Ctrl+A`<br />`Home` |
| `cursor.end` | Move the cursor to the end of the line. | `Ctrl+E`<br />`End` |
| `cursor.up` | Move the cursor up one line. | `Up` |
| `cursor.down` | Move the cursor down one line. | `Down` |
| `cursor.left` | Move the cursor one character to the left. | `Left` |
| `cursor.right` | Move the cursor one character to the right. | `Right`<br />`Ctrl+F` |
| `cursor.wordLeft` | Move the cursor one word to the left. | `Ctrl+Left`<br />`Alt+Left`<br />`Alt+B` |
| `cursor.wordRight` | Move the cursor one word to the right. | `Ctrl+Right`<br />`Alt+Right`<br />`Alt+F` |
#### Editing
| Command | Action | Keys |
| ---------------------- | ------------------------------------------------ | -------------------------------------------------------- |
| `edit.deleteRightAll` | Delete from the cursor to the end of the line. | `Ctrl+K` |
| `edit.deleteLeftAll` | Delete from the cursor to the start of the line. | `Ctrl+U` |
| `edit.clear` | Clear all text in the input field. | `Ctrl+C` |
| `edit.deleteWordLeft` | Delete the previous word. | `Ctrl+Backspace`<br />`Alt+Backspace`<br />`Ctrl+W` |
| `edit.deleteWordRight` | Delete the next word. | `Ctrl+Delete`<br />`Alt+Delete`<br />`Alt+D` |
| `edit.deleteLeft` | Delete the character to the left. | `Backspace`<br />`Ctrl+H` |
| `edit.deleteRight` | Delete the character to the right. | `Delete`<br />`Ctrl+D` |
| `edit.undo` | Undo the most recent text edit. | `Ctrl+Z`<br />`Alt+Z`<br />`Cmd/Win+Z` |
| `edit.redo` | Redo the most recent undone text edit. | `Ctrl+Shift+Z`<br />`Shift+Cmd/Win+Z`<br />`Alt+Shift+Z` |
#### Scrolling
| Command | Action | Keys |
| ----------------- | ------------------------ | ----------------------------- |
| `scroll.up` | Scroll content up. | `Shift+Up` |
| `scroll.down` | Scroll content down. | `Shift+Down` |
| `scroll.home` | Scroll to the top. | `Ctrl+Home`<br />`Shift+Home` |
| `scroll.end` | Scroll to the bottom. | `Ctrl+End`<br />`Shift+End` |
| `scroll.pageUp` | Scroll up by one page. | `Page Up` |
| `scroll.pageDown` | Scroll down by one page. | `Page Down` |
#### History & Search
| Command | Action | Keys |
| ----------------------- | -------------------------------------------- | -------- |
| `history.previous` | Show the previous entry in history. | `Ctrl+P` |
| `history.next` | Show the next entry in history. | `Ctrl+N` |
| `history.search.start` | Start reverse search through history. | `Ctrl+R` |
| `history.search.submit` | Submit the selected reverse-search match. | `Enter` |
| `history.search.accept` | Accept a suggestion while reverse searching. | `Tab` |
#### Navigation
| Command | Action | Keys |
| --------------------- | -------------------------------------------------- | --------------- |
| `nav.up` | Move selection up in lists. | `Up` |
| `nav.down` | Move selection down in lists. | `Down` |
| `nav.dialog.up` | Move up within dialog options. | `Up`<br />`K` |
| `nav.dialog.down` | Move down within dialog options. | `Down`<br />`J` |
| `nav.dialog.next` | Move to the next item or question in a dialog. | `Tab` |
| `nav.dialog.previous` | Move to the previous item or question in a dialog. | `Shift+Tab` |
#### Suggestions & Completions
| Command | Action | Keys |
| ----------------------- | --------------------------------------- | -------------------- |
| `suggest.accept` | Accept the inline suggestion. | `Tab`<br />`Enter` |
| `suggest.focusPrevious` | Move to the previous completion option. | `Up`<br />`Ctrl+P` |
| `suggest.focusNext` | Move to the next completion option. | `Down`<br />`Ctrl+N` |
| `suggest.expand` | Expand an inline suggestion. | `Right` |
| `suggest.collapse` | Collapse an inline suggestion. | `Left` |
#### Text Input
| Command | Action | Keys |
| ------------------------------------ | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `input.submit` | Submit the current prompt. | `Enter` |
| `input.queueMessage` | Queue the current prompt to be processed after the current task finishes. | `Tab` |
| `input.newline` | Insert a newline without submitting. | `Ctrl+Enter`<br />`Cmd/Win+Enter`<br />`Alt+Enter`<br />`Shift+Enter`<br />`Ctrl+J` |
| `input.openExternalEditor` | Open the current prompt or the plan in an external editor. | `Ctrl+G`<br />`Ctrl+Shift+G` |
| `input.deprecatedOpenExternalEditor` | Deprecated command to open external editor. | `Ctrl+X` |
| `input.paste` | Paste from the clipboard. | `Ctrl+V`<br />`Cmd/Win+V`<br />`Alt+V` |
#### App Controls
| Command | Action | Keys |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `app.showErrorDetails` | Toggle the debug console for detailed error information. | `F12` |
| `app.showFullTodos` | Toggle the full TODO list. | `Ctrl+T` |
| `app.showIdeContextDetail` | Show IDE context details. | `F4` |
| `app.toggleMarkdown` | Toggle Markdown rendering. | `Alt+M` |
| `app.toggleCopyMode` | Toggle copy mode when in alternate buffer mode. | `F9` |
| `app.toggleMouseMode` | Toggle mouse mode (scrolling and clicking). | `Ctrl+S` |
| `app.toggleYolo` | Toggle YOLO (auto-approval) mode for tool calls. | `Ctrl+Y` |
| `app.cycleApprovalMode` | Cycle through approval modes: default (prompt), auto_edit (auto-approve edits), and plan (read-only). Plan mode is skipped when the agent is busy. | `Shift+Tab` |
| `app.showMoreLines` | Expand and collapse blocks of content when not in alternate buffer mode. | `Ctrl+O` |
| `app.expandPaste` | Expand or collapse a paste placeholder when cursor is over placeholder. | `Ctrl+O` |
| `app.focusShellInput` | Move focus from Gemini to the active shell. | `Tab` |
| `app.unfocusShellInput` | Move focus from the shell back to Gemini. | `Shift+Tab` |
| `app.clearScreen` | Clear the terminal screen and redraw the UI. | `Ctrl+L` |
| `app.restart` | Restart the application. | `R`<br />`Shift+R` |
| `app.suspend` | Suspend the CLI and move it to the background. | `Ctrl+Z` |
| `app.showShellUnfocusWarning` | Show warning when trying to move focus away from shell input. | `Tab` |
| `app.voiceModePTT` | Hold to speak in Voice Mode. | `Space` |
#### Background Shell Controls
| Command | Action | Keys |
| --------------------------- | ------------------------------------------------------------------ | ----------- |
| `background.escape` | Dismiss background shell list. | `Esc` |
| `background.select` | Confirm selection in background shell list. | `Enter` |
| `background.toggle` | Toggle current background shell visibility. | `Ctrl+B` |
| `background.toggleList` | Toggle background shell list. | `Ctrl+L` |
| `background.kill` | Kill the active background shell. | `Ctrl+K` |
| `background.unfocus` | Move focus from background shell to Gemini. | `Shift+Tab` |
| `background.unfocusList` | Move focus from background shell list to Gemini. | `Tab` |
| `background.unfocusWarning` | Show warning when trying to move focus away from background shell. | `Tab` |
| `app.dumpFrame` | Dump the current frame as a snapshot. | `F8` |
| `app.startRecording` | Start recording the session. | `F6` |
| `app.stopRecording` | Stop recording the session. | `F7` |
#### Extension Controls
| Command | Action | Keys |
| ------------------ | ------------------------------------------- | ---- |
| `extension.update` | Update the current extension if available. | `I` |
| `extension.link` | Link the current extension to a local path. | `L` |
<!-- KEYBINDINGS-AUTOGEN:END -->
## Customizing Keybindings
You can add alternative keybindings or remove default keybindings by creating a
`keybindings.json` file in your home gemini directory (typically
`~/.gemini/keybindings.json`).
### Configuration Format
The configuration uses a JSON array of objects, similar to VS Code's keybinding
schema. Each object must specify a `command` from the reference tables above and
a `key` combination.
```json
[
{
"command": "edit.clear",
"key": "cmd+l"
},
{
// prefix "-" to unbind a key
"command": "-app.toggleYolo",
"key": "ctrl+y"
},
{
"command": "input.submit",
"key": "ctrl+y"
},
{
// multiple modifiers
"command": "cursor.right",
"key": "shift+alt+a"
},
{
// Some mac keyboards send "Å" instead of "shift+option+a"
"command": "cursor.right",
"key": "Å"
},
{
// some base keys have special multi-char names
"command": "cursor.right",
"key": "shift+pageup"
}
]
```
- **Unbinding** To remove an existing or default keybinding, prefix a minus sign
(`-`) to the `command` name.
- **No Auto-unbinding** The same key can be bound to multiple commands in
different contexts at the same time. Therefore, creating a binding does not
automatically unbind the key from other commands.
- **Explicit Modifiers**: Key matching is explicit. For example, a binding for
`ctrl+f` will only trigger on exactly `ctrl+f`, not `ctrl+shift+f` or
`alt+ctrl+f`.
- **Literal Characters**: Terminals often translate complex key combinations
(especially on macOS with the `Option` key) into special characters, losing
modifier and keystroke information along the way. For example,`shift+5` might
be sent as `%`. In these cases, you must bind to the literal character `%` as
bindings to `shift+5` will never fire. To see precisely what is being sent,
enable `Debug Keystroke Logging` and hit f12 to open the debug log console.
- **Key Modifiers**: The supported key modifiers are:
- `ctrl`
- `shift`,
- `alt` (synonyms: `opt`, `option`)
- `cmd` (synonym: `meta`)
- **Base Key**: The base key can be any single unicode code point or any of the
following special keys:
- **Navigation**: `up`, `down`, `left`, `right`, `home`, `end`, `pageup`,
`pagedown`
- **Actions**: `enter`, `escape`, `tab`, `space`, `backspace`, `delete`,
`clear`, `insert`, `printscreen`
- **Toggles**: `capslock`, `numlock`, `scrolllock`, `pausebreak`
- **Function Keys**: `f1` through `f35`
- **Numpad**: `numpad0` through `numpad9`, `numpad_add`, `numpad_subtract`,
`numpad_multiply`, `numpad_divide`, `numpad_decimal`, `numpad_separator`
## Additional context-specific shortcuts
- `Option+B/F/M` (macOS only): Are interpreted as `Cmd+B/F/M` even if your
terminal isn't configured to send Meta with Option.
- `!` on an empty prompt: Enter or exit shell mode.
- `?` on an empty prompt: Toggle the shortcuts panel above the input. Press
`Esc`, `Backspace`, any printable key, or a registered app hotkey to close it.
The panel also auto-hides while the agent is running/streaming or when
action-required dialogs are shown. Press `?` again to close the panel and
insert a `?` into the prompt.
- `Tab` + `Tab` (while typing in the prompt): Toggle between minimal and full UI
details when no completion/search interaction is active. The selected mode is
remembered for future sessions. Full UI remains the default on first run, and
single `Tab` keeps its existing completion/focus behavior.
- `Shift + Tab` (while typing in the prompt): Cycle approval modes: default,
auto-edit, and plan (skipped when agent is busy).
- `\` (at end of a line) + `Enter`: Insert a newline without leaving single-line
mode.
- `Esc` pressed twice quickly: Clear the input prompt if it is not empty,
otherwise browse and rewind previous interactions.
- `Up Arrow` / `Down Arrow`: When the cursor is at the top or bottom of a
single-line input, navigate backward or forward through prompt history.
- `Number keys (1-9, multi-digit)` inside selection dialogs: Jump directly to
the numbered radio option and confirm when the full number is entered.
- `Ctrl + O`: Expand or collapse paste placeholders (`[Pasted Text: X lines]`)
inline when the cursor is over the placeholder.
- `Ctrl + X` (while a plan is presented): Open the plan in an external editor to
[collaboratively edit or comment](../cli/plan-mode.md#collaborative-plan-editing)
on the implementation strategy.
- `Double-click` on a paste placeholder (alternate buffer mode only): Expand to
view full content inline. Double-click again to collapse.
## Vi mode shortcuts
When vim mode is enabled with `/vim` or `general.vimMode: true`, Gemini CLI
supports NORMAL and INSERT modes.
### Mode switching
| Action | Keys |
| -------------------------------------------- | --------- |
| Enter NORMAL mode from INSERT mode | `Esc` |
| Enter INSERT mode at the cursor | `i` |
| Enter INSERT mode after the cursor | `a` |
| Enter INSERT mode at the start of the line | `I` |
| Enter INSERT mode at the end of the line | `A` |
| Insert a new line below and switch to INSERT | `o` |
| Insert a new line above and switch to INSERT | `O` |
| Clear input in NORMAL mode | `Esc Esc` |
### Navigation in NORMAL mode
| Action | Keys |
| --------------------------------- | --------------- |
| Move left | `h` |
| Move down | `j` |
| Move up | `k` |
| Move right | `l` |
| Move to start of line | `0` |
| Move to first non-whitespace char | `^` |
| Move to end of line | `$` |
| Move forward by word | `w` |
| Move backward by word | `b` |
| Move to end of word | `e` |
| Move forward by WORD | `W` |
| Move backward by WORD | `B` |
| Move to end of WORD | `E` |
| Go to first line | `gg` |
| Go to last line | `G` |
| Go to line N | `N G` or `N gg` |
Counts are supported for navigation commands. For example, `5j` moves down five
lines and `3w` moves forward three words.
### Editing in NORMAL mode
| Action | Keys |
| ------------------------------ | ----- |
| Delete character under cursor | `x` |
| Delete to end of line | `D` |
| Delete line | `dd` |
| Change to end of line | `C` |
| Change line | `cc` |
| Delete forward word | `dw` |
| Delete backward word | `db` |
| Delete to end of word | `de` |
| Delete forward WORD | `dW` |
| Delete backward WORD | `dB` |
| Delete to end of WORD | `dE` |
| Change forward word | `cw` |
| Change backward word | `cb` |
| Change to end of word | `ce` |
| Change forward WORD | `cW` |
| Change backward WORD | `cB` |
| Change to end of WORD | `cE` |
| Delete to start of line | `d0` |
| Delete to first non-whitespace | `d^` |
| Change to start of line | `c0` |
| Change to first non-whitespace | `c^` |
| Delete from first line to here | `dgg` |
| Delete from here to last line | `dG` |
| Change from first line to here | `cgg` |
| Change from here to last line | `cG` |
| Undo last change | `u` |
| Repeat last command | `.` |
Counts are also supported for editing commands. For example, `3dd` deletes three
lines and `2cw` changes two words.
### Find, replace, yank, and paste in NORMAL mode
| Action | Keys |
| ----------------------------------------- | ----------- |
| Find next matching character | `f{char}` |
| Find previous matching character | `F{char}` |
| Move until before next matching character | `t{char}` |
| Move until after previous matching char | `T{char}` |
| Repeat latest character find | `;` |
| Repeat latest character find in reverse | `,` |
| Delete character before cursor | `X` |
| Toggle case under cursor | `~` |
| Replace character under cursor | `r{char}` |
| Yank line | `yy` |
| Yank to end of line | `Y` or `y$` |
| Yank word / WORD | `yw`, `yW` |
| Yank to end of word / WORD | `ye`, `yE` |
| Paste after cursor | `p` |
| Paste before cursor | `P` |
Delete and change operators also compose with character-find motions, so
commands such as `dfx`, `dtx`, `cFx`, and `cTx` are supported.
## Limitations
- On [Windows Terminal](https://en.wikipedia.org/wiki/Windows_Terminal):
- `shift+enter` is only supported in version 1.25 and higher.
- `shift+tab`
[is not supported](https://github.com/google-gemini/gemini-cli/issues/20314)
on Node 20 and earlier versions of Node 22.
- On macOS's [Terminal](<https://en.wikipedia.org/wiki/Terminal_(macOS)>):
- `shift+enter` is not supported.
+245
View File
@@ -0,0 +1,245 @@
# Memory Import Processor
The Memory Import Processor is a feature that lets you modularize your GEMINI.md
files by importing content from other files using the `@file.md` syntax.
## Overview
This feature enables you to break down large GEMINI.md files into smaller, more
manageable components that can be reused across different contexts. The import
processor supports both relative and absolute paths, with built-in safety
features to prevent circular imports and ensure file access security.
## Syntax
Use the `@` symbol followed by the path to the file you want to import:
```markdown
# Main GEMINI.md file
This is the main content.
@./components/instructions.md
More content here.
@./shared/configuration.md
```
## Supported path formats
### Relative paths
- `@./file.md` - Import from the same directory
- `@../file.md` - Import from parent directory
- `@./components/file.md` - Import from subdirectory
### Absolute paths
- `@/absolute/path/to/file.md` - Import using absolute path
## Examples
### Basic import
```markdown
# My GEMINI.md
Welcome to my project!
@./get-started.md
## Features
@./features/overview.md
```
### Nested imports
The imported files can themselves contain imports, creating a nested structure:
```markdown
# main.md
@./header.md @./content.md @./footer.md
```
```markdown
# header.md
# Project Header
@./shared/title.md
```
## Safety features
### Circular import detection
The processor automatically detects and prevents circular imports:
```markdown
# file-a.md
@./file-b.md
```
```markdown
# file-b.md
@./file-a.md <!-- This will be detected and prevented -->
```
### File access security
The `validateImportPath` function ensures that imports are only allowed from
specified directories, preventing access to sensitive files outside the allowed
scope.
### Maximum import depth
To prevent infinite recursion, there's a configurable maximum import depth
(default: 5 levels).
## Error handling
### Missing files
If a referenced file doesn't exist, the import will fail gracefully with an
error comment in the output.
### File access errors
Permission issues or other file system errors are handled gracefully with
appropriate error messages.
## Code region detection
The import processor uses the `marked` library to detect code blocks and inline
code spans, ensuring that `@` imports inside these regions are properly ignored.
This provides robust handling of nested code blocks and complex Markdown
structures.
## Import tree structure
The processor returns an import tree that shows the hierarchy of imported files,
similar to Claude's `/memory` feature. This helps users debug problems with
their GEMINI.md files by showing which files were read and their import
relationships.
Example tree structure:
```
Memory Files
L project: GEMINI.md
L a.md
L b.md
L c.md
L d.md
L e.md
L f.md
L included.md
```
The tree preserves the order that files were imported and shows the complete
import chain for debugging purposes.
## Comparison to Claude Code's `/memory` (`claude.md`) approach
Claude Code's `/memory` feature (as seen in `claude.md`) produces a flat, linear
document by concatenating all included files, always marking file boundaries
with clear comments and path names. It does not explicitly present the import
hierarchy, but the LLM receives all file contents and paths, which is sufficient
for reconstructing the hierarchy if needed.
> [!NOTE] The import tree is mainly for clarity during development and has
> limited relevance to LLM consumption.
## API reference
### `processImports(content, basePath, debugMode?, importState?)`
Processes import statements in GEMINI.md content.
**Parameters:**
- `content` (string): The content to process for imports
- `basePath` (string): The directory path where the current file is located
- `debugMode` (boolean, optional): Whether to enable debug logging (default:
false)
- `importState` (ImportState, optional): State tracking for circular import
prevention
**Returns:** Promise&lt;ProcessImportsResult&gt; - Object containing processed
content and import tree
### `ProcessImportsResult`
```typescript
interface ProcessImportsResult {
content: string; // The processed content with imports resolved
importTree: MemoryFile; // Tree structure showing the import hierarchy
}
```
### `MemoryFile`
```typescript
interface MemoryFile {
path: string; // The file path
imports?: MemoryFile[]; // Direct imports, in the order they were imported
}
```
### `validateImportPath(importPath, basePath, allowedDirectories)`
Validates import paths to ensure they are safe and within allowed directories.
**Parameters:**
- `importPath` (string): The import path to validate
- `basePath` (string): The base directory for resolving relative paths
- `allowedDirectories` (string[]): Array of allowed directory paths
**Returns:** boolean - Whether the import path is valid
### `findProjectRoot(startDir)`
Finds the project root by searching for a `.git` directory upwards from the
given start directory. Implemented as an **async** function using non-blocking
file system APIs to avoid blocking the Node.js event loop.
**Parameters:**
- `startDir` (string): The directory to start searching from
**Returns:** Promise&lt;string&gt; - The project root directory (or the start
directory if no `.git` is found)
## Best Practices
1. **Use descriptive file names** for imported components
2. **Keep imports shallow** - avoid deeply nested import chains
3. **Document your structure** - maintain a clear hierarchy of imported files
4. **Test your imports** - ensure all referenced files exist and are accessible
5. **Use relative paths** when possible for better portability
## Troubleshooting
### Common issues
1. **Import not working**: Check that the file exists and the path is correct
2. **Circular import warnings**: Review your import structure for circular
references
3. **Permission errors**: Ensure the files are readable and within allowed
directories
4. **Path resolution issues**: Use absolute paths if relative paths aren't
resolving correctly
### Debug mode
Enable debug mode to see detailed logging of the import process:
```typescript
const result = await processImports(content, basePath, true);
```
+499
View File
@@ -0,0 +1,499 @@
# Policy engine
Gemini CLI includes a powerful policy engine that provides fine-grained control
over tool execution. It allows users and administrators to define rules that
determine whether a tool call should be allowed, denied, or require user
confirmation.
## Quick start
To create your first policy:
1. **Create the policy directory** if it doesn't exist:
**macOS/Linux**
```bash
mkdir -p ~/.gemini/policies
```
**Windows (PowerShell)**
```powershell
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.gemini\policies"
```
2. **Create a new policy file** (for example,
`~/.gemini/policies/my-rules.toml`). You can use any filename ending in
`.toml`; all such files in this directory will be loaded and combined:
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "rm -rf"
decision = "deny"
priority = 100
```
3. **Run a command** that triggers the policy (for example, ask Gemini CLI to
`rm -rf /`). The tool will now be blocked automatically.
## Core concepts
The policy engine operates on a set of rules. Each rule is a combination of
conditions and a resulting decision. When a large language model wants to
execute a tool, the policy engine evaluates all rules to find the
highest-priority rule that matches the tool call.
A rule consists of the following main components:
- **Conditions**: Criteria that a tool call must meet for the rule to apply.
This can include the tool's name, the arguments provided to it, or the current
approval mode.
- **Decision**: The action to take if the rule matches (`allow`, `deny`, or
`ask_user`).
- **Priority**: A number that determines the rule's precedence. Higher numbers
win.
For example, this rule will ask for user confirmation before executing any `git`
command.
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git"
decision = "ask_user"
priority = 100
```
### Conditions
Conditions are the criteria that a tool call must meet for a rule to apply. The
primary conditions are the tool's name and its arguments.
#### Tool Name
The `toolName` in the rule must match the name of the tool being called. For a
complete list of built-in tool names, see the
[Tools reference](/docs/reference/tools#available-tools).
- **Wildcards**: You can use wildcards to match multiple tools.
- `*`: Matches **any tool** (built-in or MCP).
- `mcp_server_*`: Matches any tool from a specific MCP server.
- `mcp_*_toolName`: Matches a specific tool name across **all** MCP servers.
- `mcp_*`: Matches **any tool from any MCP server**.
> **Recommendation:** While FQN wildcards are supported, the recommended
> approach for MCP tools is to use the `mcpName` field in your TOML rules. See
> [Special syntax for MCP tools](#special-syntax-for-mcp-tools).
#### Arguments pattern
If `argsPattern` is specified, the tool's arguments are converted to a stable
JSON string, which is then tested against the provided regular expression. If
the arguments don't match the pattern, the rule does not apply. For a list of
argument keys available for each tool, see the **Parameters** in the
[Tools reference](/docs/reference/tools#available-tools).
#### Execution environment
If `interactive` is specified, the rule will only apply if the CLI's execution
environment matches the specified boolean value:
- `true`: The rule applies only in interactive mode.
- `false`: The rule applies only in non-interactive (headless) mode.
If omitted, the rule applies to both interactive and non-interactive
environments.
### Decisions
There are three possible decisions a rule can enforce:
- `allow`: The tool call is executed automatically without user interaction.
- `deny`: The tool call is blocked and is not executed. For global rules (those
without an `argsPattern`), tools that are denied are **completely excluded
from the model's memory**. This means the model will not even see the tool as
an option, which is more secure and saves context window space.
- `ask_user`: The user is prompted to approve or deny the tool call. (In
non-interactive mode, this is treated as `deny`.)
<!-- prettier-ignore -->
> [!NOTE]
> The `deny` decision is the recommended way to exclude tools. The
> legacy `tools.exclude` setting in `settings.json` is deprecated in favor of
> policy rules with a `deny` decision.
### Priority system and tiers
> [!WARNING] The **Workspace** tier (project-level policies) is currently
> non-functional. Defining policies in a workspace's `.gemini/policies`
> directory will not have any effect. See
> [issue #18186](https://github.com/google-gemini/gemini-cli/issues/18186). Use
> User or Admin policies instead.
The policy engine uses a sophisticated priority system to resolve conflicts when
multiple rules match a single tool call. The core principle is simple: **the
rule with the highest priority wins**.
To provide a clear hierarchy, policies are organized into three tiers. Each tier
has a designated number that forms the base of the final priority calculation.
| Tier | Base | Description |
| :-------- | :--- | :-------------------------------------------------------------------------------------------- |
| Default | 1 | Built-in policies that ship with Gemini CLI. |
| Extension | 2 | Policies defined in extensions. |
| Workspace | 3 | **(Currently disabled)** Policies defined in the current workspace's configuration directory. |
| User | 4 | Custom policies defined by the user. |
| Admin | 5 | Policies managed by an administrator (for example, in an enterprise environment). |
Within a TOML policy file, you assign a priority value from **0 to 999**. The
engine transforms this into a final priority using the following formula:
`final_priority = tier_base + (toml_priority / 1000)`
This system guarantees that:
- Admin policies always override User, Workspace, and Default policies (defined
in policy TOML files).
- User policies override Workspace and Default policies.
- Workspace policies override Default policies.
- You can still order rules within a single tier with fine-grained control.
For example:
- A `priority: 50` rule in a Default policy TOML becomes `1.050`.
- A `priority: 10` rule in a Workspace policy TOML becomes `2.010`.
- A `priority: 100` rule in a User policy TOML becomes `3.100`.
- A `priority: 20` rule in an Admin policy TOML becomes `4.020`.
### Approval modes
Approval modes allow the policy engine to apply different sets of rules based on
the CLI's operational mode. A rule in a TOML policy file can be associated with
one or more modes (for example, `yolo`, `autoEdit`, `plan`). The rule will only
be active if the CLI is running in one of its specified modes. If a rule has no
modes specified, it is always active.
- `default`: The standard interactive mode where most write tools require
confirmation.
- `autoEdit`: Optimized for automated code editing; some write tools may be
auto-approved.
- `plan`: A strict, read-only mode for research and design. See
[Customizing Plan Mode Policies](../cli/plan-mode.md#customizing-policies).
- `yolo`: A mode where all tools are auto-approved (use with extreme caution).
To maintain the integrity of Plan Mode as a safe research environment,
persistent tool approvals are context-aware. When you select **"Allow for all
future sessions"**, the policy engine explicitly includes the current mode and
all more permissive modes in the hierarchy (`plan` < `default` < `autoEdit` <
`yolo`).
- **Approvals in `plan` mode**: These represent an intentional choice to trust a
tool globally. The resulting rule explicitly includes all modes (`plan`,
`default`, `autoEdit`, and `yolo`).
- **Approvals in other modes**: These only apply to the current mode and those
more permissive. For example:
- An approval granted in **`default`** mode applies to `default`, `autoEdit`,
and `yolo`.
- An approval granted in **`autoEdit`** mode applies to `autoEdit` and `yolo`.
- An approval granted in **`yolo`** mode applies only to `yolo`. This ensures
that trust flows correctly to more permissive environments while maintaining
the safety of more restricted modes like `plan`.
## Rule matching
When a tool call is made, the engine checks it against all active rules,
starting from the highest priority. The first rule that matches determines the
outcome.
A rule matches a tool call if all of its conditions are met:
1. **Tool name**: The `toolName` in the TOML rule must match the name of the
tool being called.
- **Wildcards**: You can use wildcards like `*`, `mcp_server_*`, or
`mcp_*_toolName` to match multiple tools. See [Tool Name](#tool-name) for
details.
2. **Arguments pattern**: If `argsPattern` is specified, the tool's arguments
are converted to a stable JSON string, which is then tested against the
provided regular expression. If the arguments don't match the pattern, the
rule does not apply.
## Configuration
Policies are defined in `.toml` files. The CLI loads these files from Default,
User, and (if configured) Admin directories.
### Policy locations
| Tier | Type | Location |
| :------------ | :----- | :------------------------------------------------------- |
| **User** | Custom | `~/.gemini/policies/*.toml` |
| **Workspace** | Custom | **(Disabled)** `$WORKSPACE_ROOT/.gemini/policies/*.toml` |
| **Admin** | System | _See below (OS specific)_ |
#### System-wide policies (Admin)
Administrators can enforce system-wide policies (Tier 4) that override all user
and default settings. These policies can be loaded from standard system
locations or supplemental paths.
##### Standard Locations
These are the default paths the CLI searches for admin policies:
| OS | Policy Directory Path |
| :---------- | :------------------------------------------------ |
| **Linux** | `/etc/gemini-cli/policies` |
| **macOS** | `/Library/Application Support/GeminiCli/policies` |
| **Windows** | `C:\ProgramData\gemini-cli\policies` |
##### Supplemental Admin Policies
Administrators can also specify supplemental policy paths using:
- The `--admin-policy` command-line flag.
- The `adminPolicyPaths` setting in a system settings file.
These supplemental policies are assigned the same **Admin** tier (Base 4) as
policies in standard locations.
**Security Guard**: Supplemental admin policies are **ignored** if any `.toml`
policy files are found in the standard system location. This prevents flag-based
overrides when a central system policy has already been established.
#### Security Requirements
To prevent privilege escalation, the CLI enforces strict security checks on the
**standard system policy directory**. If checks fail, the policies in that
directory are **ignored**.
- **Linux / macOS:** Must be owned by `root` (UID 0) and NOT writable by group
or others (for example, `chmod 755`).
- **Windows:** Must be in `C:\ProgramData`. Standard users (`Users`, `Everyone`)
must NOT have `Write`, `Modify`, or `Full Control` permissions. If you see a
security warning, use the folder properties to remove write permissions for
non-admin groups. You may need to "Disable inheritance" in Advanced Security
Settings.
<!-- prettier-ignore -->
> [!NOTE]
> Supplemental admin policies (provided via `--admin-policy` or
> `adminPolicyPaths` settings) are **NOT** subject to these strict ownership
> checks, as they are explicitly provided by the user or administrator in their
> current execution context.
### TOML rule schema
This section describes the fields available in a TOML policy rule.
For valid built-in `toolName` values and their argument structures (used by
`argsPattern`), see the
[Tools reference](/docs/reference/tools#available-tools).
```toml
[[rule]]
# A unique name for the tool, or an array of names.
toolName = "run_shell_command"
# (Optional) The name of a subagent. If provided, the rule only applies to tool
# calls made by this specific subagent.
subagent = "codebase_investigator"
# (Optional) The name of an MCP server. Can be combined with toolName
# to form a composite FQN internally like "mcp_mcpName_toolName".
mcpName = "my-custom-server"
# (Optional) Metadata hints provided by the tool. A rule matches if all
# key-value pairs provided here are present in the tool's annotations.
toolAnnotations = { readOnlyHint = true }
# (Optional) A regex to match against the tool's arguments.
argsPattern = '"command":"(git|npm)'
# (Optional) A string or array of strings that a shell command must start with.
# This is syntactic sugar for `toolName = "run_shell_command"` and an
# `argsPattern`.
commandPrefix = "git"
# (Optional) A regex to match against the entire shell command.
# This is also syntactic sugar for `toolName = "run_shell_command"`.
# Note: This pattern is tested against the JSON representation of the arguments
# (e.g., `{"command":"<your_command>"}`). Because it prepends `"command":"`,
# it effectively matches from the start of the command.
# Anchors like `^` or `$` apply to the full JSON string,
# so `^` should usually be avoided here.
# You cannot use commandPrefix and commandRegex in the same rule.
commandRegex = "git (commit|push)"
# The decision to take. Must be "allow", "deny", or "ask_user".
decision = "ask_user"
# The priority of the rule, from 0 to 999.
priority = 10
# (Optional) A custom message to display when a tool call is denied by this
# rule. This message is returned to the model and user,
# useful for explaining *why* it was denied.
denyMessage = "Deletion is permanent"
# (Optional) An array of approval modes where this rule is active.
# If omitted or empty, the rule applies to all modes.
modes = ["default", "autoEdit", "yolo"]
# (Optional) A boolean to restrict the rule to interactive (true) or
# non-interactive (false) environments.
# If omitted, the rule applies to both.
interactive = true
# (Optional) If true, lets shell commands use redirection operators
# (>, >>, <, <<, <<<). By default, the policy engine asks for confirmation
# when redirection is detected, even if a rule matches the command.
# This permission is granular; it only applies to the specific rule it's
# defined in. In chained commands (e.g., cmd1 > file && cmd2), each
# individual command rule must permit redirection if it's used.
allowRedirection = true
```
### Using arrays (lists)
To apply the same rule to multiple tools or command prefixes, you can provide an
array of strings for the `toolName` and `commandPrefix` fields.
**Example:**
This single rule will apply to both the `write_file` and `replace` tools.
```toml
[[rule]]
toolName = ["write_file", "replace"]
decision = "ask_user"
priority = 10
```
### Special syntax for `run_shell_command`
To simplify writing policies for `run_shell_command`, you can use
`commandPrefix` or `commandRegex` instead of the more complex `argsPattern`.
These are policy-rule shorthands, not arguments of the `run_shell_command` tool
itself. For the tool's invocation arguments, see [Shell tool](/docs/tools/shell)
and [Tools reference](/docs/reference/tools#available-tools).
- `commandPrefix`: Matches if the `command` argument starts with the given
string.
- `commandRegex`: Matches if the `command` argument matches the given regular
expression.
**Example:**
This rule will ask for user confirmation before executing any `git` command.
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git"
decision = "ask_user"
priority = 100
```
### Special syntax for MCP tools
You can create rules that target tools from Model Context Protocol (MCP) servers
using the `mcpName` field. **This is the recommended approach** for defining MCP
policies, as it is much more robust than manually writing Fully Qualified Names
(FQNs) or string wildcards.
<!-- prettier-ignore -->
> [!WARNING]
> Do not use underscores (`_`) in your MCP server names (for example, use
> `my-server` rather than `my_server`). The policy parser splits Fully Qualified
> Names (`mcp_server_tool`) on the _first_ underscore following the `mcp_`
> prefix. If your server name contains an underscore, the parser will
> misinterpret the server identity, which can cause wildcard rules and security
> policies to fail silently.
**1. Targeting a specific tool on a server**
Combine `mcpName` and `toolName` to target a single operation. When using
`mcpName`, the `toolName` field should strictly be the simple name of the tool
(for example, `search`), **not** the Fully Qualified Name (for example,
`mcp_server_search`).
```toml
# Allows the `search` tool on the `my-jira-server` MCP
[[rule]]
mcpName = "my-jira-server"
toolName = "search"
decision = "allow"
priority = 200
```
**2. Targeting all tools on a specific server**
Specify only the `mcpName` to apply a rule to every tool provided by that
server.
**Note:** This applies to all decision types (`allow`, `deny`, `ask_user`).
```toml
# Denies all tools from the `untrusted-server` MCP
[[rule]]
mcpName = "untrusted-server"
decision = "deny"
priority = 500
denyMessage = "This server is not trusted by the admin."
```
**3. Targeting all MCP servers**
Use `mcpName = "*"` to create a rule that applies to **all** tools from **any**
registered MCP server. This is useful for setting category-wide defaults.
```toml
# Ask user for any tool call from any MCP server
[[rule]]
toolName = "*"
mcpName = "*"
decision = "ask_user"
priority = 10
```
### Special syntax for subagents
You can secure and govern subagents using standard policy rules by treating the
subagent's name as the `toolName`.
When the main agent invokes a subagent (e.g., using the unified `invoke_agent`
tool), the Policy Engine automatically treats the target `agent_name` as a
virtual tool alias for rule matching.
**Example:**
This rule denies access to the `codebase_investigator` subagent.
```toml
[[rule]]
toolName = "codebase_investigator"
decision = "deny"
priority = 500
deny_message = "Deep codebase analysis is restricted for this session."
```
- **Backward Compatibility**: Any rules written targeting historical 1:1
subagent tool names will continue to match transparently.
- **Context differentiation**: To create rules based on **who** is calling a
tool, use the `subagent` field instead. See
[TOML rule schema](#toml-rule-schema).
## Default policies
Gemini CLI ships with a set of default policies to provide a safe out-of-the-box
experience.
- **Read-only tools** (like `read_file`, `glob`) are generally **allowed**.
- **Agent delegation** defaults to **`ask_user`** to ensure remote agents can
prompt for confirmation, but local sub-agent actions are executed silently and
checked individually.
- **Write tools** (like `write_file`, `run_shell_command`) default to
**`ask_user`**.
- In **`yolo`** mode, a high-priority rule allows all tools.
- In **`autoEdit`** mode, rules allow certain write operations to happen without
prompting.
+222
View File
@@ -0,0 +1,222 @@
# Tools reference
Gemini CLI uses tools to interact with your local environment, access
information, and perform actions on your behalf. These tools extend the model's
capabilities beyond text generation, letting it read files, execute commands,
and search the web.
## How to use Gemini CLI's tools
Tools are generally invoked automatically by Gemini CLI when it needs to perform
an action. However, you can also trigger specific tools manually using shorthand
syntax.
### Automatic execution and security
When the model wants to use a tool, Gemini CLI evaluates the request against its
security policies.
- **User confirmation:** You must manually approve tools that modify files or
execute shell commands (mutators). The CLI shows you a diff or the exact
command before you confirm.
- **Sandboxing:** You can run tool executions in secure, containerized
environments to isolate changes from your host system. For more details, see
the [Sandboxing](../cli/sandbox.md) guide.
- **Trusted folders:** You can configure which directories allow the model to
use system tools. For more details, see the
[Trusted folders](../cli/trusted-folders.md) guide.
Review confirmation prompts carefully before allowing a tool to execute.
### How to use manually-triggered tools
You can directly trigger key tools using special syntax in your prompt:
- **[File access](../tools/file-system.md#read_many_files) (`@`):** Use the `@`
symbol followed by a file or directory path to include its content in your
prompt. This triggers the `read_many_files` tool.
- **[Shell commands](../tools/shell.md) (`!`):** Use the `!` symbol followed by
a system command to execute it directly. This triggers the `run_shell_command`
tool.
## How to manage tools
Using built-in commands, you can inspect available tools and configure how they
behave.
### Tool discovery
Use the `/tools` command to see what tools are currently active in your session.
- **`/tools`**: Lists all registered tools with their display names.
- **`/tools desc`**: Lists all tools with their full descriptions.
This is especially useful for verifying that
[MCP servers](../tools/mcp-server.md) or custom tools are loaded correctly.
### Tool configuration
You can enable, disable, or configure specific tools in your settings. For
example, you can set a specific pager for shell commands or configure the
browser used for web searches. See the [Settings](../cli/settings.md) guide for
details.
## Available tools
The following sections list all available tools, categorized by their primary
function. For detailed parameter information, see the linked documentation for
each tool.
### Execution
| Tool | Kind | Description |
| :--------------------------------------- | :-------- | :----------------------------------------------------------------------------------------------------------------------- |
| [`run_shell_command`](../tools/shell.md) | `Execute` | Executes arbitrary shell commands. Supports interactive sessions and background processes. Requires manual confirmation. |
### File System
| Tool | Kind | Description |
| :------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------- |
| [`glob`](../tools/file-system.md) | `Search` | Finds files matching specific glob patterns across the workspace. |
| [`grep_search`](../tools/file-system.md) | `Search` | Searches for a regular expression pattern within file contents. Legacy alias: `search_file_content`. |
| [`list_directory`](../tools/file-system.md) | `Read` | Lists the names of files and subdirectories within a specified path. |
| [`read_file`](../tools/file-system.md) | `Read` | Reads the content of a specific file. Supports text, images, audio, and PDF. |
| [`read_many_files`](../tools/file-system.md) | `Read` | Reads and concatenates content from multiple files. Often triggered by the `@` symbol in your prompt. |
| [`replace`](../tools/file-system.md) | `Edit` | Performs precise text replacement within a file. Requires manual confirmation. |
| [`write_file`](../tools/file-system.md) | `Edit` | Creates or overwrites a file with new content. Requires manual confirmation. |
### Interaction
| Tool | Kind | Description |
| :--------------------------------- | :------------ | :------------------------------------------------------------------------------------- |
| [`ask_user`](../tools/ask-user.md) | `Communicate` | Requests clarification or missing information via an interactive dialog. |
| [`write_todos`](../tools/todos.md) | `Other` | Maintains an internal list of subtasks. The model uses this to track its own progress. |
### Task Tracker (Experimental)
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development. Enable via `experimental.taskTracker`.
| Tool | Kind | Description |
| :---------------------------------------------- | :------ | :-------------------------------------------------------------------------- |
| [`tracker_create_task`](../tools/tracker.md) | `Other` | Creates a new task in the experimental tracker. |
| [`tracker_update_task`](../tools/tracker.md) | `Other` | Updates an existing task's status, description, or dependencies. |
| [`tracker_get_task`](../tools/tracker.md) | `Other` | Retrieves the full details of a specific task. |
| [`tracker_list_tasks`](../tools/tracker.md) | `Other` | Lists tasks in the tracker, optionally filtered by status, type, or parent. |
| [`tracker_add_dependency`](../tools/tracker.md) | `Other` | Adds a dependency between two tasks, ensuring topological execution. |
| [`tracker_visualize`](../tools/tracker.md) | `Other` | Renders an ASCII tree visualization of the current task graph. |
### MCP
| Tool | Kind | Description |
| :------------------------------------------------ | :------- | :--------------------------------------------------------------------- |
| [`list_mcp_resources`](../tools/mcp-resources.md) | `Search` | Lists all available resources exposed by connected MCP servers. |
| [`read_mcp_resource`](../tools/mcp-resources.md) | `Read` | Reads the content of a specific Model Context Protocol (MCP) resource. |
### Memory
| Tool | Kind | Description |
| :----------------------------------------------- | :------ | :----------------------------------------------------------------------------------- |
| [`activate_skill`](../tools/activate-skill.md) | `Other` | Loads specialized procedural expertise from the `.gemini/skills` directory. |
| [`get_internal_docs`](../tools/internal-docs.md) | `Think` | Accesses Gemini CLI's own documentation for accurate answers about its capabilities. |
### Planning
| Tool | Kind | Description |
| :---------------------------------------- | :----- | :--------------------------------------------------------------------------------------- |
| [`enter_plan_mode`](../tools/planning.md) | `Plan` | Switches the CLI to a safe, read-only "Plan Mode" for researching complex changes. |
| [`exit_plan_mode`](../tools/planning.md) | `Plan` | Finalizes a plan, presents it for review, and requests approval to start implementation. |
### System
| Tool | Kind | Description |
| :-------------- | :------ | :----------------------------------------------------------------------------------------------------------------- |
| `complete_task` | `Other` | Finalizes a subagent's mission and returns the result to the parent agent. This tool is not available to the user. |
### Task Tracking
| Tool | Kind | Description |
| :----------------------- | :------ | :-------------------------------------------------------------------------- |
| `tracker_add_dependency` | `Think` | Adds a dependency between two existing tasks in the tracker. |
| `tracker_create_task` | `Think` | Creates a new task in the internal tracker to monitor progress. |
| `tracker_get_task` | `Think` | Retrieves the details and current status of a specific tracked task. |
| `tracker_list_tasks` | `Think` | Lists all tasks currently being tracked. |
| `tracker_update_task` | `Think` | Updates the status or details of an existing task. |
| `tracker_visualize` | `Think` | Generates a visual representation of the current task dependency graph. |
| `update_topic` | `Think` | Updates the current topic and status to keep the user informed of progress. |
### Web
| Tool | Kind | Description |
| :-------------------------------------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`google_web_search`](../tools/web-search.md) | `Search` | Performs a Google Search to find up-to-date information. |
| [`web_fetch`](../tools/web-fetch.md) | `Fetch` | Retrieves and processes content from specific URLs. **Warning:** This tool can access local and private network addresses (for example, localhost), which may pose a security risk if used with untrusted prompts. In Plan Mode, this tool requires explicit user confirmation. |
### Tool argument keys
When writing [`argsPattern`](./policy-engine.md#arguments-pattern) rules for the
[policy engine](./policy-engine.md), you need to know the JSON argument keys for
each tool. The following table lists the keys that appear in the JSON
representation of each tool's arguments.
| Tool | JSON argument keys |
| :----------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `run_shell_command` | `command`, `description`, `dir_path`, `is_background` |
| `glob` | `pattern`, `dir_path`, `case_sensitive`, `respect_git_ignore`, `respect_gemini_ignore` |
| `grep_search` | `pattern`, `dir_path`, `include_pattern`, `exclude_pattern`, `names_only`, `case_sensitive`, `fixed_strings`, `context`, `after`, `before`, `no_ignore`, `max_matches_per_file`, `total_max_matches` |
| `list_directory` | `dir_path`, `ignore`, `file_filtering_options` |
| `read_file` | `file_path`, `start_line`, `end_line` |
| `read_many_files` | `include`, `exclude`, `recursive`, `useDefaultExcludes` |
| `write_file` | `file_path`, `content` |
| `replace` | `file_path`, `old_string`, `new_string`, `instruction`, `allow_multiple` |
| `ask_user` | `questions` (array of `question`, `header`, `type`, `options`) |
| `write_todos` | `todos` (array of `description`, `status`) |
| `activate_skill` | `name` |
| `get_internal_docs` | `path` |
| `enter_plan_mode` | `reason` |
| `exit_plan_mode` | `plan_path` |
| `tracker_create_task` | `title`, `description`, `type` |
| `tracker_update_task` | `id`, `title`, `description`, `status`, `dependencies` |
| `tracker_get_task` | `id` |
| `tracker_list_tasks` | `status`, `type`, `parentId` |
| `tracker_add_dependency` | `taskId`, `dependencyId` |
| `tracker_visualize` | _(none)_ |
| `update_topic` | `title`, `summary`, `strategic_intent` |
| `google_web_search` | `query` |
| `web_fetch` | `prompt` |
For example, to write a policy rule that blocks any `write_file` call targeting
a `.env` file, you would match against the `file_path` key:
```toml
[[rule]]
toolName = "write_file"
argsPattern = '"file_path":".*\.env"'
decision = "deny"
priority = 100
denyMessage = "Writing to .env files is not allowed."
```
For full argument descriptions and types, see the individual tool pages linked
in the [tables above](#available-tools).
## Under the hood
For developers, the tool system is designed to be extensible and robust. The
`ToolRegistry` class manages all available tools.
You can extend Gemini CLI with custom tools by configuring
`tools.discoveryCommand` in your settings or by connecting to MCP servers.
<!-- prettier-ignore -->
> [!NOTE]
> For a deep dive into the internal Tool API and how to implement your
> own tools in the codebase, see the `packages/core/src/tools/` directory in
> GitHub.
## Next steps
- Learn how to [Set up an MCP server](../tools/mcp-server.md).
- Explore [Agent Skills](../cli/skills.md) for specialized expertise.
- See the [Command reference](./commands.md) for slash commands.