chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 11:58:09 +08:00
commit c48e26cdd0
2909 changed files with 1591131 additions and 0 deletions
+126
View File
@@ -0,0 +1,126 @@
# ACP Mode
ACP (Agent Client Protocol) mode is a special operational mode of Gemini CLI
designed for programmatic control, primarily for IDE and other developer tool
integrations. It uses a JSON-RPC protocol over stdio to communicate between
Gemini CLI agent and a client.
To start Gemini CLI in ACP mode, use the `--acp` flag:
```bash
gemini --acp
```
## Agent Client Protocol (ACP)
ACP is an open protocol that standardizes how AI coding agents communicate with
code editors and IDEs. It addresses the challenge of fragmented distribution,
where agents traditionally needed custom integrations for each client. With ACP,
developers can implement their agent once, and it becomes compatible with any
ACP-compliant editor.
For a comprehensive introduction to ACP, including its architecture and
benefits, refer to the official
[ACP Introduction](https://agentclientprotocol.com/get-started/introduction)
documentation.
### Existing integrations using ACP
The ACP Agent Registry simplifies the distribution and management of
ACP-compatible agents across various IDEs. Gemini CLI is an ACP-compatible agent
and can be found in this registry.
For more general information about the registry, and how to use it with specific
IDEs like JetBrains and Zed, refer to the
[IDE Integration](../ide-integration/index.md) documentation.
You can also find more information on the official
[ACP Agent Registry](https://agentclientprotocol.com/get-started/registry) page.
## Architecture and protocol basics
ACP mode establishes a client-server relationship between your tool (the client)
and Gemini CLI (the server).
- **Communication:** The entire communication happens over standard input/output
(stdio) using the JSON-RPC 2.0 protocol.
- **Client's role:** The client is responsible for sending requests (for
example, prompts) and handling responses and notifications from Gemini CLI.
- **Gemini CLI's role:** In ACP mode, Gemini CLI listens for incoming JSON-RPC
requests, processes them, and sends back responses.
The core of the ACP implementation can be found in
`packages/cli/src/acp/acpClient.ts`.
### Extending with MCP
ACP can be used with the Model Context Protocol (MCP). This lets an ACP client
(like an IDE) expose its own functionality as "tools" that the Gemini model can
use.
1. The client implements an **MCP server** that advertises its tools.
2. During the ACP `initialize` handshake, the client provides the connection
details for its MCP server.
3. Gemini CLI connects to the MCP server, discovers the available tools, and
makes them available to the AI model.
4. When the model decides to use one of these tools, Gemini CLI sends a tool
call request to the MCP server.
This mechanism lets for a powerful, two-way integration where the agent can
leverage the IDE's capabilities to perform tasks. The MCP client logic is in
`packages/core/src/tools/mcp-client.ts`.
## Capabilities and supported methods
The ACP protocol exposes a number of methods for ACP clients (for example IDEs)
to control Gemini CLI.
### Core methods
- `initialize`: Establishes the initial connection and lets the client to
register its MCP server.
- `authenticate`: Authenticates the user.
- `newSession`: Starts a new chat session.
- `loadSession`: Loads a previous session.
- `prompt`: Sends a prompt to the agent.
- `cancel`: Cancels an ongoing prompt.
### Session control
- `setSessionMode`: Allows changing the approval level for tool calls (for
example, to `auto-approve`).
- `unstable_setSessionModel`: Changes the model for the current session.
### File system proxy
ACP includes a proxied file system service. This means that when the agent needs
to read or write files, it does so through the ACP client. This is a security
feature that ensures the agent only has access to the files that the client (and
by extension, the user) has explicitly allowed.
## Debugging and telemetry
You can get insights into the ACP communication and the agent's behavior through
debugging logs and telemetry.
### Debugging logs
To enable general debugging logs, start Gemini CLI with the `--debug` flag:
```bash
gemini --acp --debug
```
### Telemetry
For more detailed telemetry, you can use the following environment variables to
capture telemetry data to a file:
- `GEMINI_TELEMETRY_ENABLED=true`
- `GEMINI_TELEMETRY_TARGET=local`
- `GEMINI_TELEMETRY_OUTFILE=/path/to/your/log.json`
This will write a JSON log file containing detailed information about all the
events happening within the agent, including ACP requests and responses. The
integration test `integration-tests/acp-telemetry.test.ts` provides a working
example of how to set this up.
+164
View File
@@ -0,0 +1,164 @@
# Auto Memory
Auto Memory is an experimental feature that mines your past Gemini CLI sessions
in the background and proposes durable memory updates and reusable
[Agent Skills](./skills.md). You review each candidate before it becomes
available to future sessions: apply memory updates, promote skills, or discard
anything you do not want.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development.
## Overview
Every session you run with Gemini CLI is recorded locally as a transcript. Auto
Memory scans those transcripts for durable facts, preferences, workflow
constraints, and procedural patterns that recur across sessions. It can draft
memory updates as unified diff `.patch` files and draft reusable procedures as
`SKILL.md` files. All candidates are held in a project-local inbox until you
approve or discard them.
You'll use Auto Memory when you want to:
- **Capture team workflows** that you find yourself walking the agent through
more than once.
- **Preserve durable project context** such as repeated verification commands,
local constraints, or personal project notes.
- **Codify hard-won fixes** for project-specific landmines so future sessions
avoid them.
- **Bootstrap a skills library** without writing every `SKILL.md` by hand.
Auto Memory complements direct memory-file editing. The agent can still persist
explicit user instructions by editing the appropriate Markdown memory file; Auto
Memory infers candidates from past sessions, writes reviewable patches or skill
drafts, and never applies them without your approval.
## Prerequisites
- Gemini CLI installed and authenticated.
- At least one idle project session with 10 or more user messages. Auto Memory
ignores active, trivial, and sub-agent sessions.
## How to enable Auto Memory
Auto Memory is off by default. Enable it in your settings file:
1. Open your global settings file at `~/.gemini/settings.json`. If you only
want Auto Memory in one project, edit `.gemini/settings.json` in that
project instead.
2. Add the experimental flag:
```json
{
"experimental": {
"autoMemory": true
}
}
```
3. Restart Gemini CLI. The flag requires a restart because the extraction
service starts during session boot.
## How Auto Memory works
Auto Memory runs as a background task on session startup. It does not block the
UI, consume your interactive turns, or surface tool prompts.
1. **Eligibility scan.** The service indexes recent sessions from
`~/.gemini/tmp/<project>/chats/`. Sessions are eligible only if they have
been idle for at least three hours and contain at least 10 user messages.
2. **Lock acquisition.** A lock file in the project's memory directory
coordinates across multiple CLI instances so extraction runs at most once at
a time. A state file records processed session versions, and extraction is
throttled so short back-to-back CLI launches do not repeatedly scan history.
3. **Candidate extraction.** A background extraction agent reviews the session
index, reads any sessions that look like they contain durable memory or
repeated procedural workflows, and drafts candidates. It defaults to
creating no artifacts unless the evidence is strong, so many runs produce no
inbox items.
4. **Safety boundaries.** Auto Memory writes candidates to a review inbox. It
cannot directly edit active memory files, settings, credentials, or project
`GEMINI.md` files.
5. **Patch validation.** Skill update patches are parsed and dry-run before
they are surfaced. Memory patches are parsed, target-allowlisted, and
applied atomically only when you approve them from the inbox.
6. **Notification.** When a run produces new candidates, Gemini CLI surfaces an
inline message telling you how many items are waiting.
## How to review extracted items
Use the `/memory inbox` slash command to open the inbox dialog at any time:
**Command:** `/memory inbox`
The dialog groups pending items into new skills, skill updates, and memory
updates. From there you can:
- **Read** the full `SKILL.md` body before deciding.
- **Promote** a skill to your user (`~/.gemini/skills/`) or workspace
(`.gemini/skills/`) directory.
- **Discard** a skill you do not want.
- **Apply** or reject a `.patch` proposal against an existing skill.
- **Review** memory diffs before they touch active files.
- **Apply** or dismiss private and global memory patches. Private patches target
the project memory directory; global patches target only your personal
`~/.gemini/GEMINI.md` file.
Promoted skills become discoverable in the next session and follow the standard
[skill discovery precedence](./skills.md#skill-discovery-tiers). Applied memory
patches update the underlying memory files and reload memory for the current
session.
## How to disable Auto Memory
To turn off background extraction, set the flag back to `false` in your settings
file and restart Gemini CLI:
```json
{
"experimental": {
"autoMemory": false
}
}
```
Disabling the flag stops the background service immediately on the next session
start. Existing inbox items remain on disk; you can either drain them with
`/memory inbox` first or remove the project memory directory manually.
## Data and privacy
- Auto Memory only reads session files that already exist locally on your
machine.
- Auto Memory uses model calls to analyze selected local transcript content
during extraction. No candidates are applied automatically, but transcript
excerpts may be sent to the configured model as part of those calls.
- The extraction agent is instructed to redact secrets, tokens, and credentials
it encounters and to never copy large tool outputs verbatim.
- Drafted skills and memory patches live in your project's memory directory
until you promote, apply, dismiss, or discard them. They are not automatically
loaded into any session.
## Limitations
- The extraction agent runs on a preview Gemini Flash model. Extraction quality
depends on the model's ability to recognize durable patterns versus one-off
incidents.
- Auto Memory does not extract memory or skills from the current session. It
only considers sessions that have been idle for three hours or more.
- Project or workspace shared instructions in project `GEMINI.md` files are not
auto-extractable. Auto Memory can propose private project memory, global
personal memory, and skills.
- Inbox items are stored per project. Skills extracted in one workspace are not
visible from another until you promote them to the user-scope skills
directory.
## Next steps
- Learn how skills are discovered and activated in [Agent Skills](./skills.md).
- Explore the [memory management tutorial](./tutorials/memory-management.md) for
the complementary explicit-memory and `GEMINI.md` workflows.
- Review the experimental settings catalog in
[Settings](./settings.md#experimental).
+95
View File
@@ -0,0 +1,95 @@
# Checkpointing
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 lets you 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:
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:
- 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.
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 need to edit
your `settings.json` file.
<!-- prettier-ignore -->
> [!CAUTION]
> The `--checkpointing` command-line flag was removed in version
> 0.11.0. Checkpointing can now only be enabled through the `settings.json`
> configuration file.
Add the following key to your `settings.json`:
```json
{
"general": {
"checkpointing": {
"enabled": true
}
}
}
```
## Using the `/restore` command
Once enabled, checkpoints are created automatically. To manage them, you use the
`/restore` command.
### List available checkpoints
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 (for example,
`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:
```
/restore <checkpoint_file>
```
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.
+134
View File
@@ -0,0 +1,134 @@
# Gemini CLI cheatsheet
This page provides a reference for commonly used Gemini CLI commands, options,
and parameters.
## CLI commands
| Command | Description | Example |
| ---------------------------------- | ---------------------------------- | ------------------------------------------------------------ |
| `gemini` | Start interactive REPL | `gemini` |
| `gemini -p "query"` | Query non-interactively | `gemini -p "summarize README.md"` |
| gemini "query" | Query and continue interactively | gemini "explain this project" |
| `cat file \| gemini` | Process piped content | `cat logs.txt \| gemini`<br>`Get-Content logs.txt \| gemini` |
| `gemini -i "query"` | Execute and continue interactively | `gemini -i "What is the purpose of this project?"` |
| `gemini -r "latest"` | Continue most recent session | `gemini -r "latest"` |
| `gemini -r "latest" "query"` | Continue session with a new prompt | `gemini -r "latest" "Check for type errors"` |
| `gemini -r "<session-id>" "query"` | Resume session by ID | `gemini -r "abc123" "Finish this PR"` |
| `gemini update` | Update to latest version | `gemini update` |
| `gemini extensions` | Manage extensions | See [Extensions Management](#extensions-management) |
| `gemini mcp` | Configure MCP servers | See [MCP Server Management](#mcp-server-management) |
### Positional arguments
| Argument | Type | Description |
| -------- | ----------------- | ---------------------------------------------------------------------------------------------------------- |
| `query` | string (variadic) | Positional prompt. Defaults to interactive mode in a TTY. Use `-p/--prompt` for non-interactive execution. |
## Interactive commands
These commands are available within the interactive REPL.
| Command | Description |
| -------------------- | ----------------------------------------------- |
| `/skills reload` | Reload discovered skills from disk |
| `/agents reload` | Reload the agent registry |
| `/commands list` | List available custom slash commands |
| `/commands reload` | Reload custom slash commands |
| `/memory reload` | Reload context files (for example, `GEMINI.md`) |
| `/mcp reload` | Restart and reload MCP servers |
| `/extensions reload` | Reload all active extensions |
| `/help` | Show help for all commands |
| `/quit` | Exit the interactive session |
## CLI Options
| Option | Alias | Type | Default | Description |
| -------------------------------- | ----- | ------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--debug` | `-d` | boolean | `false` | Run in debug mode with verbose logging |
| `--version` | `-v` | - | - | Show CLI version number and exit |
| `--help` | `-h` | - | - | Show help information |
| `--model` | `-m` | string | `auto` | Model to use. See [Model Selection](#model-selection) for available values. |
| `--prompt` | `-p` | string | - | Prompt text. Appended to stdin input if provided. Forces non-interactive mode. |
| `--prompt-interactive` | `-i` | string | - | Execute prompt and continue in interactive mode |
| `--worktree` | `-w` | string | - | Start Gemini in a new git worktree. If no name is provided, one is generated automatically. Requires `experimental.worktrees: true` in settings. |
| `--sandbox` | `-s` | boolean | `false` | Run in a sandboxed environment for safer execution |
| `--skip-trust` | - | boolean | `false` | Trust the current workspace for this session, skipping the folder trust check. |
| `--approval-mode` | - | string | `default` | Approval mode for tool execution. Choices: `default`, `auto_edit`, `yolo`, `plan` |
| `--yolo` | `-y` | boolean | `false` | **Deprecated.** Auto-approve all actions. Use `--approval-mode=yolo` instead. |
| `--experimental-acp` | - | boolean | - | Start in ACP (Agent Code Pilot) mode. **Experimental feature.** |
| `--experimental-zed-integration` | - | boolean | - | Run in Zed editor integration mode. **Experimental feature.** |
| `--allowed-mcp-server-names` | - | array | - | Allowed MCP server names (comma-separated or multiple flags) |
| `--allowed-tools` | - | array | - | **Deprecated.** Use the [Policy Engine](../reference/policy-engine.md) instead. Tools that are allowed to run without confirmation (comma-separated or multiple flags) |
| `--extensions` | `-e` | array | - | List of extensions to use. If not provided, all extensions are enabled (comma-separated or multiple flags) |
| `--list-extensions` | `-l` | boolean | - | List all available extensions and exit |
| `--resume` | `-r` | string | - | Resume a previous session. Use `"latest"` for most recent or index number (for example `--resume 5`) |
| `--list-sessions` | - | boolean | - | List available sessions for the current project and exit |
| `--delete-session` | - | string | - | Delete a session by index number (use `--list-sessions` to see available sessions) |
| `--include-directories` | - | array | - | Additional directories to include in the workspace (comma-separated or multiple flags) |
| `--screen-reader` | - | boolean | - | Enable screen reader mode for accessibility |
| `--output-format` | `-o` | string | `text` | The format of the CLI output. Choices: `text`, `json`, `stream-json` |
## Model selection
The `--model` (or `-m`) flag lets you specify which Gemini model to use. You can
use either model aliases (user-friendly names) or concrete model names.
### Model aliases
These are convenient shortcuts that map to specific models:
| Alias | Resolves To | Description |
| ------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `auto` | `gemini-2.5-pro` or `gemini-3-pro-preview` | **Default.** Resolves to the preview model if preview features are enabled, otherwise resolves to the standard pro model. |
| `pro` | `gemini-2.5-pro` or `gemini-3-pro-preview` | For complex reasoning tasks. Uses preview model if enabled. |
| `flash` | `gemini-2.5-flash` | Fast, balanced model for most tasks. |
| `flash-lite` | `gemini-2.5-flash-lite` | Fastest model for simple tasks. |
## Extensions management
| Command | Description | Example |
| -------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------ |
| `gemini extensions install <source>` | Install extension from Git URL or local path | `gemini extensions install https://github.com/user/my-extension` |
| `gemini extensions install <source> --ref <ref>` | Install from specific branch/tag/commit | `gemini extensions install https://github.com/user/my-extension --ref develop` |
| `gemini extensions install <source> --auto-update` | Install with auto-update enabled | `gemini extensions install https://github.com/user/my-extension --auto-update` |
| `gemini extensions uninstall <name>` | Uninstall one or more extensions | `gemini extensions uninstall my-extension` |
| `gemini extensions list` | List all installed extensions | `gemini extensions list` |
| `gemini extensions update <name>` | Update a specific extension | `gemini extensions update my-extension` |
| `gemini extensions update --all` | Update all extensions | `gemini extensions update --all` |
| `gemini extensions enable <name>` | Enable an extension | `gemini extensions enable my-extension` |
| `gemini extensions disable <name>` | Disable an extension | `gemini extensions disable my-extension` |
| `gemini extensions link <path>` | Link local extension for development | `gemini extensions link /path/to/extension` |
| `gemini extensions new <path>` | Create new extension from template | `gemini extensions new ./my-extension` |
| `gemini extensions validate <path>` | Validate extension structure | `gemini extensions validate ./my-extension` |
See [Extensions Documentation](../extensions/index.md) for more details.
## MCP server management
| Command | Description | Example |
| ------------------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `gemini mcp add <name> <command>` | Add stdio-based MCP server | `gemini mcp add github npx -y @modelcontextprotocol/server-github` |
| `gemini mcp add <name> <url> --transport http` | Add HTTP-based MCP server | `gemini mcp add api-server http://localhost:3000 --transport http` |
| `gemini mcp add <name> <command> --env KEY=value` | Add with environment variables | `gemini mcp add slack node server.js --env SLACK_TOKEN=xoxb-xxx` |
| `gemini mcp add <name> <command> --scope user` | Add with user scope | `gemini mcp add db node db-server.js --scope user` |
| `gemini mcp add <name> <command> --include-tools tool1,tool2` | Add with specific tools | `gemini mcp add github npx -y @modelcontextprotocol/server-github --include-tools list_repos,get_pr` |
| `gemini mcp remove <name>` | Remove an MCP server | `gemini mcp remove github` |
| `gemini mcp list` | List all configured MCP servers | `gemini mcp list` |
See [MCP Server Integration](../tools/mcp-server.md) for more details.
## Skills management
| Command | Description | Example |
| -------------------------------- | ------------------------------------- | ------------------------------------------------- |
| `gemini skills list` | List all discovered agent skills | `gemini skills list` |
| `gemini skills install <source>` | Install skill from Git, path, or file | `gemini skills install https://github.com/u/repo` |
| `gemini skills link <path>` | Link local agent skills via symlink | `gemini skills link /path/to/my-skills` |
| `gemini skills uninstall <name>` | Uninstall an agent skill | `gemini skills uninstall my-skill` |
| `gemini skills enable <name>` | Enable an agent skill | `gemini skills enable my-skill` |
| `gemini skills disable <name>` | Disable an agent skill | `gemini skills disable my-skill` |
| `gemini skills enable --all` | Enable all skills | `gemini skills enable --all` |
| `gemini skills disable --all` | Disable all skills | `gemini skills disable --all` |
See [Agent Skills Documentation](./skills.md) for more details.
+207
View File
@@ -0,0 +1,207 @@
# Creating Agent Skills
Agent Skills let you extend Gemini CLI with specialized expertise, procedural
workflows, and task-specific resources. This guide walks you through both
automated and manual methods for creating and organizing your skills.
## Quickstart: Create a skill with a prompt
The fastest way to create a new skill is to use the built-in `skill-creator`.
This meta-skill guides you through designing, scaffolding, and validating your
expertise.
Simply ask Gemini CLI to create a skill for you:
> "Create a new skill called 'code-reviewer' that analyzes local files for
> common errors and style violations."
Gemini will then:
1. Generate a new directory for your skill (for example, `my-new-skill/`).
2. Create a `SKILL.md` file with the necessary YAML frontmatter (`name` and
`description`).
3. Create the standard resource directories: `scripts/`, `references/`, and
`assets/`.
Once created, you can find your new skill in `.gemini/skills/code-reviewer/`.
## Manual creation
1. **Create a directory** for your skill (for example, `my-new-skill/`).
2. **Create a `SKILL.md` file** inside the new directory.
### 1. Create the directory structure
The first step is to create the necessary folders for your skill and its
scripts.
**macOS/Linux**
```bash
mkdir -p .gemini/skills/code-reviewer/scripts
```
**Windows (PowerShell)**
```powershell
New-Item -ItemType Directory -Force -Path ".gemini\skills\code-reviewer\scripts"
```
### 2. Define the skill (`SKILL.md`)
The `SKILL.md` file defines the skill's purpose and instructions for the agent.
Create a file at `.gemini/skills/code-reviewer/SKILL.md`.
```markdown
---
name: code-reviewer
description:
Expertise in reviewing code changes for correctness, security, and style. Use
when the user asks to "review" their code or a PR.
---
# Code Reviewer Instructions
You act as a senior software engineer specialized in code quality. When this
skill is active, you MUST:
1. **Analyze**: Review the provided code for logical errors, security
vulnerabilities, and style violations.
2. **Review**: Use the bundled `scripts/review.js` utility to perform an
automated check.
3. **Feedback**: Provide constructive feedback, clearly distinguishing between
critical issues and minor improvements.
```
### 3. Add the tool logic
Skills can bundle resources like scripts to perform deterministic tasks. Create
a file at `.gemini/skills/code-reviewer/scripts/review.js`.
```javascript
// .gemini/skills/code-reviewer/scripts/review.js
const file = process.argv[2];
if (!file) {
console.error('Usage: node review.js <file>');
process.exit(1);
}
console.log(`Reviewing ${file}...`);
// Simple mock review logic
setTimeout(() => {
console.log(`Result: Success (No major issues found in ${file})`);
}, 500);
```
### 4. Test the skill
Gemini CLI automatically discovers skills in the `.gemini/skills` directory.
1. Start a new session and ask a question that triggers the skill's
description: "Can you review index.js"
2. Gemini identifies the request matches the `code-reviewer` description and
asks for permission to activate it.
3. Once you approve, Gemini executes the bundled script:
`node .gemini/skills/code-reviewer/scripts/review.js index.js`
To determine whether your skill has been correctly loaded, run the command:
```bash
/skills
```
### 5. Optional: Share your skill
You can share your skills in several ways depending on your target audience.
- **Workspace skills**: Commit your skill to a `.gemini/skills/` directory in
your project repository.
- **Extensions**: Bundle your skill within a
[Gemini CLI extension](../extensions/writing-extensions.md).
- **Git repositories**: Share the skill directory as a standalone Git repo and
install it using `gemini skills install <url>`.
---
## Core concepts
Now that you've built your first skill, let's explore the core components and
workflows for developing more complex expertise.
### Skill structure
While a `SKILL.md` file is the only required component, we recommend the
following structure for organizing your skill's resources.
```text
my-skill/
├── SKILL.md (Required) Instructions and metadata
├── scripts/ (Optional) Executable scripts
├── references/ (Optional) Static documentation
└── assets/ (Optional) Templates and other resources
```
When a skill is activated, the model is granted access to this entire directory.
You can instruct the model to use the tools and files found within these
folders.
### Metadata and triggers
The `SKILL.md` file uses YAML frontmatter for metadata.
- **`name`**: A unique identifier for the skill. This should match the directory
name.
- **`description`**: **CRITICAL.** This is how Gemini decides when to use the
skill. Be specific about the tasks it handles and the keywords that should
trigger it.
### Discovery tiers
Gemini CLI discovers skills from several locations, following a specific order
of precedence (lowest to highest):
1. **Built-in Skills**: Included with Gemini CLI (pre-approved).
2. **Extension Skills**: Bundled within [extensions](../extensions/).
3. **User Skills**: `~/.gemini/skills/` or the `~/.agents/skills/` alias.
4. **Workspace Skills**: `.gemini/skills/` or the `.agents/skills/` alias.
### Discovery aliases
You can use `.agents/skills` as an alternative to `.gemini/skills`. This alias
is compatible with other AI agent tools following the
[Agent Skills](https://agentskills.io) standard.
## Advanced development
Once you've built a basic skill, you can use specialized scripts and workflows
to streamline your development process.
### Creation scripts
If you are developing a skill and want to use the same scripts the built-in
tools use, you can find them in the core package. These scripts help automate
the initialization, validation, and packaging of skills.
- **Initialize**: `node scripts/init_skill.cjs <name> --path <dir>`
- **Validate**: `node scripts/validate_skill.cjs <path/to/skill>`
- **Package**: `node scripts/package_skill.cjs <path/to/skill>` (Creates a
`.skill` zip file)
### Linking for local development
If you are developing a skill in a separate directory, you can link it to your
user skills directory for testing:
```bash
gemini skills link .
```
## Next steps
- [Skill best practices](./skills-best-practices.md): Learn strategies for
building reliable and effective skills.
- [Agent Skills overview](./skills.md): Deep dive into discovery tiers and the
skill lifecycle.
- [Get started with Agent Skills](./tutorials/skills-getting-started.md): A
quick walkthrough of triggering and using skills.
+331
View File
@@ -0,0 +1,331 @@
# 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.
## 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.
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 (`:`).
- 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`.
<!-- prettier-ignore -->
> [!TIP]
> After creating or modifying `.toml` command files, run
> `/commands reload` to pick up your changes without restarting the CLI.
> To see all available command files, run `/commands list`.
## TOML file format (v1)
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.
### 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.**
## 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`.
### 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.
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.
**Example (`git/fix.toml`):**
```toml
# Invoked via: /git:fix "Button is misaligned"
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".`
**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 lets you safely
pass arguments to shell commands, ensuring the resulting command is
syntactically correct and secure while preventing command injection
vulnerabilities.
**Example (`/grep-code.toml`):**
```toml
prompt = """
Please summarize the findings for the pattern `{{args}}`.
Search Results:
!{grep -r {{args}} .}
"""
```
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 (for
example, 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 you provide arguments to the command (for example, `/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 (for example, `/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.
```toml
# In: <project>/.gemini/commands/changelog.toml
# Invoked via: /changelog 1.2.0 added "Support for default argument parsing."
description = "Adds a new entry to the project's CHANGELOG.md file."
prompt = """
# Task: Update Changelog
You are an expert maintainer of this software project. A user has invoked a command to add a new entry to the changelog.
**The user's raw command is appended below your instructions.**
Your task is to parse the `<version>`, `<change_type>`, and `<message>` from their input and use the `write_file` tool to correctly update the `CHANGELOG.md` file.
## Expected Format
The command follows this format: `/changelog <version> <type> <message>`
- `<type>` must be one of: "added", "changed", "fixed", "removed".
## Behavior
1. Read the `CHANGELOG.md` file.
2. Find the section for the specified `<version>`.
3. Add the `<message>` under the correct `<type>` heading.
4. If the version or type section doesn't exist, create it.
5. Adhere strictly to the "Keep a Changelog" format.
"""
```
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.
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. 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, for example,
`[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.
````toml
# In: <project>/.gemini/commands/git/commit.toml
# Invoked via: /git:commit
description = "Generates a Git commit message based on staged changes."
# The prompt uses !{...} to execute the command and inject its output.
prompt = """
Please generate a Conventional Commit message based on the following git diff:
```diff
!{git diff --staged}
```
"""
````
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.
**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 (for example,
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.
```toml
# In: <project>/.gemini/commands/review.toml
# Invoked via: /review FileCommandLoader.ts
description = "Reviews the provided context using a best practice guide."
prompt = """
You are an expert code reviewer.
Your task is to review {{args}}.
Use the following best practices when providing your review:
@{docs/best-practices.md}
"""
```
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.
---
## Example: A "Pure Function" refactoring command
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.
**macOS/Linux**
```bash
mkdir -p ~/.gemini/commands/refactor
touch ~/.gemini/commands/refactor/pure.toml
```
**Windows (PowerShell)**
```powershell
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.gemini\commands\refactor"
New-Item -ItemType File -Force -Path "$env:USERPROFILE\.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.
```toml
# In: ~/.gemini/commands/refactor/pure.toml
# This command will be invoked via: /refactor:pure
description = "Asks the model to refactor the current context into a pure function."
prompt = """
Please analyze the code I've provided in the current context.
Refactor it into a pure function.
Your response should include:
1. The refactored, pure function code block.
2. A brief explanation of the key changes you made and why they contribute to purity.
"""
```
**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:
```
> @my-messy-function.js
> /refactor:pure
```
Gemini CLI will then execute the multi-line prompt defined in your TOML file.
+613
View File
@@ -0,0 +1,613 @@
# 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.
<!-- prettier-ignore -->
> [!WARNING]
> 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](../reference/configuration.md).
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.
**Example of merging and precedence:**
Here is how settings from different levels are combined.
- **System defaults `system-defaults.json`:**
```json
{
"ui": {
"theme": "default-corporate-theme"
},
"context": {
"includeDirectories": ["/etc/gemini-cli/common-context"]
}
}
```
- **User `settings.json` (`~/.gemini/settings.json`):**
```json
{
"ui": {
"theme": "user-preferred-dark-theme"
},
"mcpServers": {
"corp-server": {
"command": "/usr/local/bin/corp-server-dev"
},
"user-tool": {
"command": "npm start --prefix ~/tools/my-tool"
}
},
"context": {
"includeDirectories": ["~/gemini-context"]
}
}
```
- **Workspace `settings.json` (`<project>/.gemini/settings.json`):**
```json
{
"ui": {
"theme": "project-specific-light-theme"
},
"mcpServers": {
"project-tool": {
"command": "npm start"
}
},
"context": {
"includeDirectories": ["./project-context"]
}
}
```
- **System overrides `settings.json`:**
```json
{
"ui": {
"theme": "system-enforced-theme"
},
"mcpServers": {
"corp-server": {
"command": "/usr/local/bin/corp-server-prod"
}
},
"context": {
"includeDirectories": ["/etc/gemini-cli/global-context"]
}
}
```
This results in the following merged configuration:
- **Final merged configuration:**
```json
{
"ui": {
"theme": "system-enforced-theme"
},
"mcpServers": {
"corp-server": {
"command": "/usr/local/bin/corp-server-prod"
},
"user-tool": {
"command": "npm start --prefix ~/tools/my-tool"
},
"project-tool": {
"command": "npm start"
}
},
"context": {
"includeDirectories": [
"/etc/gemini-cli/common-context",
"~/gemini-context",
"./project-context",
"/etc/gemini-cli/global-context"
]
}
}
```
**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.
- **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.
By using the system settings file, you can enforce the security and
configuration patterns described below.
### Enforcing system settings with a wrapper script
While the `GEMINI_CLI_SYSTEM_SETTINGS_PATH` environment variable provides
flexibility, a user could potentially override it to point to a different
settings file, bypassing the centrally managed configuration. To mitigate this,
enterprises can deploy a wrapper script or alias that ensures the environment
variable is always set to the corporate-controlled path.
This approach ensures that no matter how the user calls the `gemini` command,
the enterprise settings are always loaded with the highest precedence.
**Example wrapper script:**
Administrators can create a script named `gemini` and place it in a directory
that appears earlier in the user's `PATH` than the actual Gemini CLI binary (for
example, `/usr/local/bin/gemini`).
```bash
#!/bin/bash
# Enforce the path to the corporate system settings file.
# This ensures that the company's configuration is always applied.
export GEMINI_CLI_SYSTEM_SETTINGS_PATH="/etc/gemini-cli/settings.json"
# Find the original gemini executable.
# This is a simple example; a more robust solution might be needed
# depending on the installation method.
REAL_GEMINI_PATH=$(type -aP gemini | grep -v "^$(type -P gemini)$" | head -n 1)
if [ -z "$REAL_GEMINI_PATH" ]; then
echo "Error: The original 'gemini' executable was not found." >&2
exit 1
fi
# Pass all arguments to the real Gemini CLI executable.
exec "$REAL_GEMINI_PATH" "$@"
```
By deploying this script, the `GEMINI_CLI_SYSTEM_SETTINGS_PATH` is set within
the script's environment, and the `exec` command replaces the script process
with the actual Gemini CLI process, which inherits the environment variable.
This makes it significantly more difficult for a user to bypass the enforced
settings.
**PowerShell Profile (Windows alternative):**
On Windows, administrators can achieve similar results by adding the environment
variable to the system-wide or user-specific PowerShell profile:
```powershell
Add-Content -Path $PROFILE -Value '$env:GEMINI_CLI_SYSTEM_SETTINGS_PATH="C:\ProgramData\gemini-cli\settings.json"'
```
## User isolation in shared environments
In shared compute environments (like ML experiment runners or shared build
servers), you can isolate Gemini CLI state by overriding the user's home
directory.
By default, Gemini CLI stores configuration and history in `~/.gemini`. You can
use the `GEMINI_CLI_HOME` environment variable to point to a unique directory
for a specific user or job. The CLI will create a `.gemini` folder inside the
specified path.
**macOS/Linux**
```bash
# Isolate state for a specific job
export GEMINI_CLI_HOME="/tmp/gemini-job-123"
gemini
```
**Windows (PowerShell)**
```powershell
# Isolate state for a specific job
$env:GEMINI_CLI_HOME="C:\temp\gemini-job-123"
gemini
```
## Restricting tool access
You can significantly enhance security by controlling which tools the Gemini
model can use. This is achieved through the `tools.core` setting and the
[Policy Engine](../reference/policy-engine.md). For a list of available tools,
see the [Tools reference](../reference/tools.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.
**Example:** Allow only safe, read-only file operations and listing files.
```json
{
"tools": {
"core": ["ReadFileTool", "GlobTool", "ShellTool(ls)"]
}
}
```
### Blocklisting with `excludeTools` (Deprecated)
> **Deprecated:** Use the [Policy Engine](../reference/policy-engine.md) for
> more robust control.
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.
```json
{
"tools": {
"exclude": ["ShellTool(rm -rf)"]
}
}
```
<!-- prettier-ignore -->
> [!WARNING]
> Blocklisting with `excludeTools` is less secure than
> allowlisting with `tools.core`, 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.**
### Disabling YOLO mode
To ensure that users cannot bypass the confirmation prompt for tool execution,
you can disable YOLO mode at the policy level. This adds a critical layer of
safety, as it prevents the model from executing tools without explicit user
approval.
**Example:** Force all tool executions to require user confirmation.
```json
{
"security": {
"disableYoloMode": true
}
}
```
This setting is highly recommended in an enterprise environment to prevent
unintended tool execution.
## Managing custom tools (MCP servers)
If your organization uses custom tools via
[Model-Context Protocol (MCP) servers](../tools/mcp-server.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**:
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 (for example, 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.
### 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.
### 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 lets you 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.
**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
{
"mcp": {
"allowed": ["third-party-analyzer"]
},
"mcpServers": {
"third-party-analyzer": {
"command": "/usr/local/bin/start-3p-analyzer.sh",
"includeTools": ["code-search", "get-ticket-details"]
}
}
}
```
#### 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:
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.
2. Provide the canonical _definition_ for each server on the allowlist.
```json
{
"mcp": {
"allowed": ["corp-data-api", "source-code-analyzer"]
},
"mcpServers": {
"corp-data-api": {
"command": "/usr/local/bin/start-corp-api.sh",
"timeout": 5000
},
"source-code-analyzer": {
"command": "/usr/local/bin/start-analyzer.sh"
}
}
}
```
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.
**Example system `settings.json`:**
This configuration defines servers but does not enforce the allowlist. The
administrator has NOT included the "mcp.allowed" setting.
```json
{
"mcpServers": {
"corp-data-api": {
"command": "/usr/local/bin/start-corp-api.sh"
}
}
}
```
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.
**Example:** Force all tool execution to happen within a Docker sandbox.
```json
{
"tools": {
"sandbox": "docker"
}
}
```
You can also specify a custom, hardened Docker image for the sandbox 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.
**Example (for an MCP server):**
```json
{
"mcpServers": {
"proxied-server": {
"command": "node",
"args": ["mcp_server.js"],
"env": {
"HTTP_PROXY": "http://proxy.example.com:8080",
"HTTPS_PROXY": "http://proxy.example.com:8080"
}
}
}
}
```
## Telemetry and auditing
For auditing and monitoring purposes, you can configure Gemini CLI to send
telemetry data to a central location. This lets you 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`.
```json
{
"telemetry": {
"enabled": true,
"target": "gcp",
"logPrompts": false
}
}
```
<!-- prettier-ignore -->
> [!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
`security.auth.enforcedType` in the system-level `settings.json` file. This
prevents users from choosing a different authentication method. See the
[Authentication docs](../get-started/authentication.mdx) for more details.
**Example:** Enforce the use of Google login for all users.
```json
{
"security": {
"auth": {
"enforcedType": "oauth-personal"
}
}
}
```
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.
### Restricting logins to corporate domains
For enterprises using Google Workspace, you can enforce that users only
authenticate with their corporate Google accounts. This is a network-level
control that is configured on a proxy server, not within Gemini CLI itself. It
works by intercepting authentication requests to Google and adding a special
HTTP header.
This policy prevents users from logging in with personal Gmail accounts or other
non-corporate Google accounts.
For detailed instructions, see the Google Workspace Admin Help article on
[blocking access to consumer accounts](https://support.google.com/a/answer/1668854?hl=en#zippy=%2Cstep-choose-a-web-proxy-server%2Cstep-configure-the-network-to-block-certain-accounts).
The general steps are as follows:
1. **Intercept Requests**: Configure your web proxy to intercept all requests
to `google.com`.
2. **Add HTTP Header**: For each intercepted request, add the
`X-GoogApps-Allowed-Domains` HTTP header.
3. **Specify Domains**: The value of the header should be a comma-separated
list of your approved Google Workspace domain names.
**Example header:**
```
X-GoogApps-Allowed-Domains: my-corporate-domain.com, secondary-domain.com
```
When this header is present, Google's authentication service will only allow
logins from accounts belonging to the specified domains.
## 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.
```json
{
"tools": {
"sandbox": "docker",
"core": [
"ReadFileTool",
"GlobTool",
"ShellTool(ls)",
"ShellTool(cat)",
"ShellTool(grep)"
]
},
"mcp": {
"allowed": ["corp-tools"]
},
"mcpServers": {
"corp-tools": {
"command": "/opt/gemini-tools/start.sh",
"timeout": 5000
}
},
"telemetry": {
"enabled": true,
"target": "gcp",
"otlpEndpoint": "https://telemetry-prod.example.com:4317",
"logPrompts": false
},
"advanced": {
"bugCommand": {
"urlTemplate": "https://servicedesk.example.com/new-ticket?title={title}&details={info}"
}
},
"privacy": {
"usageStatisticsEnabled": false
}
}
```
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.
- 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.
- Disables general usage statistics collection.
+71
View File
@@ -0,0 +1,71 @@
# Ignoring files
This document provides an overview of the Gemini Ignore (`.geminiignore`)
feature of Gemini CLI.
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 `@` command to share files, any paths in your `.geminiignore`
file will be automatically excluded.
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.
- `!` negates a pattern.
You can update your `.geminiignore` file at any time. To apply the changes, you
must restart your Gemini CLI session.
## How to use `.geminiignore`
To enable `.geminiignore`:
1. Create a file named `.geminiignore` in the root of your project directory.
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`.
### `.geminiignore` examples
You can use `.geminiignore` to ignore directories and files:
```
# Exclude your /packages/ directory and all subdirectories
/packages/
# Exclude your apikeys.txt file
apikeys.txt
```
You can use wildcards in your `.geminiignore` file with `*`:
```
# Exclude all .md files
*.md
```
Finally, you can exclude files and directories from exclusion with `!`:
```
# Exclude all .md files except README.md
*.md
!README.md
```
To remove paths from your `.geminiignore` file, delete the relevant lines.
+116
View File
@@ -0,0 +1,116 @@
# 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.
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:
1. **Global context file:**
- **Location:** `~/.gemini/GEMINI.md` (in your user home directory).
- **Scope:** Provides default instructions for all your projects.
2. **Environment and workspace context files:**
- **Location:** The CLI searches for `GEMINI.md` files in your configured
workspace directories and their parent directories.
- **Scope:** Provides context relevant to the projects you are currently
working on.
3. **Just-in-time (JIT) context files:**
- **Location:** When a tool accesses a file or directory, the CLI
automatically scans for `GEMINI.md` files in that directory and its
ancestors up to a trusted root.
- **Scope:** Lets the model discover highly specific instructions for
particular components only when they are needed.
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:
```markdown
# Project: My TypeScript Library
## General Instructions
- When you generate new TypeScript code, follow the existing coding style.
- Ensure all new functions and classes have JSDoc comments.
- Prefer functional programming paradigms where appropriate.
## Coding Style
- Use 2 spaces for indentation.
- Prefix interface names with `I` (for example, `IUserService`).
- Always use strict equality (`===` and `!==`).
```
## Manage context with the `/memory` command
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 reload`**: Forces a re-scan and reload of all `GEMINI.md` files
from all configured locations.
## 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.
**Example `GEMINI.md` with imports:**
```markdown
# Main GEMINI.md file
This is the main content.
@./components/instructions.md
More content here.
@../shared/style-guide.md
```
For more details, see the [Memory Import Processor](../reference/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.
**Example `settings.json`:**
```json
{
"context": {
"fileName": ["AGENTS.md", "CONTEXT.md", "GEMINI.md"]
}
}
```
## Next steps
- Learn about [Ignoring files](./gemini-ignore.md) to exclude content from the
context system.
- Explore the [Memory tool](../tools/memory.md) to save persistent memories.
- See how to use [Custom commands](./custom-commands.md) to automate common
prompts.
+212
View File
@@ -0,0 +1,212 @@
# Advanced Model Configuration
This guide details the Model Configuration system within Gemini CLI. Designed
for researchers, AI quality engineers, and advanced users, this system provides
a rigorous framework for managing generative model hyperparameters and
behaviors.
<!-- prettier-ignore -->
> [!WARNING]
> This is a power-user feature. Configuration values are passed
> directly to the model provider with minimal validation. Incorrect settings
> (for example, incompatible parameter combinations) may result in runtime
> errors from the API.
## 1. System Overview
The Model Configuration system (`ModelConfigService`) enables deterministic
control over model generation. It decouples the requested model identifier (for
example, a CLI flag or agent request) from the underlying API configuration.
This allows for:
- **Precise Hyperparameter Tuning**: Direct control over `temperature`, `topP`,
`thinkingBudget`, and other SDK-level parameters.
- **Environment-Specific Behavior**: Distinct configurations for different
operating contexts (for example, testing vs. production).
- **Agent-Scoped Customization**: Applying specific settings only when a
particular agent is active.
The system operates on two core primitives: **Aliases** and **Overrides**.
## 2. Configuration Primitives
These settings are located under the `modelConfigs` key in your configuration
file.
### Aliases (`customAliases`)
Aliases are named, reusable configuration presets. Users should define their own
aliases (or override system defaults) in the `customAliases` map.
- **Inheritance**: An alias can `extends` another alias (including system
defaults like `chat-base`), inheriting its `modelConfig`. Child aliases can
overwrite or augment inherited settings.
- **Abstract Aliases**: An alias is not required to specify a concrete `model`
if it serves purely as a base for other aliases.
**Example Hierarchy**:
```json
"modelConfigs": {
"customAliases": {
"base": {
"modelConfig": {
"generateContentConfig": { "temperature": 0.0 }
}
},
"chat-base": {
"extends": "base",
"modelConfig": {
"generateContentConfig": { "temperature": 0.7 }
}
}
}
}
```
### Overrides (`overrides`)
Overrides are conditional rules that inject configuration based on the runtime
context. They are evaluated dynamically for each model request.
- **Match Criteria**: Overrides apply when the request context matches the
specified `match` properties.
- `model`: Matches the requested model name or alias.
- `overrideScope`: Matches the distinct scope of the request (typically the
agent name, for example, `codebaseInvestigator`).
**Example Override**:
```json
"modelConfigs": {
"overrides": [
{
"match": {
"overrideScope": "codebaseInvestigator"
},
"modelConfig": {
"generateContentConfig": { "temperature": 0.1 }
}
}
]
}
```
## 3. Resolution Strategy
The `ModelConfigService` resolves the final configuration through a two-step
process:
### Step 1: Alias Resolution
The requested model string is looked up in the merged map of system `aliases`
and user `customAliases`.
1. If found, the system recursively resolves the `extends` chain.
2. Settings are merged from parent to child (child wins).
3. This results in a base `ResolvedModelConfig`.
4. If not found, the requested string is treated as the raw model name.
### Step 2: Override Application
The system evaluates the `overrides` list against the request context (`model`
and `overrideScope`).
1. **Filtering**: All matching overrides are identified.
2. **Sorting**: Matches are prioritized by **specificity** (the number of
matched keys in the `match` object).
- Specific matches (for example, `model` + `overrideScope`) override broad
matches (for example, `model` only).
- Tie-breaking: If specificity is equal, the order of definition in the
`overrides` array is preserved (last one wins).
3. **Merging**: The configurations from the sorted overrides are merged
sequentially onto the base configuration.
## 4. Configuration Reference
The configuration follows the `ModelConfigServiceConfig` interface.
### `ModelConfig` Object
Defines the actual parameters for the model.
| Property | Type | Description |
| :---------------------- | :------- | :------------------------------------------------------------------------ |
| `model` | `string` | The identifier of the model to be called (for example, `gemini-2.5-pro`). |
| `generateContentConfig` | `object` | The configuration object passed to the `@google/genai` SDK. |
### `GenerateContentConfig` (Common Parameters)
Directly maps to the SDK's `GenerateContentConfig`. Common parameters include:
- **`temperature`**: (`number`) Controls output randomness. Lower values (0.0)
are deterministic; higher values (>0.7) are creative.
- **`topP`**: (`number`) Nucleus sampling probability.
- **`maxOutputTokens`**: (`number`) Limit on generated response length.
- **`thinkingConfig`**: (`object`) Configuration for models with reasoning
capabilities (for example, `thinkingBudget`, `includeThoughts`).
## 5. Practical Examples
### Defining a Deterministic Baseline
Create an alias for tasks requiring high precision, extending the standard chat
configuration but enforcing zero temperature.
```json
"modelConfigs": {
"customAliases": {
"precise-mode": {
"extends": "chat-base",
"modelConfig": {
"generateContentConfig": {
"temperature": 0.0,
"topP": 1.0
}
}
}
}
}
```
### Agent-Specific Parameter Injection
Enforce extended thinking budgets for a specific agent without altering the
global default, for example for the `codebaseInvestigator`.
```json
"modelConfigs": {
"overrides": [
{
"match": {
"overrideScope": "codebaseInvestigator"
},
"modelConfig": {
"generateContentConfig": {
"thinkingConfig": { "thinkingBudget": 4096 }
}
}
}
]
}
```
### Experimental Model Evaluation
Route traffic for a specific alias to a preview model for A/B testing, without
changing client code.
```json
"modelConfigs": {
"overrides": [
{
"match": {
"model": "gemini-2.5-pro"
},
"modelConfig": {
"model": "gemini-2.5-pro-experimental-001"
}
}
]
}
```
+107
View File
@@ -0,0 +1,107 @@
# Git Worktrees (experimental)
When working on multiple tasks at once, you can use Git worktrees to give each
Gemini session its own copy of the codebase. Git worktrees create separate
working directories that each have their own files and branch while sharing the
same repository history. This prevents changes in one session from colliding
with another.
Learn more about [session management](./session-management.md).
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development. Your
> feedback is invaluable as we refine this feature. If you have ideas,
> suggestions, or encounter issues:
>
> - [Open an issue](https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.yml) on GitHub.
> - Use the **/bug** command within Gemini CLI to file an issue.
Learn more in the official Git worktree
[documentation](https://git-scm.com/docs/git-worktree).
## How to enable Git worktrees
Git worktrees are an experimental feature. You must enable them in your settings
using the `/settings` command or by manually editing your `settings.json` file.
1. Use the `/settings` command.
2. Search for and set **Enable Git Worktrees** to `true`.
Alternatively, add the following to your `settings.json`:
```json
{
"experimental": {
"worktrees": true
}
}
```
## How to use Git worktrees
Use the `--worktree` (`-w`) flag to create an isolated worktree and start Gemini
CLI in it.
- **Start with a specific name:** The value you pass becomes both the directory
name (within `.gemini/worktrees/`) and the branch name.
```bash
gemini --worktree feature-search
```
- **Start with a random name:** If you omit the name, Gemini generates a random
one automatically (for example, `worktree-a1b2c3d4`).
```bash
gemini --worktree
```
<!-- prettier-ignore -->
> [!NOTE]
> Remember to initialize your development environment in each new
> worktree according to your project's setup. Depending on your stack, this
> might include running dependency installation (`npm install`, `yarn`), setting
> up virtual environments, or following your project's standard build process.
## How to exit a Git worktree session
When you exit a worktree session (using `/quit` or `Ctrl+C`), Gemini leaves the
worktree intact so your work is not lost. This includes your uncommitted changes
(modified files, staged changes, or untracked files) and any new commits you
have made.
Gemini prioritizes a fast and safe exit: it **does not automatically delete**
your worktree or branch. You are responsible for cleaning up your worktrees
manually once you are finished with them.
When you exit, Gemini displays instructions on how to resume your work or how to
manually remove the worktree if you no longer need it.
## Resuming work in a Git worktree
To resume a session in a worktree, navigate to the worktree directory and start
Gemini CLI with the `--resume` flag and the session ID:
```bash
cd .gemini/worktrees/feature-search
gemini --resume <session_id>
```
## Managing Git worktrees manually
For more control over worktree location and branch configuration, or to clean up
a preserved worktree, you can use Git directly:
- **Clean up a preserved Git worktree:**
```bash
git worktree remove .gemini/worktrees/feature-search --force
git branch -D worktree-feature-search
```
- **Create a Git worktree manually:**
```bash
git worktree add ../project-feature-search -b feature-search
cd ../project-feature-search && gemini
```
[Open an issue]: https://github.com/google-gemini/gemini-cli/issues
+51
View File
@@ -0,0 +1,51 @@
# Headless mode reference
Headless mode provides a programmatic interface to Gemini CLI, returning
structured text or JSON output without an interactive terminal UI.
## Technical reference
Headless mode is triggered when the CLI is run in a non-TTY environment or when
providing a query with the `-p` (or `--prompt`) flag.
### Output formats
You can specify the output format using the `--output-format` flag.
#### JSON output
Returns a single JSON object containing the response and usage statistics.
- **Schema:**
- `response`: (string) The model's final answer.
- `stats`: (object) Token usage and API latency metrics.
- `error`: (object, optional) Error details if the request failed.
#### Streaming JSON output
Returns a stream of newline-delimited JSON (JSONL) events.
- **Event types:**
- `init`: Session metadata (session ID, model).
- `message`: User and assistant message chunks.
- `tool_use`: Tool call requests with arguments.
- `tool_result`: Output from executed tools.
- `error`: Non-fatal warnings and system errors.
- `result`: Final outcome with aggregated statistics and per-model token usage
breakdowns.
## Exit codes
The CLI returns standard exit codes to indicate the result of the headless
execution:
- `0`: Success.
- `1`: General error or API failure.
- `42`: Input error (invalid prompt or arguments).
- `53`: Turn limit exceeded.
## Next steps
- Follow the [Automation tutorial](./tutorials/automation.md) for practical
scripting examples.
- See the [CLI reference](./cli-reference.md) for all available flags.
+59
View File
@@ -0,0 +1,59 @@
# Model routing
Gemini CLI includes a model routing feature that automatically switches to a
fallback model in case of a model failure. This feature is enabled by default
and provides resilience when the primary model is unavailable.
## How it works
Model routing is managed by the `ModelAvailabilityService`, which monitors model
health and automatically routes requests to available models based on defined
policies.
1. **Model failure:** If the currently selected model fails (for example, due
to quota or server errors), the CLI will initiate the fallback process.
2. **User consent:** Depending on the failure and the model's policy, the CLI
may prompt you to switch to a fallback model (by default always prompts
you).
Some internal utility calls (such as prompt completion and classification)
use a silent fallback chain for `gemini-2.5-flash-lite` and will fall back
to `gemini-2.5-flash` and `gemini-2.5-pro` without prompting or changing the
configured model.
3. **Model switch:** If approved, or if the policy allows for silent fallback,
the CLI will use an available fallback model for the current turn or the
remainder of the session.
### Local Model Routing (Experimental)
Gemini CLI supports using a local model for routing decisions. When configured,
Gemini CLI will use a locally-running **Gemma** model to make routing decisions
(instead of sending routing decisions to a hosted model). This feature can help
reduce costs associated with hosted model usage while offering similar routing
decision latency and quality.
The easiest way to set this up is using the automated `gemini gemma setup`
command.
For more details on how to configure local model routing, see
[`gemini gemma` — Local Model Routing Setup](../core/gemma-setup.md).
### Model selection precedence
The model used by Gemini CLI is determined by the following order of precedence:
1. **`--model` command-line flag:** A model specified with the `--model` flag
when launching the CLI will always be used.
2. **`GEMINI_MODEL` environment variable:** If the `--model` flag is not used,
the CLI will use the model specified in the `GEMINI_MODEL` environment
variable.
3. **`model.name` in `settings.json`:** If neither of the above are set, the
model specified in the `model.name` property of your `settings.json` file
will be used.
4. **Local model (experimental):** If the Gemma local model router is enabled
in your `settings.json` file, the CLI will use the local Gemma model
(instead of Gemini models) to route the request to an appropriate model.
5. **Default model:** If none of the above are set, the default model will be
used. The default model is `auto`
+80
View File
@@ -0,0 +1,80 @@
# Model steering (experimental)
Model steering lets you provide real-time guidance and feedback to Gemini CLI
while it is actively executing a task. This lets you correct course, add missing
context, or skip unnecessary steps without having to stop and restart the agent.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
Model steering is particularly useful during complex [Plan Mode](./plan-mode.md)
workflows or long-running subagent executions where you want to ensure the agent
stays on the right track.
## Enabling model steering
Model steering is an experimental feature and is disabled by default. You can
enable it using the `/settings` command or by updating your `settings.json`
file.
1. Type `/settings` in Gemini CLI.
2. Search for **Model Steering**.
3. Set the value to **true**.
Alternatively, add the following to your `settings.json`:
```json
{
"experimental": {
"modelSteering": true
}
}
```
## Using model steering
When model steering is enabled, Gemini CLI treats any text you type while the
agent is working as a steering hint.
1. Start a task (for example, "Refactor the database service").
2. While the agent is working (the spinner is visible), type your feedback in
the input box.
3. Press **Enter**.
Gemini CLI acknowledges your hint with a brief message and injects it directly
into the model's context for the very next turn. The model then re-evaluates its
current plan and adjusts its actions accordingly.
### Common use cases
You can use steering hints to guide the model in several ways:
- **Correcting a path:** "Actually, the utilities are in `src/common/utils`."
- **Skipping a step:** "Skip the unit tests for now and just focus on the
implementation."
- **Adding context:** "The `User` type is defined in `packages/core/types.ts`."
- **Redirecting the effort:** "Stop searching the codebase and start drafting
the plan now."
- **Handling ambiguity:** "Use the existing `Logger` class instead of creating a
new one."
## How it works
When you submit a steering hint, Gemini CLI performs the following actions:
1. **Immediate acknowledgment:** It uses a small, fast model to generate a
one-sentence acknowledgment so you know your hint was received.
2. **Context injection:** It prepends an internal instruction to your hint that
tells the main agent to:
- Re-evaluate the active plan.
- Classify the update (for example, as a new task or extra context).
- Apply minimal-diff changes to affected tasks.
3. **Real-time update:** The hint is delivered to the agent at the beginning of
its next turn, ensuring the most immediate course correction possible.
## Next steps
- Tackle complex tasks with [Plan Mode](./plan-mode.md).
- Build custom [Agent Skills](./skills.md).
+55
View File
@@ -0,0 +1,55 @@
# Gemini CLI model selection (`/model` command)
Select your Gemini CLI model. The `/model` command lets you configure the model
used by Gemini CLI, giving you more control over your results. Use **Pro**
models for complex tasks and reasoning, **Flash** models for high speed results,
or the (recommended) **Auto** setting to choose the best model for your tasks.
<!-- prettier-ignore -->
> [!NOTE]
> The `/model` command (and the `--model` flag) does not override the
> model used by sub-agents. Consequently, even when using the `/model` flag you
> may see other models used in your model usage reports.
## How to use the `/model` command
Use the following command in Gemini CLI:
```
/model
```
Running this command will open a dialog with your options:
| Option | Description | Models |
| ----------------- | -------------------------------------------------------------- | -------------------------------------------- |
| Auto (Gemini 3) | Let the system choose the best Gemini 3 model for your task. | gemini-3-pro-preview, gemini-3-flash-preview |
| Auto (Gemini 2.5) | Let the system choose the best Gemini 2.5 model for your task. | gemini-2.5-pro, gemini-2.5-flash |
| Manual | Select a specific model. | Any available model. |
We recommend selecting one of the above **Auto** options. However, you can
select **Manual** to select a specific model from those available.
You can also use the `--model` flag to specify a particular Gemini model on
startup. For more details, refer to the
[configuration documentation](../reference/configuration.md).
Changes to these settings will be applied to all subsequent interactions with
Gemini CLI.
## Best practices for model selection
- **Default to Auto.** For most users, the _Auto_ option model provides a
balance between speed and performance, automatically selecting the correct
model based on the complexity of the task. Example: Developing a web
application could include a mix of complex tasks (building architecture and
scaffolding the project) and simple tasks (generating CSS).
- **Switch to Pro if you aren't getting the results you want.** If you think you
need your model to be a little "smarter," you can manually select Pro. Pro
will provide you with the highest levels of reasoning and creativity. Example:
A complex or multi-stage debugging task.
- **Switch to Flash or Flash-Lite if you need faster results.** If you need a
simple response quickly, Flash or Flash-Lite is the best option. Example:
Converting a JSON object to a YAML string.
+59
View File
@@ -0,0 +1,59 @@
# Notifications (experimental)
Gemini CLI can send system notifications to alert you when a session completes
or when it needs your attention, such as when it's waiting for you to approve a
tool call.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
Notifications are particularly useful when running long-running tasks or using
[Plan Mode](./plan-mode.md), letting you switch to other windows while Gemini
CLI works in the background.
## Requirements
### Terminal support
The CLI uses the OSC 9 terminal escape sequence to trigger system notifications.
This is supported by several modern terminal emulators including iTerm2,
WezTerm, Ghostty, and Kitty. If your terminal does not support OSC 9
notifications, Gemini CLI falls back to a terminal bell (BEL) to get your
attention. Most terminals respond to BEL with a taskbar flash or system alert
sound.
## Enable notifications
Notifications are disabled by default. You can enable them using the `/settings`
command or by updating your `settings.json` file.
1. Open the settings dialog by typing `/settings` in an interactive session.
2. Navigate to the **General** category.
3. Toggle the **Enable Notifications** setting to **On**.
Alternatively, add the following to your `settings.json`:
```json
{
"general": {
"enableNotifications": true
}
}
```
## Types of notifications
Gemini CLI sends notifications for the following events:
- **Action required:** Triggered when the model is waiting for user input or
tool approval. This helps you know when the CLI has paused and needs you to
intervene.
- **Session complete:** Triggered when a session finishes successfully. This is
useful for tracking the completion of automated tasks.
## Next steps
- Start planning with [Plan Mode](./plan-mode.md).
- Configure your experience with other [settings](./settings.md).
+509
View File
@@ -0,0 +1,509 @@
# Plan Mode
Plan Mode is a read-only environment for architecting robust solutions before
implementation. With Plan Mode, you can:
- **Research:** Explore the project in a read-only state to prevent accidental
changes.
- **Design:** Understand problems, evaluate trade-offs, and choose a solution.
- **Plan:** Align on an execution strategy before any code is modified.
Plan Mode is enabled by default. You can manage this setting using the
`/settings` command.
## How to enter Plan Mode
Plan Mode integrates seamlessly into your workflow, letting you switch between
planning and execution as needed.
You can either configure Gemini CLI to start in Plan Mode by default or enter
Plan Mode manually during a session.
### Launch in Plan Mode
To start Gemini CLI directly in Plan Mode by default:
1. Use the `/settings` command.
2. Set **Default Approval Mode** to `Plan`.
To launch Gemini CLI in Plan Mode once:
1. Use `gemini --approval-mode=plan` when launching Gemini CLI.
### Enter Plan Mode manually
To start Plan Mode while using Gemini CLI:
- **Keyboard shortcut:** Press `Shift+Tab` to cycle through approval modes
(`Default` -> `Auto-Edit` -> `Plan`). Plan Mode is automatically removed from
the rotation when Gemini CLI is actively processing or showing confirmation
dialogs.
- **Command:** Type `/plan [goal]` in the input box. The `[goal]` is optional;
for example, `/plan implement authentication` will switch to Plan Mode and
immediately submit the prompt to the model.
- **Natural Language:** Ask Gemini CLI to "start a plan for...". Gemini CLI
calls the
[`enter_plan_mode`](../tools/planning.md#1-enter_plan_mode-enterplanmode) tool
to switch modes. This tool is not available when Gemini CLI is in
[YOLO mode](../reference/configuration.md#command-line-arguments).
## How to use Plan Mode
Plan Mode lets you collaborate with Gemini CLI to design a solution before
Gemini CLI takes action.
1. **Provide a goal:** Start by describing what you want to achieve. Gemini CLI
will then enter Plan Mode (if it's not already) to research the task.
2. **Discuss and agree on strategy:** As Gemini CLI analyzes your codebase, it
will discuss its findings and proposed strategy with you to ensure
alignment. It may ask you questions or present different implementation
options using [`ask_user`](../tools/ask-user.md). **Gemini CLI will stop and
wait for your confirmation** before drafting the formal plan. You should
reach an informal agreement on the approach before proceeding.
3. **Review the plan:** Once you've agreed on the strategy, Gemini CLI creates
a detailed implementation plan as a Markdown file in your plans directory.
- **View:** You can open and read this file to understand the proposed
changes.
- **Edit:** Press `Ctrl+X` to open the plan directly in your configured
external editor.
4. **Approve or iterate:** Gemini CLI will present the finalized plan for your
formal approval.
- **Approve:** If you're satisfied with the plan, approve it to start the
implementation immediately: **Yes, automatically accept edits** or **Yes,
manually accept edits**.
- **Iterate:** If the plan needs adjustments, provide feedback in the input
box or [edit the plan file directly](#collaborative-plan-editing). Gemini
CLI will refine the strategy and update the plan.
- **Cancel:** You can cancel your plan with `Esc`.
For more complex or specialized planning tasks, you can
[customize the planning workflow with skills](#custom-planning-with-skills).
### Collaborative plan editing
You can collaborate with Gemini CLI by making direct changes or leaving comments
in the implementation plan. This is often faster and more precise than
describing complex changes in natural language.
1. **Open the plan:** Press `Ctrl+X` when Gemini CLI presents a plan for
review.
2. **Edit or comment:** The plan opens in your configured external editor (for
example, VS Code or Vim). You can:
- **Modify steps:** Directly reorder, delete, or rewrite implementation
steps.
- **Leave comments:** Add inline questions or feedback (for example, "Wait,
shouldn't we use the existing `Logger` class here?").
3. **Save and close:** Save your changes and close the editor.
4. **Review and refine:** Gemini CLI automatically detects the changes, reviews
your comments, and adjusts the implementation strategy. It then presents the
refined plan for your final approval.
## How to exit Plan Mode
You can exit Plan Mode at any time, whether you have finalized a plan or want to
switch back to another mode.
- **Approve a plan:** When Gemini CLI presents a finalized plan, approving it
automatically exits Plan Mode and starts the implementation.
- **Keyboard shortcut:** Press `Shift+Tab` to cycle to the desired mode.
- **Natural language:** Ask Gemini CLI to "exit plan mode" or "stop planning."
## Tool Restrictions
Plan Mode enforces strict safety policies to prevent accidental changes.
These are the only allowed tools:
- **FileSystem (Read):**
[`read_file`](../tools/file-system.md#2-read_file-readfile),
[`list_directory`](../tools/file-system.md#1-list_directory-readfolder),
[`glob`](../tools/file-system.md#4-glob-findfiles)
- **Search:** [`grep_search`](../tools/file-system.md#5-grep_search-searchtext),
[`google_web_search`](../tools/web-search.md),
[`web_fetch`](../tools/web-fetch.md) (requires explicit confirmation),
[`get_internal_docs`](../tools/internal-docs.md)
- **Research Subagents:**
[`codebase_investigator`](../core/subagents.md#codebase-investigator),
[`cli_help`](../core/subagents.md#cli-help-agent)
- **Interaction:** [`ask_user`](../tools/ask-user.md)
- **MCP tools (Read):** Read-only [MCP tools](../tools/mcp-server.md) (for
example, `github_read_issue`, `postgres_read_schema`) and core
[MCP resource tools](../tools/mcp-resources.md) (`list_mcp_resources`,
`read_mcp_resource`) are allowed.
- **Planning (Write):**
[`write_file`](../tools/file-system.md#3-write_file-writefile) and
[`replace`](../tools/file-system.md#6-replace-edit) only allowed for `.md`
files in the `~/.gemini/tmp/<project>/<session-id>/plans/` directory or your
[custom plans directory](#custom-plan-directory-and-policies).
- **Skills:** [`activate_skill`](../cli/skills.md) (allows loading specialized
instructions and resources in a read-only manner)
## Customization and best practices
Plan Mode is secure by default, but you can adapt it to fit your specific
workflows. You can customize how Gemini CLI plans by using skills, adjusting
safety policies, changing where plans are stored, or adding hooks.
### Custom planning with skills
You can use [Agent Skills](../cli/skills.md) to customize how Gemini CLI
approaches planning for specific types of tasks. When a skill is activated
during Plan Mode, its specialized instructions and procedural workflows will
guide the research, design, and planning phases.
For example:
- A **"Database Migration"** skill could ensure the plan includes data safety
checks and rollback strategies.
- A **"Security Audit"** skill could prompt Gemini CLI to look for specific
vulnerabilities during codebase exploration.
- A **"Frontend Design"** skill could guide Gemini CLI to use specific UI
components and accessibility standards in its proposal.
To use a skill in Plan Mode, you can explicitly ask Gemini CLI to "use the
`<skill-name>` skill to plan..." or Gemini CLI may autonomously activate it
based on the task description.
### Custom policies
Plan Mode's default tool restrictions are managed by the
[policy engine](../reference/policy-engine.md) and defined in the built-in
[`plan.toml`] file. The built-in policy (Tier 1) enforces the read-only state,
but you can customize these rules by creating your own policies in your
`~/.gemini/policies/` directory (Tier 2).
#### Global vs. mode-specific rules
As described in the
[policy engine documentation](../reference/policy-engine.md#approval-modes), any
rule that does not explicitly specify `modes` is considered "always active" and
will apply to Plan Mode as well.
To maintain the integrity of Plan Mode as a safe research environment,
persistent tool approvals are context-aware. Approvals granted in modes like
Default or Auto-Edit do not apply to Plan Mode, ensuring that tools trusted for
implementation don't automatically execute while you're researching. However,
approvals granted while in Plan Mode are treated as intentional choices for
global trust and apply to all modes.
If you want to manually restrict a rule to other modes but _not_ to Plan Mode,
you must explicitly specify the target modes. For example, to allow `npm test`
in default and Auto-Edit modes but not in Plan Mode:
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "npm test"
decision = "allow"
priority = 100
# By omitting "plan", this rule will not be active in Plan Mode.
modes = ["default", "autoEdit"]
```
#### Example: Automatically approve read-only MCP tools
By default, read-only MCP tools require user confirmation in Plan Mode. You can
use `toolAnnotations` and the `mcpName` wildcard to customize this behavior for
your specific environment.
`~/.gemini/policies/mcp-read-only.toml`
```toml
[[rule]]
toolName = "*"
mcpName = "*"
toolAnnotations = { readOnlyHint = true }
decision = "allow"
priority = 100
modes = ["plan"]
```
For more information on how the policy engine works, see the
[policy engine](../reference/policy-engine.md) docs.
#### Example: Allow git commands in Plan Mode
This rule lets you check the repository status and see changes while in Plan
Mode.
`~/.gemini/policies/git-research.toml`
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = ["git status", "git diff"]
decision = "allow"
priority = 100
modes = ["plan"]
```
#### Example: Enable custom subagents in Plan Mode
Built-in research [subagents](../core/subagents.md) like
[`codebase_investigator`](../core/subagents.md#codebase-investigator) and
[`cli_help`](../core/subagents.md#cli-help-agent) are enabled by default in Plan
Mode. You can enable additional
[custom subagents](../core/subagents.md#creating-custom-subagents) by adding a
rule to your policy.
`~/.gemini/policies/research-subagents.toml`
```toml
[[rule]]
toolName = "my_custom_subagent"
decision = "allow"
priority = 100
modes = ["plan"]
```
Tell Gemini CLI it can use these tools in your prompt, for example: _"You can
check ongoing changes in git."_
### Custom plan directory and policies
By default, planning artifacts are stored in a managed temporary directory
outside your project: `~/.gemini/tmp/<project>/<session-id>/plans/`.
You can configure a custom directory for plans in your `settings.json`. For
example, to store plans in a `.gemini/plans` directory within your project:
```json
{
"general": {
"plan": {
"directory": ".gemini/plans"
}
}
}
```
To maintain the safety of Plan Mode, user-configured paths for the plans
directory are restricted to the project root. This ensures that custom planning
locations defined within a project's workspace cannot be used to escape and
overwrite sensitive files elsewhere. Any user-configured directory must reside
within the project boundary.
Using a custom directory requires updating your
[policy engine](../reference/policy-engine.md) configurations to allow
`write_file` and `replace` in that specific location. For example, to allow
writing to the `.gemini/plans` directory within your project, create a policy
file at `~/.gemini/policies/plan-custom-directory.toml`:
```toml
[[rule]]
toolName = ["write_file", "replace"]
decision = "allow"
priority = 100
modes = ["plan"]
# Adjust the pattern to match your custom directory.
# This example matches any .md file in a .gemini/plans directory within the project.
argsPattern = "\"file_path\":\"[^\"]+[\\\\/]+\\.gemini[\\\\/]+plans[\\\\/]+[\\w-]+\\.md\""
```
### Using hooks with Plan Mode
You can use the [hook system](../hooks/writing-hooks.md) to automate parts of
the planning workflow or enforce additional checks when Gemini CLI transitions
into or out of Plan Mode.
Hooks such as `BeforeTool` or `AfterTool` can be configured to intercept the
`enter_plan_mode` and `exit_plan_mode` tool calls.
> [!WARNING] When hooks are triggered by **tool executions**, they do **not**
> run when you manually toggle Plan Mode using the `/plan` command or the
> `Shift+Tab` keyboard shortcut. If you need hooks to execute on mode changes,
> ensure the transition is initiated by the agent (for example, by asking "start
> a plan for...").
#### Example: Archive approved plans to GCS (`AfterTool`)
If your organizational policy requires a record of all execution plans, you can
use an `AfterTool` hook to securely copy the plan artifact to Google Cloud
Storage whenever Gemini CLI exits Plan Mode to start the implementation.
**`.gemini/hooks/archive-plan.sh`:**
```bash
#!/usr/bin/env bash
# Extract the plan filename from the tool input JSON
plan_filename=$(jq -r '.tool_input.plan_filename // empty')
# Construct the absolute path using the GEMINI_PLANS_DIR environment variable
plan_path="$GEMINI_PLANS_DIR/$plan_filename"
if [ -f "$plan_path" ]; then
# Generate a unique filename using a timestamp
filename="$(date +%s)_$(basename "$plan_path")"
# Upload the plan to GCS in the background so it doesn't block the CLI
gsutil cp "$plan_path" "gs://my-audit-bucket/gemini-plans/$filename" > /dev/null 2>&1 &
fi
# AfterTool hooks should generally allow the flow to continue
echo '{"decision": "allow"}'
```
To register this `AfterTool` hook, add it to your `settings.json`:
```json
{
"hooks": {
"AfterTool": [
{
"matcher": "exit_plan_mode",
"hooks": [
{
"name": "archive-plan",
"type": "command",
"command": "~/.gemini/hooks/archive-plan.sh"
}
]
}
]
}
}
```
## Commands
- **`/plan copy`**: Copy the currently approved plan to your clipboard.
## Planning workflows
Plan Mode provides building blocks for structured research and design. These are
implemented as [extensions](../extensions/index.md) using core planning tools
like [`enter_plan_mode`](../tools/planning.md#1-enter_plan_mode-enterplanmode),
[`exit_plan_mode`](../tools/planning.md#2-exit_plan_mode-exitplanmode), and
[`ask_user`](../tools/ask-user.md).
### Built-in planning workflow
The built-in planner uses an adaptive workflow to analyze your project, consult
you on trade-offs via [`ask_user`](../tools/ask-user.md), and draft a plan for
your approval.
### Custom planning workflows
You can install or create specialized planners to suit your workflow.
#### Conductor
[Conductor] is designed for spec-driven development. It organizes work into
"tracks" and stores persistent artifacts in your project's `conductor/`
directory:
- **Automate transitions:** Switches to read-only mode via
[`enter_plan_mode`](../tools/planning.md#1-enter_plan_mode-enterplanmode).
- **Streamline decisions:** Uses [`ask_user`](../tools/ask-user.md) for
architectural choices.
- **Maintain project context:** Stores artifacts in the project directory using
[custom plan directory and policies](#custom-plan-directory-and-policies).
- **Handoff execution:** Transitions to implementation via
[`exit_plan_mode`](../tools/planning.md#2-exit_plan_mode-exitplanmode).
#### Build your own
Since Plan Mode is built on modular building blocks, you can develop your own
custom planning workflow as an [extensions](../extensions/index.md). By
leveraging core tools and [custom policies](#custom-policies), you can define
how Gemini CLI researches and stores plans for your specific domain.
To build a custom planning workflow, you can use:
- **Tool usage:** Use core tools like
[`enter_plan_mode`](../tools/planning.md#1-enter_plan_mode-enterplanmode),
[`ask_user`](../tools/ask-user.md), and
[`exit_plan_mode`](../tools/planning.md#2-exit_plan_mode-exitplanmode) to
manage the research and design process.
- **Customization:** Set your own storage locations and policy rules using
[custom plan directories](#custom-plan-directory-and-policies) and
[custom policies](#custom-policies).
<!-- prettier-ignore -->
> [!TIP]
> Use [Conductor] as a reference when building your own custom
> planning workflow.
By using Plan Mode as its execution environment, your custom methodology can
enforce read-only safety during the design phase while benefiting from
high-reasoning model routing.
## Automatic Model Routing
When using an [auto model](../reference/configuration.md#model), Gemini CLI
automatically optimizes [model routing](../cli/telemetry.md#model-routing) based
on the current phase of your task:
1. **Planning Phase:** While in Plan Mode, the CLI routes requests to a
high-reasoning **Pro** model to ensure robust architectural decisions and
high-quality plans.
2. **Implementation Phase:** Once a plan is approved and you exit Plan Mode,
the CLI detects the existence of the approved plan and automatically
switches to a high-speed **Flash** model. This provides a faster, more
responsive experience during the implementation of the plan.
If the high-reasoning model is unavailable or you don't have access to it,
Gemini CLI automatically and silently falls back to a faster model to ensure
your workflow isn't interrupted.
This behavior is enabled by default to provide the best balance of quality and
performance. You can disable this automatic switching in your settings:
```json
{
"general": {
"plan": {
"modelRouting": false
}
}
}
```
## Cleanup
By default, Gemini CLI automatically cleans up old session data, including all
associated plan files and task trackers.
- **Default behavior:** Sessions (and their plans) are retained for **30 days**.
- **Configuration:** You can customize this behavior via the `/settings` command
(search for **Enable Session Cleanup** or **Keep chat history**) or in your
`settings.json` file. See
[session retention](../cli/session-management.md#session-retention) for more
details.
Manual deletion also removes all associated artifacts:
- **Command Line:** Use `gemini --delete-session <index|id>`.
- **Session Browser:** Press `/resume`, navigate to a session, and press `x`.
If you use a [custom plans directory](#custom-plan-directory-and-policies),
those files are not automatically deleted and must be managed manually.
## Non-interactive execution
When running Gemini CLI in non-interactive environments (such as headless
scripts or CI/CD pipelines), Plan Mode optimizes for automated workflows:
- **Automatic transitions:** The policy engine automatically approves the
`enter_plan_mode` and `exit_plan_mode` tools without prompting for user
confirmation.
- **Automated implementation:** When exiting Plan Mode to execute the plan,
Gemini CLI automatically switches to
[YOLO mode](../reference/policy-engine.md#approval-modes) instead of the
standard Default mode. This allows the CLI to execute the implementation steps
automatically without hanging on interactive tool approvals.
**Example:**
```bash
gemini --approval-mode plan -p "Analyze telemetry and suggest improvements"
```
[`plan.toml`]:
https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/policy/policies/plan.toml
[Conductor]: https://github.com/gemini-cli-extensions/conductor
[open an issue]: https://github.com/google-gemini/gemini-cli/issues
+51
View File
@@ -0,0 +1,51 @@
# Rewind
The `/rewind` command lets you go back to a previous state in your conversation
and, optionally, revert any file changes made by the AI during those
interactions. This is a powerful tool for undoing mistakes, exploring different
approaches, or simply cleaning up your session history.
## Usage
To use the rewind feature, simply type `/rewind` into the input prompt and press
**Enter**.
Alternatively, you can use the keyboard shortcut: **Press `Esc` twice**.
## Interface
When you trigger a rewind, an interactive list of your previous interactions
appears.
1. **Select interaction:** Use the **Up/Down arrow keys** to navigate through
the list. The most recent interactions are at the bottom.
2. **Preview:** As you select an interaction, you'll see a preview of the user
prompt and, if applicable, the number of files changed during that step.
3. **Confirm selection:** Press **Enter** on the interaction you want to rewind
back to.
4. **Action selection:** After selecting an interaction, you'll be presented
with a confirmation dialog with up to three options:
- **Rewind conversation and revert code changes:** Reverts both the chat
history and the file modifications to the state before the selected
interaction.
- **Rewind conversation:** Only reverts the chat history. File changes are
kept.
- **Revert code changes:** Only reverts the file modifications. The chat
history is kept.
- **Do nothing (esc):** Cancels the rewind operation.
If no code changes were made since the selected point, the options related to
reverting code changes will be hidden.
## Key considerations
- **Destructive action:** Rewinding is a destructive action for your current
session history and potentially your files. Use it with care.
- **Agent awareness:** When you rewind the conversation, the AI model loses all
memory of the interactions that were removed. If you only revert code changes,
you may need to inform the model that the files have changed.
- **Manual edits:** Rewinding only affects file changes made by the AI's edit
tools. It does **not** undo manual edits you've made or changes triggered by
the shell tool (`!`).
- **Compression:** Rewind works across chat compression points by reconstructing
the history from stored session data.
+472
View File
@@ -0,0 +1,472 @@
# Sandboxing in Gemini CLI
This document provides a guide to sandboxing in Gemini CLI, including
prerequisites, quickstart, and configuration.
## Prerequisites
Before using sandboxing, you need to install and set up Gemini CLI:
```bash
npm install -g @google/gemini-cli
```
To verify the installation:
```bash
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.
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.
## Quickstart
You can enable sandboxing using a command flag, environment variable, or
configuration file.
### Using the command flag
```bash
gemini -s -p "analyze the code structure"
```
### Using an environment variable
**macOS/Linux**
```bash
export GEMINI_SANDBOX=true
gemini -p "run the test suite"
```
**Windows (PowerShell)**
```powershell
$env:GEMINI_SANDBOX="true"
gemini -p "run the test suite"
```
### Configuring via settings.json
```json
{
"tools": {
"sandbox": "docker"
}
}
```
## Configuration
Enable sandboxing using one of the following methods (in order of precedence):
1. **Command flag**: `-s` or `--sandbox`
2. **Environment variable**:
`GEMINI_SANDBOX=true|docker|podman|sandbox-exec|runsc|lxc`
3. **Settings file**: `"sandbox": true` in the `tools` object of your
`settings.json` file (for example, `{"tools": {"sandbox": true}}`).
## Sandboxing methods
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.
Built-in profiles (set via `SEATBELT_PROFILE` env var):
- `permissive-open` (default): Write restrictions, network allowed
- `permissive-proxied`: Write restrictions, network via proxy
- `restrictive-open`: Strict restrictions, network allowed
- `restrictive-proxied`: Strict restrictions, network via proxy
- `strict-open`: Read and write restrictions, network allowed
- `strict-proxied`: Read and write restrictions, network via proxy
### 2. Container-based (Docker/Podman)
Cross-platform sandboxing with complete process isolation using container
technology. By default, it uses the `ghcr.io/google/gemini-cli:latest` image.
**Prerequisites:**
- Docker or Podman must be installed and running on your system.
**How it works (Workspace directory):**
Inside the sandbox container, your current working directory is mounted at the
**exact same absolute path** as it is on your host machine. For example, if you
run the CLI from `/Users/you/project` on your host machine, the sandbox will
mount your local project folder and operate within `/Users/you/project` inside
the container. This allows the AI to seamlessly read and modify your project
files while remaining isolated from the rest of your system.
**Quick setup:**
To enable Docker sandboxing, run Gemini CLI with the sandbox flag and specify
Docker as the provider:
```bash
# Using the environment variable (Recommended)
export GEMINI_SANDBOX=docker
gemini -p "build the project"
# Or configure it permanently in your settings.json
# {"tools": {"sandbox": "docker"}}
```
**Customizing the Sandbox Image:**
If your project requires specific dependencies, you can specify a custom image
name or have Gemini CLI build one for you automatically. You can use any Docker
or Podman image as your sandbox, provided it has standard shell utilities (like
`bash`) available.
**Option A: Using an existing custom image (e.g., Artifact Registry)**
To configure a custom image that is hosted on a registry (or built locally),
update your `settings.json` to use an object for the sandbox configuration, or
set the `GEMINI_SANDBOX_IMAGE` environment variable.
_Example: Configuring via `settings.json`_
```json
{
"tools": {
"sandbox": {
"command": "docker",
"image": "us-central1-docker.pkg.dev/my-project/my-repo/my-custom-sandbox:latest"
}
}
}
```
_Example: Configuring via environment variable_
```bash
export GEMINI_SANDBOX_IMAGE="us-central1-docker.pkg.dev/my-project/my-repo/my-custom-sandbox:latest"
```
**Option B: Building a local custom image automatically**
If you prefer to define your environment as code, you can provide a Dockerfile
and Gemini CLI will build the image automatically.
1. Create a `.gemini/sandbox.Dockerfile` in your project root.
2. Ensure you have the `gh` CLI installed and authenticated (if you are using
the default `ghcr.io/google/gemini-cli` image as a base).
3. Run your command with the `BUILD_SANDBOX` environment variable set:
```bash
BUILD_SANDBOX=1 GEMINI_SANDBOX=docker gemini -p "run my custom build"
```
### 3. Windows Native Sandbox (Windows only)
... **Troubleshooting and Side Effects:**
The Windows Native sandbox uses the `icacls` command to set a "Low Mandatory
Level" on files and directories it needs to write to.
- **Persistence**: These integrity level changes are persistent on the
filesystem. Even after the sandbox session ends, files created or modified by
the sandbox will retain their "Low" integrity level.
- **Manual Reset**: If you need to reset the integrity level of a file or
directory, you can use:
```powershell
icacls "C:\path\to\dir" /setintegritylevel Medium
```
- **System Folders**: The sandbox manager automatically skips setting integrity
levels on system folders (like `C:\Windows`) for safety.
### 4. gVisor / runsc (Linux only)
Strongest isolation available: runs containers inside a user-space kernel via
[gVisor](https://github.com/google/gvisor). gVisor intercepts all container
system calls and handles them in a sandboxed kernel written in Go, providing a
strong security barrier between AI operations and the host OS.
**Prerequisites:**
- Linux (gVisor supports Linux only)
- Docker installed and running
- gVisor/runsc runtime configured
When you set `sandbox: "runsc"`, Gemini CLI runs
`docker run --runtime=runsc ...` to execute containers with gVisor isolation.
runsc is not auto-detected; you must specify it explicitly (e.g.
`GEMINI_SANDBOX=runsc` or `sandbox: "runsc"`).
To set up runsc:
1. Install the runsc binary.
2. Configure the Docker daemon to use the runsc runtime.
3. Verify the installation.
### 5. LXC/LXD (Linux only, experimental)
Full-system container sandboxing using LXC/LXD. Unlike Docker/Podman, LXC
containers run a complete Linux system with `systemd`, `snapd`, and other system
services. This is ideal for tools that don't work in standard Docker containers,
such as Snapcraft and Rockcraft.
**Prerequisites**:
- Linux only.
- LXC/LXD must be installed (`snap install lxd` or `apt install lxd`).
- A container must be created and running before starting Gemini CLI. Gemini
does **not** create the container automatically.
**Quick setup**:
```bash
# Initialize LXD (first time only)
lxd init --auto
# Create and start an Ubuntu container
lxc launch ubuntu:24.04 gemini-sandbox
# Enable LXC sandboxing
export GEMINI_SANDBOX=lxc
gemini -p "build the project"
```
**Custom container name**:
```bash
export GEMINI_SANDBOX=lxc
export GEMINI_SANDBOX_IMAGE=my-snapcraft-container
gemini -p "build the snap"
```
**Limitations**:
- Linux only (LXC is not available on macOS or Windows).
- The container must already exist and be running.
- The workspace directory is bind-mounted into the container at the same
absolute path — the path must be writable inside the container.
- Used with tools like Snapcraft or Rockcraft that require a full system.
## Tool sandboxing
Tool-level sandboxing provides granular isolation for individual tool executions
(like `shell_exec` and `write_file`) instead of sandboxing the entire Gemini CLI
process.
This approach offers better integration with your local environment for non-tool
tasks (like UI rendering and configuration loading) while still providing
security for tool-driven operations.
### How to turn off tool sandboxing
If you experience issues with tool sandboxing or prefer full-process isolation,
you can disable it by setting `security.toolSandboxing` to `false` in your
`settings.json` file.
```json
{
"security": {
"toolSandboxing": false
}
}
```
<!-- prettier-ignore -->
> [!NOTE]
> Changing the `security.toolSandboxing` setting requires a restart of Gemini
> CLI to take effect.
## Sandbox expansion
Sandbox expansion is a dynamic permission system that lets Gemini CLI request
additional permissions for a command when needed.
When a sandboxed command fails due to permission restrictions (like restricted
file paths or network access), or when a command is proactively identified as
requiring extra permissions (like `npm install`), Gemini CLI will present you
with a "Sandbox Expansion Request."
### How sandbox expansion works
1. **Detection**: Gemini CLI detects a sandbox denial or proactively identifies
a command that requires extra permissions.
2. **Request**: A modal dialog is shown, explaining which additional
permissions (e.g., specific directories or network access) are required.
3. **Approval**: If you approve the expansion, the command is executed with the
extended permissions for that specific run.
This mechanism ensures you don't have to manually re-run commands with more
permissive sandbox settings, while still maintaining control over what the AI
can access.
### Including files outside the workspace
By default, the sandbox only has access to the current project workspace. If you
need the sandbox to have permission to operate on certain files or directories
from the local file system outside of the project workspace, you can mount them
using the `SANDBOX_MOUNTS` environment variable.
Provide a comma-separated list of mount definitions in the format
`from:to:opts`. If `to` is omitted, it defaults to the same path as `from`. If
`opts` is omitted, it defaults to `ro` (read-only). Note that the `from` path
must be an absolute path.
**Example**:
```bash
export SANDBOX_MOUNTS="/path/on/host:/path/in/container:rw,/another/path:ro"
```
## Running inside a Docker container
If you are running Gemini CLI itself from within an official or custom Docker
container and want to enable sandboxing, you must share the host's Docker socket
and ensure your workspace paths align.
1. **Mount the Docker socket**: Map `/var/run/docker.sock` so the CLI can spawn
sibling sandbox containers via the host's Docker daemon.
2. **Align workspace paths**: The path to your workspace inside the container
must exactly match the absolute path on the host. Because the sandbox
container is spawned by the host's Docker daemon, it resolves volume mounts
against the host file system.
**Example**:
```bash
docker run -it \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /absolute/path/on/host/project:/absolute/path/on/host/project \
-w /absolute/path/on/host/project \
-e GEMINI_SANDBOX=docker \
ghcr.io/google/gemini-cli:latest
```
## Advanced settings
### 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.
**Example (Podman)**:
To disable SELinux labeling for volume mounts, you can set the following:
**macOS/Linux**
```bash
export SANDBOX_FLAGS="--security-opt label=disable"
```
**Windows (PowerShell)**
```powershell
$env:SANDBOX_FLAGS="--security-opt label=disable"
```
Multiple flags can be provided as a space-separated string:
**macOS/Linux**
```bash
export SANDBOX_FLAGS="--flag1 --flag2=value"
```
**Windows (PowerShell)**
```powershell
$env:SANDBOX_FLAGS="--flag1 --flag2=value"
```
### Linux UID/GID handling
The sandbox automatically handles user permissions on Linux. Override these
permissions with:
**macOS/Linux**
```bash
export SANDBOX_SET_UID_GID=true # Force host UID/GID
export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
```
**Windows (PowerShell)**
```powershell
$env:SANDBOX_SET_UID_GID="true" # Force host UID/GID
$env:SANDBOX_SET_UID_GID="false" # Disable UID/GID mapping
```
## Troubleshooting
### Common issues
**"Operation not permitted"**
- Operation requires access outside sandbox.
- Try more permissive profile or add mount points.
**Missing commands**
- Add to a custom Dockerfile. Automatic `BUILD_SANDBOX` builds are only
available when running Gemini CLI from source; npm installs need a prebuilt
image instead.
- Install via `sandbox.bashrc`.
**Network issues**
- Check sandbox profile allows network.
- Verify proxy configuration.
### Debug mode
```bash
DEBUG=1 gemini -s -p "debug command"
```
<!-- prettier-ignore -->
> [!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
```bash
# Check environment
gemini -s -p "run shell command: env | grep SANDBOX"
# List mounts
gemini -s -p "run shell command: mount | grep workspace"
```
## Security notes
- Sandboxing reduces but doesn't eliminate all risks.
- Use the most restrictive profile that allows your work.
- Container overhead is minimal after first build.
- GUI applications may not work in sandboxes.
## Related documentation
- [Configuration](../reference/configuration.md): Full configuration options.
- [Commands](../reference/commands.md): Available commands.
- [Troubleshooting](../resources/troubleshooting.md): General troubleshooting.
+215
View File
@@ -0,0 +1,215 @@
# Session management
Session management saves your conversation history so you can resume your work
where you left off. Use these features to review past interactions, manage
history across different projects, and configure how long data is retained.
## Automatic saving
Your session history is recorded automatically as you interact with the model.
This background process ensures your work is preserved even if you interrupt a
session.
- **What is saved:** The complete conversation history, including:
- Your prompts and the model's responses.
- All tool executions (inputs and outputs).
- Token usage statistics (input, output, cached, etc.).
- Assistant thoughts and reasoning summaries (when available).
- **Location:** Sessions are stored in `~/.gemini/tmp/<project_hash>/chats/`,
where `<project_hash>` is a unique identifier based on your project's root
directory.
- **Scope:** Sessions are project-specific. Switching directories to a different
project switches to that project's session history.
## Resuming sessions
You can resume a previous session to continue the conversation with all prior
context restored. Resuming is supported both through command-line flags and an
interactive browser.
### From the command line
When starting Gemini CLI, use the `--resume` (or `-r`) flag to load existing
sessions.
- **Resume latest:**
```bash
gemini --resume
```
This immediately loads the most recent session.
- **Resume by index:** List available sessions first (see
[Listing sessions](#listing-sessions)), then use the index number:
```bash
gemini --resume 1
```
- **Resume by ID:** You can also provide the full session UUID:
```bash
gemini --resume a1b2c3d4-e5f6-7890-abcd-ef1234567890
```
### From the interactive interface
While the CLI is running, use the `/resume` slash command to open the **Session
Browser**:
```text
/resume
```
When typing `/resume` (or `/chat`) in slash completion, commands are grouped
under titled separators:
- `-- auto --` (session browser)
- `list` is selectable and opens the session browser
- `-- checkpoints --` (manual tagged checkpoint commands)
Unique prefixes such as `/resum` and `/cha` resolve to the same grouped menu.
The Session Browser provides an interactive interface where you can perform the
following actions:
- **Browse:** Scroll through a list of your past sessions.
- **Preview:** See details like the session date, message count, and the first
user prompt.
- **Search:** Press `/` to enter search mode, then type to filter sessions by ID
or content.
- **Select:** Press **Enter** to resume the selected session.
- **Esc:** Press **Esc** to exit the Session Browser.
### Manual chat checkpoints
For named branch points inside a session, use chat checkpoints:
```text
/resume save decision-point
/resume list
/resume resume decision-point
```
Compatibility aliases:
- `/chat ...` works for the same commands.
- `/resume checkpoints ...` also remains supported during migration.
## Parallel sessions with Git worktrees
When working on multiple tasks at once, you can use
[Git worktrees](./git-worktrees.md) to give each Gemini session its own copy of
the codebase. This prevents changes in one session from colliding with another.
## Managing sessions
You can list and delete sessions to keep your history organized and manage disk
space.
### Listing sessions
To see a list of all available sessions for the current project from the command
line, use the `--list-sessions` flag:
```bash
gemini --list-sessions
```
Output example:
```text
Available sessions for this project (3):
1. Fix bug in auth (2 days ago) [a1b2c3d4]
2. Refactor database schema (5 hours ago) [e5f67890]
3. Update documentation (Just now) [abcd1234]
```
### Deleting sessions
You can remove old or unwanted sessions to free up space or declutter your
history.
**From the command line:** Use the `--delete-session` flag with an index or ID:
```bash
gemini --delete-session 2
```
**From the Session Browser:**
1. Open the browser with `/resume`.
2. Navigate to the session you want to remove.
3. Press **x**.
## Configuration
You can configure how Gemini CLI manages your session history in your
`settings.json` file. These settings let you control retention policies and
session lengths.
### Session retention
By default, Gemini CLI automatically cleans up old session data to prevent your
history from growing indefinitely. When a session is deleted, Gemini CLI also
removes all associated data, including implementation plans, task trackers, tool
outputs, and activity logs.
The default policy is to **retain sessions for 30 days**.
#### Configuration
You can customize these policies using the `/settings` command or by manually
editing your `settings.json` file:
```json
{
"general": {
"sessionRetention": {
"enabled": true,
"maxAge": "30d",
"maxCount": 50
}
}
}
```
- **`enabled`**: (boolean) Master switch for session cleanup. Defaults to
`true`.
- **`maxAge`**: (string) Duration to keep sessions (for example, "24h", "7d",
"4w"). Sessions older than this are deleted. Defaults to `"30d"`.
- **`maxCount`**: (number) Maximum number of sessions to retain. The oldest
sessions exceeding this count are deleted. Defaults to undefined (unlimited).
- **`minRetention`**: (string) Minimum retention period (safety limit). Defaults
to `"1d"`. Sessions newer than this period are never deleted by automatic
cleanup.
### Session limits
You can limit the length of individual sessions to prevent context windows from
becoming too large and expensive.
```json
{
"model": {
"maxSessionTurns": 100
}
}
```
- **`maxSessionTurns`**: (number) The maximum number of turns (user and model
exchanges) allowed in a single session. Set to `-1` for unlimited (default).
**Behavior when limit is reached:**
- **Interactive mode:** The CLI shows an informational message and stops
sending requests to the model. You must manually start a new session.
- **Non-interactive mode:** The CLI exits with an error.
## Next steps
- Explore the [Memory tool](../tools/memory.md) to save persistent information
across sessions.
- Learn how to [Checkpoint](./checkpointing.md) your session state.
- Check out the [CLI reference](./cli-reference.md) for all command-line flags.
+198
View File
@@ -0,0 +1,198 @@
# Gemini CLI settings (`/settings` command)
Control your Gemini CLI experience with the `/settings` command. The `/settings`
command opens a dialog to view and edit all your Gemini CLI settings, including
your UI experience, keybindings, and accessibility features.
Your Gemini CLI settings are stored in a `settings.json` file. In addition to
using the `/settings` command, you can also edit them in one of the following
locations:
- **User settings**: `~/.gemini/settings.json`
- **Workspace settings**: `your-project/.gemini/settings.json`
<!-- prettier-ignore -->
> [!IMPORTANT]
> Workspace settings override user settings.
## Settings reference
Here is a list of all the available settings, grouped by category and ordered as
they appear in the UI.
<!-- SETTINGS-AUTOGEN:START -->
### General
| UI Label | Setting | Description | Default |
| ----------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| Vim Mode | `general.vimMode` | Enable Vim keybindings | `false` |
| Default Approval Mode | `general.defaultApprovalMode` | The default approval mode for tool execution. 'default' prompts for approval, 'auto_edit' auto-approves edit tools, and 'plan' is read-only mode. YOLO mode (auto-approve all actions) can only be enabled via command line (--yolo or --approval-mode=yolo). | `"default"` |
| Enable Auto Update | `general.enableAutoUpdate` | Enable automatic updates. | `true` |
| Enable Terminal Notifications | `general.enableNotifications` | Enable terminal run-event notifications for action-required prompts and session completion. | `false` |
| Terminal Notification Method | `general.notificationMethod` | How to send terminal notifications. | `"auto"` |
| Enable Plan Mode | `general.plan.enabled` | Enable Plan Mode for read-only safety during planning. | `true` |
| Plan Directory | `general.plan.directory` | The directory where planning artifacts are stored. If not specified, defaults to the system temporary directory. A custom directory requires a policy to allow write access in Plan Mode. | `undefined` |
| Plan Model Routing | `general.plan.modelRouting` | Automatically switch between Pro and Flash models based on Plan Mode status. Uses Pro for the planning phase and Flash for the implementation phase. | `true` |
| Retry Fetch Errors | `general.retryFetchErrors` | Retry on "exception TypeError: fetch failed sending request" errors. | `true` |
| Max Chat Model Attempts | `general.maxAttempts` | Maximum number of attempts for requests to the main chat model. Cannot exceed 10. | `10` |
| Debug Keystroke Logging | `general.debugKeystrokeLogging` | Enable debug logging of keystrokes to the console. | `false` |
| Enable Session Cleanup | `general.sessionRetention.enabled` | Enable automatic session cleanup | `true` |
| Keep chat history | `general.sessionRetention.maxAge` | Automatically delete chats older than this time period (e.g., "30d", "7d", "24h", "1w") | `"30d"` |
| Topic & Update Narration | `general.topicUpdateNarration` | Enable the Topic & Update communication model for reduced chattiness and structured progress reporting. | `true` |
| Log RAG Snippets | `general.logRagSnippets` | Log full Code Customization (RAG) retrieved snippets to a local file for debugging. | `false` |
### Output
| UI Label | Setting | Description | Default |
| ------------- | --------------- | ------------------------------------------------------ | -------- |
| Output Format | `output.format` | The format of the CLI output. Can be `text` or `json`. | `"text"` |
### UI
| UI Label | Setting | Description | Default |
| ------------------------------------ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Auto Theme Switching | `ui.autoThemeSwitching` | Automatically switch between default light and dark themes based on terminal background color. | `true` |
| Terminal Background Polling Interval | `ui.terminalBackgroundPollingInterval` | Interval in seconds to poll the terminal background color. | `60` |
| Hide Window Title | `ui.hideWindowTitle` | Hide the window title bar | `false` |
| Inline Thinking | `ui.inlineThinkingMode` | Display model thinking inline: off or full. | `"off"` |
| Show Thoughts in Title | `ui.showStatusInTitle` | Show Gemini CLI model thoughts in the terminal window title during the working phase | `false` |
| Dynamic Window Title | `ui.dynamicWindowTitle` | Update the terminal window title with current status icons (Ready: ◇, Action Required: ✋, Working: ✦) | `true` |
| Show Home Directory Warning | `ui.showHomeDirectoryWarning` | Show a warning when running Gemini CLI in the home directory. | `true` |
| Show Compatibility Warnings | `ui.showCompatibilityWarnings` | Show warnings about terminal or OS compatibility issues. | `true` |
| Hide Tips | `ui.hideTips` | Hide helpful tips in the UI | `false` |
| Escape Pasted @ Symbols | `ui.escapePastedAtSymbols` | When enabled, @ symbols in pasted text are escaped to prevent unintended @path expansion. | `false` |
| Show Shortcuts Hint | `ui.showShortcutsHint` | Show the "? for shortcuts" hint above the input. | `true` |
| Compact Tool Output | `ui.compactToolOutput` | Display tool outputs (like directory listings and file reads) in a compact, structured format. | `true` |
| Hide Banner | `ui.hideBanner` | Hide the application banner | `false` |
| Hide Context Summary | `ui.hideContextSummary` | Hide the context summary (GEMINI.md, MCP servers) above the input. | `false` |
| Hide CWD | `ui.footer.hideCWD` | Hide the current working directory in the footer. | `false` |
| Hide Sandbox Status | `ui.footer.hideSandboxStatus` | Hide the sandbox status indicator in the footer. | `false` |
| Hide Model Info | `ui.footer.hideModelInfo` | Hide the model name and context usage in the footer. | `false` |
| Hide Context Window Percentage | `ui.footer.hideContextPercentage` | Hides the context window usage percentage. | `true` |
| Hide Footer | `ui.hideFooter` | Hide the footer from the UI | `false` |
| Show Memory Usage | `ui.showMemoryUsage` | Display memory usage information in the UI | `false` |
| Show Line Numbers | `ui.showLineNumbers` | Show line numbers in the chat. | `true` |
| Show Citations | `ui.showCitations` | Show citations for generated text in the chat. | `false` |
| Show Model Info In Chat | `ui.showModelInfoInChat` | Show the model name in the chat for each model turn. | `false` |
| Show User Identity | `ui.showUserIdentity` | Show the signed-in user's identity (e.g. email) in the UI. | `true` |
| Use Alternate Screen Buffer | `ui.useAlternateBuffer` | Use an alternate screen buffer for the UI, preserving shell history. | `false` |
| Render Process | `ui.renderProcess` | Enable Ink render process for the UI. | `true` |
| Terminal Buffer | `ui.terminalBuffer` | Use the new terminal buffer architecture for rendering. | `false` |
| Use Background Color | `ui.useBackgroundColor` | Whether to use background colors in the UI. | `true` |
| Incremental Rendering | `ui.incrementalRendering` | Enable incremental rendering for the UI. This option will reduce flickering but may cause rendering artifacts. Only supported when useAlternateBuffer is enabled. | `true` |
| Show Spinner | `ui.showSpinner` | Show the spinner during operations. | `true` |
| Loading Phrases | `ui.loadingPhrases` | What to show while the model is working: tips, witty comments, all, or off. | `"off"` |
| Error Verbosity | `ui.errorVerbosity` | Controls whether recoverable errors are hidden (low) or fully shown (full). | `"low"` |
| Screen Reader Mode | `ui.accessibility.screenReader` | Render output in plain-text to be more screen reader accessible | `false` |
### IDE
| UI Label | Setting | Description | Default |
| -------- | ------------- | ---------------------------- | ------- |
| IDE Mode | `ide.enabled` | Enable IDE integration mode. | `false` |
### Billing
| UI Label | Setting | Description | Default |
| ---------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Overage Strategy | `billing.overageStrategy` | How to handle quota exhaustion when AI credits are available. 'ask' prompts each time, 'always' automatically uses credits, 'never' disables credit usage. | `"ask"` |
### Model
| UI Label | Setting | Description | Default |
| ----------------------------- | ---------------------------- | -------------------------------------------------------------------------------------- | ----------- |
| Model | `model.name` | The Gemini model to use for conversations. | `undefined` |
| Max Session Turns | `model.maxSessionTurns` | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` |
| Context Compression Threshold | `model.compressionThreshold` | The fraction of context usage at which to trigger context compression (e.g. 0.2, 0.3). | `0.5` |
| Disable Loop Detection | `model.disableLoopDetection` | Disable automatic detection and prevention of infinite loops. | `false` |
| Skip Next Speaker Check | `model.skipNextSpeakerCheck` | Skip the next speaker check. | `true` |
### Agents
| UI Label | Setting | Description | Default |
| ------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------- | ------- |
| Confirm Sensitive Actions | `agents.browser.confirmSensitiveActions` | Require manual confirmation for sensitive browser actions (e.g., fill_form, evaluate_script). | `false` |
| Block File Uploads | `agents.browser.blockFileUploads` | Hard-block file upload requests from the browser agent. | `false` |
### Context
| UI Label | Setting | Description | Default |
| ------------------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Memory Discovery Max Dirs | `context.discoveryMaxDirs` | Maximum number of directories to search for memory. | `200` |
| Load Memory From Include Directories | `context.loadMemoryFromIncludeDirectories` | Controls how /memory reload loads GEMINI.md files. When true, include directories are scanned; when false, only the current directory is used. | `false` |
| Respect .gitignore | `context.fileFiltering.respectGitIgnore` | Respect .gitignore files when searching. | `true` |
| Respect .geminiignore | `context.fileFiltering.respectGeminiIgnore` | Respect .geminiignore files when searching. | `true` |
| Enable Recursive File Search | `context.fileFiltering.enableRecursiveFileSearch` | Enable recursive file search functionality when completing @ references in the prompt. | `true` |
| Enable Fuzzy Search | `context.fileFiltering.enableFuzzySearch` | Enable fuzzy search when searching for files. | `true` |
| Custom Ignore File Paths | `context.fileFiltering.customIgnoreFilePaths` | Additional ignore file paths to respect. These files take precedence over .geminiignore and .gitignore. Files earlier in the array take precedence over files later in the array, e.g. the first file takes precedence over the second one. | `[]` |
### Tools
| UI Label | Setting | Description | Default |
| -------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Sandbox Allowed Paths | `tools.sandboxAllowedPaths` | List of additional paths that the sandbox is allowed to access. | `[]` |
| Sandbox Network Access | `tools.sandboxNetworkAccess` | Whether the sandbox is allowed to access the network. | `false` |
| Enable Interactive Shell | `tools.shell.enableInteractiveShell` | Use node-pty for an interactive shell experience. Fallback to child_process still applies. | `true` |
| Show Color | `tools.shell.showColor` | Show color in shell output. | `true` |
| Use Ripgrep | `tools.useRipgrep` | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` |
| Tool Output Truncation Threshold | `tools.truncateToolOutputThreshold` | Maximum characters to show when truncating large tool outputs. Set to 0 or negative to disable truncation. | `40000` |
| Disable LLM Correction | `tools.disableLLMCorrection` | Disable LLM-based error correction for edit tools. When enabled, tools will fail immediately if exact string matches are not found, instead of attempting to self-correct. | `true` |
### Security
| UI Label | Setting | Description | Default |
| ------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| Tool Sandboxing | `security.toolSandboxing` | Tool-level sandboxing. Isolates individual tools instead of the entire CLI process. | `false` |
| Disable YOLO Mode | `security.disableYoloMode` | Disable YOLO mode, even if enabled by a flag. | `false` |
| Disable Always Allow | `security.disableAlwaysAllow` | Disable "Always allow" options in tool confirmation dialogs. | `false` |
| Allow Permanent Tool Approval | `security.enablePermanentToolApproval` | Enable the "Allow for all future sessions" option in tool confirmation dialogs. | `false` |
| Auto-add to Policy by Default | `security.autoAddToPolicyByDefault` | When enabled, the "Allow for all future sessions" option becomes the default choice for low-risk tools in trusted workspaces. | `false` |
| Blocks extensions from Git | `security.blockGitExtensions` | Blocks installing and loading extensions from Git. | `false` |
| Extension Source Regex Allowlist | `security.allowedExtensions` | List of Regex patterns for allowed extensions. If nonempty, only extensions that match the patterns in this list are allowed. Overrides the blockGitExtensions setting. | `[]` |
| Folder Trust | `security.folderTrust.enabled` | Setting to track whether Folder trust is enabled. | `true` |
| Enable Environment Variable Redaction | `security.environmentVariableRedaction.enabled` | Enable redaction of environment variables that may contain secrets. | `false` |
| Enable Context-Aware Security | `security.enableConseca` | Enable the context-aware security checker. This feature uses an LLM to dynamically generate and enforce security policies for tool use based on your prompt, providing an additional layer of protection against unintended actions. | `false` |
### Advanced
| UI Label | Setting | Description | Default |
| --------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Auto Configure Max Old Space Size | `advanced.autoConfigureMemory` | Automatically configure Node.js memory limits. Note: Because memory is allocated during the initial process boot, this setting is only read from the global user settings file and ignores workspace-level overrides. | `true` |
| Ignore Local .env | `advanced.ignoreLocalEnv` | Whether to ignore generic .env files in the project directory. | `false` |
### Experimental
| UI Label | Setting | Description | Default |
| ---------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| Gemma Models | `experimental.gemma` | Enable access to Gemma 4 models via Gemini API. | `true` |
| Voice Mode | `experimental.voiceMode` | Enable experimental voice dictation and commands (/voice, /voice model). | `false` |
| Voice Activation Mode | `experimental.voice.activationMode` | How to trigger voice recording with the Space key. | `"push-to-talk"` |
| Voice Transcription Backend | `experimental.voice.backend` | The backend to use for voice transcription. Note: When using the Gemini Live backend, voice recordings are sent to Google Cloud for transcription. | `"gemini-live"` |
| Whisper Model | `experimental.voice.whisperModel` | The Whisper model to use for local transcription. | `"ggml-base.en.bin"` |
| Voice Stop Grace Period (ms) | `experimental.voice.stopGracePeriodMs` | How long to wait for final transcription after stopping recording. | `4000` |
| Enable Git Worktrees | `experimental.worktrees` | Enable automated Git worktree management for parallel work. | `false` |
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 for pasting. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
| Use OSC 52 Copy | `experimental.useOSC52Copy` | Use OSC 52 for copying. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
| Enable Gemma Model Router | `experimental.gemmaModelRouter.enabled` | Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim. | `false` |
| Auto-start LiteRT Server | `experimental.gemmaModelRouter.autoStartServer` | Automatically start the LiteRT-LM server when Gemini CLI starts and the Gemma router is enabled. | `false` |
| Auto Memory | `experimental.autoMemory` | Automatically extract memory patches and skills from past sessions in the background. Every change is written as a unified diff `.patch` file under `<projectMemoryDir>/.inbox/<kind>/` and held for review in /memory inbox; nothing is applied until you approve it. | `false` |
| Use the generalist profile to manage agent contexts. | `experimental.generalistProfile` | Suitable for general coding and software development tasks. | `false` |
| Enable Context Management | `experimental.contextManagement` | Enable logic for context management. | `false` |
### Skills
| UI Label | Setting | Description | Default |
| ------------------- | ---------------- | -------------------- | ------- |
| Enable Agent Skills | `skills.enabled` | Enable Agent Skills. | `true` |
### HooksConfig
| UI Label | Setting | Description | Default |
| ------------------ | --------------------------- | -------------------------------------------------------------------------------- | ------- |
| Enable Hooks | `hooksConfig.enabled` | Canonical toggle for the hooks system. When disabled, no hooks will be executed. | `true` |
| Hook Notifications | `hooksConfig.notifications` | Show visual indicators when hooks are executing. | `true` |
<!-- SETTINGS-AUTOGEN:END -->
+78
View File
@@ -0,0 +1,78 @@
# Agent Skill best practices
Create high-quality, reliable Agent Skills by following these established design
principles and patterns.
## Design for discovery
The most important part of a skill is its `description`. This is the only
information the model has before activation.
- **Be specific**: Use keywords that are likely to appear in user prompts (for
example, "audit," "security," "refactor," "migration").
- **Define the trigger**: Clearly state _when_ the skill should be used (for
example, "Use this skill when the user asks to review a PR for performance
regressions").
- **Avoid overlap**: Ensure your skill descriptions are distinct from one
another and from the general capabilities of the model.
## Progressive disclosure
The "context window" is a shared resource. Use a three-level loading system to
manage context efficiently.
1. **Metadata (name + description)**: Always in context (~100 words).
2. **`SKILL.md` body**: Loaded only after the skill triggers (<5k words).
3. **Bundled resources**: Loaded only as needed by the model.
**Best practice**: Keep the `SKILL.md` body focused on core procedural
instructions. Move detailed reference material, schemas, and examples into
separate files in a `references/` directory.
## Degrees of freedom
Match the level of instruction specificity to the task's fragility.
- **High freedom (text-based instructions)**: Use when multiple approaches are
valid or decisions depend heavily on context.
- **Medium freedom (pseudocode or scripts with parameters)**: Use when a
preferred pattern exists but some variation is acceptable.
- **Low freedom (specific scripts, few parameters)**: Use when operations are
fragile and error-prone, or a specific sequence MUST be followed.
## Bundle resources effectively
Leverage the skill's ability to include scripts and assets to extend the agent's
capabilities.
- **Use scripts for deterministic tasks**: If a task can be automated with a
script (for example, running a linter, fetching data from an API), bundle it
in the `scripts/` folder.
- **Agentic ergonomics**: Ensure scripts output LLM-friendly stdout. Suppress
verbose tracebacks and provide clear, concise success/failure messages.
- **Provide templates**: Include common file headers or boilerplate code in the
`assets/` folder to ensure the agent produces consistent output.
## Anatomy of a great skill
A well-structured skill directory organizes its resources into specialized
sub-folders.
```text
my-skill/
├── SKILL.md (Required) Core instructions and metadata
├── scripts/ (Optional) Executable logic (Node.js, Python, etc.)
├── references/ (Optional) Documentation to be loaded as needed
└── assets/ (Optional) Templates and non-executable resources
```
## Security and privacy
Design your skills with security in mind to protect your workspace and data.
- **Avoid hardcoded secrets**: Never include API keys or passwords in your
skill's scripts or documentation.
- **Review third-party skills**: Inspect the `SKILL.md` and scripts of any skill
before installing it from an untrusted source.
- **Limit scope**: Design skills to be as focused as possible to minimize the
potential impact of errors.
+141
View File
@@ -0,0 +1,141 @@
# Agent Skills
Agent Skills let you extend Gemini CLI with specialized expertise, procedural
workflows, and task-specific resources. Based on the
[Agent Skills](https://agentskills.io) open standard, a "skill" is a
self-contained directory that packages instructions and assets into a
discoverable capability.
Unlike general context files ([GEMINI.md](./gemini-md.md)), which provide
persistent workspace-wide background, Skills represent **on-demand expertise**.
This lets Gemini CLI maintain a vast library of specialized capabilities—such as
security auditing, cloud deployments, or codebase migrations—without cluttering
the model's immediate context window.
## How it works
The lifecycle of an Agent Skill involves discovery, activation, and conditional
resource access.
1. **Discovery**: At the start of a session, Gemini CLI scans the discovery
tiers and injects the name and description of all enabled skills into the
system prompt.
2. **Activation**: When Gemini identifies a task matching a skill's
description, it calls the `activate_skill` tool.
3. **Consent**: You will see a confirmation prompt in the UI detailing the
skill's name, purpose, and the directory path it will gain access to.
4. **Injection**: Upon your approval:
- The `SKILL.md` body and folder structure is added to the conversation
history.
- The skill's directory is added to the agent's allowed file paths, granting
it permission to read any bundled assets.
5. **Execution**: The model proceeds with the specialized expertise active. It
is instructed to prioritize the skill's procedural guidance within reason.
## Discovery tiers
Gemini CLI discovers skills from several locations, following a specific order
of precedence (lowest to highest):
1. **Built-in skills**: Standard skills included with Gemini CLI that provide
foundational capabilities.
2. **Extension skills**: Skills bundled within installed
[extensions](../extensions/index.md).
3. **User skills**: Located in `~/.gemini/skills/` or the `~/.agents/skills/`
alias.
4. **Workspace skills**: Located in `.gemini/skills/` or the `.agents/skills/`
alias. Workspace skills are shared with your team via version control.
### Precedence and aliases
If multiple skills share the same name, the version from the higher-precedence
location is used. Within the same tier (user or workspace), the
`.agents/skills/` alias takes precedence over the `.gemini/skills/` directory.
The `.agents/skills/` alias provides an interoperable path for managing
agent-specific expertise that remains compatible across different AI tools.
## Key benefits
Agent Skills provide several advantages for managing specialized knowledge and
complex workflows.
- **Shared expertise**: Package complex workflows (like a specific team's PR
review process) into a folder that anyone can use.
- **Repeatable workflows**: Ensure complex multi-step tasks are performed
consistently by providing a procedural framework.
- **Resource bundling**: Include scripts, templates, or example data alongside
instructions so the agent has everything it needs.
- **Progressive disclosure**: Only skill metadata (name and description) is
loaded initially. Detailed instructions and resources are only disclosed when
the model explicitly activates the skill, saving context tokens.
<!-- prettier-ignore -->
> [!NOTE]
> `/skills disable` and `/skills enable` default to the `user` scope. Use
> `--scope workspace` to manage workspace-specific settings.
To see all available skills in your current session, use the `/skills list`
command.
## Managing skills
You can manage Agent Skills through interactive session commands or directly
from your terminal.
### In an interactive session
Use the `/skills` slash command to view and manage available expertise:
- `/skills list [all] [nodesc]`: Shows discovered skills. Use `all` to include
built-in skills and `nodesc` to hide descriptions.
- `/skills link <path> [--scope user|workspace]`: Links skills from a local
directory.
- `/skills disable <name>`: Prevents a specific skill from being used.
- `/skills enable <name>`: Re-enables a disabled skill.
- `/skills reload` (or `/skills refresh`): Refreshes the list of discovered
skills from all tiers.
### From the terminal
The `gemini skills` command provides management utilities:
```bash
# List all discovered skills. Use --all to include built-in skills.
gemini skills list --all
# Install a skill from a Git repository or local directory.
# Use --consent to skip the security confirmation prompt.
gemini skills install https://github.com/user/repo.git --consent
# Uninstall a skill.
gemini skills uninstall my-skill --scope workspace
```
#### Command options
The skill management commands support several global and command-specific
options.
- `--scope`: Either `user` (global, default) or `workspace` (local to the
project).
- `--path`: The sub-directory within a Git repository containing the skill.
- `--consent`: Acknowledge security risks and skip the interactive confirmation
during installation.
For more details on CLI commands, see the
[CLI reference](./cli-reference.md#skills-management).
## Next steps
Explore these resources to refine your skills and understand the framework
better.
- [Get started with Agent Skills](./tutorials/skills-getting-started.md): A
quick walkthrough of triggering and using skills.
- [Creating Agent Skills](./creating-skills.md): Create your first skill and
bundle custom logic.
- [Using Agent Skills](./using-agent-skills.md): Learn how to leverage built-in
and custom skills.
- [Best practices](./skills-best-practices.md): Learn strategies for building
effective skills.
+129
View File
@@ -0,0 +1,129 @@
# System Prompt Override (GEMINI_SYSTEM_MD)
The core system instructions that guide Gemini CLI can be completely replaced
with your own Markdown file. This feature is controlled via the
`GEMINI_SYSTEM_MD` environment variable.
## Overview
The `GEMINI_SYSTEM_MD` variable instructs the CLI to use an external Markdown
file for its system prompt, completely overriding the built-in default. This is
a full replacement, not a merge. If you use a custom file, none of the original
core instructions will apply unless you include them yourself.
This feature is intended for advanced users who need to enforce strict,
project-specific behavior or create a customized persona.
<!-- prettier-ignore -->
> [!TIP]
> You can export the current default system prompt to a file first, review
> it, and then selectively modify or replace it (see
> [“Export the default prompt”](#export-the-default-prompt-recommended)).
## How to enable
You can set the environment variable temporarily in your shell, or persist it
via a `.gemini/.env` file. See
[Persisting Environment Variables](../get-started/authentication.mdx#persisting-environment-variables).
- Use the project default path (`.gemini/system.md`):
- `GEMINI_SYSTEM_MD=true` or `GEMINI_SYSTEM_MD=1`
- The CLI reads `./.gemini/system.md` (relative to your current project
directory).
- Use a custom file path:
- `GEMINI_SYSTEM_MD=/absolute/path/to/my-system.md`
- Relative paths are supported and resolved from the current working
directory.
- Tilde expansion is supported (for example, `~/my-system.md`).
- Disable the override (use builtin prompt):
- `GEMINI_SYSTEM_MD=false` or `GEMINI_SYSTEM_MD=0` or unset the variable.
If the override is enabled but the target file does not exist, the CLI will
error with: `missing system prompt file '<path>'`.
## Quick examples
- Oneoff session using a project file:
- `GEMINI_SYSTEM_MD=1 gemini`
- Persist for a project using `.gemini/.env`:
- Create `.gemini/system.md`, then add to `.gemini/.env`:
- `GEMINI_SYSTEM_MD=1`
- Use a custom file under your home directory:
- `GEMINI_SYSTEM_MD=~/prompts/system.md gemini`
## UI indicator
When `GEMINI_SYSTEM_MD` is active, the CLI shows a `|⌐■_■|` indicator in the UI
to signal custom systemprompt mode.
## Variable Substitution
When using a custom system prompt file, you can use the following variables to
dynamically include built-in content:
- `${AgentSkills}`: Injects a complete section (including header) of all
available agent skills.
- `${SubAgents}`: Injects a complete section (including header) of available
sub-agents.
- `${AvailableTools}`: Injects a bulleted list of all currently enabled tool
names.
- Tool Name Variables: Injects the actual name of a tool using the pattern:
`${toolName}_ToolName` (for example, `${write_file_ToolName}`,
`${run_shell_command_ToolName}`).
This pattern is generated dynamically for all available tools.
### Example
```markdown
# Custom System Prompt
You are a helpful assistant. ${AgentSkills}
${SubAgents}
## Tooling
The following tools are available to you: ${AvailableTools}
You can use ${write_file_ToolName} to save logs.
```
## Export the default prompt (recommended)
Before overriding, export the current default prompt so you can review required
safety and workflow rules.
- Write the builtin prompt to the project default path:
- `GEMINI_WRITE_SYSTEM_MD=1 gemini`
- Or write to a custom path:
- `GEMINI_WRITE_SYSTEM_MD=~/prompts/DEFAULT_SYSTEM.md gemini`
This creates the file and writes the current builtin system prompt to it.
## Best practices: system.md vs GEMINI.md
- system.md (firmware):
- Nonnegotiable operational rules: safety, tooluse protocols, approvals, and
mechanics that keep the CLI reliable.
- Stable across tasks and projects (or per project when needed).
- GEMINI.md (strategy):
- Persona, goals, methodologies, and project/domain context.
- Evolves per task; relies on system.md for safe execution.
Keep system.md minimal but complete for safety and tool operation. Keep
GEMINI.md focused on highlevel guidance and project specifics.
## Troubleshooting
- Error: `missing system prompt file '…'`
- Ensure the referenced path exists and is readable.
- For `GEMINI_SYSTEM_MD=1|true`, create `./.gemini/system.md` in your project.
- Override not taking effect
- Confirm the variable is loaded (use `.gemini/.env` or export in your shell).
- Paths are resolved from the current working directory; try an absolute path.
- Restore defaults
- Unset `GEMINI_SYSTEM_MD` or set it to `0`/`false`.
File diff suppressed because it is too large Load Diff
+288
View File
@@ -0,0 +1,288 @@
# 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.
## Available themes
Gemini CLI comes with a selection of pre-defined themes, which you can list
using the `/theme` command within Gemini CLI:
- **Dark themes:**
- `ANSI`
- `Atom One`
- `Ayu`
- `Default`
- `Dracula`
- `GitHub`
- `Holiday`
- `Shades Of Purple`
- `Solarized Dark`
- `Tokyo Night`
- **Light themes:**
- `ANSI Light`
- `Ayu Light`
- `Default Light`
- `GitHub Light`
- `Google Code`
- `Solarized Light`
- `Xcode`
### Changing themes
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.
4. Confirm your selection to apply the theme.
<!-- prettier-ignore -->
> [!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](../reference/configuration.md) so your preference is remembered
across sessions.
---
## Custom color themes
Gemini CLI lets you 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
nested configuration objects. For example:
```json
{
"ui": {
"customThemes": {
"MyCustomTheme": {
"name": "MyCustomTheme",
"type": "custom",
"background": {
"primary": "#181818"
},
"text": {
"primary": "#f0f0f0",
"secondary": "#a0a0a0"
}
}
}
}
}
```
**Configuration objects:**
- **`text`**: Defines text colors.
- `primary`: The default text color.
- `secondary`: Used for less prominent text.
- `link`: Color for URLs and links.
- `accent`: Used for highlights and emphasis.
- `response`: Precedence over `primary` for rendering model responses.
- **`background`**: Defines background colors.
- `primary`: The main background color of the UI.
- `diff.added`: Background for added lines in diffs.
- `diff.removed`: Background for removed lines in diffs.
- **`border`**: Defines border colors.
- `default`: The standard border color.
- `focused`: Border color when an element is focused.
- **`status`**: Colors for status indicators.
- `success`: Used for successful operations.
- `warning`: Used for warnings.
- `error`: Used for errors.
- **`ui`**: Other UI elements.
- `comment`: Color for code comments.
- `symbol`: Color for code symbols and operators.
- `gradient`: An array of colors used for gradient effects.
**Required properties:**
- `name` (must match the key in the `customThemes` object and be a string)
- `type` (must be the string `"custom"`)
While all sub-properties are technically optional, we recommend providing at
least `background.primary`, `text.primary`, `text.secondary`, and the various
accent colors via `text.link`, `text.accent`, and `status` to ensure a cohesive
UI.
You can use either hex codes (for example, `#FF0000`) **or** standard CSS color
names (for example, `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.
### 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.
To load a theme from a file, set the `theme` property in your `settings.json` to
the path of your theme file:
```json
{
"ui": {
"theme": "/path/to/your/theme.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`:**
```json
{
"name": "Gruvbox Dark",
"type": "custom",
"background": {
"primary": "#282828",
"diff": {
"added": "#2b3312",
"removed": "#341212"
}
},
"text": {
"primary": "#ebdbb2",
"secondary": "#a89984",
"link": "#83a598",
"accent": "#d3869b"
},
"border": {
"default": "#3c3836",
"focused": "#458588"
},
"status": {
"success": "#b8bb26",
"warning": "#fabd2f",
"error": "#fb4934"
},
"ui": {
"comment": "#928374",
"symbol": "#8ec07c",
"gradient": ["#cc241d", "#d65d0e", "#d79921"]
}
}
```
<!-- prettier-ignore -->
> [!WARNING]
> 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
<img src="/docs/assets/theme-custom.png" alt="Custom theme example" width="600" />
### 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](../reference/configuration.md) as other
settings.
### Themes from extensions
[Extensions](../extensions/reference.md#themes) can also provide custom themes.
Once an extension is installed and enabled, its themes are automatically added
to the selection list in the `/theme` command.
Themes from extensions appear with the extension name in parentheses to help you
identify their source, for example: `shades-of-green (green-extension)`.
---
## Dark themes
### ANSI
<img src="/docs/assets/theme-ansi-dark.png" alt="ANSI theme" width="600">
### Atom One
<img src="/docs/assets/theme-atom-one-dark.png" alt="Atom One theme" width="600">
### Ayu
<img src="/docs/assets/theme-ayu-dark.png" alt="Ayu theme" width="600">
### Default
<img src="/docs/assets/theme-default-dark.png" alt="Default theme" width="600">
### Dracula
<img src="/docs/assets/theme-dracula-dark.png" alt="Dracula theme" width="600">
### GitHub
<img src="/docs/assets/theme-github-dark.png" alt="GitHub theme" width="600">
### Holiday
<img src="/docs/assets/theme-holiday-dark.png" alt="Holiday theme" width="600">
### Shades Of Purple
<img src="/docs/assets/theme-shades-of-purple-dark.png" alt="Shades Of Purple theme" width="600">
### Solarized Dark
<img src="/docs/assets/theme-solarized-dark.png" alt="Solarized Dark theme" width="600">
### Tokyo Night
<img src="/docs/assets/theme-tokyonight-dark.png" alt="Tokyo Night theme" width="600">
## Light themes
### ANSI Light
<img src="/docs/assets/theme-ansi-light.png" alt="ANSI Light theme" width="600">
### Ayu Light
<img src="/docs/assets/theme-ayu-light.png" alt="Ayu Light theme" width="600">
### Default Light
<img src="/docs/assets/theme-default-light.png" alt="Default Light theme" width="600">
### GitHub Light
<img src="/docs/assets/theme-github-light.png" alt="GitHub Light theme" width="600">
### Google Code
<img src="/docs/assets/theme-google-light.png" alt="Google Code theme" width="600">
### Solarized Light
<img src="/docs/assets/theme-solarized-light.png" alt="Solarized Light theme" width="600">
### Xcode
<img src="/docs/assets/theme-xcode-light.png" alt="Xcode Light theme" width="600">
+20
View File
@@ -0,0 +1,20 @@
# 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.
**Token caching is available for:**
- API key users (Gemini API key)
- Vertex AI users (with project and location setup)
**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
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.
+154
View File
@@ -0,0 +1,154 @@
# Trusted Folders
The Trusted Folders feature is a security setting that gives you control over
which projects can use the full capabilities of 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.
Add the following to your user `settings.json` file:
```json
{
"security": {
"folderTrust": {
"enabled": true
}
}
}
```
## How it works: The trust dialog
Once the feature is enabled, the first time you run 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 (for example,
`my-project`).
- **Trust parent folder**: Grants trust to the parent directory (for example,
`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.
## Understanding folder contents: The discovery phase
Before you make a choice, Gemini CLI performs a **discovery phase** to scan the
folder for potential configurations. This information is displayed in the trust
dialog to help you make an informed decision.
The discovery UI lists the following categories of items found in the project:
- **Commands**: Custom `.toml` command definitions that add new functionality.
- **MCP Servers**: Configured Model Context Protocol servers that the CLI will
attempt to connect to.
- **Hooks**: System or custom hooks that can intercept and modify CLI behavior.
- **Skills**: Local agent skills that provide specialized capabilities.
- **Setting overrides**: Any project-specific configurations that override your
global user settings.
### Security warnings and errors
The trust dialog also highlights critical information that requires your
attention:
- **Security Warnings**: The CLI will explicitly flag potentially dangerous
settings, such as auto-approving certain tools or disabling the security
sandbox.
- **Discovery Errors**: If the CLI encounters issues while scanning the folder
(for example, a malformed `settings.json` file), these errors will be
displayed prominently.
By reviewing these details, you can ensure that you only grant trust to projects
that you know are safe.
## Why trust matters: The impact of an untrusted workspace
When a folder is **untrusted**, 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.
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.
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.
6. **MCP servers do not connect**: The CLI will not attempt to connect to any
[Model Context Protocol (MCP)](../tools/mcp-server.md) servers.
7. **Custom commands are not loaded**: The CLI will not load any custom
commands from .toml files, including both project-specific and global user
commands.
Granting trust to a folder unlocks the full functionality of Gemini CLI for that
workspace.
## Headless and automated environments
When running Gemini CLI in a headless environment (for example, a CI/CD
pipeline) where interactive prompts are not possible, the trust dialog cannot be
displayed. If the folder is untrusted and the Folder Trust feature is enabled,
the CLI will throw a `FatalUntrustedWorkspaceError` and exit.
To proceed in these environments, you can bypass the trust check using one of
the following methods:
- **Command-line flag:** Run the CLI with the `--skip-trust` flag.
- **Environment variable:** Set the `GEMINI_CLI_TRUST_WORKSPACE=true`
environment variable.
These methods will trust the current workspace for the duration of the session
without prompting.
For detailed instructions on managing folder trust within CI/CD workflows,
review the
[Gemini CLI trust guidance for GitHub Actions](https://github.com/google-github-actions/run-gemini-cli/blob/main/docs/trust-guidance.md).
## Overriding the trust file location
By default, trust settings are saved to `~/.gemini/trustedFolders.json`. If you
need to store this file in a different location, you can set the
`GEMINI_CLI_TRUSTED_FOLDERS_PATH` environment variable to the desired absolute
file path.
## Managing your trust settings
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.
- **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:
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.
+284
View File
@@ -0,0 +1,284 @@
# Automate tasks with headless mode
Automate tasks with Gemini CLI. Learn how to use headless mode, pipe data into
Gemini CLI, automate workflows with shell scripts, and generate structured JSON
output for other applications.
## Prerequisites
- Gemini CLI installed and authenticated.
- Familiarity with shell scripting (Bash/Zsh).
## Why headless mode?
Headless mode runs Gemini CLI once and exits. It's perfect for:
- **CI/CD:** Analyzing pull requests automatically.
- **Batch processing:** Summarizing a large number of log files.
- **Tool building:** Creating your own "AI wrapper" scripts.
## How to use headless mode
Run Gemini CLI in headless mode by providing a prompt with the `-p` (or
`--prompt`) flag. This bypasses the interactive chat interface and prints the
response to standard output (stdout). Positional arguments without the flag
default to interactive mode, unless the input or output is piped or redirected.
Run a single command:
```bash
gemini -p "Write a poem about TypeScript"
```
## How to pipe input to Gemini CLI
Feed data into Gemini using the standard Unix pipe `|`. Gemini reads the
standard input (stdin) as context and answers your question using standard
output.
Pipe a file:
**macOS/Linux**
```bash
cat error.log | gemini -p "Explain why this failed"
```
**Windows (PowerShell)**
```powershell
Get-Content error.log | gemini -p "Explain why this failed"
```
Pipe a command:
```bash
git diff | gemini -p "Write a commit message for these changes"
```
## Use Gemini CLI output in scripts
Because Gemini prints to stdout, you can chain it with other tools or save the
results to a file.
### Scenario: Bulk documentation generator
You have a folder of Python scripts and want to generate a `README.md` for each
one.
1. Save the following code as `generate_docs.sh` (or `generate_docs.ps1` for
Windows):
**macOS/Linux (`generate_docs.sh`)**
```bash
#!/bin/bash
# Loop through all Python files
for file in *.py; do
echo "Generating docs for $file..."
# Ask Gemini CLI to generate the documentation and print it to stdout
gemini -p "Generate a Markdown documentation summary for @$file. Print the
result to standard output." > "${file%.py}.md"
done
```
**Windows PowerShell (`generate_docs.ps1`)**
```powershell
# Loop through all Python files
Get-ChildItem -Filter *.py | ForEach-Object {
Write-Host "Generating docs for $($_.Name)..."
$newName = $_.Name -replace '\.py$', '.md'
# Ask Gemini CLI to generate the documentation and print it to stdout
gemini -p "Generate a Markdown documentation summary for @$($_.Name). Print the result to standard output." | Out-File -FilePath $newName -Encoding utf8
}
```
2. Make the script executable and run it in your directory:
**macOS/Linux**
```bash
chmod +x generate_docs.sh
./generate_docs.sh
```
**Windows (PowerShell)**
```powershell
.\generate_docs.ps1
```
This creates a corresponding Markdown file for every Python file in the
folder.
## Extract structured JSON data
When writing a script, you often need structured data (JSON) to pass to tools
like `jq`. To get pure JSON data from the model, combine the
`--output-format json` flag with `jq` to parse the response field.
### Scenario: Extract and return structured data
1. Save the following script as `generate_json.sh` (or `generate_json.ps1` for
Windows):
**macOS/Linux (`generate_json.sh`)**
```bash
#!/bin/bash
# Ensure we are in a project root
if [ ! -f "package.json" ]; then
echo "Error: package.json not found."
exit 1
fi
# Extract data
gemini --output-format json "Return a raw JSON object with keys 'version' and 'deps' from @package.json" | jq -r '.response' > data.json
```
**Windows PowerShell (`generate_json.ps1`)**
```powershell
# Ensure we are in a project root
if (-not (Test-Path "package.json")) {
Write-Error "Error: package.json not found."
exit 1
}
# Extract data (requires jq installed, or you can use ConvertFrom-Json)
$output = gemini --output-format json "Return a raw JSON object with keys 'version' and 'deps' from @package.json" | ConvertFrom-Json
$output.response | Out-File -FilePath data.json -Encoding utf8
```
2. Run the script:
**macOS/Linux**
```bash
chmod +x generate_json.sh
./generate_json.sh
```
**Windows (PowerShell)**
```powershell
.\generate_json.ps1
```
3. Check `data.json`. The file should look like this:
```json
{
"version": "1.0.0",
"deps": {
"react": "^18.2.0"
}
}
```
## Build your own custom AI tools
Use headless mode to perform custom, automated AI tasks.
### Scenario: Create a "Smart Commit" alias
You can add a function to your shell configuration to create a `git commit`
wrapper that writes the message for you.
**macOS/Linux (Bash/Zsh)**
1. Open your `.zshrc` file (or `.bashrc` if you use Bash) in your preferred
text editor.
```bash
nano ~/.zshrc
```
**Note**: If you use VS Code, you can run `code ~/.zshrc`.
2. Scroll to the very bottom of the file and paste this code:
```bash
function gcommit() {
# Get the diff of staged changes
diff=$(git diff --staged)
if [ -z "$diff" ]; then
echo "No staged changes to commit."
return 1
fi
# Ask Gemini to write the message
echo "Generating commit message..."
msg=$(echo "$diff" | gemini -p "Write a concise Conventional Commit message for this diff. Output ONLY the message.")
# Commit with the generated message
git commit -m "$msg"
}
```
Save your file and exit.
3. Run this command to make the function available immediately:
```bash
source ~/.zshrc
```
**Windows (PowerShell)**
1. Open your PowerShell profile in your preferred text editor.
```powershell
notepad $PROFILE
```
2. Scroll to the very bottom of the file and paste this code:
```powershell
function gcommit {
# Get the diff of staged changes
$diff = git diff --staged
if (-not $diff) {
Write-Host "No staged changes to commit."
return
}
# Ask Gemini to write the message
Write-Host "Generating commit message..."
$msg = $diff | gemini -p "Write a concise Conventional Commit message for this diff. Output ONLY the message."
# Commit with the generated message
git commit -m "$msg"
}
```
Save your file and exit.
3. Run this command to make the function available immediately:
```powershell
. $PROFILE
```
4. Use your new command:
```bash
gcommit
```
Gemini CLI will analyze your staged changes and commit them with a generated
message.
## Next steps
- Explore the [Headless mode reference](../../cli/headless.md) for full JSON
schema details.
- Learn about [Shell commands](shell-commands.md) to let the agent run scripts
instead of just writing them.
+144
View File
@@ -0,0 +1,144 @@
# File management with Gemini CLI
Explore, analyze, and modify your codebase using Gemini CLI. In this guide,
you'll learn how to provide Gemini CLI with files and directories, modify and
create files, and control what Gemini CLI can see.
## Prerequisites
- Gemini CLI installed and authenticated.
- A project directory to work with (for example, a git repository).
## Providing context by reading files
Gemini CLI will generally try to read relevant files, sometimes prompting you
for access (depending on your settings). To ensure that Gemini CLI uses a file,
you can also include it directly.
### Direct file inclusion (`@`)
If you know the path to the file you want to work on, use the `@` symbol. This
forces the CLI to read the file immediately and inject its content into your
prompt.
```bash
`@src/components/UserProfile.tsx Explain how this component handles user data.`
```
### Working with multiple files
Complex features often span multiple files. You can chain `@` references to give
the agent a complete picture of the dependencies.
```bash
`@src/components/UserProfile.tsx @src/types/User.ts Refactor the component to use the updated User interface.`
```
### Including entire directories
For broad questions or refactoring, you can include an entire directory. Be
careful with large folders, as this consumes more tokens.
```bash
`@src/utils/ Check these utility functions for any deprecated API usage.`
```
## How to find files (Exploration)
If you _don't_ know the exact file path, you can ask Gemini CLI to find it for
you. This is useful when navigating a new codebase or looking for specific
logic.
### Scenario: Find a component definition
You know there's a `UserProfile` component, but you don't know where it lives.
```none
`Find the file that defines the UserProfile component.`
```
Gemini uses the `glob` or `list_directory` tools to search your project
structure. It will return the specific path (for example,
`src/components/UserProfile.tsx`), which you can then use with `@` in your next
turn.
<!-- prettier-ignore -->
> [!TIP]
> You can also ask for lists of files, like "Show me all the TypeScript
> configuration files in the root directory."
## How to modify code
Once Gemini CLI has context, you can direct it to make specific edits. The agent
is capable of complex refactoring, not just simple text replacement.
```none
`Update @src/components/UserProfile.tsx to show a loading spinner if the user data is null.`
```
Gemini CLI uses the `replace` tool to propose a targeted code change.
### Creating new files
You can also ask the agent to create entirely new files or folder structures.
```none
`Create a new file @src/components/LoadingSpinner.tsx with a simple Tailwind CSS spinner.`
```
Gemini CLI uses the `write_file` tool to generate the new file from scratch.
## Review and confirm changes
Gemini CLI prioritizes safety. Before any file is modified, it presents a
unified diff of the proposed changes.
```diff
- if (!user) return null;
+ if (!user) return <LoadingSpinner />;
```
- **Red lines (-):** Code that will be removed.
- **Green lines (+):** Code that will be added.
Press **y** to confirm and apply the change to your local file system. If the
diff doesn't look right, press **n** to cancel and refine your prompt.
## Verify the result
After the edit is complete, verify the fix. You can simply read the file again
or, better yet, run your project's tests.
```none
`Run the tests for the UserProfile component.`
```
Gemini CLI uses the `run_shell_command` tool to execute your test runner (for
example, `npm test` or `jest`). This ensures the changes didn't break existing
functionality.
## Advanced: Controlling what Gemini sees
By default, Gemini CLI respects your `.gitignore` file. It won't read or search
through `node_modules`, build artifacts, or other ignored paths.
If you have sensitive files (like `.env`) or large assets that you want to keep
hidden from the AI _without_ ignoring them in Git, you can create a
`.geminiignore` file in your project root.
**Example `.geminiignore`:**
```text
.env
local-db-dump.sql
private-notes.md
```
## Next steps
- Learn how to [Manage context and memory](memory-management.md) to keep your
agent smarter over long sessions.
- See [Execute shell commands](shell-commands.md) for more on running tests and
builds.
- Explore the technical [File system reference](../../tools/file-system.md) for
advanced tool parameters.
+115
View File
@@ -0,0 +1,115 @@
# Set up an MCP server
Connect Gemini CLI to your external databases and services. In this guide,
you'll learn how to extend Gemini CLI's capabilities by installing the GitHub
MCP server and using it to manage your repositories.
## Prerequisites
- Gemini CLI installed.
- **Docker:** Required for this specific example (many MCP servers run as Docker
containers).
- **GitHub token:** A Personal Access Token (PAT) with repo permissions.
## How to prepare your credentials
Most MCP servers require authentication. For GitHub, you need a PAT.
1. Create a [fine-grained PAT](https://github.com/settings/tokens?type=beta).
2. Grant it **Read** access to **Metadata** and **Contents**, and
**Read/Write** access to **Issues** and **Pull Requests**.
3. Store it in your environment:
**macOS/Linux**
```bash
export GITHUB_PERSONAL_ACCESS_TOKEN="github_pat_..."
```
**Windows (PowerShell)**
```powershell
$env:GITHUB_PERSONAL_ACCESS_TOKEN="github_pat_..."
```
## How to configure Gemini CLI
You tell Gemini about new servers by editing your `settings.json`.
1. Open `~/.gemini/settings.json` (or the project-specific
`.gemini/settings.json`).
2. Add the `mcpServers` block. This tells Gemini: "Run this docker container
and talk to it."
```json
{
"mcpServers": {
"github": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:latest"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PERSONAL_ACCESS_TOKEN}"
}
}
}
}
```
<!-- prettier-ignore -->
> [!NOTE]
> The `command` is `docker`, and the rest are arguments passed to it. We
> map the local environment variable into the container so your secret isn't
> hardcoded in the config file.
## How to verify the connection
Restart Gemini CLI. It will automatically try to start the defined servers.
**Command:** `/mcp list`
You should see: `✓ github: docker ... - Connected`
If you see `Disconnected` or an error, check that Docker is running and your API
token is valid.
## How to use the new tools
Now that the server is running, the agent has new capabilities ("tools"). You
don't need to learn special commands; just ask in natural language.
### Scenario: Listing pull requests
**Prompt:** `List the open PRs in the google/gemini-cli repository.`
The agent will:
1. Recognize the request matches a GitHub tool.
2. Call `mcp_github_list_pull_requests`.
3. Present the data to you.
### Scenario: Creating an issue
**Prompt:**
`Create an issue in my repo titled "Bug: Login fails" with the description "See logs".`
## Troubleshooting
- **Server won't start?** Try running the docker command manually in your
terminal to see if it prints an error (for example, "image not found").
- **Tools not found?** Run `/mcp reload` to force the CLI to re-query the server
for its capabilities.
## Next steps
- Explore the [MCP servers reference](../../tools/mcp-server.md) to learn about
SSE and HTTP transports for remote servers.
- Browse the
[official MCP server list](https://github.com/modelcontextprotocol/servers) to
find connectors for Slack, Postgres, Google Drive, and more.
+128
View File
@@ -0,0 +1,128 @@
# Manage context and memory
Control what Gemini CLI knows about you and your projects. In this guide, you'll
learn how to define project-wide rules with `GEMINI.md`, teach the agent
persistent facts, and inspect the active context.
## Prerequisites
- Gemini CLI installed and authenticated.
- A project directory where you want to enforce specific rules.
## Why manage context?
Gemini CLI is powerful but general. It doesn't know your preferred testing
framework, your indentation style, or your preference against `any` in
TypeScript. Context management solves this by giving the agent persistent
memory.
You'll use these features when you want to:
- **Enforce standards:** Ensure every generated file matches your team's style
guide.
- **Set a persona:** Tell the agent to act as a "Senior Rust Engineer" or "QA
Specialist."
- **Remember facts:** Save details like "My database port is 5432" so you don't
have to repeat them.
## How to define project-wide rules (GEMINI.md)
The most powerful way to control the agent's behavior is through `GEMINI.md`
files. These are Markdown files containing instructions that are automatically
loaded into every conversation.
### Scenario: Create a project context file
1. In the root of your project, create a file named `GEMINI.md`.
2. Add your instructions:
```markdown
# Project Instructions
- **Framework:** We use React with Vite.
- **Styling:** Use Tailwind CSS for all styling. Do not write custom CSS.
- **Testing:** All new components must include a Vitest unit test.
- **Tone:** Be concise. Don't explain basic React concepts.
```
3. Start a new session. Gemini CLI will now know these rules automatically.
### Scenario: Using the hierarchy
Context is loaded hierarchically. This lets you have general rules for
everything and specific rules for sub-projects.
1. **Global:** `~/.gemini/GEMINI.md` (Rules for _every_ project you work on).
2. **Project Root:** `./GEMINI.md` (Rules for the current repository).
3. **Subdirectory:** `./src/GEMINI.md` (Rules specific to the `src` folder).
**Example:** You might set "Always use strict typing" in your global config, but
"Use Python 3.11" only in your backend repository.
## How to teach the agent facts (Memory)
Sometimes you don't want to write a config file. You just want to tell the agent
something once and have it remember forever. You can do this naturally in chat.
### Scenario: Saving a memory
Just tell the agent to remember something.
**Prompt:** `Remember that I prefer using 'const' over 'let' wherever possible.`
The agent will edit the appropriate memory Markdown file, so the fact is loaded
in future sessions.
**Prompt:** `Save the fact that the staging server IP is 10.0.0.5.`
### Scenario: Using memory in conversation
Once a fact is saved, you don't need to invoke it explicitly. The agent "knows"
it.
**Next Prompt:** `Write a script to deploy to staging.`
**Agent Response:** "I'll write a script to deploy to **10.0.0.5**..."
## How to manage and inspect context
As your project grows, you might want to see exactly what instructions the agent
is following.
### Scenario: View active context
To see the full, concatenated set of instructions currently loaded (from all
`GEMINI.md` files and saved memories), use the `/memory show` command.
**Command:** `/memory show`
This prints the raw text the model receives at the start of the session. It's
excellent for debugging why the agent might be ignoring a rule.
### Scenario: Refresh context
If you edit a `GEMINI.md` file while a session is running, the agent won't know
immediately. Force a reload with:
**Command:** `/memory reload`
## Best practices
- **Keep it focused:** Avoid adding excessive content to `GEMINI.md`. Keep
instructions actionable and relevant to code generation.
- **Use negative constraints:** Explicitly telling the agent what _not_ to do
(for example, "Do not use class components") is often more effective than
vague positive instructions.
- **Review often:** Periodically check your `GEMINI.md` files to remove outdated
rules.
## Next steps
- Learn about [Session management](session-management.md) to see how short-term
history works.
- Explore the [Command reference](../../reference/commands.md) for more
`/memory` options.
- Read the technical spec for [Project context](../../cli/gemini-md.md).
- Try the experimental [Auto Memory](../auto-memory.md) feature to extract
memory updates and reusable skills from your past sessions automatically.
+90
View File
@@ -0,0 +1,90 @@
# Use Plan Mode with model steering for complex tasks
Architecting a complex solution requires precision. By combining Plan Mode's
structured environment with model steering's real-time feedback, you can guide
Gemini CLI through the research and design phases to ensure the final
implementation plan is exactly what you need.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
## Prerequisites
- Gemini CLI installed and authenticated.
- [Plan Mode](../plan-mode.md) enabled in your settings.
- [Model steering](../model-steering.md) enabled in your settings.
## Why combine Plan Mode and model steering?
[Plan Mode](../plan-mode.md) typically follows a linear path: research, propose,
and draft. Adding model steering lets you:
1. **Direct the research:** Correct the agent if it's looking in the wrong
directory or missing a key dependency.
2. **Iterate mid-draft:** Suggest a different architectural pattern while the
agent is still writing the plan.
3. **Speed up the loop:** Avoid waiting for a full research turn to finish
before providing critical context.
## Step 1: Start a complex task
Enter Plan Mode and start a task that requires research.
**Prompt:** `/plan I want to implement a new notification service using Redis.`
Gemini CLI enters Plan Mode and starts researching your existing codebase to
identify where the new service should live.
## Step 2: Steer the research phase
As you see the agent calling tools like `list_directory` or `grep_search`, you
might realize it's missing the relevant context.
**Action:** While the spinner is active, type your hint:
`"Don't forget to check packages/common/queues for the existing Redis config."`
**Result:** Gemini CLI acknowledges your hint and immediately incorporates it
into its research. You'll see it start exploring the directory you suggested in
its very next turn.
## Step 3: Refine the design mid-turn
After research, the agent starts drafting the implementation plan. If you notice
it's proposing a design that doesn't align with your goals, steer it.
**Action:** Type:
`"Actually, let's use a Publisher/Subscriber pattern instead of a simple queue for this service."`
**Result:** The agent stops drafting the current version of the plan,
re-evaluates the design based on your feedback, and starts a new draft that uses
the Pub/Sub pattern.
## Step 4: Approve and implement
Once the agent has used your hints to craft the perfect plan, review the final
`.md` file.
**Action:** Type: `"Looks perfect. Let's start the implementation."`
Gemini CLI exits Plan Mode and transitions to the implementation phase. Because
the plan was refined in real-time with your feedback, the agent can now execute
each step with higher confidence and fewer errors.
## Tips for effective steering
- **Be specific:** Instead of "do it differently," try "use the existing
`Logger` class in `src/utils`."
- **Steer early:** Providing feedback during the research phase is more
efficient than waiting for the final plan to be drafted.
- **Use for context:** Steering is a great way to provide knowledge that might
not be obvious from reading the code (for example, "We are planning to
deprecate this module next month").
## Next steps
- Explore [Agent Skills](../skills.md) to add specialized expertise to your
planning turns.
- See the [Model steering reference](../model-steering.md) for technical
details.
+118
View File
@@ -0,0 +1,118 @@
# Manage sessions and history
Resume, browse, and rewind your conversations with Gemini CLI. In this guide,
you'll learn how to switch between tasks, manage your session history, and undo
mistakes using the rewind feature.
## Prerequisites
- Gemini CLI installed and authenticated.
- At least one active or past session.
## How to resume where you left off
It's common to switch context—maybe you're waiting for a build and want to work
on a different feature. Gemini makes it easy to jump back in.
### Scenario: Resume the last session
The fastest way to pick up your most recent work is with the `--resume` flag (or
`-r`).
```bash
gemini -r
```
This restores your chat history and memory, so you can say "Continue with the
next step" immediately.
### Scenario: Browse past sessions
If you want to find a specific conversation from yesterday, use the interactive
browser.
**Command:** `/resume`
This opens a searchable list of all your past sessions. You'll see:
- A timestamp (for example, "2 hours ago").
- The first user message (helping you identify the topic).
- The number of turns in the conversation.
Select a session and press **Enter** to load it.
## How to manage your workspace
Over time, you'll accumulate a lot of history. Keeping your session list clean
helps you find what you need.
### Scenario: Deleting sessions
In the `/resume` browser, navigate to a session you no longer need and press
**x**. This permanently deletes the history for that specific conversation.
You can also manage sessions from the command line:
```bash
# List all sessions with their IDs
gemini --list-sessions
# Delete a specific session by ID or index
gemini --delete-session 1
```
### Scenario: Delete session on exit
If you're doing a one-off task and don't want to leave any session history
behind, use the `--delete` flag when exiting:
```
/exit --delete
```
This removes the current session's conversation history and tool output files
before exiting. It's useful for privacy-sensitive tasks or quick one-off
interactions.
## How to rewind time (Undo mistakes)
Gemini CLI's **Rewind** feature is like `Ctrl+Z` for your workflow.
### Scenario: Triggering rewind
At any point in a chat, type `/rewind` or press **Esc** twice.
### Scenario: Choosing a restore point
You'll see a list of your recent interactions. Select the point _before_ the
undesired changes occurred.
### Scenario: Choosing what to revert
Gemini gives you granular control over the undo process. You can choose to:
1. **Rewind conversation:** Only remove the chat history. The files stay
changed. (Useful if the code is good but the chat got off track).
2. **Revert code changes:** Keep the chat history but undo the file edits.
(Useful if you want to keep the context but retry the implementation).
3. **Rewind both:** Restore everything to exactly how it was.
## How to fork conversations
Sometimes you want to try two different approaches to the same problem.
1. Start a session and get to a decision point.
2. Save the current state with `/resume save decision-point`.
3. Try your first approach.
4. Later, use `/resume resume decision-point` to fork the conversation back to
that moment and try a different approach.
This creates a new branch of history without losing your original work.
## Next steps
- Learn about [Checkpointing](../../cli/checkpointing.md) to understand the
underlying safety mechanism.
- Explore [Task planning](task-planning.md) to keep complex sessions organized.
- See the [Command reference](../../reference/commands.md) for `/resume`
options, grouped checkpoint menus, and `/chat` compatibility aliases.
+108
View File
@@ -0,0 +1,108 @@
# Execute shell commands
Use the CLI to run builds, manage git, and automate system tasks without leaving
the conversation. In this guide, you'll learn how to run commands directly,
automate complex workflows, and manage background processes safely.
## Prerequisites
- Gemini CLI installed and authenticated.
- Basic familiarity with your system's shell (Bash, Zsh, PowerShell, and so on).
## How to run commands directly (`!`)
Sometimes you just need to check a file size or git status without asking the AI
to do it for you. You can pass commands directly to your shell using the `!`
prefix.
**Example:** `!ls -la`
This executes `ls -la` immediately and prints the output to your terminal.
Gemini CLI also records the command and its output in the current session
context, so the model can reference it in follow-up prompts. Very large outputs
may be truncated.
### Scenario: Entering Shell mode
If you're doing a lot of manual work, toggle "Shell Mode" by typing `!` and
pressing **Enter**. Now, everything you type is sent to the shell until you exit
(usually by pressing **Esc** or typing `exit`).
## How to automate complex tasks
You can automate tasks using a combination of Gemini CLI and shell commands.
### Scenario: Run tests and fix failures
You want to run tests and fix any failures.
**Prompt:**
`Run the unit tests. If any fail, analyze the error and try to fix the code.`
**Workflow:**
1. Gemini calls `run_shell_command('npm test')`.
2. You see a confirmation prompt: `Allow command 'npm test'? [y/N]`.
3. You press `y`.
4. The tests run. If they fail, Gemini reads the error output.
5. Gemini uses `read_file` to inspect the failing test.
6. Gemini uses `replace` to fix the bug.
7. Gemini runs `npm test` again to verify the fix.
This loop lets Gemini work autonomously.
## How to manage background processes
You can ask Gemini to start long-running tasks, like development servers or file
watchers.
**Prompt:** `Start the React dev server in the background.`
Gemini will run the command (for example, `npm run dev`) and detach it.
### Scenario: Viewing active shells
To see what's running in the background, use the `/shells` command.
**Command:** `/shells`
This opens a dashboard where you can view logs or kill runaway processes.
## How to handle interactive commands
Gemini CLI attempts to handle interactive commands (like `git add -p` or
confirmation prompts) by streaming the output to you. However, for highly
interactive tools (like `vim` or `top`), it's often better to run them yourself
in a separate terminal window or use the `!` prefix.
## Safety features
Giving an AI access to your shell is powerful but risky. Gemini CLI includes
several safety layers.
### Confirmation prompts
By default, **every** shell command requested by the agent requires your
explicit approval.
- **Allow once:** Runs the command one time.
- **Allow always:** Trusts this specific command for the rest of the session.
- **Deny:** Stops the agent.
### Sandboxing
For maximum security, especially when running untrusted code or exploring new
projects, we strongly recommend enabling Sandboxing. This runs all shell
commands inside a secure Docker container.
**Enable sandboxing:** Use the `--sandbox` flag when starting the CLI:
`gemini --sandbox`.
## Next steps
- Learn about [Sandboxing](../../cli/sandbox.md) to safely run destructive
commands.
- See the [Shell tool reference](../../tools/shell.md) for configuration options
like timeouts and working directories.
- Explore [Task planning](task-planning.md) to see how shell commands fit into
larger workflows.
@@ -0,0 +1,158 @@
# Get started with Agent Skills
Agent Skills extend Gemini CLI with specialized expertise. In this tutorial,
you'll learn how to create your first skill, bundle custom logic, and activate
it during a session.
## Create your first skill
A skill is defined by a directory containing a `SKILL.md` file and
subdirectories containing reference materials or scripts used by the skill.
Let's create an **API Auditor** skill that runs a script to help you verify if
local or remote endpoints are responding correctly.
### 1. Create the directory structure
The first step is to create the necessary folders for your skill and its
scripts.
**macOS/Linux**
```bash
mkdir -p .gemini/skills/api-auditor/scripts
```
**Windows (PowerShell)**
```powershell
New-Item -ItemType Directory -Force -Path ".gemini\skills\api-auditor\scripts"
```
### 2. Create the definition (`SKILL.md`)
The `SKILL.md` file defines the skill's purpose and instructions for the agent.
Create a file at `.gemini/skills/api-auditor/SKILL.md`. This tells the agent
_when_ to use the skill and _how_ to behave.
```markdown
---
name: api-auditor
description:
Expertise in auditing and testing API endpoints. Use when the user asks to
"check", "test", or "audit" a URL or API.
---
# API Auditor Instructions
You act as a QA engineer specialized in API reliability. When this skill is
active, you MUST:
1. **Audit**: Use the bundled `scripts/audit.js` utility to check the status of
the provided URL.
2. **Report**: Analyze the output (status codes, latency) and explain any
failures in plain English.
3. **Secure**: Remind the user if they are testing a sensitive endpoint without
an `https://` protocol.
```
### 3. Add the tool logic
Skills can bundle resources like scripts to perform deterministic tasks. Create
a file at `.gemini/skills/api-auditor/scripts/audit.js`. This is the code the
agent will run.
```javascript
// .gemini/skills/api-auditor/scripts/audit.js
const url = process.argv[2];
if (!url) {
console.error('Usage: node audit.js <url>');
process.exit(1);
}
console.log(`Auditing ${url}...`);
fetch(url, { method: 'HEAD' })
.then((r) => console.log(`Result: Success (Status ${r.status})`))
.catch((e) => console.error(`Result: Failed (${e.message})`));
```
## Verify discovery
Gemini CLI automatically discovers skills in the `.gemini/skills` directory (as
well as the `.agents/skills` alias).
To check if Gemini CLI found your new skill, use the `/skills list` command
within an interactive session:
```bash
/skills list
```
You should see `api-auditor` in the list of available skills. If you just added
the files, you can run `/skills reload` to refresh the list without restarting
the session.
### If your skill doesn't appear
If `/skills list` doesn't show your skill, check the following:
1. **The folder must be trusted (workspace skills only).** Skills under
`<workspace>/.gemini/skills/` are only loaded when the workspace folder is
marked as trusted. Run `/trust` and restart the session if needed. Skills
under `~/.gemini/skills/` (user scope) are not affected by trust.
2. **Check the path layout.** `SKILL.md` is discovered either at the root of
the skills directory (`.gemini/skills/SKILL.md`) or one directory deep
(`.gemini/skills/<skill-name>/SKILL.md`). The recommended layout uses a
subdirectory per skill so you can bundle scripts and other resources
alongside it. Files nested more than one directory deep are not discovered.
3. **The filename must be exactly `SKILL.md`.** Capitalization matters on
case-sensitive filesystems (Linux, and macOS when configured as such):
`skill.md` or `Skill.md` will be ignored.
4. **Frontmatter must include both `name:` and `description:`, and must be the
first thing in the file.** A `SKILL.md` is silently skipped if either field
is missing, if the delimiters (`---` on their own lines) are absent, or if
any text (an H1 title, a comment, even a blank line) appears before the
opening `---`.
5. **The skill name comes from the `name:` field, not the directory name.** If
your frontmatter says `name: foo`, the skill appears as `foo` in
`/skills list` regardless of what its parent directory is called. The
characters `: \ / < > * ? " |` in the name are replaced with `-`.
## How to use the skill
Now that the skill is discovered, you can trigger its activation by asking a
relevant question.
1. **Trigger**: Start a new session and ask: "Can you audit https://google.com"
2. **Activation**: Gemini identifies that the request matches the `api-auditor`
description and calls the `activate_skill` tool.
3. **Consent**: You will see a confirmation prompt. Type **y** to approve.
4. **Execution**: Once activated, Gemini uses the `run_shell_command` tool to
execute your bundled script:
`node .gemini/skills/api-auditor/scripts/audit.js https://google.com`
## Pro tip: Use the skill-creator
If you don't want to create the files manually, you can use the built-in
`skill-creator` skill. Simply ask Gemini:
> "Create a new skill called 'api-auditor' that tests if URLs are responding."
The `skill-creator` will handle the directory structure and boilerplate for you.
## Manage skills
You can also manage skills using the `gemini skills` command from your terminal:
- **Install**: `gemini skills install <url-or-path>`
- **Link**: `gemini skills link <path>` (useful for local development)
- **Uninstall**: `gemini skills uninstall <name>`
## Next steps
- [Creating Agent Skills](../creating-skills.md): Detailed guide on advanced
skill features and metadata.
- [Using Agent Skills](../using-agent-skills.md): More ways to discover and
manage your skill library.
- [Skill best practices](../skills-best-practices.md): Learn how to design
reliable and effective expertise.
+93
View File
@@ -0,0 +1,93 @@
# Plan tasks with todos
Keep complex jobs on the rails with Gemini CLI's built-in task planning. In this
guide, you'll learn how to ask for a plan, execute it step-by-step, and monitor
progress with the todo list.
## Prerequisites
- Gemini CLI installed and authenticated.
- A complex task in mind (for example, a multi-file refactor or new feature).
## Why use task planning?
Standard LLMs have a limited context window and can "forget" the original goal
after 10 turns of code generation. Task planning provides:
1. **Visibility:** You see exactly what the agent plans to do _before_ it
starts.
2. **Focus:** The agent knows exactly which step it's working on right now.
3. **Resilience:** If the agent gets stuck, the plan helps it get back on
track.
## How to ask for a plan
The best way to trigger task planning is to explicitly ask for it.
**Prompt:**
`I want to migrate this project from JavaScript to TypeScript. Please make a plan first.`
Gemini will analyze your codebase and use the `write_todos` tool to generate a
structured list.
**Example Plan:**
1. [ ] Create `tsconfig.json`.
2. [ ] Rename `.js` files to `.ts`.
3. [ ] Fix type errors in `utils.js`.
4. [ ] Fix type errors in `server.js`.
5. [ ] Verify build passes.
## How to review and iterate
Once the plan is generated, it appears in your CLI. Review it.
- **Missing steps?** Tell the agent: "You forgot to add a step for installing
`@types/node`."
- **Wrong order?** Tell the agent: "Let's verify the build _after_ each file,
not just at the end."
The agent will update the todo list dynamically.
## How to execute the plan
Tell the agent to proceed.
**Prompt:** `Looks good. Start with the first step.`
As the agent works, you'll see the todo list update in real-time above the input
box.
- **Current focus:** The active task is highlighted (for example,
`[IN_PROGRESS] Create tsconfig.json`).
- **Progress:** Completed tasks are marked as done.
## How to monitor progress (`Ctrl+T`)
For a long-running task, the full todo list might be hidden to save space. You
can toggle the full view at any time.
**Action:** Press **Ctrl+T**.
This shows the complete list, including pending, in-progress, and completed
items. It's a great way to check "how much is left?" without scrolling back up.
## How to handle unexpected changes
Plans change. Maybe you discover a library is incompatible halfway through.
**Prompt:**
`Actually, let's skip the 'server.js' refactor for now. It's too risky.`
The agent will mark that task as `cancelled` or remove it, and move to the next
item. This dynamic adjustment is what makes the todo system powerful—it's a
living document, not a static text block.
## Next steps
- Explore [Session management](session-management.md) to save your plan and
finish it tomorrow.
- See the [Todo tool reference](../../tools/todos.md) for technical schema
details.
- Learn about [Memory management](memory-management.md) to persist planning
preferences (for example, "Always create a test plan first").
+78
View File
@@ -0,0 +1,78 @@
# Web search and fetch
Access the live internet directly from your prompt. In this guide, you'll learn
how to search for up-to-date documentation, fetch deep context from specific
URLs, and apply that knowledge to your code.
## Prerequisites
- Gemini CLI installed and authenticated.
- An internet connection.
## How to research new technologies
Imagine you want to use a library released yesterday. The model doesn't know
about it yet. You need to teach it.
### Scenario: Find documentation
**Prompt:**
`Search for the 'Bun 1.0' release notes and summarize the key changes.`
Gemini uses the `google_web_search` tool to find relevant pages and synthesizes
an answer. This "grounding" process ensures the agent isn't hallucinating
features that don't exist.
**Prompt:** `Find the documentation for the 'React Router v7' loader API.`
## How to fetch deep context
Search gives you a summary, but sometimes you need the raw details. The
`web_fetch` tool lets you feed a specific URL directly into the agent's context.
### Scenario: Reading a blog post
You found a blog post with the exact solution to your bug.
**Prompt:**
`Read https://example.com/fixing-memory-leaks and explain how to apply it to my code.`
Gemini will retrieve the page content (stripping away ads and navigation) and
use it to answer your question.
### Scenario: Comparing sources
You can even fetch multiple pages to compare approaches.
**Prompt:**
`Compare the pagination patterns in https://api.example.com/v1/docs and https://api.example.com/v2/docs.`
## How to apply knowledge to code
The real power comes when you combine web tools with file editing.
**Workflow:**
1. **Search:** "How do I implement auth with Supabase?"
2. **Fetch:** "Read this guide: https://supabase.com/docs/guides/auth."
3. **Implement:** "Great. Now use that pattern to create an `auth.ts` file in
my project."
## How to troubleshoot errors
When you hit an obscure error message, paste it into the chat.
**Prompt:**
`I'm getting 'Error: hydration mismatch' in Next.js. Search for recent solutions.`
The agent will search sources such as GitHub issues, StackOverflow, and forums
to find relevant fixes that might be too new to be in its base training set.
## Next steps
- Explore [File management](file-management.md) to see how to apply the code you
generate.
- See the [Web search tool reference](../../tools/web-search.md) for citation
details.
- See the [Web fetch tool reference](../../tools/web-fetch.md) for technical
limitations.
+89
View File
@@ -0,0 +1,89 @@
# Managing Agent Skills
Agent Skills provide Gemini CLI with specialized expertise on demand. This guide
covers advanced management techniques, including using slash commands, terminal
utilities, and understanding discovery tiers.
## Discovery tiers
Gemini CLI discovers skills from several locations, following a specific order
of precedence (lowest to highest):
1. **Built-in Skills**: Included with Gemini CLI and always available.
2. **Extension Skills**: Bundled within [extensions](../extensions/index.md).
3. **User Skills**: Located in `~/.gemini/skills/` or the `~/.agents/skills/`
alias. These are available across all your projects.
4. **Workspace Skills**: Located in `.gemini/skills/` or the `.agents/skills/`
alias within your current directory. These are project-specific.
> **Tip:** If multiple skills share the same name, the version from the
> higher-precedence location is used.
## In-session management
Use the `/skills` slash command during an interactive session to manage your
available expertise.
- **List skills**: `/skills list` (shows discovered skills).
- Use `/skills list all` to include internal built-in skills.
- Use `/skills list nodesc` to hide descriptions.
- **Reload skills**: `/skills reload` (or `/skills refresh`) to scan for new or
modified skills without restarting the CLI.
- **Toggle status**:
- `/skills disable <name>`: Prevents a skill from being triggered.
- `/skills enable <name>`: Re-enables a disabled skill.
- **Link local skills**: `/skills link <path> [--scope user|workspace]` to
immediately use a skill you are developing.
## Terminal utilities
The `gemini skills` command provides management utilities directly from your
system shell.
### Install a skill
To install a skill from a remote repository or a local `.skill` package:
```bash
gemini skills install https://github.com/user/my-awesome-skill
```
By default, this installs to your **user profile**. Use `--scope workspace` to
install it only for the current project.
### Link for development
If you are developing a skill, use the `link` command to create a reference to
your local directory:
```bash
gemini skills link ./path/to/my-skill
```
### Uninstall a skill
To completely remove an installed or linked skill:
```bash
gemini skills uninstall <name>
```
## Security and consent
Agent Skills can execute scripts and access your files. To protect your
environment:
1. **Installation consent**: When installing from a remote URL, you will be
asked to confirm the source.
2. **Activation consent**: Every time a skill is triggered during a session,
the agent must ask for permission to activate it and gain access to its
resources.
## Next steps
- [Get started with Agent Skills](./tutorials/skills-getting-started.md): A
walkthrough for creating your first skill.
- [Creating Agent Skills](./creating-skills.md): Detailed guide on bundling
scripts and assets.
- [Skill best practices](./skills-best-practices.md): Strategies for building
reliable expertise.