cleanup(markdown): Prettier format all markdown @ 80 char width (#10714)

This commit is contained in:
Richie Foreman
2025-10-09 08:17:37 -04:00
committed by GitHub
parent 0cd490a9b8
commit a08938010c
60 changed files with 4796 additions and 1733 deletions
+42 -15
View File
@@ -1,30 +1,49 @@
# Checkpointing
The Gemini CLI includes a Checkpointing feature that automatically saves a snapshot of your project's state before any file modifications are made by AI-powered tools. This allows you to safely experiment with and apply code changes, knowing you can instantly revert back to the state before the tool was run.
The Gemini CLI includes a Checkpointing feature that automatically saves a
snapshot of your project's state before any file modifications are made by
AI-powered tools. This allows you to safely experiment with and apply code
changes, knowing you can instantly revert back to the state before the tool was
run.
## How It Works
When you approve a tool that modifies the file system (like `write_file` or `replace`), the CLI automatically creates a "checkpoint." This checkpoint includes:
When you approve a tool that modifies the file system (like `write_file` or
`replace`), the CLI automatically creates a "checkpoint." This checkpoint
includes:
1. **A Git Snapshot:** A commit is made in a special, shadow Git repository located in your home directory (`~/.gemini/history/<project_hash>`). This snapshot captures the complete state of your project files at that moment. It does **not** interfere with your own project's Git repository.
2. **Conversation History:** The entire conversation you've had with the agent up to that point is saved.
3. **The Tool Call:** The specific tool call that was about to be executed is also stored.
1. **A Git Snapshot:** A commit is made in a special, shadow Git repository
located in your home directory (`~/.gemini/history/<project_hash>`). This
snapshot captures the complete state of your project files at that moment.
It does **not** interfere with your own project's Git repository.
2. **Conversation History:** The entire conversation you've had with the agent
up to that point is saved.
3. **The Tool Call:** The specific tool call that was about to be executed is
also stored.
If you want to undo the change or simply go back, you can use the `/restore` command. Restoring a checkpoint will:
If you want to undo the change or simply go back, you can use the `/restore`
command. Restoring a checkpoint will:
- Revert all files in your project to the state captured in the snapshot.
- Restore the conversation history in the CLI.
- Re-propose the original tool call, allowing you to run it again, modify it, or simply ignore it.
- Re-propose the original tool call, allowing you to run it again, modify it, or
simply ignore it.
All checkpoint data, including the Git snapshot and conversation history, is stored locally on your machine. The Git snapshot is stored in the shadow repository while the conversation history and tool calls are saved in a JSON file in your project's temporary directory, typically located at `~/.gemini/tmp/<project_hash>/checkpoints`.
All checkpoint data, including the Git snapshot and conversation history, is
stored locally on your machine. The Git snapshot is stored in the shadow
repository while the conversation history and tool calls are saved in a JSON
file in your project's temporary directory, typically located at
`~/.gemini/tmp/<project_hash>/checkpoints`.
## Enabling the Feature
The Checkpointing feature is disabled by default. To enable it, you can either use a command-line flag or edit your `settings.json` file.
The Checkpointing feature is disabled by default. To enable it, you can either
use a command-line flag or edit your `settings.json` file.
### Using the Command-Line Flag
You can enable checkpointing for the current session by using the `--checkpointing` flag when starting the Gemini CLI:
You can enable checkpointing for the current session by using the
`--checkpointing` flag when starting the Gemini CLI:
```bash
gemini --checkpointing
@@ -32,7 +51,8 @@ gemini --checkpointing
### Using the `settings.json` File
To enable checkpointing by default for all sessions, you need to edit your `settings.json` file.
To enable checkpointing by default for all sessions, you need to edit your
`settings.json` file.
Add the following key to your `settings.json`:
@@ -48,7 +68,8 @@ Add the following key to your `settings.json`:
## Using the `/restore` Command
Once enabled, checkpoints are created automatically. To manage them, you use the `/restore` command.
Once enabled, checkpoints are created automatically. To manage them, you use the
`/restore` command.
### List Available Checkpoints
@@ -58,11 +79,15 @@ To see a list of all saved checkpoints for the current project, simply run:
/restore
```
The CLI will display a list of available checkpoint files. These file names are typically composed of a timestamp, the name of the file being modified, and the name of the tool that was about to be run (e.g., `2025-06-22T10-00-00_000Z-my-file.txt-write_file`).
The CLI will display a list of available checkpoint files. These file names are
typically composed of a timestamp, the name of the file being modified, and the
name of the tool that was about to be run (e.g.,
`2025-06-22T10-00-00_000Z-my-file.txt-write_file`).
### Restore a Specific Checkpoint
To restore your project to a specific checkpoint, use the checkpoint file from the list:
To restore your project to a specific checkpoint, use the checkpoint file from
the list:
```
/restore <checkpoint_file>
@@ -74,4 +99,6 @@ For example:
/restore 2025-06-22T10-00-00_000Z-my-file.txt-write_file
```
After running the command, your files and conversation will be immediately restored to the state they were in when the checkpoint was created, and the original tool prompt will reappear.
After running the command, your files and conversation will be immediately
restored to the state they were in when the checkpoint was created, and the
original tool prompt will reappear.
+181 -69
View File
@@ -1,6 +1,8 @@
# 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 (`!`).
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 (`/`)
@@ -9,19 +11,31 @@ Slash commands provide meta-level control over the CLI itself.
### Built-in Commands
- **`/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.
- **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:** Save and resume conversation history for branching conversation state interactively, or resuming a previous state from a later session.
- **Description:** Save and resume conversation history for branching
conversation state interactively, or resuming a previous state from a later
session.
- **Sub-commands:**
- **`save`**
- **Description:** Saves the current conversation history. You must add a `<tag>` for identifying the conversation state.
- **Description:** Saves the current conversation history. You must add a
`<tag>` for identifying the conversation state.
- **Usage:** `/chat save <tag>`
- **Details on Checkpoint Location:** The default locations for saved chat checkpoints are:
- **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>\`
- When you run `/chat list`, the CLI only scans these specific directories to find available checkpoints.
- **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).
- When you run `/chat list`, the CLI only scans these specific
directories to find available checkpoints.
- **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).
- **`resume`**
- **Description:** Resumes a conversation from a previous save.
- **Usage:** `/chat resume <tag>`
@@ -31,164 +45,255 @@ Slash commands provide meta-level control over the CLI itself.
- **Description:** Deletes a saved conversation checkpoint.
- **Usage:** `/chat delete <tag>`
- **`share`**
- **Description** Writes the current conversation to a provided Markdown or JSON file.
- **Usage** `/chat share file.md` or `/chat share file.json`. If no filename is provided, then the CLI will generate one.
- **Description** Writes the current conversation to a provided Markdown
or JSON file.
- **Usage** `/chat share file.md` or `/chat share file.json`. If no
filename is provided, then the CLI will generate one.
- **`/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.
- **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.
- **`/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.
- **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.
- **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.
- **Description:** Copies the last output produced by Gemini CLI to your
clipboard, for easy sharing or reuse.
- **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.
- **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.
- **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`.
- **Description:** Display all directories added by `/directory add` and
`--include-directories`.
- **Usage:** `/directory show`
- **`/editor`**
- **Description:** Open a dialog for selecting supported editors.
- **`/extensions`**
- **Description:** Lists all active extensions in the current Gemini CLI session. See [Gemini CLI Extensions](../extensions/index.md).
- **Description:** Lists all active extensions in the current Gemini CLI
session. See [Gemini CLI Extensions](../extensions/index.md).
- **`/help`** (or **`/?`**)
- **Description:** Display help information about Gemini CLI, including available commands and their usage.
- **Description:** Display help information about Gemini CLI, including
available commands and their usage.
- **`/mcp`**
- **Description:** List configured Model Context Protocol (MCP) servers, their connection status, server details, and available tools.
- **Description:** List configured Model Context Protocol (MCP) servers, their
connection status, server details, and available tools.
- **Sub-commands:**
- **`desc`** or **`descriptions`**:
- **Description:** Show detailed descriptions for MCP servers and tools.
- **`nodesc`** or **`nodescriptions`**:
- **Description:** Hide tool descriptions, showing only the tool names.
- **`schema`**:
- **Description:** Show the full JSON schema for the tool's configured parameters.
- **Keyboard Shortcut:** Press **Ctrl+T** at any time to toggle between showing and hiding tool descriptions.
- **Description:** Show the full JSON schema for the tool's configured
parameters.
- **Keyboard Shortcut:** Press **Ctrl+T** at any time to toggle between
showing and hiding tool descriptions.
- **`/memory`**
- **Description:** Manage the AI's instructional context (hierarchical memory loaded from `GEMINI.md` files).
- **Description:** Manage the AI's instructional context (hierarchical memory
loaded from `GEMINI.md` files).
- **Sub-commands:**
- **`add`**:
- **Description:** Adds the following text to the AI's memory. Usage: `/memory add <text to remember>`
- **Description:** Adds the following text to the AI's memory. Usage:
`/memory add <text to remember>`
- **`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.
- **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.
- **`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.
- **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.
- **`list`**:
- **Description:** Lists the paths of the GEMINI.md files in use for hierarchical memory.
- **Note:** For more details on how `GEMINI.md` files contribute to hierarchical memory, see the [CLI Configuration documentation](../get-started/configuration.md).
- **Description:** Lists the paths of the GEMINI.md files in use for
hierarchical memory.
- **Note:** For more details on how `GEMINI.md` files contribute to
hierarchical memory, see the
[CLI Configuration documentation](../get-started/configuration.md).
- **`/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.
- **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 the CLI is invoked with the `--checkpointing` option or configured via [settings](../get-started/configuration.md). See [Checkpointing documentation](../cli/checkpointing.md) for more details.
- **Note:** Only available if the CLI is invoked with the `--checkpointing`
option or configured via [settings](../get-started/configuration.md). See
[Checkpointing documentation](../cli/checkpointing.md) for more details.
- **`/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.
- **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.
- **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.
- **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.
- **`/stats`**
- **Description:** Display detailed statistics for the current Gemini CLI session, including token usage, cached token savings (when available), and session duration. Note: Cached token information is only displayed when cached tokens are being used, which occurs with API key authentication but not with OAuth authentication at this time.
- **Description:** Display detailed statistics for the current Gemini CLI
session, including token usage, cached token savings (when available), and
session duration. Note: Cached token information is only displayed when
cached tokens are being used, which occurs with API key authentication but
not with OAuth authentication at this time.
- [**`/theme`**](./themes.md)
- **Description:** Open a dialog that lets you change the visual theme of Gemini CLI.
- **Description:** Open a dialog that lets you change the visual theme of
Gemini CLI.
- **`/auth`**
- **Description:** Open a dialog that lets you change the authentication method.
- **Description:** Open a dialog that lets you change the authentication
method.
- **`/about`**
- **Description:** Show version info. Please share this information when filing issues.
- **Description:** Show version info. Please share this information when
filing issues.
- [**`/tools`**](../tools/index.md)
- **Description:** Display a list of tools that are currently available within Gemini CLI.
- **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.
- **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.
- **`/privacy`**
- **Description:** Display the Privacy Notice and allow users to select whether they consent to the collection of their data for service improvement purposes.
- **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.
- **`/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.
- **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:**
- **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)
- **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)
- **INSERT mode:** Standard text input with escape to return to NORMAL mode
- **Editing commands:** Delete with `x`, change with `c`, insert with `i`, `a`, `o`, `O`; complex operations like `dd`, `cc`, `dw`, `cw`
- **Editing commands:** Delete with `x`, change with `c`, insert with `i`,
`a`, `o`, `O`; complex operations like `dd`, `cc`, `dw`, `cw`
- **Count support:** Prefix commands with numbers (e.g., `3h`, `5w`, `10G`)
- **Repeat last command:** Use `.` to repeat the last editing operation
- **Persistent setting:** Vim mode preference is saved to `~/.gemini/settings.json` and restored between sessions
- **Status indicator:** When enabled, shows `[NORMAL]` or `[INSERT]` in the footer
- **Persistent setting:** Vim mode preference is saved to
`~/.gemini/settings.json` and restored between sessions
- **Status indicator:** When enabled, shows `[NORMAL]` or `[INSERT]` in the
footer
- **`/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.
- **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.
### 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, please see the dedicated [Custom Commands documentation](./custom-commands.md).
Custom commands allow you to create personalized shortcuts for your most-used
prompts. For detailed instructions on how to create, manage, and use them,
please see the dedicated [Custom Commands documentation](./custom-commands.md).
## Input Prompt Shortcuts
These shortcuts apply directly to the input prompt for text manipulation.
- **Undo:**
- **Keyboard shortcut:** Press **Ctrl+z** to undo the last action in the input prompt.
- **Keyboard shortcut:** Press **Ctrl+z** to undo the last action in the input
prompt.
- **Redo:**
- **Keyboard shortcut:** Press **Ctrl+Shift+Z** to redo the last undone action in the input prompt.
- **Keyboard shortcut:** Press **Ctrl+Shift+Z** 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.
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.
- **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 (e.g., `@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.
- 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 (e.g.,
`@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.
- **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 (e.g., permission issues), this will also be reported.
- 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 (e.g., permission issues),
this will also be reported.
## Shell mode & passthrough commands (`!`)
The `!` prefix lets you interact with your system's shell directly from within Gemini CLI.
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 `cmd.exe` on Windows. Any output or errors from the command are displayed in the terminal.
- **Description:** Execute the given `<shell_command>` using `bash` on
Linux/macOS or `cmd.exe` on Windows. 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)
@@ -196,11 +301,18 @@ The `!` prefix lets you interact with your system's shell directly from within G
- **`!` (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.
- 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.
- 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.
- **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 the Gemini CLI.
- **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 the Gemini CLI.
+115 -40
View File
@@ -1,48 +1,69 @@
# Custom Commands
Custom commands let you save and reuse your favorite or most frequently used prompts as personal shortcuts within Gemini CLI. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
Custom commands let you save and reuse your favorite or most frequently used
prompts as personal shortcuts within Gemini CLI. You can create commands that
are specific to a single project or commands that are available globally across
all your projects, streamlining your workflow and ensuring consistency.
## File locations and precedence
Gemini CLI discovers commands from two locations, loaded in a specific order:
1. **User Commands (Global):** Located in `~/.gemini/commands/`. These commands are available in any project you are working on.
2. **Project Commands (Local):** Located in `<your-project-root>/.gemini/commands/`. These commands are specific to the current project and can be checked into version control to be shared with your team.
1. **User Commands (Global):** Located in `~/.gemini/commands/`. These commands
are available in any project you are working on.
2. **Project Commands (Local):** Located in
`<your-project-root>/.gemini/commands/`. These commands are specific to the
current project and can be checked into version control to be shared with
your team.
If a command in the project directory has the same name as a command in the user directory, the **project command will always be used.** This allows projects to override global commands with project-specific versions.
If a command in the project directory has the same name as a command in the user
directory, the **project command will always be used.** This allows projects to
override global commands with project-specific versions.
## Naming and namespacing
The name of a command is determined by its file path relative to its `commands` directory. Subdirectories are used to create namespaced commands, with the path separator (`/` or `\`) being converted to a colon (`:`).
The name of a command is determined by its file path relative to its `commands`
directory. Subdirectories are used to create namespaced commands, with the path
separator (`/` or `\`) being converted to a colon (`:`).
- A file at `~/.gemini/commands/test.toml` becomes the command `/test`.
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced command `/git:commit`.
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced
command `/git:commit`.
## TOML File Format (v1)
Your command definition files must be written in the TOML format and use the `.toml` file extension.
Your command definition files must be written in the TOML format and use the
`.toml` file extension.
### Required fields
- `prompt` (String): The prompt that will be sent to the Gemini model when the command is executed. This can be a single-line or multi-line string.
- `prompt` (String): The prompt that will be sent to the Gemini model when the
command is executed. This can be a single-line or multi-line string.
### Optional fields
- `description` (String): A brief, one-line description of what the command does. This text will be displayed next to your command in the `/help` menu. **If you omit this field, a generic description will be generated from the filename.**
- `description` (String): A brief, one-line description of what the command
does. This text will be displayed next to your command in the `/help` menu.
**If you omit this field, a generic description will be generated from the
filename.**
## Handling arguments
Custom commands support two powerful methods for handling arguments. The CLI automatically chooses the correct method based on the content of your command\'s `prompt`.
Custom commands support two powerful methods for handling arguments. The CLI
automatically chooses the correct method based on the content of your command\'s
`prompt`.
### 1. Context-aware injection with `{{args}}`
If your `prompt` contains the special placeholder `{{args}}`, the CLI will replace that placeholder with the text the user typed after the command name.
If your `prompt` contains the special placeholder `{{args}}`, the CLI will
replace that placeholder with the text the user typed after the command name.
The behavior of this injection depends on where it is used:
**A. Raw injection (outside Shell commands)**
When used in the main body of the prompt, the arguments are injected exactly as the user typed them.
When used in the main body of the prompt, the arguments are injected exactly as
the user typed them.
**Example (`git/fix.toml`):**
@@ -53,11 +74,16 @@ description = "Generates a fix for a given issue."
prompt = "Please provide a code fix for the issue described here: {{args}}."
```
The model receives: `Please provide a code fix for the issue described here: "Button is misaligned".`
The model receives:
`Please provide a code fix for the issue described here: "Button is misaligned".`
**B. Using arguments in Shell commands (inside `!{...}` blocks)**
When you use `{{args}}` inside a shell injection block (`!{...}`), the arguments are automatically **shell-escaped** before replacement. This allows you to safely pass arguments to shell commands, ensuring the resulting command is syntactically correct and secure while preventing command injection vulnerabilities.
When you use `{{args}}` inside a shell injection block (`!{...}`), the arguments
are automatically **shell-escaped** before replacement. This allows you to
safely pass arguments to shell commands, ensuring the resulting command is
syntactically correct and secure while preventing command injection
vulnerabilities.
**Example (`/grep-code.toml`):**
@@ -74,22 +100,30 @@ When you run `/grep-code It\'s complicated`:
1. The CLI sees `{{args}}` used both outside and inside `!{...}`.
2. Outside: The first `{{args}}` is replaced raw with `It\'s complicated`.
3. Inside: The second `{{args}}` is replaced with the escaped version (e.g., on Linux: `"It\'s complicated"`).
3. Inside: The second `{{args}}` is replaced with the escaped version (e.g., on
Linux: `"It\'s complicated"`).
4. The command executed is `grep -r "It\'s complicated" .`.
5. The CLI prompts you to confirm this exact, secure command before execution.
6. The final prompt is sent.
### 2. Default argument handling
If your `prompt` does **not** contain the special placeholder `{{args}}`, the CLI uses a default behavior for handling arguments.
If your `prompt` does **not** contain the special placeholder `{{args}}`, the
CLI uses a default behavior for handling arguments.
If you provide arguments to the command (e.g., `/mycommand arg1`), the CLI will append the full command you typed to the end of the prompt, separated by two newlines. This allows the model to see both the original instructions and the specific arguments you just provided.
If you provide arguments to the command (e.g., `/mycommand arg1`), the CLI will
append the full command you typed to the end of the prompt, separated by two
newlines. This allows the model to see both the original instructions and the
specific arguments you just provided.
If you do **not** provide any arguments (e.g., `/mycommand`), the prompt is sent to the model exactly as it is, with nothing appended.
If you do **not** provide any arguments (e.g., `/mycommand`), the prompt is sent
to the model exactly as it is, with nothing appended.
**Example (`changelog.toml`):**
This example shows how to create a robust command by defining a role for the model, explaining where to find the user's input, and specifying the expected format and behavior.
This example shows how to create a robust command by defining a role for the
model, explaining where to find the user's input, and specifying the expected
format and behavior.
```toml
# In: <project>/.gemini/commands/changelog.toml
@@ -118,25 +152,45 @@ The command follows this format: `/changelog <version> <type> <message>`
"""
```
When you run `/changelog 1.2.0 added "New feature"`, the final text sent to the model will be the original prompt followed by two newlines and the command you typed.
When you run `/changelog 1.2.0 added "New feature"`, the final text sent to the
model will be the original prompt followed by two newlines and the command you
typed.
### 3. Executing Shell commands with `!{...}`
You can make your commands dynamic by executing shell commands directly within your `prompt` and injecting their output. This is ideal for gathering context from your local environment, like reading file content or checking the status of Git.
You can make your commands dynamic by executing shell commands directly within
your `prompt` and injecting their output. This is ideal for gathering context
from your local environment, like reading file content or checking the status of
Git.
When a custom command attempts to execute a shell command, Gemini CLI will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
When a custom command attempts to execute a shell command, Gemini CLI will now
prompt you for confirmation before proceeding. This is a security measure to
ensure that only intended commands can be run.
**How it works:**
1. **Inject commands:** Use the `!{...}` syntax.
2. **Argument substitution:** If `{{args}}` is present inside the block, it is automatically shell-escaped (see [Context-Aware Injection](#1-context-aware-injection-with-args) above).
3. **Robust parsing:** The parser correctly handles complex shell commands that include nested braces, such as JSON payloads. **Note:** The content inside `!{...}` must have balanced braces (`{` and `}`). If you need to execute a command containing unbalanced braces, consider wrapping it in an external script file and calling the script within the `!{...}` block.
4. **Security check and confirmation:** The CLI performs a security check on the final, resolved command (after arguments are escaped and substituted). A dialog will appear showing the exact command(s) to be executed.
5. **Execution and error reporting:** The command is executed. If the command fails, the output injected into the prompt will include the error messages (stderr) followed by a status line, e.g., `[Shell command exited with code 1]`. This helps the model understand the context of the failure.
2. **Argument substitution:** If `{{args}}` is present inside the block, it is
automatically shell-escaped (see
[Context-Aware Injection](#1-context-aware-injection-with-args) above).
3. **Robust parsing:** The parser correctly handles complex shell commands that
include nested braces, such as JSON payloads. **Note:** The content inside
`!{...}` must have balanced braces (`{` and `}`). If you need to execute a
command containing unbalanced braces, consider wrapping it in an external
script file and calling the script within the `!{...}` block.
4. **Security check and confirmation:** The CLI performs a security check on
the final, resolved command (after arguments are escaped and substituted). A
dialog will appear showing the exact command(s) to be executed.
5. **Execution and error reporting:** The command is executed. If the command
fails, the output injected into the prompt will include the error messages
(stderr) followed by a status line, e.g.,
`[Shell command exited with code 1]`. This helps the model understand the
context of the failure.
**Example (`git/commit.toml`):**
This command gets the staged git diff and uses it to ask the model to write a commit message.
This command gets the staged git diff and uses it to ask the model to write a
commit message.
````toml
# In: <project>/.gemini/commands/git/commit.toml
@@ -156,24 +210,39 @@ Please generate a Conventional Commit message based on the following git diff:
````
When you run `/git:commit`, the CLI first executes `git diff --staged`, then replaces `!{git diff --staged}` with the output of that command before sending the final, complete prompt to the model.
When you run `/git:commit`, the CLI first executes `git diff --staged`, then
replaces `!{git diff --staged}` with the output of that command before sending
the final, complete prompt to the model.
### 4. Injecting file content with `@{...}`
You can directly embed the content of a file or a directory listing into your prompt using the `@{...}` syntax. This is useful for creating commands that operate on specific files.
You can directly embed the content of a file or a directory listing into your
prompt using the `@{...}` syntax. This is useful for creating commands that
operate on specific files.
**How it works:**
- **File injection**: `@{path/to/file.txt}` is replaced by the content of `file.txt`.
- **Multimodal support**: If the path points to a supported image (e.g., PNG, JPEG), PDF, audio, or video file, it will be correctly encoded and injected as multimodal input. Other binary files are handled gracefully and skipped.
- **Directory listing**: `@{path/to/dir}` is traversed and each file present within the directory and all subdirectories is inserted into the prompt. This respects `.gitignore` and `.geminiignore` if enabled.
- **Workspace-aware**: The command searches for the path in the current directory and any other workspace directories. Absolute paths are allowed if they are within the workspace.
- **Processing order**: File content injection with `@{...}` is processed _before_ shell commands (`!{...}`) and argument substitution (`{{args}}`).
- **Parsing**: The parser requires the content inside `@{...}` (the path) to have balanced braces (`{` and `}`).
- **File injection**: `@{path/to/file.txt}` is replaced by the content of
`file.txt`.
- **Multimodal support**: If the path points to a supported image (e.g., PNG,
JPEG), PDF, audio, or video file, it will be correctly encoded and injected as
multimodal input. Other binary files are handled gracefully and skipped.
- **Directory listing**: `@{path/to/dir}` is traversed and each file present
within the directory and all subdirectories is inserted into the prompt. This
respects `.gitignore` and `.geminiignore` if enabled.
- **Workspace-aware**: The command searches for the path in the current
directory and any other workspace directories. Absolute paths are allowed if
they are within the workspace.
- **Processing order**: File content injection with `@{...}` is processed
_before_ shell commands (`!{...}`) and argument substitution (`{{args}}`).
- **Parsing**: The parser requires the content inside `@{...}` (the path) to
have balanced braces (`{` and `}`).
**Example (`review.toml`):**
This command injects the content of a _fixed_ best practices file (`docs/best-practices.md`) and uses the user\'s arguments to provide context for the review.
This command injects the content of a _fixed_ best practices file
(`docs/best-practices.md`) and uses the user\'s arguments to provide context for
the review.
```toml
# In: <project>/.gemini/commands/review.toml
@@ -191,7 +260,9 @@ Use the following best practices when providing your review:
"""
```
When you run `/review FileCommandLoader.ts`, the `@{docs/best-practices.md}` placeholder is replaced by the content of that file, and `{{args}}` is replaced by the text you provided, before the final prompt is sent to the model.
When you run `/review FileCommandLoader.ts`, the `@{docs/best-practices.md}`
placeholder is replaced by the content of that file, and `{{args}}` is replaced
by the text you provided, before the final prompt is sent to the model.
---
@@ -201,7 +272,8 @@ Let's create a global command that asks the model to refactor a piece of code.
**1. Create the file and directories:**
First, ensure the user commands directory exists, then create a `refactor` subdirectory for organization and the final TOML file.
First, ensure the user commands directory exists, then create a `refactor`
subdirectory for organization and the final TOML file.
```bash
mkdir -p ~/.gemini/commands/refactor
@@ -210,7 +282,9 @@ touch ~/.gemini/commands/refactor/pure.toml
**2. Add the content to the file:**
Open `~/.gemini/commands/refactor/pure.toml` in your editor and add the following content. We are including the optional `description` for best practice.
Open `~/.gemini/commands/refactor/pure.toml` in your editor and add the
following content. We are including the optional `description` for best
practice.
```toml
# In: ~/.gemini/commands/refactor/pure.toml
@@ -230,7 +304,8 @@ Your response should include:
**3. Run the Command:**
That's it! You can now run your command in the CLI. First, you might add a file to the context, and then invoke your command:
That's it! You can now run your command in the CLI. First, you might add a file
to the context, and then invoke your command:
```
> @my-messy-function.js
+131 -44
View File
@@ -1,21 +1,37 @@
# Gemini CLI for the Enterprise
This document outlines configuration patterns and best practices for deploying and managing Gemini CLI in an enterprise environment. By leveraging system-level settings, administrators can enforce security policies, manage tool access, and ensure a consistent experience for all users.
This document outlines configuration patterns and best practices for deploying
and managing Gemini CLI in an enterprise environment. By leveraging system-level
settings, administrators can enforce security policies, manage tool access, and
ensure a consistent experience for all users.
> **A Note on Security:** The patterns described in this document are intended to help administrators create a more controlled and secure environment for using Gemini CLI. However, they should not be considered a foolproof security boundary. A determined user with sufficient privileges on their local machine may still be able to circumvent these configurations. These measures are designed to prevent accidental misuse and enforce corporate policy in a managed environment, not to defend against a malicious actor with local administrative rights.
> **A Note on Security:** The patterns described in this document are intended
> to help administrators create a more controlled and secure environment for
> using Gemini CLI. However, they should not be considered a foolproof security
> boundary. A determined user with sufficient privileges on their local machine
> may still be able to circumvent these configurations. These measures are
> designed to prevent accidental misuse and enforce corporate policy in a
> managed environment, not to defend against a malicious actor with local
> administrative rights.
## Centralized Configuration: The System Settings File
The most powerful tools for enterprise administration are the system-wide settings files. These files allow you to define a baseline configuration (`system-defaults.json`) and a set of overrides (`settings.json`) that apply to all users on a machine. For a complete overview of configuration options, see the [Configuration documentation](../get-started/configuration.md).
The most powerful tools for enterprise administration are the system-wide
settings files. These files allow you to define a baseline configuration
(`system-defaults.json`) and a set of overrides (`settings.json`) that apply to
all users on a machine. For a complete overview of configuration options, see
the [Configuration documentation](../get-started/configuration.md).
Settings are merged from four files. The precedence order for single-value settings (like `theme`) is:
Settings are merged from four files. The precedence order for single-value
settings (like `theme`) is:
1. System Defaults (`system-defaults.json`)
2. User Settings (`~/.gemini/settings.json`)
3. Workspace Settings (`<project>/.gemini/settings.json`)
4. System Overrides (`settings.json`)
This means the System Overrides file has the final say. For settings that are arrays (`includeDirectories`) or objects (`mcpServers`), the values are merged.
This means the System Overrides file has the final say. For settings that are
arrays (`includeDirectories`) or objects (`mcpServers`), the values are merged.
**Example of Merging and Precedence:**
@@ -122,26 +138,39 @@ This results in the following merged configuration:
**Why:**
- **`theme`**: The value from the system overrides (`system-enforced-theme`) is used, as it has the highest precedence.
- **`mcpServers`**: The objects are merged. The `corp-server` definition from the system overrides takes precedence over the user's definition. The unique `user-tool` and `project-tool` are included.
- **`includeDirectories`**: The arrays are concatenated in the order of System Defaults, User, Workspace, and then System Overrides.
- **`theme`**: The value from the system overrides (`system-enforced-theme`) is
used, as it has the highest precedence.
- **`mcpServers`**: The objects are merged. The `corp-server` definition from
the system overrides takes precedence over the user's definition. The unique
`user-tool` and `project-tool` are included.
- **`includeDirectories`**: The arrays are concatenated in the order of System
Defaults, User, Workspace, and then System Overrides.
- **Location**:
- **Linux**: `/etc/gemini-cli/settings.json`
- **Windows**: `C:\ProgramData\gemini-cli\settings.json`
- **macOS**: `/Library/Application Support/GeminiCli/settings.json`
- The path can be overridden using the `GEMINI_CLI_SYSTEM_SETTINGS_PATH` environment variable.
- **Control**: This file should be managed by system administrators and protected with appropriate file permissions to prevent unauthorized modification by users.
- The path can be overridden using the `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
environment variable.
- **Control**: This file should be managed by system administrators and
protected with appropriate file permissions to prevent unauthorized
modification by users.
By using the system settings file, you can enforce the security and configuration patterns described below.
By using the system settings file, you can enforce the security and
configuration patterns described below.
## Restricting Tool Access
You can significantly enhance security by controlling which tools the Gemini model can use. This is achieved through the `tools.core` and `tools.exclude` settings. For a list of available tools, see the [Tools documentation](../tools/index.md).
You can significantly enhance security by controlling which tools the Gemini
model can use. This is achieved through the `tools.core` and `tools.exclude`
settings. For a list of available tools, see the
[Tools documentation](../tools/index.md).
### Allowlisting with `coreTools`
The most secure approach is to explicitly add the tools and commands that users are permitted to execute to an allowlist. This prevents the use of any tool not on the approved list.
The most secure approach is to explicitly add the tools and commands that users
are permitted to execute to an allowlist. This prevents the use of any tool not
on the approved list.
**Example:** Allow only safe, read-only file operations and listing files.
@@ -155,7 +184,8 @@ The most secure approach is to explicitly add the tools and commands that users
### Blocklisting with `excludeTools`
Alternatively, you can add specific tools that are considered dangerous in your environment to a blocklist.
Alternatively, you can add specific tools that are considered dangerous in your
environment to a blocklist.
**Example:** Prevent the use of the shell tool for removing files.
@@ -167,32 +197,54 @@ Alternatively, you can add specific tools that are considered dangerous in your
}
```
**Security Note:** Blocklisting with `excludeTools` is less secure than allowlisting with `coreTools`, as it relies on blocking known-bad commands, and clever users may find ways to bypass simple string-based blocks. **Allowlisting is the recommended approach.**
**Security Note:** Blocklisting with `excludeTools` is less secure than
allowlisting with `coreTools`, as it relies on blocking known-bad commands, and
clever users may find ways to bypass simple string-based blocks. **Allowlisting
is the recommended approach.**
## Managing Custom Tools (MCP Servers)
If your organization uses custom tools via [Model-Context Protocol (MCP) servers](../core/tools-api.md), it is crucial to understand how server configurations are managed to apply security policies effectively.
If your organization uses custom tools via
[Model-Context Protocol (MCP) servers](../core/tools-api.md), it is crucial to
understand how server configurations are managed to apply security policies
effectively.
### How MCP Server Configurations are Merged
Gemini CLI loads `settings.json` files from three levels: System, Workspace, and User. When it comes to the `mcpServers` object, these configurations are **merged**:
Gemini CLI loads `settings.json` files from three levels: System, Workspace, and
User. When it comes to the `mcpServers` object, these configurations are
**merged**:
1. **Merging:** The lists of servers from all three levels are combined into a single list.
2. **Precedence:** If a server with the **same name** is defined at multiple levels (e.g., a server named `corp-api` exists in both system and user settings), the definition from the highest-precedence level is used. The order of precedence is: **System > Workspace > User**.
1. **Merging:** The lists of servers from all three levels are combined into a
single list.
2. **Precedence:** If a server with the **same name** is defined at multiple
levels (e.g., a server named `corp-api` exists in both system and user
settings), the definition from the highest-precedence level is used. The
order of precedence is: **System > Workspace > User**.
This means a user **cannot** override the definition of a server that is already defined in the system-level settings. However, they **can** add new servers with unique names.
This means a user **cannot** override the definition of a server that is already
defined in the system-level settings. However, they **can** add new servers with
unique names.
### Enforcing a Catalog of Tools
The security of your MCP tool ecosystem depends on a combination of defining the canonical servers and adding their names to an allowlist.
The security of your MCP tool ecosystem depends on a combination of defining the
canonical servers and adding their names to an allowlist.
### Restricting Tools Within an MCP Server
For even greater security, especially when dealing with third-party MCP servers, you can restrict which specific tools from a server are exposed to the model. This is done using the `includeTools` and `excludeTools` properties within a server's definition. This allows you to use a subset of tools from a server without allowing potentially dangerous ones.
For even greater security, especially when dealing with third-party MCP servers,
you can restrict which specific tools from a server are exposed to the model.
This is done using the `includeTools` and `excludeTools` properties within a
server's definition. This allows you to use a subset of tools from a server
without allowing potentially dangerous ones.
Following the principle of least privilege, it is highly recommended to use `includeTools` to create an allowlist of only the necessary tools.
Following the principle of least privilege, it is highly recommended to use
`includeTools` to create an allowlist of only the necessary tools.
**Example:** Only allow the `code-search` and `get-ticket-details` tools from a third-party MCP server, even if the server offers other tools like `delete-ticket`.
**Example:** Only allow the `code-search` and `get-ticket-details` tools from a
third-party MCP server, even if the server offers other tools like
`delete-ticket`.
```json
{
@@ -210,15 +262,21 @@ Following the principle of least privilege, it is highly recommended to use `inc
#### More Secure Pattern: Define and Add to Allowlist in System Settings
To create a secure, centrally-managed catalog of tools, the system administrator **must** do both of the following in the system-level `settings.json` file:
To create a secure, centrally-managed catalog of tools, the system administrator
**must** do both of the following in the system-level `settings.json` file:
1. **Define the full configuration** for every approved server in the `mcpServers` object. This ensures that even if a user defines a server with the same name, the secure system-level definition will take precedence.
2. **Add the names** of those servers to an allowlist using the `mcp.allowed` setting. This is a critical security step that prevents users from running any servers that are not on this list. If this setting is omitted, the CLI will merge and allow any server defined by the user.
1. **Define the full configuration** for every approved server in the
`mcpServers` object. This ensures that even if a user defines a server with
the same name, the secure system-level definition will take precedence.
2. **Add the names** of those servers to an allowlist using the `mcp.allowed`
setting. This is a critical security step that prevents users from running
any servers that are not on this list. If this setting is omitted, the CLI
will merge and allow any server defined by the user.
**Example System `settings.json`:**
1. Add the _names_ of all approved servers to an allowlist.
This will prevent users from adding their own servers.
1. Add the _names_ of all approved servers to an allowlist. This will prevent
users from adding their own servers.
2. Provide the canonical _definition_ for each server on the allowlist.
@@ -239,16 +297,20 @@ To create a secure, centrally-managed catalog of tools, the system administrator
}
```
This pattern is more secure because it uses both definition and an allowlist. Any server a user defines will either be overridden by the system definition (if it has the same name) or blocked because its name is not in the `mcp.allowed` list.
This pattern is more secure because it uses both definition and an allowlist.
Any server a user defines will either be overridden by the system definition (if
it has the same name) or blocked because its name is not in the `mcp.allowed`
list.
### Less Secure Pattern: Omitting the Allowlist
If the administrator defines the `mcpServers` object but fails to also specify the `mcp.allowed` allowlist, users may add their own servers.
If the administrator defines the `mcpServers` object but fails to also specify
the `mcp.allowed` allowlist, users may add their own servers.
**Example System `settings.json`:**
This configuration defines servers but does not enforce the allowlist.
The administrator has NOT included the "mcp.allowed" setting.
This configuration defines servers but does not enforce the allowlist. The
administrator has NOT included the "mcp.allowed" setting.
```json
{
@@ -260,11 +322,16 @@ The administrator has NOT included the "mcp.allowed" setting.
}
```
In this scenario, a user can add their own server in their local `settings.json`. Because there is no `mcp.allowed` list to filter the merged results, the user's server will be added to the list of available tools and allowed to run.
In this scenario, a user can add their own server in their local
`settings.json`. Because there is no `mcp.allowed` list to filter the merged
results, the user's server will be added to the list of available tools and
allowed to run.
## Enforcing Sandboxing for Security
To mitigate the risk of potentially harmful operations, you can enforce the use of sandboxing for all tool execution. The sandbox isolates tool execution in a containerized environment.
To mitigate the risk of potentially harmful operations, you can enforce the use
of sandboxing for all tool execution. The sandbox isolates tool execution in a
containerized environment.
**Example:** Force all tool execution to happen within a Docker sandbox.
@@ -276,11 +343,17 @@ To mitigate the risk of potentially harmful operations, you can enforce the use
}
```
You can also specify a custom, hardened Docker image for the sandbox using the `--sandbox-image` command-line argument or by building a custom `sandbox.Dockerfile` as described in the [Sandboxing documentation](./sandbox.md).
You can also specify a custom, hardened Docker image for the sandbox using the
`--sandbox-image` command-line argument or by building a custom
`sandbox.Dockerfile` as described in the
[Sandboxing documentation](./sandbox.md).
## Controlling Network Access via Proxy
In corporate environments with strict network policies, you can configure Gemini CLI to route all outbound traffic through a corporate proxy. This can be set via an environment variable, but it can also be enforced for custom tools via the `mcpServers` configuration.
In corporate environments with strict network policies, you can configure Gemini
CLI to route all outbound traffic through a corporate proxy. This can be set via
an environment variable, but it can also be enforced for custom tools via the
`mcpServers` configuration.
**Example (for an MCP Server):**
@@ -301,9 +374,13 @@ In corporate environments with strict network policies, you can configure Gemini
## Telemetry and Auditing
For auditing and monitoring purposes, you can configure Gemini CLI to send telemetry data to a central location. This allows you to track tool usage and other events. For more information, see the [telemetry documentation](./telemetry.md).
For auditing and monitoring purposes, you can configure Gemini CLI to send
telemetry data to a central location. This allows you to track tool usage and
other events. For more information, see the
[telemetry documentation](./telemetry.md).
**Example:** Enable telemetry and send it to a local OTLP collector. If `otlpEndpoint` is not specified, it defaults to `http://localhost:4317`.
**Example:** Enable telemetry and send it to a local OTLP collector. If
`otlpEndpoint` is not specified, it defaults to `http://localhost:4317`.
```json
{
@@ -315,11 +392,15 @@ For auditing and monitoring purposes, you can configure Gemini CLI to send telem
}
```
**Note:** Ensure that `logPrompts` is set to `false` in an enterprise setting to avoid collecting potentially sensitive information from user prompts.
**Note:** Ensure that `logPrompts` is set to `false` in an enterprise setting to
avoid collecting potentially sensitive information from user prompts.
## Authentication
You can enforce a specific authentication method for all users by setting the `enforcedAuthType` in the system-level `settings.json` file. This prevents users from choosing a different authentication method. See the [Authentication docs](./authentication.md) for more details.
You can enforce a specific authentication method for all users by setting the
`enforcedAuthType` in the system-level `settings.json` file. This prevents users
from choosing a different authentication method. See the
[Authentication docs](./authentication.md) for more details.
**Example:** Enforce the use of Google login for all users.
@@ -329,11 +410,16 @@ You can enforce a specific authentication method for all users by setting the `e
}
```
If a user has a different authentication method configured, they will be prompted to switch to the enforced method. In non-interactive mode, the CLI will exit with an error if the configured authentication method does not match the enforced one.
If a user has a different authentication method configured, they will be
prompted to switch to the enforced method. In non-interactive mode, the CLI will
exit with an error if the configured authentication method does not match the
enforced one.
## Putting It All Together: Example System `settings.json`
Here is an example of a system `settings.json` file that combines several of the patterns discussed above to create a secure, controlled environment for Gemini CLI.
Here is an example of a system `settings.json` file that combines several of the
patterns discussed above to create a secure, controlled environment for Gemini
CLI.
```json
{
@@ -376,7 +462,8 @@ Here is an example of a system `settings.json` file that combines several of the
This configuration:
- Forces all tool execution into a Docker sandbox.
- Strictly uses an allowlist for a small set of safe shell commands and file tools.
- Strictly uses an allowlist for a small set of safe shell commands and file
tools.
- Defines and allows a single corporate MCP server for custom tools.
- Enables telemetry for auditing, without logging prompt content.
- Redirects the `/bug` command to an internal ticketing system.
+19 -7
View File
@@ -1,22 +1,33 @@
# Ignoring Files
This document provides an overview of the Gemini Ignore (`.geminiignore`) feature of the Gemini CLI.
This document provides an overview of the Gemini Ignore (`.geminiignore`)
feature of the Gemini CLI.
The Gemini CLI includes the ability to automatically ignore files, similar to `.gitignore` (used by Git) and `.aiexclude` (used by Gemini Code Assist). Adding paths to your `.geminiignore` file will exclude them from tools that support this feature, although they will still be visible to other services (such as Git).
The Gemini CLI includes the ability to automatically ignore files, similar to
`.gitignore` (used by Git) and `.aiexclude` (used by Gemini Code Assist). Adding
paths to your `.geminiignore` file will exclude them from tools that support
this feature, although they will still be visible to other services (such as
Git).
## How it works
When you add a path to your `.geminiignore` file, tools that respect this file will exclude matching files and directories from their operations. For example, when you use the [`read_many_files`](../tools/multi-file.md) command, any paths in your `.geminiignore` file will be automatically excluded.
When you add a path to your `.geminiignore` file, tools that respect this file
will exclude matching files and directories from their operations. For example,
when you use the [`read_many_files`](../tools/multi-file.md) command, any paths
in your `.geminiignore` file will be automatically excluded.
For the most part, `.geminiignore` follows the conventions of `.gitignore` files:
For the most part, `.geminiignore` follows the conventions of `.gitignore`
files:
- Blank lines and lines starting with `#` are ignored.
- Standard glob patterns are supported (such as `*`, `?`, and `[]`).
- Putting a `/` at the end will only match directories.
- Putting a `/` at the beginning anchors the path relative to the `.geminiignore` file.
- Putting a `/` at the beginning anchors the path relative to the
`.geminiignore` file.
- `!` negates a pattern.
You can update your `.geminiignore` file at any time. To apply the changes, you must restart your Gemini CLI session.
You can update your `.geminiignore` file at any time. To apply the changes, you
must restart your Gemini CLI session.
## How to use `.geminiignore`
@@ -27,7 +38,8 @@ To enable `.geminiignore`:
To add a file or directory to `.geminiignore`:
1. Open your `.geminiignore` file.
2. Add the path or file you want to ignore, for example: `/archive/` or `apikeys.txt`.
2. Add the path or file you want to ignore, for example: `/archive/` or
`apikeys.txt`.
### `.geminiignore` examples
+37 -14
View File
@@ -1,30 +1,44 @@
# Provide Context with GEMINI.md Files
Context files, which use the default name `GEMINI.md`, are a powerful feature for providing instructional context to the Gemini model. You can use these files to give project-specific instructions, define a persona, or provide coding style guides to make the AI's responses more accurate and tailored to your needs.
Context files, which use the default name `GEMINI.md`, are a powerful feature
for providing instructional context to the Gemini model. You can use these files
to give project-specific instructions, define a persona, or provide coding style
guides to make the AI's responses more accurate and tailored to your needs.
Instead of repeating instructions in every prompt, you can define them once in a context file.
Instead of repeating instructions in every prompt, you can define them once in a
context file.
## Understand the context hierarchy
The CLI uses a hierarchical system to source context. It loads various context files from several locations, concatenates the contents of all found files, and sends them to the model with every prompt. The CLI loads files in the following order:
The CLI uses a hierarchical system to source context. It loads various context
files from several locations, concatenates the contents of all found files, and
sends them to the model with every prompt. The CLI loads files in the following
order:
1. **Global context file:**
- **Location:** `~/.gemini/GEMINI.md` (in your user home directory).
- **Scope:** Provides default instructions for all your projects.
2. **Project root and ancestor context files:**
- **Location:** The CLI searches for a `GEMINI.md` file in your current working directory and then in each parent directory up to the project root (identified by a `.git` folder).
- **Location:** The CLI searches for a `GEMINI.md` file in your current
working directory and then in each parent directory up to the project root
(identified by a `.git` folder).
- **Scope:** Provides context relevant to the entire project.
3. **Sub-directory context files:**
- **Location:** The CLI also scans for `GEMINI.md` files in subdirectories below your current working directory. It respects rules in `.gitignore` and `.geminiignore`.
- **Scope:** Lets you write highly specific instructions for a particular component or module.
- **Location:** The CLI also scans for `GEMINI.md` files in subdirectories
below your current working directory. It respects rules in `.gitignore`
and `.geminiignore`.
- **Scope:** Lets you write highly specific instructions for a particular
component or module.
The CLI footer displays the number of loaded context files, which gives you a quick visual cue of the active instructional context.
The CLI footer displays the number of loaded context files, which gives you a
quick visual cue of the active instructional context.
### Example `GEMINI.md` file
Here is an example of what you can include in a `GEMINI.md` file at the root of a TypeScript project:
Here is an example of what you can include in a `GEMINI.md` file at the root of
a TypeScript project:
```markdown
# Project: My TypeScript Library
@@ -46,13 +60,19 @@ Here is an example of what you can include in a `GEMINI.md` file at the root of
You can interact with the loaded context files by using the `/memory` command.
- **`/memory show`**: Displays the full, concatenated content of the current hierarchical memory. This lets you inspect the exact instructional context being provided to the model.
- **`/memory refresh`**: Forces a re-scan and reload of all `GEMINI.md` files from all configured locations.
- **`/memory add <text>`**: Appends your text to your global `~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly.
- **`/memory show`**: Displays the full, concatenated content of the current
hierarchical memory. This lets you inspect the exact instructional context
being provided to the model.
- **`/memory refresh`**: Forces a re-scan and reload of all `GEMINI.md` files
from all configured locations.
- **`/memory add <text>`**: Appends your text to your global
`~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly.
## Modularize context with imports
You can break down large `GEMINI.md` files into smaller, more manageable components by importing content from other files using the `@file.md` syntax. This feature supports both relative and absolute paths.
You can break down large `GEMINI.md` files into smaller, more manageable
components by importing content from other files using the `@file.md` syntax.
This feature supports both relative and absolute paths.
**Example `GEMINI.md` with imports:**
@@ -68,11 +88,14 @@ More content here.
@../shared/style-guide.md
```
For more details, see the [Memory Import Processor](../core/memport.md) documentation.
For more details, see the [Memory Import Processor](../core/memport.md)
documentation.
## Customize the context file name
While `GEMINI.md` is the default filename, you can configure this in your `settings.json` file. To specify a different name or a list of names, use the `context.fileName` property.
While `GEMINI.md` is the default filename, you can configure this in your
`settings.json` file. To specify a different name or a list of names, use the
`context.fileName` property.
**Example `settings.json`:**
+5 -2
View File
@@ -244,7 +244,9 @@ Key command-line options for headless usage:
| `--yolo`, `-y` | Auto-approve all actions | `gemini -p "query" --yolo` |
| `--approval-mode` | Set approval mode | `gemini -p "query" --approval-mode auto_edit` |
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](../get-started/configuration.md).
For complete details on all available configuration options, settings files, and
environment variables, see the
[Configuration Guide](../get-started/configuration.md).
## Examples
@@ -317,7 +319,8 @@ tail -5 usage.log
## Resources
- [CLI Configuration](../get-started/configuration.md) - Complete configuration guide
- [CLI Configuration](../get-started/configuration.md) - Complete configuration
guide
- [Authentication](../get-started/authentication.md) - Setup authentication
- [Commands](./commands.md) - Interactive commands reference
- [Tutorials](./tutorials.md) - Step-by-step automation guides
+32 -15
View File
@@ -1,30 +1,46 @@
# Gemini CLI
Within Gemini CLI, `packages/cli` is the frontend for users to send and receive prompts with the Gemini AI model and its associated tools. For a general overview of Gemini CLI, see the [main documentation page](../index.md).
Within Gemini CLI, `packages/cli` is the frontend for users to send and receive
prompts with the Gemini AI model and its associated tools. For a general
overview of Gemini CLI, see the [main documentation page](../index.md).
## Basic features
- **[Commands](./commands.md):** A reference for all built-in slash commands (e.g., `/help`, `/chat`, `/tools`).
- **[Custom Commands](./custom-commands.md):** Create your own commands and shortcuts for frequently used prompts.
- **[Headless Mode](./headless.md):** Use Gemini CLI programmatically for scripting and automation.
- **[Themes](./themes.md):** Customizing the CLI's appearance with different themes.
- **[Keyboard Shortcuts](./keyboard-shortcuts.md):** A reference for all keyboard shortcuts to improve your workflow.
- **[Commands](./commands.md):** A reference for all built-in slash commands
(e.g., `/help`, `/chat`, `/tools`).
- **[Custom Commands](./custom-commands.md):** Create your own commands and
shortcuts for frequently used prompts.
- **[Headless Mode](./headless.md):** Use Gemini CLI programmatically for
scripting and automation.
- **[Themes](./themes.md):** Customizing the CLI's appearance with different
themes.
- **[Keyboard Shortcuts](./keyboard-shortcuts.md):** A reference for all
keyboard shortcuts to improve your workflow.
- **[Tutorials](./tutorials.md):** Step-by-step guides for common tasks.
## Advanced features
- **[Checkpointing](./checkpointing.md):** Automatically save and restore snapshots of your session and files.
- **[Enterprise Configuration](./enterprise.md):** Deploying and manage Gemini CLI in an enterprise environment.
- **[Sandboxing](./sandbox.md):** Isolate tool execution in a secure, containerized environment.
- **[Telemetry](./telemetry.md):** Configure observability to monitor usage and performance.
- **[Checkpointing](./checkpointing.md):** Automatically save and restore
snapshots of your session and files.
- **[Enterprise Configuration](./enterprise.md):** Deploying and manage Gemini
CLI in an enterprise environment.
- **[Sandboxing](./sandbox.md):** Isolate tool execution in a secure,
containerized environment.
- **[Telemetry](./telemetry.md):** Configure observability to monitor usage and
performance.
- **[Token Caching](./token-caching.md):** Optimize API costs by caching tokens.
- **[Trusted Folders](./trusted-folders.md):** A security feature to control which projects can use the full capabilities of the CLI.
- **[Ignoring Files (.geminiignore)](./gemini-ignore.md):** Exclude specific files and directories from being accessed by tools.
- **[Context Files (GEMINI.md)](./gemini-md.md):** Provide persistent, hierarchical context to the model.
- **[Trusted Folders](./trusted-folders.md):** A security feature to control
which projects can use the full capabilities of the CLI.
- **[Ignoring Files (.geminiignore)](./gemini-ignore.md):** Exclude specific
files and directories from being accessed by tools.
- **[Context Files (GEMINI.md)](./gemini-md.md):** Provide persistent,
hierarchical context to the model.
## Non-interactive mode
Gemini CLI can be run in a non-interactive mode, which is useful for scripting and automation. In this mode, you pipe input to the CLI, it executes the command, and then it exits.
Gemini CLI can be run in a non-interactive mode, which is useful for scripting
and automation. In this mode, you pipe input to the CLI, it executes the
command, and then it exits.
The following example pipes a command to Gemini CLI from your terminal:
@@ -38,4 +54,5 @@ You can also use the `--prompt` or `-p` flag:
gemini -p "What is fine tuning?"
```
For comprehensive documentation on headless usage, scripting, automation, and advanced examples, see the **[Headless Mode](./headless.md)** guide.
For comprehensive documentation on headless usage, scripting, automation, and
advanced examples, see the **[Headless Mode](./headless.md)** guide.
+24 -10
View File
@@ -1,6 +1,7 @@
# Sandboxing in the Gemini CLI
This document provides a guide to sandboxing in the Gemini CLI, including prerequisites, quickstart, and configuration.
This document provides a guide to sandboxing in the Gemini CLI, including
prerequisites, quickstart, and configuration.
## Prerequisites
@@ -18,30 +19,36 @@ gemini --version
## Overview of sandboxing
Sandboxing isolates potentially dangerous operations (such as shell commands or file modifications) from your host system, providing a security barrier between AI operations and your environment.
Sandboxing isolates potentially dangerous operations (such as shell commands or
file modifications) from your host system, providing a security barrier between
AI operations and your environment.
The benefits of sandboxing include:
- **Security**: Prevent accidental system damage or data loss.
- **Isolation**: Limit file system access to project directory.
- **Consistency**: Ensure reproducible environments across different systems.
- **Safety**: Reduce risk when working with untrusted code or experimental commands.
- **Safety**: Reduce risk when working with untrusted code or experimental
commands.
## Sandboxing methods
Your ideal method of sandboxing may differ depending on your platform and your preferred container solution.
Your ideal method of sandboxing may differ depending on your platform and your
preferred container solution.
### 1. macOS Seatbelt (macOS only)
Lightweight, built-in sandboxing using `sandbox-exec`.
**Default profile**: `permissive-open` - restricts writes outside project directory but allows most other operations.
**Default profile**: `permissive-open` - restricts writes outside project
directory but allows most other operations.
### 2. Container-based (Docker/Podman)
Cross-platform sandboxing with complete process isolation.
**Note**: Requires building the sandbox image locally or using a published image from your organization's registry.
**Note**: Requires building the sandbox image locally or using a published image
from your organization's registry.
## Quickstart
@@ -67,7 +74,8 @@ gemini -p "run the test suite"
1. **Command flag**: `-s` or `--sandbox`
2. **Environment variable**: `GEMINI_SANDBOX=true|docker|podman|sandbox-exec`
3. **Settings file**: `"sandbox": true` in the `tools` object of your `settings.json` file (e.g., `{"tools": {"sandbox": true}}`).
3. **Settings file**: `"sandbox": true` in the `tools` object of your
`settings.json` file (e.g., `{"tools": {"sandbox": true}}`).
### macOS Seatbelt profiles
@@ -81,7 +89,10 @@ Built-in profiles (set via `SEATBELT_PROFILE` env var):
### Custom Sandbox Flags
For container-based sandboxing, you can inject custom flags into the `docker` or `podman` command using the `SANDBOX_FLAGS` environment variable. This is useful for advanced configurations, such as disabling security features for specific use cases.
For container-based sandboxing, you can inject custom flags into the `docker` or
`podman` command using the `SANDBOX_FLAGS` environment variable. This is useful
for advanced configurations, such as disabling security features for specific
use cases.
**Example (Podman)**:
@@ -99,7 +110,8 @@ export SANDBOX_FLAGS="--flag1 --flag2=value"
## Linux UID/GID handling
The sandbox automatically handles user permissions on Linux. Override these permissions with:
The sandbox automatically handles user permissions on Linux. Override these
permissions with:
```bash
export SANDBOX_SET_UID_GID=true # Force host UID/GID
@@ -131,7 +143,9 @@ export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
DEBUG=1 gemini -s -p "debug command"
```
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect gemini-cli due to automatic exclusion. Use `.gemini/.env` files for gemini-cli specific debug settings.
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect
gemini-cli due to automatic exclusion. Use `.gemini/.env` files for gemini-cli
specific debug settings.
### Inspect sandbox
+58 -30
View File
@@ -257,13 +257,15 @@ for Gemini CLI:
- `mimetype` (string, if applicable)
- `extension` (string, if applicable)
- `programming_language` (string, if applicable)
- `diff_stat` (json string, if applicable): A JSON string with the following members:
- `diff_stat` (json string, if applicable): A JSON string with the following
members:
- `ai_added_lines` (int)
- `ai_removed_lines` (int)
- `user_added_lines` (int)
- `user_removed_lines` (int)
- `gemini_cli.api_request`: This event occurs when making a request to Gemini API.
- `gemini_cli.api_request`: This event occurs when making a request to Gemini
API.
- **Attributes**:
- `model`
- `request_text` (if applicable)
@@ -277,7 +279,8 @@ for Gemini CLI:
- `duration_ms`
- `auth_type`
- `gemini_cli.api_response`: This event occurs upon receiving a response from Gemini API.
- `gemini_cli.api_response`: This event occurs upon receiving a response from
Gemini API.
- **Attributes**:
- `model`
- `status_code`
@@ -291,7 +294,8 @@ for Gemini CLI:
- `response_text` (if applicable)
- `auth_type`
- `gemini_cli.tool_output_truncated`: This event occurs when the output of a tool call is too large and gets truncated.
- `gemini_cli.tool_output_truncated`: This event occurs when the output of a
tool call is too large and gets truncated.
- **Attributes**:
- `tool_name` (string)
- `original_content_length` (int)
@@ -300,27 +304,32 @@ for Gemini CLI:
- `lines` (int)
- `prompt_id` (string)
- `gemini_cli.malformed_json_response`: This event occurs when a `generateJson` response from Gemini API cannot be parsed as a json.
- `gemini_cli.malformed_json_response`: This event occurs when a `generateJson`
response from Gemini API cannot be parsed as a json.
- **Attributes**:
- `model`
- `gemini_cli.flash_fallback`: This event occurs when Gemini CLI switches to flash as fallback.
- `gemini_cli.flash_fallback`: This event occurs when Gemini CLI switches to
flash as fallback.
- **Attributes**:
- `auth_type`
- `gemini_cli.slash_command`: This event occurs when a user executes a slash command.
- `gemini_cli.slash_command`: This event occurs when a user executes a slash
command.
- **Attributes**:
- `command` (string)
- `subcommand` (string, if applicable)
- `gemini_cli.extension_enable`: This event occurs when an extension is enabled
- `gemini_cli.extension_install`: This event occurs when an extension is installed
- `gemini_cli.extension_install`: This event occurs when an extension is
installed
- **Attributes**:
- `extension_name` (string)
- `extension_version` (string)
- `extension_source` (string)
- `status` (string)
- `gemini_cli.extension_uninstall`: This event occurs when an extension is uninstalled
- `gemini_cli.extension_uninstall`: This event occurs when an extension is
uninstalled
### Metrics
@@ -348,7 +357,8 @@ Metrics are numerical measurements of behavior over time.
- `status_code`
- `error_type` (if applicable)
- `gemini_cli.api.request.latency` (Histogram, ms): Measures API request latency.
- `gemini_cli.api.request.latency` (Histogram, ms): Measures API request
latency.
- **Attributes**:
- `model`
- **Note**: This metric overlaps with `gen_ai.client.operation.duration` below
@@ -364,44 +374,62 @@ Metrics are numerical measurements of behavior over time.
- `gemini_cli.file.operation.count` (Counter, Int): Counts file operations.
- **Attributes**:
- `operation` (string: "create", "read", "update"): The type of file operation.
- `operation` (string: "create", "read", "update"): The type of file
operation.
- `lines` (Int, if applicable): Number of lines in the file.
- `mimetype` (string, if applicable): Mimetype of the file.
- `extension` (string, if applicable): File extension of the file.
- `model_added_lines` (Int, if applicable): Number of lines added/changed by the model.
- `model_removed_lines` (Int, if applicable): Number of lines removed/changed by the model.
- `user_added_lines` (Int, if applicable): Number of lines added/changed by user in AI proposed changes.
- `user_removed_lines` (Int, if applicable): Number of lines removed/changed by user in AI proposed changes.
- `programming_language` (string, if applicable): The programming language of the file.
- `model_added_lines` (Int, if applicable): Number of lines added/changed by
the model.
- `model_removed_lines` (Int, if applicable): Number of lines
removed/changed by the model.
- `user_added_lines` (Int, if applicable): Number of lines added/changed by
user in AI proposed changes.
- `user_removed_lines` (Int, if applicable): Number of lines removed/changed
by user in AI proposed changes.
- `programming_language` (string, if applicable): The programming language
of the file.
- `gemini_cli.chat_compression` (Counter, Int): Counts chat compression operations
- `gemini_cli.chat_compression` (Counter, Int): Counts chat compression
operations
- **Attributes**:
- `tokens_before`: (Int): Number of tokens in context prior to compression
- `tokens_after`: (Int): Number of tokens in context after compression
#### GenAI Semantic Convention
The following metrics comply with [OpenTelemetry GenAI semantic conventions]
for standardized observability across GenAI applications:
The following metrics comply with [OpenTelemetry GenAI semantic conventions] for
standardized observability across GenAI applications:
- `gen_ai.client.token.usage` (Histogram, token): Number of input and output tokens used per operation.
- `gen_ai.client.token.usage` (Histogram, token): Number of input and output
tokens used per operation.
- **Attributes**:
- `gen_ai.operation.name` (string): The operation type (e.g., "generate_content", "chat")
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or "gcp.vertex_ai")
- `gen_ai.operation.name` (string): The operation type (e.g.,
"generate_content", "chat")
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or
"gcp.vertex_ai")
- `gen_ai.token.type` (string): The token type ("input" or "output")
- `gen_ai.request.model` (string, optional): The model name used for the request
- `gen_ai.response.model` (string, optional): The model name that generated the response
- `gen_ai.request.model` (string, optional): The model name used for the
request
- `gen_ai.response.model` (string, optional): The model name that generated
the response
- `server.address` (string, optional): GenAI server address
- `server.port` (int, optional): GenAI server port
- `gen_ai.client.operation.duration` (Histogram, s): GenAI operation duration in seconds.
- `gen_ai.client.operation.duration` (Histogram, s): GenAI operation duration in
seconds.
- **Attributes**:
- `gen_ai.operation.name` (string): The operation type (e.g., "generate_content", "chat")
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or "gcp.vertex_ai")
- `gen_ai.request.model` (string, optional): The model name used for the request
- `gen_ai.response.model` (string, optional): The model name that generated the response
- `gen_ai.operation.name` (string): The operation type (e.g.,
"generate_content", "chat")
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or
"gcp.vertex_ai")
- `gen_ai.request.model` (string, optional): The model name used for the
request
- `gen_ai.response.model` (string, optional): The model name that generated
the response
- `server.address` (string, optional): GenAI server address
- `server.port` (int, optional): GenAI server port
- `error.type` (string, optional): Error type if the operation failed
[OpenTelemetry GenAI semantic conventions]: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-metrics.md
[OpenTelemetry GenAI semantic conventions]:
https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-metrics.md
+45 -16
View File
@@ -1,10 +1,13 @@
# Themes
Gemini CLI supports a variety of themes to customize its color scheme and appearance. You can change the theme to suit your preferences via the `/theme` command or `"theme":` configuration setting.
Gemini CLI supports a variety of themes to customize its color scheme and
appearance. You can change the theme to suit your preferences via the `/theme`
command or `"theme":` configuration setting.
## Available Themes
Gemini CLI comes with a selection of pre-defined themes, which you can list using the `/theme` command within Gemini CLI:
Gemini CLI comes with a selection of pre-defined themes, which you can list
using the `/theme` command within Gemini CLI:
- **Dark Themes:**
- `ANSI`
@@ -25,24 +28,33 @@ Gemini CLI comes with a selection of pre-defined themes, which you can list usin
1. Enter `/theme` into Gemini CLI.
2. A dialog or selection prompt appears, listing the available themes.
3. Using the arrow keys, select a theme. Some interfaces might offer a live preview or highlight as you select.
3. Using the arrow keys, select a theme. Some interfaces might offer a live
preview or highlight as you select.
4. Confirm your selection to apply the theme.
**Note:** If a theme is defined in your `settings.json` file (either by name or by a file path), you must remove the `"theme"` setting from the file before you can change the theme using the `/theme` command.
**Note:** If a theme is defined in your `settings.json` file (either by name or
by a file path), you must remove the `"theme"` setting from the file before you
can change the theme using the `/theme` command.
### Theme Persistence
Selected themes are saved in Gemini CLI's [configuration](../get-started/configuration.md) so your preference is remembered across sessions.
Selected themes are saved in Gemini CLI's
[configuration](../get-started/configuration.md) so your preference is
remembered across sessions.
---
## Custom Color Themes
Gemini CLI allows you to create your own custom color themes by specifying them in your `settings.json` file. This gives you full control over the color palette used in the CLI.
Gemini CLI allows you to create your own custom color themes by specifying them
in your `settings.json` file. This gives you full control over the color palette
used in the CLI.
### How to Define a Custom Theme
Add a `customThemes` block to your user, project, or system `settings.json` file. Each custom theme is defined as an object with a unique name and a set of color keys. For example:
Add a `customThemes` block to your user, project, or system `settings.json`
file. Each custom theme is defined as an object with a unique name and a set of
color keys. For example:
```json
{
@@ -92,15 +104,23 @@ Add a `customThemes` block to your user, project, or system `settings.json` file
- `Comment`
- `Gray`
You can use either hex codes (e.g., `#FF0000`) **or** standard CSS color names (e.g., `coral`, `teal`, `blue`) for any color value. See [CSS color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) for a full list of supported names.
You can use either hex codes (e.g., `#FF0000`) **or** standard CSS color names
(e.g., `coral`, `teal`, `blue`) for any color value. See
[CSS color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords)
for a full list of supported names.
You can define multiple custom themes by adding more entries to the `customThemes` object.
You can define multiple custom themes by adding more entries to the
`customThemes` object.
### Loading Themes from a File
In addition to defining custom themes in `settings.json`, you can also load a theme directly from a JSON file by specifying the file path in your `settings.json`. This is useful for sharing themes or keeping them separate from your main configuration.
In addition to defining custom themes in `settings.json`, you can also load a
theme directly from a JSON file by specifying the file path in your
`settings.json`. This is useful for sharing themes or keeping them separate from
your main configuration.
To load a theme from a file, set the `theme` property in your `settings.json` to the path of your theme file:
To load a theme from a file, set the `theme` property in your `settings.json` to
the path of your theme file:
```json
{
@@ -110,7 +130,8 @@ To load a theme from a file, set the `theme` property in your `settings.json` to
}
```
The theme file must be a valid JSON file that follows the same structure as a custom theme defined in `settings.json`.
The theme file must be a valid JSON file that follows the same structure as a
custom theme defined in `settings.json`.
**Example `my-theme.json`:**
@@ -136,7 +157,11 @@ The theme file must be a valid JSON file that follows the same structure as a cu
}
```
**Security Note:** For your safety, Gemini CLI will only load theme files that are located within your home directory. If you attempt to load a theme from outside your home directory, a warning will be displayed and the theme will not be loaded. This is to prevent loading potentially malicious theme files from untrusted sources.
**Security Note:** For your safety, Gemini CLI will only load theme files that
are located within your home directory. If you attempt to load a theme from
outside your home directory, a warning will be displayed and the theme will not
be loaded. This is to prevent loading potentially malicious theme files from
untrusted sources.
### Example Custom Theme
@@ -144,9 +169,13 @@ The theme file must be a valid JSON file that follows the same structure as a cu
### Using Your Custom Theme
- Select your custom theme using the `/theme` command in Gemini CLI. Your custom theme will appear in the theme selection dialog.
- Or, set it as the default by adding `"theme": "MyCustomTheme"` to the `ui` object in your `settings.json`.
- Custom themes can be set at the user, project, or system level, and follow the same [configuration precedence](../get-started/configuration.md) as other settings.
- Select your custom theme using the `/theme` command in Gemini CLI. Your custom
theme will appear in the theme selection dialog.
- Or, set it as the default by adding `"theme": "MyCustomTheme"` to the `ui`
object in your `settings.json`.
- Custom themes can be set at the user, project, or system level, and follow the
same [configuration precedence](../get-started/configuration.md) as other
settings.
---
+9 -3
View File
@@ -1,6 +1,9 @@
# Token Caching and Cost Optimization
Gemini CLI automatically optimizes API costs through token caching when using API key authentication (Gemini API key or Vertex AI). This feature reuses previous system instructions and context to reduce the number of tokens processed in subsequent requests.
Gemini CLI automatically optimizes API costs through token caching when using
API key authentication (Gemini API key or Vertex AI). This feature reuses
previous system instructions and context to reduce the number of tokens
processed in subsequent requests.
**Token caching is available for:**
@@ -9,6 +12,9 @@ Gemini CLI automatically optimizes API costs through token caching when using AP
**Token caching is not available for:**
- OAuth users (Google Personal/Enterprise accounts) - the Code Assist API does not support cached content creation at this time
- OAuth users (Google Personal/Enterprise accounts) - the Code Assist API does
not support cached content creation at this time
You can view your token usage and cached token savings using the `/stats` command. When cached tokens are available, they will be displayed in the stats output.
You can view your token usage and cached token savings using the `/stats`
command. When cached tokens are available, they will be displayed in the stats
output.
+47 -20
View File
@@ -1,10 +1,14 @@
# Trusted Folders
The Trusted Folders feature is a security setting that gives you control over which projects can use the full capabilities of the Gemini CLI. It prevents potentially malicious code from running by asking you to approve a folder before the CLI loads any project-specific configurations from it.
The Trusted Folders feature is a security setting that gives you control over
which projects can use the full capabilities of the Gemini CLI. It prevents
potentially malicious code from running by asking you to approve a folder before
the CLI loads any project-specific configurations from it.
## Enabling the Feature
The Trusted Folders feature is **disabled by default**. To use it, you must first enable it in your settings.
The Trusted Folders feature is **disabled by default**. To use it, you must
first enable it in your settings.
Add the following to your user `settings.json` file:
@@ -20,42 +24,65 @@ Add the following to your user `settings.json` file:
## How It Works: The Trust Dialog
Once the feature is enabled, the first time you run the Gemini CLI from a folder, a dialog will automatically appear, prompting you to make a choice:
Once the feature is enabled, the first time you run the Gemini CLI from a
folder, a dialog will automatically appear, prompting you to make a choice:
- **Trust folder**: Grants full trust to the current folder (e.g., `my-project`).
- **Trust parent folder**: Grants trust to the parent directory (e.g., `safe-projects`), which automatically trusts all of its subdirectories as well. This is useful if you keep all your safe projects in one place.
- **Don't trust**: Marks the folder as untrusted. The CLI will operate in a restricted "safe mode."
- **Trust folder**: Grants full trust to the current folder (e.g.,
`my-project`).
- **Trust parent folder**: Grants trust to the parent directory (e.g.,
`safe-projects`), which automatically trusts all of its subdirectories as
well. This is useful if you keep all your safe projects in one place.
- **Don't trust**: Marks the folder as untrusted. The CLI will operate in a
restricted "safe mode."
Your choice is saved in a central file (`~/.gemini/trustedFolders.json`), so you will only be asked once per folder.
Your choice is saved in a central file (`~/.gemini/trustedFolders.json`), so you
will only be asked once per folder.
## Why Trust Matters: The Impact of an Untrusted Workspace
When a folder is **untrusted**, the Gemini CLI runs in a restricted "safe mode" to protect you. In this mode, the following features are disabled:
When a folder is **untrusted**, the Gemini CLI runs in a restricted "safe mode"
to protect you. In this mode, the following features are disabled:
1. **Workspace Settings are Ignored**: The CLI will **not** load the `.gemini/settings.json` file from the project. This prevents the loading of custom tools and other potentially dangerous configurations.
1. **Workspace Settings are Ignored**: The CLI will **not** load the
`.gemini/settings.json` file from the project. This prevents the loading of
custom tools and other potentially dangerous configurations.
2. **Environment Variables are Ignored**: The CLI will **not** load any `.env` files from the project.
2. **Environment Variables are Ignored**: The CLI will **not** load any `.env`
files from the project.
3. **Extension Management is Restricted**: You **cannot install, update, or uninstall** extensions.
3. **Extension Management is Restricted**: You **cannot install, update, or
uninstall** extensions.
4. **Tool Auto-Acceptance is Disabled**: You will always be prompted before any tool is run, even if you have auto-acceptance enabled globally.
4. **Tool Auto-Acceptance is Disabled**: You will always be prompted before any
tool is run, even if you have auto-acceptance enabled globally.
5. **Automatic Memory Loading is Disabled**: The CLI will not automatically load files into context from directories specified in local settings.
5. **Automatic Memory Loading is Disabled**: The CLI will not automatically
load files into context from directories specified in local settings.
Granting trust to a folder unlocks the full functionality of the Gemini CLI for that workspace.
Granting trust to a folder unlocks the full functionality of the Gemini CLI for
that workspace.
## Managing Your Trust Settings
If you need to change a decision or see all your settings, you have a couple of options:
If you need to change a decision or see all your settings, you have a couple of
options:
- **Change the Current Folder's Trust**: Run the `/permissions` command from within the CLI. This will bring up the same interactive dialog, allowing you to change the trust level for the current folder.
- **Change the Current Folder's Trust**: Run the `/permissions` command from
within the CLI. This will bring up the same interactive dialog, allowing you
to change the trust level for the current folder.
- **View All Trust Rules**: To see a complete list of all your trusted and untrusted folder rules, you can inspect the contents of the `~/.gemini/trustedFolders.json` file in your home directory.
- **View All Trust Rules**: To see a complete list of all your trusted and
untrusted folder rules, you can inspect the contents of the
`~/.gemini/trustedFolders.json` file in your home directory.
## The Trust Check Process (Advanced)
For advanced users, it's helpful to know the exact order of operations for how trust is determined:
For advanced users, it's helpful to know the exact order of operations for how
trust is determined:
1. **IDE Trust Signal**: If you are using the [IDE Integration](../ide-integration/index.md), the CLI first asks the IDE if the workspace is trusted. The IDE's response takes highest priority.
1. **IDE Trust Signal**: If you are using the
[IDE Integration](../ide-integration/index.md), the CLI first asks the IDE
if the workspace is trusted. The IDE's response takes highest priority.
2. **Local Trust File**: If the IDE is not connected, the CLI checks the central `~/.gemini/trustedFolders.json` file.
2. **Local Trust File**: If the IDE is not connected, the CLI checks the
central `~/.gemini/trustedFolders.json` file.
+23 -9
View File
@@ -4,17 +4,22 @@ This page contains tutorials for interacting with Gemini CLI.
## Setting up a Model Context Protocol (MCP) server
> [!CAUTION]
> Before using a third-party MCP server, ensure you trust its source and understand the tools it provides. Your use of third-party servers is at your own risk.
> [!CAUTION] Before using a third-party MCP server, ensure you trust its source
> and understand the tools it provides. Your use of third-party servers is at
> your own risk.
This tutorial demonstrates how to set up a MCP server, using the [GitHub MCP server](https://github.com/github/github-mcp-server) as an example. The GitHub MCP server provides tools for interacting with GitHub repositories, such as creating issues and commenting on pull requests.
This tutorial demonstrates how to set up a MCP server, using the
[GitHub MCP server](https://github.com/github/github-mcp-server) as an example.
The GitHub MCP server provides tools for interacting with GitHub repositories,
such as creating issues and commenting on pull requests.
### Prerequisites
Before you begin, ensure you have the following installed and configured:
- **Docker:** Install and run [Docker].
- **GitHub Personal Access Token (PAT):** Create a new [classic] or [fine-grained] PAT with the necessary scopes.
- **GitHub Personal Access Token (PAT):** Create a new [classic] or
[fine-grained] PAT with the necessary scopes.
[Docker]: https://www.docker.com/
[classic]: https://github.com/settings/tokens/new
@@ -24,7 +29,10 @@ Before you begin, ensure you have the following installed and configured:
#### Configure the MCP server in `settings.json`
In your project's root directory, create or open the [`.gemini/settings.json` file](../get-started/configuration.md). Within the file, add the `mcpServers` configuration block, which provides instructions for how to launch the GitHub MCP server.
In your project's root directory, create or open the
[`.gemini/settings.json` file](../get-started/configuration.md). Within the
file, add the `mcpServers` configuration block, which provides instructions for
how to launch the GitHub MCP server.
```json
{
@@ -49,8 +57,11 @@ In your project's root directory, create or open the [`.gemini/settings.json` fi
#### Set your GitHub token
> [!CAUTION]
> Using a broadly scoped personal access token that has access to personal and private repositories can lead to information from the private repository being leaked into the public repository. We recommend using a fine-grained access token that doesn't share access to both public and private repositories.
> [!CAUTION] Using a broadly scoped personal access token that has access to
> personal and private repositories can lead to information from the private
> repository being leaked into the public repository. We recommend using a
> fine-grained access token that doesn't share access to both public and private
> repositories.
Use an environment variable to store your GitHub PAT:
@@ -58,11 +69,14 @@ Use an environment variable to store your GitHub PAT:
GITHUB_PERSONAL_ACCESS_TOKEN="pat_YourActualGitHubTokenHere"
```
Gemini CLI uses this value in the `mcpServers` configuration that you defined in the `settings.json` file.
Gemini CLI uses this value in the `mcpServers` configuration that you defined in
the `settings.json` file.
#### Launch Gemini CLI and verify the connection
When you launch Gemini CLI, it automatically reads your configuration and launches the GitHub MCP server in the background. You can then use natural language prompts to ask Gemini CLI to perform GitHub actions. For example:
When you launch Gemini CLI, it automatically reads your configuration and
launches the GitHub MCP server in the background. You can then use natural
language prompts to ask Gemini CLI to perform GitHub actions. For example:
```bash
"get all open issues assigned to me in the 'foo/bar' repo and prioritize them"
+9 -4
View File
@@ -1,12 +1,16 @@
# Uninstalling the CLI
Your uninstall method depends on how you ran the CLI. Follow the instructions for either npx or a global npm installation.
Your uninstall method depends on how you ran the CLI. Follow the instructions
for either npx or a global npm installation.
## Method 1: Using npx
npx runs packages from a temporary cache without a permanent installation. To "uninstall" the CLI, you must clear this cache, which will remove gemini-cli and any other packages previously executed with npx.
npx runs packages from a temporary cache without a permanent installation. To
"uninstall" the CLI, you must clear this cache, which will remove gemini-cli and
any other packages previously executed with npx.
The npx cache is a directory named `_npx` inside your main npm cache folder. You can find your npm cache path by running `npm config get cache`.
The npx cache is a directory named `_npx` inside your main npm cache folder. You
can find your npm cache path by running `npm config get cache`.
**For macOS / Linux**
@@ -33,7 +37,8 @@ Remove-Item -Path (Join-Path $env:LocalAppData "npm-cache\_npx") -Recurse -Force
## Method 2: Using npm (Global Install)
If you installed the CLI globally (e.g., `npm install -g @google/gemini-cli`), use the `npm uninstall` command with the `-g` flag to remove it.
If you installed the CLI globally (e.g., `npm install -g @google/gemini-cli`),
use the `npm uninstall` command with the `-g` flag to remove it.
```bash
npm uninstall -g @google/gemini-cli