Compare commits

..

8 Commits

Author SHA1 Message Date
gemini-cli-robot a35d001fde chore(release): v0.19.2 2025-12-05 04:51:01 +00:00
gemini-cli-robot 95f9032bf4 fix(patch): cherry-pick d284fa6 to release/v0.19.1-pr-14545 [CONFLICTS] (#14558)
Co-authored-by: Jacob Richman <jacob314@gmail.com>
2025-12-04 20:33:55 -08:00
gemini-cli-robot 578c497417 chore(release): v0.19.1 2025-12-03 02:10:47 +00:00
gemini-cli-robot 6169ef04ba fix(patch): cherry-pick bde8b78 to release/v0.19.0-pr-14301 to patch version v0.19.0 and create version 0.19.1 (#14418)
Co-authored-by: Jack Wotherspoon <jackwoth@google.com>
Co-authored-by: jacob314 <jacob314@gmail.com>
2025-12-02 17:54:15 -08:00
gemini-cli-robot 933e0dc8ec chore(release): v0.19.0 2025-12-02 23:18:39 +00:00
gemini-cli-robot 90a5dc3da5 chore(release): v0.19.0-preview.1 2025-12-02 22:26:26 +00:00
gemini-cli-robot 403d29c63c fix(patch): cherry-pick 576fda1 to release/v0.19.0-preview.0-pr-14099 [CONFLICTS] (#14402)
Co-authored-by: Jack Wotherspoon <jackwoth@google.com>
2025-12-02 13:41:09 -08:00
gemini-cli-robot e1ea24806e chore(release): v0.19.0-preview.0 2025-11-26 02:44:48 +00:00
867 changed files with 17705 additions and 65356 deletions
-29
View File
@@ -1,29 +0,0 @@
description="Injects context of all relevant cli files"
prompt = """
The following output contains the complete
source code of packages/core.
**Pay extremely close attention to these files.** They define the project's
core architecture, component patterns, and testing standards.
The source code contains the content of absolutely every source code file in
packages/core.
You should very rarely need to read any other files from packages/core to resolve
prompts.
!{find packages/core \\( -path packages/cli/dist -o -path packages/core/dist -o -name node_modules \\) -prune -o -type f \\( -name "*.ts" -o -name "*.tsx" \\) ! -name "*.test.ts" ! -name "*.test.tsx" ! -name "*.d.ts" -exec echo "--- {} ---" \\; -exec cat {} \\;}
In addition to the code context, you MUST strictly adhere to the following frontend-specific development guidelines when writing code in packages/core.
## Configuration & Settings
* **Settings vs Args**: Use settings for user-configurable options; do not add new CLI arguments.
* **Schema**: Add new settings to `packages/cli/src/config/settingsSchema.ts`.
* **Documentation**:
* If `showInDialog: true`, document in `docs/get-started/configuration.md`.
* Ensure `requiresRestart` is correctly set.
## General
* **Logging**: Use `debugLogger` for errors. NEVER leave `console.log/warn/error` in the code.
* **TypeScript**: Avoid the non-null assertion operator (`!`).
{{args}}.
"""
+2 -2
View File
@@ -1,13 +1,13 @@
description="Injects context of all relevant cli files"
prompt = """
The source code contains the content of absolutely every source code file in
packages/cli and key files from packages/core. In addition to the source code, the following test files are
packages/cli. In addition to the source code, the following test files are
included as they are test files that conform to the project's testing standards:
`packages/cli/src/ui/components/InputPrompt.test.tsx` and `packages/cli/src/ui/App.test.tsx`.
You should very rarely need to read any other files from packages/cli to resolve
prompts.
!{find packages/cli -path packages/cli/dist -prune -o -type f \\( -name "*.ts" -o -name "*.tsx" \\) ! -name "*.test.ts" ! -name "*.test.tsx" ! -name "*.d.ts" -exec echo "--- {} ---" \\; -exec cat {} \\; && echo "--- packages/cli/src/ui/components/InputPrompt.test.tsx ---" && cat packages/cli/src/ui/components/InputPrompt.test.tsx && echo "--- packages/cli/src/ui/App.test.tsx ---" && cat packages/cli/src/ui/App.test.tsx && echo "--- packages/core/src/core/coreToolScheduler.ts ---" && cat packages/core/src/core/coreToolScheduler.ts && echo "--- packages/core/src/core/nonInteractiveToolExecutor.ts ---" && cat packages/core/src/core/nonInteractiveToolExecutor.ts && echo "--- packages/core/src/confirmation-bus/message-bus.ts ---" && cat packages/core/src/confirmation-bus/message-bus.ts && echo "--- packages/core/src/confirmation-bus/types.ts ---" && cat packages/core/src/confirmation-bus/types.ts && echo "--- packages/core/src/utils/events.ts ---" && cat packages/core/src/utils/events.ts && echo "--- packages/core/src/core/client.ts ---" && cat packages/core/src/core/client.ts && echo "--- packages/core/src/core/geminiChat.ts ---" && cat packages/core/src/core/geminiChat.ts && echo "--- packages/core/src/core/turn.ts ---" && cat packages/core/src/core/turn.ts && echo "--- packages/core/src/agents/executor.ts ---" && cat packages/core/src/agents/executor.ts && echo "--- packages/core/src/telemetry/types.ts ---" && cat packages/core/src/telemetry/types.ts && echo "--- packages/core/src/telemetry/loggers.ts ---" && cat packages/core/src/telemetry/loggers.ts && echo "--- packages/core/src/telemetry/uiTelemetry.ts ---" && cat packages/core/src/telemetry/uiTelemetry.ts}
!{find packages/cli -path packages/cli/dist -prune -o -type f \\( -name "*.ts" -o -name "*.tsx" \\) ! -name "*.test.ts" ! -name "*.test.tsx" ! -name "*.d.ts" -exec echo "--- {} ---" \\; -exec cat {} \\; && echo "--- packages/cli/src/ui/components/InputPrompt.test.tsx ---" && cat packages/cli/src/ui/components/InputPrompt.test.tsx && echo "--- packages/cli/src/ui/App.test.tsx ---" && cat packages/cli/src/ui/App.test.tsx}
**Pay extremely close attention to these files.** They define the project's
core architecture, component patterns, and testing standards.
-3
View File
@@ -11,6 +11,3 @@
/.github/workflows/ @google-gemini/gemini-cli-askmode-approvers
/packages/cli/package.json @google-gemini/gemini-cli-askmode-approvers
/packages/core/package.json @google-gemini/gemini-cli-askmode-approvers
# Docs have a dedicated approver group in addition to maintainers
/docs/ @google-gemini/gemini-cli-maintainers @google-gemini/gemini-cli-docs
+1
View File
@@ -2,6 +2,7 @@ name: 'Bug Report'
description: 'Report a bug to help us improve Gemini CLI'
labels:
- 'status/need-triage'
type: 'Bug'
body:
- type: 'markdown'
attributes:
+1 -2
View File
@@ -262,8 +262,7 @@ runs:
--target "${{ steps.release_branch.outputs.BRANCH_NAME }}" \
--title "Release ${{ inputs.release-tag }}" \
--notes-start-tag "${{ inputs.previous-tag }}" \
--generate-notes \
${{ inputs.npm-tag != 'latest' && '--prerelease' || '' }}
--generate-notes
- name: '🧹 Clean up release branch'
working-directory: '${{ inputs.working-directory }}'
+1 -1
View File
@@ -75,4 +75,4 @@ runs:
gh issue create \
--title "Docker build failed" \
--body "The docker build failed. See the full run for details: ${DETAILS_URL}" \
--label "release-failure"
--label "kind/bug,release-failure"
+1 -1
View File
@@ -93,4 +93,4 @@ runs:
gh issue create \
--title "Docker build failed" \
--body "The docker build failed. See the full run for details: ${DETAILS_URL}" \
--label "release-failure"
--label "kind/bug,release-failure"
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- id: 'merge-queue-ci-skipper'
uses: 'cariad-tech/merge-queue-ci-skipper@1032489e59437862c90a08a2c92809c903883772' # ratchet:cariad-tech/merge-queue-ci-skipper@main
with:
secret: '${{ secrets.GEMINI_CLI_ROBOT_GITHUB_PAT }}'
secret: '${{ secrets.GITHUB_TOKEN }}'
lint:
name: 'Lint'
+247
View File
@@ -0,0 +1,247 @@
name: 'Testing: E2E'
on:
push:
branches:
- 'main'
# This will run for PRs from the base repository, providing secrets.
pull_request:
branches:
- 'main'
- 'release/**'
# This will run for PRs from forks when a label is added.
pull_request_target:
types: ['labeled']
merge_group:
workflow_dispatch:
inputs:
branch_ref:
description: 'Branch to run on'
required: true
default: 'main'
type: 'string'
concurrency:
group: '${{ github.workflow }}-${{ github.head_ref || github.ref }}'
cancel-in-progress: |-
${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/heads/release/') }}
jobs:
merge_queue_skipper:
name: 'Merge Queue Skipper'
runs-on: 'gemini-cli-ubuntu-16-core'
permissions: 'read-all'
outputs:
skip: '${{ steps.merge-queue-e2e-skipper.outputs.skip-check }}'
steps:
- id: 'merge-queue-e2e-skipper'
uses: 'cariad-tech/merge-queue-ci-skipper@1032489e59437862c90a08a2c92809c903883772' # ratchet:cariad-tech/merge-queue-ci-skipper@main
with:
secret: '${{ secrets.GITHUB_TOKEN }}'
continue-on-error: true
e2e_linux:
name: 'E2E Test (Linux) - ${{ matrix.sandbox }}'
needs: 'merge_queue_skipper'
if: |
(needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false') &&
(github.event_name == 'push' ||
github.event_name == 'merge_group' ||
github.event_name == 'workflow_dispatch' ||
(github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event.label.name == 'maintainer:e2e:ok'))
runs-on: 'gemini-cli-ubuntu-16-core'
strategy:
fail-fast: false
matrix:
sandbox:
- 'sandbox:none'
- 'sandbox:docker'
node-version:
- '20.x'
steps:
- name: 'Checkout (fork)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name == 'pull_request_target'"
with:
ref: '${{ github.event.pull_request.head.sha }}'
repository: '${{ github.event.pull_request.head.repo.full_name }}'
- name: 'Checkout (internal)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name != 'pull_request_target'"
with:
ref: '${{ github.event.inputs.branch_ref || github.ref }}'
- name: 'Set up Node.js ${{ matrix.node-version }}'
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions-node@v4
with:
node-version: '${{ matrix.node-version }}'
- name: 'Install dependencies'
run: 'npm ci'
- name: 'Build project'
run: 'npm run build'
- name: 'Set up Docker'
if: "matrix.sandbox == 'sandbox:docker'"
uses: 'docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435' # ratchet:docker/setup-buildx-action@v3
- name: 'Run E2E tests'
env:
GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}'
KEEP_OUTPUT: 'true'
VERBOSE: 'true'
shell: 'bash'
run: |
if [[ "${{ matrix.sandbox }}" == "sandbox:docker" ]]; then
npm run test:integration:sandbox:docker
else
npm run test:integration:sandbox:none
fi
e2e_mac:
name: 'E2E Test (macOS)'
needs: 'merge_queue_skipper'
if: |
(needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false') &&
(github.event_name == 'push' ||
github.event_name == 'merge_group' ||
github.event_name == 'workflow_dispatch' ||
(github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event.label.name == 'maintainer:e2e:ok'))
runs-on: 'macos-latest'
steps:
- name: 'Checkout (fork)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name == 'pull_request_target'"
with:
ref: '${{ github.event.pull_request.head.sha }}'
repository: '${{ github.event.pull_request.head.repo.full_name }}'
- name: 'Checkout (internal)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name != 'pull_request_target'"
with:
ref: '${{ github.event.inputs.branch_ref || github.ref }}'
- name: 'Set up Node.js 20.x'
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions-node@v4
with:
node-version: '20.x'
- name: 'Install dependencies'
run: 'npm ci'
- name: 'Build project'
run: 'npm run build'
- name: 'Fix rollup optional dependencies on macOS'
if: "runner.os == 'macOS'"
run: |
npm cache clean --force
- name: 'Run E2E tests (non-Windows)'
if: "runner.os != 'Windows'"
env:
GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}'
KEEP_OUTPUT: 'true'
SANDBOX: 'sandbox:none'
VERBOSE: 'true'
run: 'npm run test:integration:sandbox:none'
e2e_windows:
name: 'Slow E2E - Win'
needs: 'merge_queue_skipper'
if: |
(needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false') &&
(github.event_name == 'push' ||
github.event_name == 'merge_group' ||
github.event_name == 'workflow_dispatch' ||
(github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event.label.name == 'maintainer:e2e:ok'))
runs-on: 'gemini-cli-windows-16-core'
continue-on-error: true
steps:
- name: 'Checkout (fork)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name == 'pull_request_target'"
with:
ref: '${{ github.event.pull_request.head.sha }}'
repository: '${{ github.event.pull_request.head.repo.full_name }}'
- name: 'Checkout (internal)'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
if: "github.event_name != 'pull_request_target'"
with:
ref: '${{ github.event.inputs.branch_ref || github.ref }}'
- name: 'Set up Node.js 20.x'
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions-node@v4
with:
node-version: '20.x'
cache: 'npm'
- name: 'Configure Windows Defender exclusions'
run: |
Add-MpPreference -ExclusionPath $env:GITHUB_WORKSPACE -Force
Add-MpPreference -ExclusionPath "$env:GITHUB_WORKSPACE\node_modules" -Force
Add-MpPreference -ExclusionPath "$env:GITHUB_WORKSPACE\packages" -Force
Add-MpPreference -ExclusionPath "$env:TEMP" -Force
shell: 'pwsh'
- name: 'Configure npm for Windows performance'
run: |
npm config set progress false
npm config set audit false
npm config set fund false
npm config set loglevel error
npm config set maxsockets 32
npm config set registry https://registry.npmjs.org/
shell: 'pwsh'
- name: 'Install dependencies'
run: 'npm ci'
shell: 'pwsh'
- name: 'Build project'
run: 'npm run build'
shell: 'pwsh'
- name: 'Run E2E tests'
env:
GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}'
KEEP_OUTPUT: 'true'
SANDBOX: 'sandbox:none'
VERBOSE: 'true'
NODE_OPTIONS: '--max-old-space-size=32768 --max-semi-space-size=256'
UV_THREADPOOL_SIZE: '32'
NODE_ENV: 'test'
shell: 'pwsh'
run: 'npm run test:integration:sandbox:none'
e2e:
name: 'E2E'
if: |
always() && (
github.event_name == 'push' ||
github.event_name == 'merge_group' ||
github.event_name == 'workflow_dispatch' ||
(github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event.label.name == 'maintainer:e2e:ok')
)
needs:
- 'e2e_linux'
- 'e2e_mac'
runs-on: 'gemini-cli-ubuntu-16-core'
steps:
- name: 'Check E2E test results'
run: |
if [[ (${{ needs.e2e_linux.result }} != 'success' && ${{ needs.e2e_linux.result }} != 'skipped') || \
(${{ needs.e2e_mac.result }} != 'success' && ${{ needs.e2e_mac.result }} != 'skipped') ]]; then
echo "One or more E2E jobs failed."
exit 1
fi
echo "All required E2E jobs passed!"
@@ -39,13 +39,15 @@ jobs:
github.event_name == 'workflow_dispatch' ||
(
(github.event_name == 'issues' || github.event_name == 'issue_comment') &&
contains(github.event.issue.labels.*.name, 'status/need-triage') &&
(github.event_name != 'issue_comment' || (
contains(github.event.comment.body, '@gemini-cli /triage') &&
(github.event.comment.author_association == 'OWNER' || github.event.comment.author_association == 'MEMBER' || github.event.comment.author_association == 'COLLABORATOR')
))
)
) &&
!contains(github.event.issue.labels.*.name, 'area/')
!contains(github.event.issue.labels.*.name, 'area/') &&
!contains(github.event.issue.labels.*.name, 'priority/')
timeout-minutes: 5
runs-on: 'ubuntu-latest'
steps:
@@ -74,8 +76,13 @@ jobs:
ISSUE_NUMBER_INPUT: '${{ github.event.inputs.issue_number }}'
LABELS: '${{ steps.get_issue_data.outputs.labels }}'
run: |
if echo "${LABELS}" | grep -q 'area/'; then
echo "Issue #${ISSUE_NUMBER_INPUT} already has 'area/' label. Stopping workflow."
if ! echo "${LABELS}" | grep -q 'status/need-triage'; then
echo "Issue #${ISSUE_NUMBER_INPUT} does not have the 'status/need-triage' label. Stopping workflow."
exit 1
fi
if echo "${LABELS}" | grep -q 'area/' || echo "${LABELS}" | grep -q 'priority/'; then
echo "Issue #${ISSUE_NUMBER_INPUT} already has 'area/' or 'priority/' labels. Stopping workflow."
exit 1
fi
@@ -103,6 +110,11 @@ jobs:
repo: context.repo.repo,
});
const allowedLabels = [
'priority/p0',
'priority/p1',
'priority/p2',
'priority/p3',
'priority/unknown',
'area/agent',
'area/enterprise',
'area/non-interactive',
@@ -149,19 +161,21 @@ jobs:
prompt: |-
## Role
You are an issue triage assistant. Your role is to analyze a GitHub issue and determine the single most appropriate area/ label based on the definitions provided.
You are an issue triage assistant. Your role is to analyze a GitHub issue and determine the single most appropriate area/ label and the single most appropriate priority/ label based on the definitions provided.
## Steps
1. Review the issue title and body: ${{ env.ISSUE_TITLE }} and ${{ env.ISSUE_BODY }}.
2. Review the available labels: ${{ env.AVAILABLE_LABELS }}.
3. Select exactly one area/ label that best matches the issue based on Reference 1: Area Definitions.
4. Fallback Logic:
4. Select exactly one priority/ label that best matches the issue based on Reference 2: Priority Definitions.
5. Fallback Logic:
- If you cannot confidently determine the correct area/ label from the definitions, you must use area/unknown.
5. Output your selected label in JSON format and nothing else. Example:
{"labels_to_set": ["area/core"]}
- If you cannot confidently determine the correct priority/ label from the definitions, you must use priority/unknown.
6. Output your two selected labels in JSON format and nothing else. Example:
{"labels_to_set": ["area/core", "priority/p1"]}
## Guidelines
- Your output must contain exactly one area/ label.
- Your output must contain exactly one area/ label and exactly one priority/ label.
- Triage only the current issue based on its title and body.
- Output only valid JSON format.
- Do not include any explanation or additional text, just the JSON.
@@ -244,6 +258,38 @@ jobs:
area/unknown
- Description: Issues that do not clearly fit into any other defined area/ category, or where information is too limited to make a determination. Use this when no other area is appropriate.
Reference 2: Priority Definitions
priority/p0: Critical / Blocker
- Definition: A catastrophic failure that makes the CLI unusable for most users or poses a severe security risk. This includes installation failures, authentication failures, persistent crashes, or critical security vulnerabilities.
- Key Questions:
- Is the CLI failing to install or run?
- Does it fail to authenticate or connect to the Gemini API, making all commands useless?
- Is it consistently crashing on basic, common commands?
- Does this represent a critical security vulnerability?
priority/p1: High
- Definition: A severe issue where a core feature (e.g., text generation, code generation, file processing) is unusable, failing, has severe performance degradation, or providing fundamentally incorrect output formatting (e.g., truncated text, broken JSON). Affects many users, and there is no reasonable workaround.
- Key Questions:
- Is a core feature failing for a specific, large user group (e.g., all Windows users, all users of a specific shell)?
- Is the CLI failing to process a supported input or misinterpreting critical flags?
- Is the CLI's output formatting consistently broken, making the response unusable?
- Is a core command or feature extremely slow, making it impractical to use?
priority/p2: Medium
- Definition: A moderately impactful issue causing inconvenience or a non-optimal experience, but a reasonable workaround exists. This also includes failures in non-core features.
- Key Questions:
- Is a command or flag behaving incorrectly, but the user can achieve their goal via other means?
- Is there a significant, non-blocking UI/UX problem in the terminal (e.g., broken progress indicators, bad terminal coloring)?
priority/p3: Low
- Definition: A minor, low-impact issue with minimal effect on functionality. This includes most cosmetic defects, typos in documentation, or unclear help text.
- Key Questions:
- Is this a typo in the README.md, gemini --help text, or other documentation?
- Is this a minor cosmetic issue (e.g., text alignment in output, an extra newline) that doesn't affect usability?
priority/unknown
- Description: Issues that do not clearly fit into any other defined priority/ category, or where information is too limited to make a determination. Use this when no other priority is appropriate.
- name: 'Apply Labels to Issue'
if: |-
${{ steps.gemini_issue_analysis.outputs.summary != '' }}
@@ -281,8 +327,8 @@ jobs:
const issueNumber = parseInt(process.env.ISSUE_NUMBER);
const labelsToAdd = parsedLabels.labels_to_set || [];
if (labelsToAdd.length !== 1) {
core.setFailed(`Expected exactly 1 label (area/), but got ${labelsToAdd.length}. Labels: ${labelsToAdd.join(', ')}`);
if (labelsToAdd.length !== 2) {
core.setFailed(`Expected exactly 2 labels (one area/ and one priority/), but got ${labelsToAdd.length}. Labels: ${labelsToAdd.join(', ')}`);
return;
}
@@ -1,127 +0,0 @@
name: 'Gemini Automated PR Labeler'
on:
pull_request_target:
types: ['opened', 'reopened', 'synchronize']
jobs:
label-pr:
timeout-minutes: 10
if: |-
${{ github.repository == 'google-gemini/gemini-cli' }}
permissions:
pull-requests: 'write'
contents: 'read'
id-token: 'write'
concurrency:
group: '${{ github.workflow }}-${{ github.event.pull_request.number }}'
cancel-in-progress: true
runs-on: 'ubuntu-latest'
steps:
- name: 'Generate GitHub App Token'
id: 'generate_token'
uses: 'actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e' # v2
with:
app-id: '${{ secrets.APP_ID }}'
private-key: '${{ secrets.PRIVATE_KEY }}'
permission-pull-requests: 'write'
- name: 'Run Gemini PR size and complexity labeller'
uses: 'google-github-actions/run-gemini-cli@a3bf79042542528e91937b3a3a6fbc4967ee3c31' # Use the specific commit SHA
env:
GH_TOKEN: '${{ steps.generate_token.outputs.token }}'
PR_NUMBER: '${{ github.event.pull_request.number }}'
REPOSITORY: '${{ github.repository }}'
with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
gcp_location: '${{ vars.GOOGLE_CLOUD_LOCATION }}'
gcp_service_account: '${{ vars.SERVICE_ACCOUNT_EMAIL }}'
gemini_api_key: '${{ secrets.GEMINI_API_KEY }}'
use_vertex_ai: '${{ vars.GOOGLE_GENAI_USE_VERTEXAI }}'
use_gemini_code_assist: '${{ vars.GOOGLE_GENAI_USE_GCA }}'
settings: |
{
"coreTools": [
"run_shell_command(gh pr diff)",
"run_shell_command(gh pr edit)",
"run_shell_command(gh pr comment)",
"run_shell_command(gh pr view)"
],
"telemetry": {
"enabled": true,
"target": "gcp"
},
"sandbox": false
}
prompt: |
You are a Pull Request labeller and Feedback Assistant. Your primary goal is to improve review velocity and help maintainers prioritize their work by automatically labeling pull requests based on size and complexity, and providing guidance for overly large PRs.
Steps:
1. Retrieve Pull Request Information:
- Use `gh pr diff ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }}` to get the diff content.
- Parse the output from `gh pr diff` to determine the total lines of code added and deleted. Calculate `TOTAL_LINES_CHANGED`.
2. Determine Pull Request Size:
- Use `gh pr view ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }} --json labels` to get the current labels on the PR.
- Check the current labels and identify if any `size/*` labels already exist (e.g., `size/xs`, `size/s`, etc.).
- If an old `size/*` label is found and it is different from the newly calculated size, remove it using:
`gh pr edit ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }} --remove-label "size-label-to-remove"`
- Based on `TOTAL_LINES_CHANGED`, select the appropriate new size label:
- `size/xs`: < 10 lines changed
- `size/s`: 10-50 lines changed
- `size/m`: 51-200 lines changed
- `size/l`: 201-1000 lines changed
- `size/xl`: > 1000 lines changed
- Do not invent new size labels.
- Apply the newly determined `size/*` label to the pull request using:
`gh pr edit ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }} --add-label "your-new-size-label"`
3. Analyze Pull Request Complexity:
- Perform Code Change Analysis: Examine the content of the code changes obtained from `gh pr diff ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }}`. Look for indicators of complexity such as:
- Number of files changed (can be inferred from the diff headers).
- Diversity of file types (e.g., changes across different languages, configuration files, documentation).
- Presence of new external dependencies.
- Introduction of new architectural components or significant refactoring.
- Complexity of individual code changes (e.g., deeply nested logic, complex algorithms, extensive conditional statements).
- Apply Heuristic-based Complexity Assessment:
- If the PR touches a small number of files with minor changes (e.g., typos, simple bug fixes, small feature additions), categorize it as `review/quick`.
- If the PR involves changes across multiple files, introduces new features, significantly refactors existing code, or has a high line count (even within `size/l`), categorize it as `review/involved`.
- Pay close attention to changes in critical or core modules as these inherently increase complexity.
- **Only use the labels `review/quick` or `review/involved` for complexity. Do not invent new complexity labels.**
- **Remove any previous `review/*` labels if they no longer apply, similar to the size label process.**
- Apply the determined `review/*` label to the pull request using:
`gh pr edit ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }} --add-label "your-complexity-label"`
4. Handle Overly Large Pull Requests (`size/xl`):
- **Conditional Check:** If the pull request has been labeled `size/xl` (i.e., > 1000 lines of code changed) in Step 2, proceed to the next sub-step.
- **Post Constructive Comment:** Post a polite and helpful comment on the pull request using:
`gh pr comment ${{ env.PR_NUMBER }} --repo ${{ env.REPOSITORY }} --body "Your comment here"`
The comment body should be:
"""
Thanks for your hard work on this pull request!
This pull request is quite large, which can make it challenging and time-consuming for reviewers to go through thoroughly.
To help us review it more efficiently and get your changes merged faster, we kindly request you consider breaking this into smaller, more focused pull requests. Each smaller PR should ideally address a single logical change or a small set of related changes.
For example, you could separate out refactoring, new feature additions, and bug fixes into individual PRs. This makes it easier to understand, review, and test each component independently.
We appreciate your understanding and cooperation. Feel free to reach out if you need any assistance with this!
"""
Guidelines:
- Automation Focus: All actions should be automated and not require manual intervention.
- Non-intrusive: The system should add labels and comments but not modify the code or close the pull request.
- Polite and Constructive: All communication, especially for large PRs, must be polite, encouraging, and constructive.
- Prioritize Clarity: The labels applied should clearly convey the PR's size and complexity to reviewers.
- Adhere to Defined Labels: Only use the specified `size/*` and `review/*` labels. Do not create or apply any other labels.
- Utilize `gh CLI`: Interact with GitHub using the `gh` command-line tool for diffing, label management, and commenting.
- Execute commands strictly as described in the steps. Do not invent new commands.
- In no case should you change other pull request that are not the one you are working on. Which can be found by using env.PR_NUMBER
- Execute each step that is defined in the steps section.
- In no case should you execute code from the pull request because this could be malicious code.
- If you fail to do this step log the errors you received
@@ -45,11 +45,11 @@ jobs:
echo '🔍 Finding issues without labels...'
NO_LABEL_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue no:label' --limit 10 --json number,title,body)"
--search 'is:open is:issue no:label' --json number,title,body)"
echo '🏷️ Finding issues that need triage...'
NEED_TRIAGE_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \
--search "is:open is:issue label:\"status/need-triage\"" --limit 10 --json number,title,body)"
--search "is:open is:issue label:\"status/need-triage\"" --limit 1000 --json number,title,body)"
echo '🔄 Merging and deduplicating issues...'
ISSUES="$(echo "${NO_LABEL_ISSUES}" "${NEED_TRIAGE_ISSUES}" | jq -c -s 'add | unique_by(.number)')"
@@ -1,152 +0,0 @@
name: '🔒 Gemini Scheduled Stale Issue Closer'
on:
schedule:
- cron: '0 0 * * 0' # Every Sunday at midnight UTC
workflow_dispatch:
inputs:
dry_run:
description: 'Run in dry-run mode (no changes applied)'
required: false
default: false
type: 'boolean'
concurrency:
group: '${{ github.workflow }}'
cancel-in-progress: true
defaults:
run:
shell: 'bash'
jobs:
close-stale-issues:
runs-on: 'ubuntu-latest'
permissions:
issues: 'write'
steps:
- name: 'Generate GitHub App Token'
id: 'generate_token'
uses: 'actions/create-github-app-token@v1'
with:
app-id: '${{ secrets.APP_ID }}'
private-key: '${{ secrets.PRIVATE_KEY }}'
permission-issues: 'write'
- name: 'Process Stale Issues'
uses: 'actions/github-script@v7'
env:
DRY_RUN: '${{ inputs.dry_run }}'
with:
github-token: '${{ steps.generate_token.outputs.token }}'
script: |
const dryRun = process.env.DRY_RUN === 'true';
if (dryRun) {
core.info('DRY RUN MODE ENABLED: No changes will be applied.');
}
const batchLabel = 'Stale';
const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
const tenDaysAgo = new Date();
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10);
core.info(`Cutoff date for creation: ${threeMonthsAgo.toISOString()}`);
core.info(`Cutoff date for updates: ${tenDaysAgo.toISOString()}`);
const query = `repo:${context.repo.owner}/${context.repo.repo} is:issue is:open created:<${threeMonthsAgo.toISOString()}`;
core.info(`Searching with query: ${query}`);
const itemsToCheck = await github.paginate(github.rest.search.issuesAndPullRequests, {
q: query,
sort: 'created',
order: 'asc',
per_page: 100
});
core.info(`Found ${itemsToCheck.length} open issues to check.`);
let processedCount = 0;
for (const issue of itemsToCheck) {
const createdAt = new Date(issue.created_at);
const updatedAt = new Date(issue.updated_at);
const reactionCount = issue.reactions.total_count;
// Basic thresholds
if (reactionCount >= 5) {
continue;
}
// Skip if it has a maintainer label
if (issue.labels.some(label => label.name.toLowerCase().includes('maintainer'))) {
continue;
}
let isStale = updatedAt < tenDaysAgo;
// If apparently active, check if it's only bot activity
if (!isStale) {
try {
const comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
per_page: 100,
sort: 'created',
direction: 'desc'
});
const lastHumanComment = comments.data.find(comment => comment.user.type !== 'Bot');
if (lastHumanComment) {
isStale = new Date(lastHumanComment.created_at) < tenDaysAgo;
} else {
// No human comments. Check if creator is human.
if (issue.user.type !== 'Bot') {
isStale = createdAt < tenDaysAgo;
} else {
isStale = true; // Bot created, only bot comments
}
}
} catch (error) {
core.warning(`Failed to fetch comments for issue #${issue.number}: ${error.message}`);
continue;
}
}
if (isStale) {
processedCount++;
const message = `Closing stale issue #${issue.number}: "${issue.title}" (${issue.html_url})`;
core.info(message);
if (!dryRun) {
// Add label
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: [batchLabel]
});
// Add comment
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: 'Hello! As part of our effort to keep our backlog manageable and focus on the most active issues, we are tidying up older reports.\n\nIt looks like this issue hasn\'t been active for a while, so we are closing it for now. However, if you are still experiencing this bug on the latest stable build, please feel free to comment on this issue or create a new one with updated details.\n\nThank you for your contribution!'
});
// Close issue
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
state: 'closed',
state_reason: 'not_planned'
});
}
}
}
core.info(`\nTotal issues processed: ${processedCount}`);
@@ -1,40 +0,0 @@
name: 'Label Child Issues for Project Rollup'
on:
issues:
types: ['opened', 'edited', 'reopened']
jobs:
labeler:
runs-on: 'ubuntu-latest'
permissions:
issues: 'write'
steps:
- name: 'Check for Parent Workstream and Apply Label'
uses: 'actions/github-script@v7'
with:
script: |
const issue = context.payload.issue;
const labelToAdd = 'workstream-rollup';
// --- Define the FULL URLs of the allowed parent workstreams ---
const allowedParentUrls = [
'https://api.github.com/repos/google-gemini/gemini-cli/issues/15374',
'https://api.github.com/repos/google-gemini/gemini-cli/issues/15456',
'https://api.github.com/repos/google-gemini/gemini-cli/issues/15324'
];
// Check if the issue has a parent_issue_url and if it's in our allowed list.
if (issue && issue.parent_issue_url && allowedParentUrls.includes(issue.parent_issue_url)) {
console.log(`SUCCESS: Issue #${issue.number} is a child of a target workstream (${issue.parent_issue_url}). Adding label.`);
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: [labelToAdd]
});
} else if (issue && issue.parent_issue_url) {
console.log(`FAILURE: Issue #${issue.number} has a parent, but it's not a target workstream. Parent URL: ${issue.parent_issue_url}`);
} else {
console.log(`FAILURE: Issue #${issue.number} is not a child of any issue. No action taken.`);
}
+1 -1
View File
@@ -132,4 +132,4 @@ jobs:
gh issue create \
--title 'Manual Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')' \
--body 'The manual release workflow failed. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
+1 -1
View File
@@ -157,4 +157,4 @@ jobs:
gh issue create \
--title "Nightly Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')" \
--body "The nightly-release workflow failed. See the full run for details: ${DETAILS_URL}" \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
@@ -205,7 +205,7 @@ jobs:
gh issue create \
--title 'Patch Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')' \
--body 'The patch-release workflow failed. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
- name: 'Comment Success on Original PR'
if: '${{ success() && github.event.inputs.original_pr }}'
+3 -3
View File
@@ -261,7 +261,7 @@ jobs:
gh issue create \
--title 'Promote Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')' \
--body 'The promote-release workflow failed during preview publish. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
publish-stable:
name: 'Publish stable'
@@ -327,7 +327,7 @@ jobs:
gh issue create \
--title 'Promote Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')' \
--body 'The promote-release workflow failed during stable publish. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
nightly-pr:
name: 'Create Nightly PR'
@@ -403,4 +403,4 @@ jobs:
gh issue create \
--title 'Promote Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')' \
--body 'The promote-release workflow failed during nightly PR creation. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
+1 -1
View File
@@ -46,4 +46,4 @@ jobs:
gh issue create \
--title 'Sandbox Release Failed on $(date +'%Y-%m-%d')' \
--body 'The sandbox-release workflow failed. See the full run for details: ${DETAILS_URL}' \
--label 'release-failure,priority/p0'
--label 'kind/bug,release-failure,priority/p0'
+1 -1
View File
@@ -47,4 +47,4 @@ jobs:
gh issue create \
--title 'Smoke test failed on ${REF} @ $(date +'%Y-%m-%d')' \
--body 'Smoke test build failed. See the full run for details: ${DETAILS_URL}' \
--label 'priority/p0'
--label 'kind/bug,priority/p0'
@@ -1,4 +1,4 @@
name: 'Testing: E2E (Chained)'
name: 'Test Chained E2E'
on:
push:
@@ -37,15 +37,14 @@ jobs:
- id: 'merge-queue-e2e-skipper'
uses: 'cariad-tech/merge-queue-ci-skipper@1032489e59437862c90a08a2c92809c903883772' # ratchet:cariad-tech/merge-queue-ci-skipper@main
with:
secret: '${{ secrets.GEMINI_CLI_ROBOT_GITHUB_PAT }}'
secret: '${{ secrets.GITHUB_TOKEN }}'
continue-on-error: true
download_repo_name:
runs-on: 'gemini-cli-ubuntu-16-core'
if: "${{github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_run'}}"
if: "github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_run'"
outputs:
repo_name: '${{ steps.output-repo-name.outputs.repo_name }}'
head_sha: '${{ steps.output-repo-name.outputs.head_sha }}'
steps:
- name: 'Mock Repo Artifact'
if: "${{ github.event_name == 'workflow_dispatch' }}"
@@ -67,7 +66,7 @@ jobs:
name: 'repo_name'
run-id: '${{ env.RUN_ID }}'
path: '${{ runner.temp }}/artifacts'
- name: 'Output Repo Name and SHA'
- name: 'Output Repo Name'
id: 'output-repo-name'
uses: 'actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd' # ratchet:actions/github-script@v8
with:
@@ -76,16 +75,8 @@ jobs:
const fs = require('fs');
const path = require('path');
const temp = '${{ runner.temp }}/artifacts';
const repoPath = path.join(temp, 'repo_name');
if (fs.existsSync(repoPath)) {
const repo_name = String(fs.readFileSync(repoPath)).trim();
core.setOutput('repo_name', repo_name);
}
const shaPath = path.join(temp, 'head_sha');
if (fs.existsSync(shaPath)) {
const head_sha = String(fs.readFileSync(shaPath)).trim();
core.setOutput('head_sha', head_sha);
}
const repo_name = String(fs.readFileSync(path.join(temp, 'repo_name')));
core.setOutput('repo_name', repo_name);
parse_run_context:
name: 'Parse run context'
@@ -100,7 +91,7 @@ jobs:
name: 'Set dynamic repository and SHA'
env:
REPO: '${{ needs.download_repo_name.outputs.repo_name || github.repository }}'
SHA: '${{ needs.download_repo_name.outputs.head_sha || github.event.inputs.head_sha || github.event.workflow_run.head_sha || github.sha }}'
SHA: '${{ github.event.inputs.head_sha || github.event.workflow_run.head_sha || github.sha }}'
shell: 'bash'
run: |
echo "REPO=$REPO" >> "$GITHUB_OUTPUT"
@@ -109,20 +100,19 @@ jobs:
set_pending_status:
runs-on: 'gemini-cli-ubuntu-16-core'
permissions: 'write-all'
if: "github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_run'"
needs:
- 'parse_run_context'
if: 'always()'
steps:
- name: 'Set pending status'
uses: 'myrotvorets/set-commit-status-action@16037e056d73b2d3c88e37e393ff369047f70886' # ratchet:myrotvorets/set-commit-status-action@master
if: 'always()'
with:
allowForks: 'true'
repo: '${{ github.repository }}'
repo: '${{ needs.parse_run_context.outputs.repository }}'
sha: '${{ needs.parse_run_context.outputs.sha }}'
token: '${{ secrets.GEMINI_CLI_ROBOT_GITHUB_PAT }}'
token: '${{ secrets.GITHUB_TOKEN }}'
status: 'pending'
context: 'E2E (Chained)'
e2e_linux:
name: 'E2E Test (Linux) - ${{ matrix.sandbox }}'
@@ -131,7 +121,7 @@ jobs:
- 'parse_run_context'
runs-on: 'gemini-cli-ubuntu-16-core'
if: |
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip != 'true')
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false')
strategy:
fail-fast: false
matrix:
@@ -160,7 +150,7 @@ jobs:
run: 'npm run build'
- name: 'Set up Docker'
if: "${{matrix.sandbox == 'sandbox:docker'}}"
if: "matrix.sandbox == 'sandbox:docker'"
uses: 'docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435' # ratchet:docker/setup-buildx-action@v3
- name: 'Run E2E tests'
@@ -183,7 +173,7 @@ jobs:
- 'parse_run_context'
runs-on: 'macos-latest'
if: |
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip != 'true')
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false')
steps:
- name: 'Checkout'
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v5
@@ -203,11 +193,11 @@ jobs:
run: 'npm run build'
- name: 'Fix rollup optional dependencies on macOS'
if: "${{runner.os == 'macOS'}}"
if: "runner.os == 'macOS'"
run: |
npm cache clean --force
- name: 'Run E2E tests (non-Windows)'
if: "${{runner.os != 'Windows'}}"
if: "runner.os != 'Windows'"
env:
GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}'
KEEP_OUTPUT: 'true'
@@ -221,7 +211,7 @@ jobs:
- 'merge_queue_skipper'
- 'parse_run_context'
if: |
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip != 'true')
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false')
runs-on: 'gemini-cli-windows-16-core'
continue-on-error: true
@@ -279,7 +269,7 @@ jobs:
e2e:
name: 'E2E'
if: |
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip != 'true')
always() && (needs.merge_queue_skipper.result !='success' || needs.merge_queue_skipper.outputs.skip == 'false')
needs:
- 'e2e_linux'
- 'e2e_mac'
@@ -298,7 +288,7 @@ jobs:
set_workflow_status:
runs-on: 'gemini-cli-ubuntu-16-core'
permissions: 'write-all'
if: 'always()'
if: "github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_run'"
needs:
- 'parse_run_context'
- 'e2e'
@@ -308,8 +298,7 @@ jobs:
if: 'always()'
with:
allowForks: 'true'
repo: '${{ github.repository }}'
repo: '${{ needs.parse_run_context.outputs.repository }}'
sha: '${{ needs.parse_run_context.outputs.sha }}'
token: '${{ secrets.GITHUB_TOKEN }}'
status: '${{ needs.e2e.result }}'
context: 'E2E (Chained)'
status: '${{ job.status }}'
+6 -11
View File
@@ -3,15 +3,11 @@ name: 'Trigger E2E'
on:
workflow_dispatch:
inputs:
repo_name:
description: 'Repository name (e.g., owner/repo)'
required: false
branch_ref:
description: 'Branch to run on'
required: true
default: 'main'
type: 'string'
head_sha:
description: 'SHA of the commit to test'
required: false
type: 'string'
pull_request:
jobs:
save_repo_name:
@@ -19,12 +15,11 @@ jobs:
steps:
- name: 'Save Repo name'
env:
REPO_NAME: '${{ github.event.inputs.repo_name || github.event.pull_request.head.repo.full_name }}'
HEAD_SHA: '${{ github.event.inputs.head_sha || github.event.pull_request.head.sha }}'
# Replace with github.event.pull_request.head.repo.full_name when switched to listen on pull request events. This repo name does not contain the org which is needed for checkout.
REPO_NAME: '${{ github.event.repository.name }}'
run: |
mkdir -p ./pr
echo '${{ env.REPO_NAME }}' > ./pr/repo_name
echo '${{ env.HEAD_SHA }}' > ./pr/head_sha
- uses: 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' # ratchet:actions/upload-artifact@v4
with:
name: 'repo_name'
-1
View File
@@ -55,4 +55,3 @@ gha-creds-*.json
patch_output.log
.genkit
.gemini-clipboard/
-1
View File
@@ -18,4 +18,3 @@ eslint.config.js
gha-creds-*.json
junit.xml
Thumbs.db
.pytest_cache
+2 -4
View File
@@ -1,4 +1,4 @@
# How to contribute
# How to Contribute
We would love to accept your patches and contributions to this project. This
document includes:
@@ -41,9 +41,7 @@ This project follows
The process for contributing code is as follows:
1. **Find an issue** that you want to work on. If an issue is tagged as
"🔒Maintainers only", this means it is reserved for project maintainers. We
will not accept pull requests related to these issues.
1. **Find an issue** that you want to work on.
2. **Fork the repository** and create a new branch.
3. **Make your changes** in the `packages/` directory.
4. **Ensure all checks pass** by running `npm run preflight`.
+3 -38
View File
@@ -363,47 +363,12 @@ performance.
- State updates should be structured to enable granular updates
- Side effects should be isolated and dependencies clearly defined
## Documentation guidelines
When working in the `/docs` directory, follow the guidelines in this section:
- **Role:** You are an expert technical writer and AI assistant for contributors
to Gemini CLI. Produce professional, accurate, and consistent documentation to
guide users of Gemini CLI.
- **Technical Accuracy:** Do not invent facts, commands, code, API names, or
output. All technical information specific to Gemini CLI must be based on code
found within this directory and its subdirectories.
- **Style Authority:** Your source for writing guidance and style is the
"Documentation contribution process" section in the root directory's
`CONTRIBUTING.md` file, as well as any guidelines provided this section.
- **Information Architecture Consideration:** Before proposing documentation
changes, consider the information architecture. If a change adds significant
new content to existing documents, evaluate if creating a new, more focused
page or changes to `sidebar.json` would provide a better user experience.
- **Proactive User Consideration:** The user experience should be a primary
concern when making changes to documentation. Aim to fill gaps in existing
knowledge whenever possible while keeping documentation concise and easy for
users to understand. If changes might hinder user understanding or
accessibility, proactively raise these concerns and propose alternatives.
## Comments policy
Only write high-value comments if at all. Avoid talking to the user through
comments.
## Logging and Error Handling
## General style requirements
- **Avoid Console Statements:** Do not use `console.log`, `console.error`, or
similar methods directly.
- **Non-User-Facing Logs:** For developer-facing debug messages, use
`debugLogger` (from `@google/gemini-cli-core`).
- **User-Facing Feedback:** To surface errors or warnings to the user, use
`coreEvents.emitFeedback` (from `@google/gemini-cli-core`).
## General requirements
- If there is something you do not understand or is ambiguous, seek confirmation
or clarification from the user before making changes based on assumptions.
- Use hyphens instead of underscores in flag names (e.g. `my-flag` instead of
`my_flag`).
- Always refer to Gemini CLI as `Gemini CLI`, never `the Gemini CLI`.
Use hyphens instead of underscores in flag names (e.g. `my-flag` instead of
`my_flag`).
+1 -1
View File
@@ -187,7 +187,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright 2025 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+4 -4
View File
@@ -1,7 +1,7 @@
# Gemini CLI
[![Gemini CLI CI](https://github.com/google-gemini/gemini-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/google-gemini/gemini-cli/actions/workflows/ci.yml)
[![Gemini CLI E2E (Chained)](https://github.com/google-gemini/gemini-cli/actions/workflows/chained_e2e.yml/badge.svg)](https://github.com/google-gemini/gemini-cli/actions/workflows/chained_e2e.yml)
[![Gemini CLI E2E](https://github.com/google-gemini/gemini-cli/actions/workflows/e2e.yml/badge.svg)](https://github.com/google-gemini/gemini-cli/actions/workflows/e2e.yml)
[![Version](https://img.shields.io/npm/v/@google/gemini-cli)](https://www.npmjs.com/package/@google/gemini-cli)
[![License](https://img.shields.io/github/license/google-gemini/gemini-cli)](https://github.com/google-gemini/gemini-cli/blob/main/LICENSE)
[![View Code Wiki](https://www.gstatic.com/_/boq-sdlc-agents-ui/_/r/YUi5dj2UWvE.svg)](https://codewiki.google/github.com/google-gemini/gemini-cli)
@@ -80,9 +80,9 @@ npm install -g @google/gemini-cli@latest
### Nightly
- New releases will be published each day at UTC 0000. This will be all changes
from the main branch as represented at time of release. It should be assumed
there are pending validations and issues. Use `nightly` tag.
- New releases will be published each week at UTC 0000 each day, This will be
all changes from the main branch as represented at time of release. It should
be assumed there are pending validations and issues. Use `nightly` tag.
```bash
npm install -g @google/gemini-cli@nightly
+2 -2
View File
@@ -37,7 +37,7 @@ input:
- **Interaction:** `packages/core` invokes these tools based on requests
from the Gemini model.
## Interaction flow
## Interaction Flow
A typical interaction with the Gemini CLI follows this flow:
@@ -69,7 +69,7 @@ A typical interaction with the Gemini CLI follows this flow:
7. **Display to user:** The CLI package formats and displays the response to
the user in the terminal.
## Key design principles
## Key Design Principles
- **Modularity:** Separating the CLI (frontend) from the Core (backend) allows
for independent development and potential future extensions (e.g., different
Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 350 KiB

+18 -134
View File
@@ -1,131 +1,15 @@
# Gemini CLI release notes
# Gemini CLI Changelog
Gemini CLI has three major release channels: nightly, preview, and stable. For
most users, we recommend the stable release.
Wondering what's new in Gemini CLI? This document provides key highlights and
notable changes to Gemini CLI.
On this page, you can find information regarding the current releases and
announcements from each release.
## v0.15.0 - Gemini CLI weekly update - 2025-11-03
For the full changelog, refer to
[Releases - google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli/releases)
on GitHub.
## Current releases
| Release channel | Notes |
| :-------------------- | :---------------------------------------------- |
| Nightly | Nightly release with the most recent changes. |
| [Preview](preview.md) | Experimental features ready for early feedback. |
| [Stable](latest.md) | Stable, recommended for general use. |
## Announcements: v0.21.0 - 2025-12-15
- **⚡️⚡️⚡️ Gemini 3 Flash + Gemini CLI:** Better, faster and cheaper than 2.5
Pro - and in some scenarios better than 3 Pro! For paid tiers + free tier
users who were on the wait list enable **Preview Features** in `/settings.`
- For more information:
[Gemini 3 Flash is now available in Gemini CLI](https://developers.googleblog.com/gemini-3-flash-is-now-available-in-gemini-cli/).
- 🎉 Gemini CLI Extensions:
- Rill: Utilize natural language to analyze Rill data, enabling the
exploration of metrics and trends without the need for manual queries.
`gemini extensions install https://github.com/rilldata/rill-gemini-extension`
- Browserbase: Interact with web pages, take screenshots, extract information,
and perform automated actions with atomic precision.
`gemini extensions install https://github.com/browserbase/mcp-server-browserbase`
- Quota Visibility: The `/stats` command now displays quota information for all
available models, including those not used in the current session. (@sehoon38)
- Fuzzy Setting Search: Users can now quickly find settings using fuzzy search
within the settings dialog. (@sehoon38)
- MCP Resource Support: Users can now discover, view, and search through
resources using the @ command. (@MrLesk)
- Auto-execute Simple Slash Commands: Simple slash commands are now executed
immediately on enter. (@jackwotherspoon)
## Announcements: v0.20.0 - 2025-12-01
- **Multi-file Drag & Drop:** Users can now drag and drop multiple files into
the terminal, and the CLI will automatically prefix each valid path with `@`.
([pr](https://github.com/google-gemini/gemini-cli/pull/14832) by
[@jackwotherspoon](https://github.com/jackwotherspoon))
- **Persistent "Always Allow" Policies:** Users can now save "Always Allow"
decisions for tool executions, with granular control over specific shell
commands and multi-cloud platform tools.
([pr](https://github.com/google-gemini/gemini-cli/pull/14737) by
[@allenhutchison](https://github.com/allenhutchison))
## Announcements: v0.19.0 - 2025-11-24
- 🎉 **New extensions:**
- **Eleven Labs:** Create, play, manage your audio play tracks with the Eleven
Labs Gemini CLI extension:
`gemini extensions install https://github.com/elevenlabs/elevenlabs-mcp`
- **Zed integration:** Users can now leverage Gemini 3 within the Zed
integration after enabling "Preview Features" in their CLIs `/settings`.
([pr](https://github.com/google-gemini/gemini-cli/pull/13398) by
[@benbrandt](https://github.com/benbrandt))
- **Interactive shell:**
- **Click-to-Focus:** When "Use Alternate Buffer" setting is enabled, users
can click within the embedded shell output to focus it for input.
([pr](https://github.com/google-gemini/gemini-cli/pull/13341) by
[@galz10](https://github.com/galz10))
- **Loading phrase:** Clearly indicates when the interactive shell is awaiting
user input. ([vid](https://imgur.com/a/kjK8bUK),
[pr](https://github.com/google-gemini/gemini-cli/pull/12535) by
[@jackwotherspoon](https://github.com/jackwotherspoon))
## Announcements: v0.18.0 - 2025-11-17
- 🎉 **New extensions:**
- **Google Workspace**: Integrate Gemini CLI with your Workspace data. Write
docs, build slides, chat with others or even get your calc on in sheets:
`gemini extensions install https://github.com/gemini-cli-extensions/workspace`
- Blog:
[https://allen.hutchison.org/2025/11/19/bringing-the-office-to-the-terminal/](https://allen.hutchison.org/2025/11/19/bringing-the-office-to-the-terminal/)
- **Redis:** Manage and search data in Redis with natural language:
`gemini extensions install https://github.com/redis/mcp-redis`
- **Anomalo:** Query your data warehouse table metadata and quality status
through commands and natural language:
`gemini extensions install https://github.com/datagravity-ai/anomalo-gemini-extension`
- **Experimental permission improvements:** We are now experimenting with a new
policy engine in Gemini CLI. This allows users and administrators to create
fine-grained policy for tool calls. Currently behind a flag. See
[policy engine documentation](../core/policy-engine.md) for more information.
- Blog:
[https://allen.hutchison.org/2025/11/26/the-guardrails-of-autonomy/](https://allen.hutchison.org/2025/11/26/the-guardrails-of-autonomy/)
- **Gemini 3 support for paid:** Gemini 3 support has been rolled out to all API
key, Google AI Pro or Google AI Ultra (for individuals, not businesses) and
Gemini Code Assist Enterprise users. Enable it via `/settings` and toggling on
**Preview Features**.
- **Updated UI rollback:** Weve temporarily rolled back our updated UI to give
it more time to bake. This means for a time you wont have embedded scrolling
or mouse support. You can re-enable with `/settings` -> **Use Alternate Screen
Buffer** -> `true`.
- **Model in history:** Users can now toggle in `/settings` to display model in
their chat history. ([gif](https://imgur.com/a/uEmNKnQ),
[pr](https://github.com/google-gemini/gemini-cli/pull/13034) by
[@scidomino](https://github.com/scidomino))
- **Multi-uninstall:** Users can now uninstall multiple extensions with a single
command. ([pic](https://imgur.com/a/9Dtq8u2),
[pr](https://github.com/google-gemini/gemini-cli/pull/13016) by
[@JayadityaGit](https://github.com/JayadityaGit))
## Announcements: v0.16.0 - 2025-11-10
- **Gemini 3 + Gemini CLI:** launch 🚀🚀🚀
- **Data Commons Gemini CLI Extension** - A new Data Commons Gemini CLI
extension that lets you query open-source statistical data from
datacommons.org. **To get started, you'll need a Data Commons API key and uv
installed**. These and other details to get you started with the extension can
be found at
[https://github.com/gemini-cli-extensions/datacommons](https://github.com/gemini-cli-extensions/datacommons).
## Announcements: v0.15.0 - 2025-11-03
- **🎉 Seamless scrollable UI and mouse support:** Weve given Gemini CLI a
major facelift to make your terminal experience smoother and much more
polished. You now get a flicker-free display with sticky headers that keep
important context visible and a stable input prompt that doesn't jump around.
We even added mouse support so you can click right where you need to type!
- **🎉 Seamless scrollable UI & mouse support:** Weve given Gemini CLI a major
facelift to make your terminal experience smoother and much more polished. You
now get a flicker-free display with sticky headers that keep important context
visible and a stable input prompt that doesn't jump around. We even added
mouse support so you can click right where you need to type!
([gif](https://imgur.com/a/O6qc7bx),
[@jacob314](https://github.com/jacob314)).
- **Announcement:**
@@ -165,7 +49,7 @@ on GitHub.
correctly. ([pr](https://github.com/google-gemini/gemini-cli/pull/12186) by
[@kevinjwang1](https://github.com/kevinjwang1)).
## Announcements: v0.12.0 - 2025-10-27
## v0.12.0 - Gemini CLI weekly update - 2025-10-27
![Codebase investigator subagent in Gemini CLI.](https://i.imgur.com/4J1njsx.png)
@@ -228,7 +112,7 @@ on GitHub.
([pr](https://github.com/google-gemini/gemini-cli/pull/11593) by
[@joshualitt](https://github.com/joshualitt)).
## Announcements: v0.11.0 - 2025-10-20
## v0.11.0 - Gemini CLI weekly update - 2025-10-20
![Gemini CLI and Jules](https://storage.googleapis.com/gweb-developer-goog-blog-assets/images/Jules_Extension_-_Blog_Header_O346JNt.original.png)
@@ -271,7 +155,7 @@ on GitHub.
([pr](https://github.com/google-gemini/gemini-cli/pull/11318) by
[@allenhutchison](https://github.com/allenhutchison))
## Announcements: v0.10.0 - 2025-10-13
## v0.10.0 - Gemini CLI weekly update - 2025-10-13
- **Polish:** The team has been heads down bug fixing and investing heavily into
polishing existing flows, tools, and interactions.
@@ -288,7 +172,7 @@ on GitHub.
([pr](https://github.com/google-gemini/gemini-cli/pull/10819) by
[@jerop](https://github.com/jerop)).
## Announcements: v0.9.0 - 2025-10-06
## v0.9.0 - Gemini CLI weekly update - 2025-10-06
- 🎉 **Interactive Shell:** Run interactive commands like `vim`, `rebase -i`, or
even `gemini` 😎 directly in Gemini CLI:
@@ -313,7 +197,7 @@ on GitHub.
([pr](https://github.com/google-gemini/gemini-cli/pull/10108) by
[@sgnagnarella](https://github.com/sgnagnarella))
## Announcements: v0.8.0 - 2025-09-29
## v0.8.0 - Gemini CLI weekly update - 2025-09-29
- 🎉 **Announcing Gemini CLI Extensions** 🎉
- Completely customize your Gemini CLI experience to fit your workflow.
@@ -352,7 +236,7 @@ on GitHub.
changes, smaller features, UI updates, reliability and bug fixes + general
polish made it in this week!
## Announcements: v0.7.0 - 2025-09-22
## v0.7.0 - Gemini CLI weekly update - 2025-09-22
- 🎉**Build your own Gemini CLI IDE plugin:** We've published a spec for
creating IDE plugins to enable rich context-aware experiences and native
@@ -390,7 +274,7 @@ on GitHub.
changes, smaller features, UI updates, reliability and bug fixes + general
polish made it in this week!
## Announcements: v0.6.0 - 2025-09-15
## v0.6.0 - Gemini CLI weekly update - 2025-09-15
- 🎉 **Higher limits for Google AI Pro and Ultra subscribers:** Were psyched to
finally announce that Google AI Pro and AI Ultra subscribers now get access to
@@ -471,7 +355,7 @@ on GitHub.
changes, smaller features, UI updates, reliability and bug fixes + general
polish made it in this week!
## Announcements: v0.5.0 - 2025-09-08
## v0.5.0 - Gemini CLI weekly update - 2025-09-08
- 🎉**FastMCP + Gemini CLI**🎉: Quickly install and manage your Gemini CLI MCP
servers with FastMCP ([video](https://imgur.com/a/m8QdCPh),
@@ -516,7 +400,7 @@ on GitHub.
changes, smaller features, UI updates, reliability and bug fixes + general
polish made it in this week!
## Announcements: v0.4.0 - 2025-09-01
## v0.4.0 - Gemini CLI weekly update - 2025-09-01
- 🎉**Gemini CLI CloudRun and Security Integrations**🎉: Automate app deployment
and security analysis with CloudRun and Security extension integrations. Once
-225
View File
@@ -1,225 +0,0 @@
# Latest stable release: v0.21.0 - v0.21.1
Released: December 16, 2025
For most users, our latest stable release is the recommended release. Install
the latest stable version with:
```
npm install -g @google/gemini-cli
```
## Highlights
- **⚡️⚡️⚡️ Gemini 3 Flash + Gemini CLI:** If you are a paid user, you can now
enable Gemini 3 Pro and Gemini 3 Flash. Go to `/settings` and set **Preview
Features** to `true` to enable Gemini 3. For more information:
[Gemini 3 Flash is now available in Gemini CLI](https://developers.googleblog.com/gemini-3-flash-is-now-available-in-gemini-cli/).
## What's Changed
- refactor(stdio): always patch stdout and use createWorkingStdio for clean
output by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14159
- chore(release): bump version to 0.21.0-nightly.20251202.2d935b379 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14409
- implement fuzzy search inside settings by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/13864
- feat: enable message bus integration by default by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14329
- docs: Recommend using --debug intead of --verbose for CLI debugging by @bbiggs
in https://github.com/google-gemini/gemini-cli/pull/14334
- feat: consolidate remote MCP servers to use `url` in config by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/13762
- Restrict integration tests tools by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14403
- track github repository names in telemetry events by @IamRiddhi in
https://github.com/google-gemini/gemini-cli/pull/13670
- Allow telemetry exporters to GCP to utilize user's login credentials, if
requested by @mboshernitsan in
https://github.com/google-gemini/gemini-cli/pull/13778
- refactor(editor): use const assertion for editor types with single source of
truth by @amsminn in https://github.com/google-gemini/gemini-cli/pull/8604
- fix(security): Fix npm audit vulnerabilities in glob and body-parser by
@afarber in https://github.com/google-gemini/gemini-cli/pull/14090
- Add new enterprise instructions by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/8641
- feat(hooks): Hook Session Lifecycle & Compression Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14151
- Avoid triggering refreshStatic unless there really is a banner to display. by
@jacob314 in https://github.com/google-gemini/gemini-cli/pull/14328
- feat(hooks): Hooks Commands Panel, Enable/Disable, and Migrate by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14225
- fix: Bundle default policies for npx distribution by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14457
- feat(hooks): Hook System Documentation by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14307
- Fix tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14458
- feat: add scheduled workflow to close stale issues by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14404
- feat: Support Extension Hooks with Security Warning by @abhipatel12 in
https://github.com/google-gemini/gemini-cli/pull/14460
- feat: Add enableAgents experimental flag by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14371
- docs: fix typo 'socus' to 'focus' in todos.md by @Viktor286 in
https://github.com/google-gemini/gemini-cli/pull/14374
- Markdown export: move the emoji to the end of the line by @mhansen in
https://github.com/google-gemini/gemini-cli/pull/12278
- fix(acp): prevent unnecessary credential cache clearing on re-authent… by
@h-michael in https://github.com/google-gemini/gemini-cli/pull/9410
- fix(cli): Fix word navigation for CJK characters by @SandyTao520 in
https://github.com/google-gemini/gemini-cli/pull/14475
- Remove example extension by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14376
- Add commands for listing and updating per-extension settings by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/12664
- chore(tests): remove obsolete test for hierarchical memory by @pareshjoshij in
https://github.com/google-gemini/gemini-cli/pull/13122
- feat(cli): support /copy in remote sessions using OSC52 by @ismellpillows in
https://github.com/google-gemini/gemini-cli/pull/13471
- Update setting search UX by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/14451
- Fix(cli): Improve Homebrew update instruction to specify gemini-cli by
@DaanVersavel in https://github.com/google-gemini/gemini-cli/pull/14502
- do not toggle the setting item when entering space by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14489
- fix: improve retry logic for fetch errors and network codes by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/14439
- remove unused isSearching field by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14509
- feat(mcp): add `--type` alias for `--transport` flag in gemini mcp add by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14503
- feat(cli): Move key restore logic to core by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13013
- feat: add auto-execute on Enter behavior to argumentless MCP prompts by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14510
- fix(shell): cursor visibility when using interactive mode by @aswinashok44 in
https://github.com/google-gemini/gemini-cli/pull/14095
- Adding session id as part of json o/p by @MJjainam in
https://github.com/google-gemini/gemini-cli/pull/14504
- fix(extensions): resolve GitHub API 415 error for source tarballs by
@jpoehnelt in https://github.com/google-gemini/gemini-cli/pull/13319
- fix(client): Correctly latch hasFailedCompressionAttempt flag by @pareshjoshij
in https://github.com/google-gemini/gemini-cli/pull/13002
- Disable flaky extension reloading test on linux by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14528
- Add support for MCP dynamic tool update by `notifications/tools/list_changed`
by @Adib234 in https://github.com/google-gemini/gemini-cli/pull/14375
- Fix privacy screen for legacy tier users by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14522
- feat: Exclude maintainer labeled issues from stale issue closer by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14532
- Grant chained workflows proper permission. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14534
- Make trigger_e2e manually fireable. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14547
- Write e2e status to local repo not forked repo by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14549
- Fixes [API Error: Cannot read properties of undefined (reading 'error')] by
@silviojr in https://github.com/google-gemini/gemini-cli/pull/14553
- Trigger chained e2e tests on all pull requests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14551
- Fix bug in the shellExecutionService resulting in both truncation and 3X bloat
by @jacob314 in https://github.com/google-gemini/gemini-cli/pull/14545
- Fix issue where we were passing the model content reflecting terminal line
wrapping. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14566
- chore/release: bump version to 0.21.0-nightly.20251204.3da4fd5f7 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14476
- feat(sessions): use 1-line generated session summary to describe sessions by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14467
- Use Robot PAT for chained e2e merge queue skipper by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14585
- fix(core): improve API response error handling and retry logic by @mattKorwel
in https://github.com/google-gemini/gemini-cli/pull/14563
- Docs: Model routing clarification by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14373
- expose previewFeatures flag in a2a by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14550
- Fix emoji width in debug console. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14593
- Fully detach autoupgrade process by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14595
- Docs: Update Gemini 3 on Gemini CLI documentation by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14601
- Disallow floating promises. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14605
- chore/release: bump version to 0.21.0-nightly.20251207.025e450ac by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14662
- feat(modelAvailabilityService): integrate model availability service into
backend logic by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14470
- Add prompt_id propagation in a2a-server task by @koxkox111 in
https://github.com/google-gemini/gemini-cli/pull/14581
- Fix: Prevent freezing in non-interactive Gemini CLI when debug mode is enabled
by @parthasaradhie in https://github.com/google-gemini/gemini-cli/pull/14580
- fix(audio): improve reading of audio files by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/14658
- Update automated triage workflow to stop assigning priority labels by
@skeshive in https://github.com/google-gemini/gemini-cli/pull/14717
- set failed status when chained e2e fails by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14725
- feat(github action) Triage and Label Pull Requests by Size and Comple… by
@DaanVersavel in https://github.com/google-gemini/gemini-cli/pull/5571
- refactor(telemetry): Improve previous PR that allows telemetry to use the CLI
auth and add testing by @mboshernitsan in
https://github.com/google-gemini/gemini-cli/pull/14589
- Always set status in chained_e2e workflow by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14730
- feat: Add OTEL log event `gemini_cli.startup_stats` for startup stats. by
@kevin-ramdass in https://github.com/google-gemini/gemini-cli/pull/14734
- feat: auto-execute on slash command completion functions by @jackwotherspoon
in https://github.com/google-gemini/gemini-cli/pull/14584
- Docs: Proper release notes by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14405
- Add support for user-scoped extension settings by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/13748
- refactor(core): Improve environment variable handling in shell execution by
@galz10 in https://github.com/google-gemini/gemini-cli/pull/14742
- Remove old E2E Workflows by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14749
- fix: handle missing local extension config and skip hooks when disabled by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14744
- chore/release: bump version to 0.21.0-nightly.20251209.ec9a8c7a7 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14751
- feat: Add support for MCP Resources by @MrLesk in
https://github.com/google-gemini/gemini-cli/pull/13178
- Always set pending status in E2E tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14756
- fix(lint): upgrade pip and use public pypi for yamllint by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14746
- fix: use Gemini API supported image formats for clipboard by @jackwotherspoon
in https://github.com/google-gemini/gemini-cli/pull/14762
- feat(a2a): Introduce restore command for a2a server by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13015
- allow final:true to be returned on a2a server edit calls. by @DavidAPierce in
https://github.com/google-gemini/gemini-cli/pull/14747
- (fix) Automated pr labeller by @DaanVersavel in
https://github.com/google-gemini/gemini-cli/pull/14788
- Update CODEOWNERS by @kklashtorny1 in
https://github.com/google-gemini/gemini-cli/pull/14830
- Docs: Fix errors preventing site rebuild. by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14842
- chore(deps): bump express from 5.1.0 to 5.2.0 by @dependabot[bot] in
https://github.com/google-gemini/gemini-cli/pull/14325
- fix(patch): cherry-pick 3f5f030 to release/v0.21.0-preview.0-pr-14843 to patch
version v0.21.0-preview.0 and create version 0.21.0-preview.1 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14851
- fix(patch): cherry-pick ee6556c to release/v0.21.0-preview.1-pr-14691 to patch
version v0.21.0-preview.1 and create version 0.21.0-preview.2 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14908
- fix(patch): cherry-pick 54de675 to release/v0.21.0-preview.2-pr-14961 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14968
- fix(patch): cherry-pick 12cbe32 to release/v0.21.0-preview.3-pr-15000 to patch
version v0.21.0-preview.3 and create version 0.21.0-preview.4 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15003
- fix(patch): cherry-pick edbe548 to release/v0.21.0-preview.4-pr-15007 to patch
version v0.21.0-preview.4 and create version 0.21.0-preview.5 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15015
- fix(patch): cherry-pick 2995af6 to release/v0.21.0-preview.5-pr-15131 to patch
version v0.21.0-preview.5 and create version 0.21.0-preview.6 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15153
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.20.2...v0.21.0
-129
View File
@@ -1,129 +0,0 @@
# Preview release: Release v0.22.0-preview.0
Released: December 16, 2025
Our preview release includes the latest, new, and experimental features. This
release may not be as stable as our [latest weekly release](latest.md).
To install the preview release:
```
npm install -g @google/gemini-cli@preview
```
## What's Changed
- feat(ide): fallback to GEMINI_CLI_IDE_AUTH_TOKEN env var by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14843
- feat: display quota stats for unused models in /stats by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14764
- feat: ensure codebase investigator uses preview model when main agent does by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14412
- chore: add closing reason to stale bug workflow by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14861
- Send the model and CLI version with the user agent by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14865
- refactor(sessions): move session summary generation to startup by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14691
- Limit search depth in path corrector by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14869
- Fix: Correct typo in code comment by @kuishou68 in
https://github.com/google-gemini/gemini-cli/pull/14671
- feat(core): Plumbing for late resolution of model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/14597
- feat: attempt more error parsing by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14899
- Add missing await. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14910
- feat(core): Add support for transcript_path in hooks for git-ai/Gemini
extension by @svarlamov in
https://github.com/google-gemini/gemini-cli/pull/14663
- refactor: implement DelegateToAgentTool with discriminated union by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14769
- feat: reset availabilityService on /auth by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14911
- chore/release: bump version to 0.21.0-nightly.20251211.8c83e1ea9 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14924
- Fix: Correctly detect MCP tool errors by @kevin-ramdass in
https://github.com/google-gemini/gemini-cli/pull/14937
- increase labeler timeout by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14922
- tool(cli): tweak the frontend tool to be aware of more core files from the cli
by @jacob314 in https://github.com/google-gemini/gemini-cli/pull/14962
- feat(cli): polish cached token stats and simplify stats display when quota is
present. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14961
- feat(settings-validation): add validation for settings schema by @lifefloating
in https://github.com/google-gemini/gemini-cli/pull/12929
- fix(ide): Update IDE extension to write auth token in env var by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14999
- Revert "chore(deps): bump express from 5.1.0 to 5.2.0" by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14998
- feat(a2a): Introduce /init command for a2a server by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13419
- feat: support multi-file drag and drop of images by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/14832
- fix(policy): allow codebase_investigator by default in read-only policy by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/15000
- refactor(ide ext): Update port file name + switch to 1-based index for
characters + remove truncation text by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/10501
- fix(vscode-ide-companion): correct license generation for workspace
dependencies by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/15004
- fix: temp fix for subagent invocation until subagent delegation is merged to
stable by @abhipatel12 in
https://github.com/google-gemini/gemini-cli/pull/15007
- test: update ide detection tests to make them more robust when run in an ide
by @kevin-ramdass in https://github.com/google-gemini/gemini-cli/pull/15008
- Remove flex from stats display. See snapshots for diffs. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14983
- Add license field into package.json by @jb-perez in
https://github.com/google-gemini/gemini-cli/pull/14473
- feat: Persistent "Always Allow" policies with granular shell & MCP support by
@allenhutchison in https://github.com/google-gemini/gemini-cli/pull/14737
- chore/release: bump version to 0.21.0-nightly.20251212.54de67536 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14969
- fix(core): commandPrefix word boundary and compound command safety by
@allenhutchison in https://github.com/google-gemini/gemini-cli/pull/15006
- chore(docs): add 'Maintainers only' label info to CONTRIBUTING.md by @jacob314
in https://github.com/google-gemini/gemini-cli/pull/14914
- Refresh hooks when refreshing extensions. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14918
- Add clarity to error messages by @gsehgal in
https://github.com/google-gemini/gemini-cli/pull/14879
- chore : remove a redundant tip by @JayadityaGit in
https://github.com/google-gemini/gemini-cli/pull/14947
- chore/release: bump version to 0.21.0-nightly.20251213.977248e09 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15029
- Disallow redundant typecasts. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/15030
- fix(auth): prioritize GEMINI_API_KEY env var and skip unnecessary key… by
@galz10 in https://github.com/google-gemini/gemini-cli/pull/14745
- fix: use zod for safety check result validation by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/15026
- update(telemetry): add hashed_extension_name to field to extension events by
@kiranani in https://github.com/google-gemini/gemini-cli/pull/15025
- fix: similar to policy-engine, throw error in case of requiring tool execution
confirmation for non-interactive mode by @MayV in
https://github.com/google-gemini/gemini-cli/pull/14702
- Clean up processes in integration tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/15102
- docs: update policy engine getting started and defaults by @NTaylorMullen in
https://github.com/google-gemini/gemini-cli/pull/15105
- Fix tool output fragmentation by encapsulating content in functionResponse by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/13082
- Simplify method signature. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/15114
- Show raw input token counts in json output. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/15021
- fix: Mark A2A requests as interactive by @MayV in
https://github.com/google-gemini/gemini-cli/pull/15108
- use previewFeatures to determine which pro model to use for A2A by @sehoon38
in https://github.com/google-gemini/gemini-cli/pull/15131
- refactor(cli): fix settings merging so that settings using the new json format
take priority over ones using the old format by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/15116
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.21.0-preview.6...v0.22.0-preview.0
-896
View File
@@ -1,896 +0,0 @@
# Gemini CLI changelog
Gemini CLI has three major release channels: nightly, preview, and stable. For
most users, we recommend the stable release.
On this page, you can find information regarding the current releases and
highlights from each release.
For the full changelog, including nightly releases, refer to
[Releases - google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli/releases)
on GitHub.
## Current Releases
| Release channel | Notes |
| :------------------------------------------ | :---------------------------------------------- |
| Nightly | Nightly release with the most recent changes. |
| [Preview](#release-v0220-preview-0-preview) | Experimental features ready for early feedback. |
| [Latest](#release-v0210---v0211-latest) | Stable, recommended for general use. |
## Release v0.21.0 - v0.21.1 (Latest)
### Highlights
- **⚡️⚡️⚡️ Gemini 3 Flash + Gemini CLI:** If you are a paid user, you can now
enable Gemini 3 Pro and Gemini 3 Flash. Go to `/settings` and set **Preview
Features** to `true` to enable Gemini 3. For more information:
[Gemini 3 Flash is now available in Gemini CLI](https://developers.googleblog.com/gemini-3-flash-is-now-available-in-gemini-cli/).
### What's Changed
- refactor(stdio): always patch stdout and use createWorkingStdio for clean
output by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14159
- chore(release): bump version to 0.21.0-nightly.20251202.2d935b379 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14409
- implement fuzzy search inside settings by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/13864
- feat: enable message bus integration by default by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14329
- docs: Recommend using --debug intead of --verbose for CLI debugging by @bbiggs
in https://github.com/google-gemini/gemini-cli/pull/14334
- feat: consolidate remote MCP servers to use `url` in config by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/13762
- Restrict integration tests tools by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14403
- track github repository names in telemetry events by @IamRiddhi in
https://github.com/google-gemini/gemini-cli/pull/13670
- Allow telemetry exporters to GCP to utilize user's login credentials, if
requested by @mboshernitsan in
https://github.com/google-gemini/gemini-cli/pull/13778
- refactor(editor): use const assertion for editor types with single source of
truth by @amsminn in https://github.com/google-gemini/gemini-cli/pull/8604
- fix(security): Fix npm audit vulnerabilities in glob and body-parser by
@afarber in https://github.com/google-gemini/gemini-cli/pull/14090
- Add new enterprise instructions by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/8641
- feat(hooks): Hook Session Lifecycle & Compression Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14151
- Avoid triggering refreshStatic unless there really is a banner to display. by
@jacob314 in https://github.com/google-gemini/gemini-cli/pull/14328
- feat(hooks): Hooks Commands Panel, Enable/Disable, and Migrate by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14225
- fix: Bundle default policies for npx distribution by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14457
- feat(hooks): Hook System Documentation by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/14307
- Fix tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14458
- feat: add scheduled workflow to close stale issues by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14404
- feat: Support Extension Hooks with Security Warning by @abhipatel12 in
https://github.com/google-gemini/gemini-cli/pull/14460
- feat: Add enableAgents experimental flag by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14371
- docs: fix typo 'socus' to 'focus' in todos.md by @Viktor286 in
https://github.com/google-gemini/gemini-cli/pull/14374
- Markdown export: move the emoji to the end of the line by @mhansen in
https://github.com/google-gemini/gemini-cli/pull/12278
- fix(acp): prevent unnecessary credential cache clearing on re-authent… by
@h-michael in https://github.com/google-gemini/gemini-cli/pull/9410
- fix(cli): Fix word navigation for CJK characters by @SandyTao520 in
https://github.com/google-gemini/gemini-cli/pull/14475
- Remove example extension by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14376
- Add commands for listing and updating per-extension settings by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/12664
- chore(tests): remove obsolete test for hierarchical memory by @pareshjoshij in
https://github.com/google-gemini/gemini-cli/pull/13122
- feat(cli): support /copy in remote sessions using OSC52 by @ismellpillows in
https://github.com/google-gemini/gemini-cli/pull/13471
- Update setting search UX by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/14451
- Fix(cli): Improve Homebrew update instruction to specify gemini-cli by
@DaanVersavel in https://github.com/google-gemini/gemini-cli/pull/14502
- do not toggle the setting item when entering space by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14489
- fix: improve retry logic for fetch errors and network codes by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/14439
- remove unused isSearching field by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14509
- feat(mcp): add `--type` alias for `--transport` flag in gemini mcp add by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14503
- feat(cli): Move key restore logic to core by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13013
- feat: add auto-execute on Enter behavior to argumentless MCP prompts by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14510
- fix(shell): cursor visibility when using interactive mode by @aswinashok44 in
https://github.com/google-gemini/gemini-cli/pull/14095
- Adding session id as part of json o/p by @MJjainam in
https://github.com/google-gemini/gemini-cli/pull/14504
- fix(extensions): resolve GitHub API 415 error for source tarballs by
@jpoehnelt in https://github.com/google-gemini/gemini-cli/pull/13319
- fix(client): Correctly latch hasFailedCompressionAttempt flag by @pareshjoshij
in https://github.com/google-gemini/gemini-cli/pull/13002
- Disable flaky extension reloading test on linux by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14528
- Add support for MCP dynamic tool update by `notifications/tools/list_changed`
by @Adib234 in https://github.com/google-gemini/gemini-cli/pull/14375
- Fix privacy screen for legacy tier users by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14522
- feat: Exclude maintainer labeled issues from stale issue closer by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14532
- Grant chained workflows proper permission. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14534
- Make trigger_e2e manually fireable. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14547
- Write e2e status to local repo not forked repo by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14549
- Fixes [API Error: Cannot read properties of undefined (reading 'error')] by
@silviojr in https://github.com/google-gemini/gemini-cli/pull/14553
- Trigger chained e2e tests on all pull requests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14551
- Fix bug in the shellExecutionService resulting in both truncation and 3X bloat
by @jacob314 in https://github.com/google-gemini/gemini-cli/pull/14545
- Fix issue where we were passing the model content reflecting terminal line
wrapping. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14566
- chore/release: bump version to 0.21.0-nightly.20251204.3da4fd5f7 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14476
- feat(sessions): use 1-line generated session summary to describe sessions by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14467
- Use Robot PAT for chained e2e merge queue skipper by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14585
- fix(core): improve API response error handling and retry logic by @mattKorwel
in https://github.com/google-gemini/gemini-cli/pull/14563
- Docs: Model routing clarification by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14373
- expose previewFeatures flag in a2a by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14550
- Fix emoji width in debug console. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14593
- Fully detach autoupgrade process by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14595
- Docs: Update Gemini 3 on Gemini CLI documentation by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14601
- Disallow floating promises. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14605
- chore/release: bump version to 0.21.0-nightly.20251207.025e450ac by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14662
- feat(modelAvailabilityService): integrate model availability service into
backend logic by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14470
- Add prompt_id propagation in a2a-server task by @koxkox111 in
https://github.com/google-gemini/gemini-cli/pull/14581
- Fix: Prevent freezing in non-interactive Gemini CLI when debug mode is enabled
by @parthasaradhie in https://github.com/google-gemini/gemini-cli/pull/14580
- fix(audio): improve reading of audio files by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/14658
- Update automated triage workflow to stop assigning priority labels by
@skeshive in https://github.com/google-gemini/gemini-cli/pull/14717
- set failed status when chained e2e fails by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14725
- feat(github action) Triage and Label Pull Requests by Size and Comple… by
@DaanVersavel in https://github.com/google-gemini/gemini-cli/pull/5571
- refactor(telemetry): Improve previous PR that allows telemetry to use the CLI
auth and add testing by @mboshernitsan in
https://github.com/google-gemini/gemini-cli/pull/14589
- Always set status in chained_e2e workflow by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14730
- feat: Add OTEL log event `gemini_cli.startup_stats` for startup stats. by
@kevin-ramdass in https://github.com/google-gemini/gemini-cli/pull/14734
- feat: auto-execute on slash command completion functions by @jackwotherspoon
in https://github.com/google-gemini/gemini-cli/pull/14584
- Docs: Proper release notes by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14405
- Add support for user-scoped extension settings by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/13748
- refactor(core): Improve environment variable handling in shell execution by
@galz10 in https://github.com/google-gemini/gemini-cli/pull/14742
- Remove old E2E Workflows by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14749
- fix: handle missing local extension config and skip hooks when disabled by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14744
- chore/release: bump version to 0.21.0-nightly.20251209.ec9a8c7a7 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14751
- feat: Add support for MCP Resources by @MrLesk in
https://github.com/google-gemini/gemini-cli/pull/13178
- Always set pending status in E2E tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14756
- fix(lint): upgrade pip and use public pypi for yamllint by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/14746
- fix: use Gemini API supported image formats for clipboard by @jackwotherspoon
in https://github.com/google-gemini/gemini-cli/pull/14762
- feat(a2a): Introduce restore command for a2a server by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13015
- allow final:true to be returned on a2a server edit calls. by @DavidAPierce in
https://github.com/google-gemini/gemini-cli/pull/14747
- (fix) Automated pr labeller by @DaanVersavel in
https://github.com/google-gemini/gemini-cli/pull/14788
- Update CODEOWNERS by @kklashtorny1 in
https://github.com/google-gemini/gemini-cli/pull/14830
- Docs: Fix errors preventing site rebuild. by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/14842
- chore(deps): bump express from 5.1.0 to 5.2.0 by @dependabot[bot] in
https://github.com/google-gemini/gemini-cli/pull/14325
- fix(patch): cherry-pick 3f5f030 to release/v0.21.0-preview.0-pr-14843 to patch
version v0.21.0-preview.0 and create version 0.21.0-preview.1 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14851
- fix(patch): cherry-pick ee6556c to release/v0.21.0-preview.1-pr-14691 to patch
version v0.21.0-preview.1 and create version 0.21.0-preview.2 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14908
- fix(patch): cherry-pick 54de675 to release/v0.21.0-preview.2-pr-14961 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14968
- fix(patch): cherry-pick 12cbe32 to release/v0.21.0-preview.3-pr-15000 to patch
version v0.21.0-preview.3 and create version 0.21.0-preview.4 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15003
- fix(patch): cherry-pick edbe548 to release/v0.21.0-preview.4-pr-15007 to patch
version v0.21.0-preview.4 and create version 0.21.0-preview.5 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15015
- fix(patch): cherry-pick 2995af6 to release/v0.21.0-preview.5-pr-15131 to patch
version v0.21.0-preview.5 and create version 0.21.0-preview.6 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15153
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.20.2...v0.21.0
## Release v0.22.0-preview-0 (Preview)
### What's Changed
- feat(ide): fallback to GEMINI_CLI_IDE_AUTH_TOKEN env var by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14843
- feat: display quota stats for unused models in /stats by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/14764
- feat: ensure codebase investigator uses preview model when main agent does by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14412
- chore: add closing reason to stale bug workflow by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/14861
- Send the model and CLI version with the user agent by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14865
- refactor(sessions): move session summary generation to startup by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/14691
- Limit search depth in path corrector by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14869
- Fix: Correct typo in code comment by @kuishou68 in
https://github.com/google-gemini/gemini-cli/pull/14671
- feat(core): Plumbing for late resolution of model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/14597
- feat: attempt more error parsing by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14899
- Add missing await. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/14910
- feat(core): Add support for transcript_path in hooks for git-ai/Gemini
extension by @svarlamov in
https://github.com/google-gemini/gemini-cli/pull/14663
- refactor: implement DelegateToAgentTool with discriminated union by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/14769
- feat: reset availabilityService on /auth by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/14911
- chore/release: bump version to 0.21.0-nightly.20251211.8c83e1ea9 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14924
- Fix: Correctly detect MCP tool errors by @kevin-ramdass in
https://github.com/google-gemini/gemini-cli/pull/14937
- increase labeler timeout by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14922
- tool(cli): tweak the frontend tool to be aware of more core files from the cli
by @jacob314 in https://github.com/google-gemini/gemini-cli/pull/14962
- feat(cli): polish cached token stats and simplify stats display when quota is
present. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14961
- feat(settings-validation): add validation for settings schema by @lifefloating
in https://github.com/google-gemini/gemini-cli/pull/12929
- fix(ide): Update IDE extension to write auth token in env var by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14999
- Revert "chore(deps): bump express from 5.1.0 to 5.2.0" by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/14998
- feat(a2a): Introduce /init command for a2a server by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/13419
- feat: support multi-file drag and drop of images by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/14832
- fix(policy): allow codebase_investigator by default in read-only policy by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/15000
- refactor(ide ext): Update port file name + switch to 1-based index for
characters + remove truncation text by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/10501
- fix(vscode-ide-companion): correct license generation for workspace
dependencies by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/15004
- fix: temp fix for subagent invocation until subagent delegation is merged to
stable by @abhipatel12 in
https://github.com/google-gemini/gemini-cli/pull/15007
- test: update ide detection tests to make them more robust when run in an ide
by @kevin-ramdass in https://github.com/google-gemini/gemini-cli/pull/15008
- Remove flex from stats display. See snapshots for diffs. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/14983
- Add license field into package.json by @jb-perez in
https://github.com/google-gemini/gemini-cli/pull/14473
- feat: Persistent "Always Allow" policies with granular shell & MCP support by
@allenhutchison in https://github.com/google-gemini/gemini-cli/pull/14737
- chore/release: bump version to 0.21.0-nightly.20251212.54de67536 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14969
- fix(core): commandPrefix word boundary and compound command safety by
@allenhutchison in https://github.com/google-gemini/gemini-cli/pull/15006
- chore(docs): add 'Maintainers only' label info to CONTRIBUTING.md by @jacob314
in https://github.com/google-gemini/gemini-cli/pull/14914
- Refresh hooks when refreshing extensions. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14918
- Add clarity to error messages by @gsehgal in
https://github.com/google-gemini/gemini-cli/pull/14879
- chore : remove a redundant tip by @JayadityaGit in
https://github.com/google-gemini/gemini-cli/pull/14947
- chore/release: bump version to 0.21.0-nightly.20251213.977248e09 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/15029
- Disallow redundant typecasts. by @gundermanc in
https://github.com/google-gemini/gemini-cli/pull/15030
- fix(auth): prioritize GEMINI_API_KEY env var and skip unnecessary key… by
@galz10 in https://github.com/google-gemini/gemini-cli/pull/14745
- fix: use zod for safety check result validation by @allenhutchison in
https://github.com/google-gemini/gemini-cli/pull/15026
- update(telemetry): add hashed_extension_name to field to extension events by
@kiranani in https://github.com/google-gemini/gemini-cli/pull/15025
- fix: similar to policy-engine, throw error in case of requiring tool execution
confirmation for non-interactive mode by @MayV in
https://github.com/google-gemini/gemini-cli/pull/14702
- Clean up processes in integration tests by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/15102
- docs: update policy engine getting started and defaults by @NTaylorMullen in
https://github.com/google-gemini/gemini-cli/pull/15105
- Fix tool output fragmentation by encapsulating content in functionResponse by
@abhipatel12 in https://github.com/google-gemini/gemini-cli/pull/13082
- Simplify method signature. by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/15114
- Show raw input token counts in json output. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/15021
- fix: Mark A2A requests as interactive by @MayV in
https://github.com/google-gemini/gemini-cli/pull/15108
- use previewFeatures to determine which pro model to use for A2A by @sehoon38
in https://github.com/google-gemini/gemini-cli/pull/15131
- refactor(cli): fix settings merging so that settings using the new json format
take priority over ones using the old format by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/15116
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.21.0-preview.6...v0.22.0-preview.0
## Release v0.20.0 - v0.20.2
### What's Changed
- Update error codes when process exiting the gemini cli by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13728
- chore(release): bump version to 0.20.0-nightly.20251126.d2a6cff4d by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13835
- feat(core): Improve request token calculation accuracy by @SandyTao520 in
https://github.com/google-gemini/gemini-cli/pull/13824
- Changes in system instruction to adapt to gemini 3.0 to ensure that the CLI
explains its actions before calling tools by @silviojr in
https://github.com/google-gemini/gemini-cli/pull/13810
- feat(hooks): Hook Tool Execution Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9108
- Add support for MCP server instructions behind config option by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/13432
- Update System Instructions for interactive vs non-interactive mode. by
@aishaneeshah in https://github.com/google-gemini/gemini-cli/pull/12315
- Add consent flag to Link command by @kevinjwang1 in
https://github.com/google-gemini/gemini-cli/pull/13832
- feat(mcp): Inject GoogleCredentialProvider headers in McpClient by
@sai-sunder-s in https://github.com/google-gemini/gemini-cli/pull/13783
- feat(core): implement towards policy-driven model fallback mechanism by
@adamfweidman in https://github.com/google-gemini/gemini-cli/pull/13781
- feat(core): Add configurable inactivity timeout for shell commands by @galz10
in https://github.com/google-gemini/gemini-cli/pull/13531
- fix(auth): improve API key authentication flow by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/13829
- feat(hooks): Hook LLM Request/Response Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9110
- feat(ui): Show waiting MCP servers in ConfigInitDisplay by @werdnum in
https://github.com/google-gemini/gemini-cli/pull/13721
- Add usage limit remaining in /stats by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/13843
- feat(shell): Standardize pager to 'cat' for shell execution by model by
@galz10 in https://github.com/google-gemini/gemini-cli/pull/13878
- chore/release: bump version to 0.20.0-nightly.20251127.5bed97064 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13877
- Revert to default LICENSE (Revert #13449) by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13876
- update(telemetry): OTel API response event with finish reasons by @kiranani in
https://github.com/google-gemini/gemini-cli/pull/13849
- feat(hooks): Hooks Comprehensive Integration Testing by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9112
- chore: fix session browser test and skip hook system tests by @jackwotherspoon
in https://github.com/google-gemini/gemini-cli/pull/14099
- feat(telemetry): Add Semantic logging for to ApiRequestEvents by @kiranani in
https://github.com/google-gemini/gemini-cli/pull/13912
- test: Add verification for $schema property in settings schema by
@maryamariyan in https://github.com/google-gemini/gemini-cli/pull/13497
- Fixes `/clear` command to preserve input history for up-arrow navigation while
still clearing the context window and screen by @korade-krushna in
https://github.com/google-gemini/gemini-cli/pull/14182
- fix(core): handle EPIPE error in hook runner when writing to stdin by
@SandyTao520 in https://github.com/google-gemini/gemini-cli/pull/14231
- fix: Exclude web-fetch tool from executing in default non-interactive mode to
avoid CLI hang. by @MayV in
https://github.com/google-gemini/gemini-cli/pull/14244
- Always use MCP server instructions by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14297
- feat: auto-execute simple slash commands on Enter by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/13985
- chore/release: bump version to 0.20.0-nightly.20251201.2fe609cb6 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14304
- feat: Add startup profiler to measure and record application initialization
phases. by @kevin-ramdass in
https://github.com/google-gemini/gemini-cli/pull/13638
- bug(core): Avoid stateful tool use in `executor`. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/14305
- feat(themes): add built-in holiday theme 🎁 by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/14301
- Updated ToC on docs intro; updated title casing to match Google style by
@pcoet in https://github.com/google-gemini/gemini-cli/pull/13717
- feat(a2a): Urgent fix - Process modelInfo agent message by @cocosheng-g in
https://github.com/google-gemini/gemini-cli/pull/14315
- feat(core): enhance availability routing with wrapped fallback and
single-model policies by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/13874
- chore(logging): log the problematic event for #12122 by @briandealwis in
https://github.com/google-gemini/gemini-cli/pull/14092
- fix: remove invalid type key in bug_report.yml by @fancive in
https://github.com/google-gemini/gemini-cli/pull/13576
- update screenshot by @Transient-Onlooker in
https://github.com/google-gemini/gemini-cli/pull/13976
- docs: Fix grammar error in Release Cadence (Nightly section) by @JuanCS-Dev in
https://github.com/google-gemini/gemini-cli/pull/13866
- fix(async): prevent missed async errors from bypassing catch handlers by
@amsminn in https://github.com/google-gemini/gemini-cli/pull/13714
- fix(zed-integration): remove extra field from acp auth request by
@marcocondrache in https://github.com/google-gemini/gemini-cli/pull/13646
- feat(cli): Documentation for model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/12967
- fix(ui): misaligned markdown table rendering by @dumbbellcode in
https://github.com/google-gemini/gemini-cli/pull/8336
- docs: Update 4 files by @g-samroberts in
https://github.com/google-gemini/gemini-cli/pull/13628
- fix: Conditionally add set -eEuo pipefail in setup-github command by @Smetalo
in https://github.com/google-gemini/gemini-cli/pull/8550
- fix(cli): fix issue updating a component while rendering a different component
by @jacob314 in https://github.com/google-gemini/gemini-cli/pull/14319
- Increase flakey test timeout by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14377
- Remove references to deleted kind/bug label by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14383
- Don't fail test if we can't cleanup by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/14389
- feat(core): Implement JIT context manager and setting by @SandyTao520 in
https://github.com/google-gemini/gemini-cli/pull/14324
- Use polling for extensions-reload integration test by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/14391
- Add docs directive to GEMINI.md by @g-samroberts in
https://github.com/google-gemini/gemini-cli/pull/14327
- Hide sessions that don't have user messages by @bl-ue in
https://github.com/google-gemini/gemini-cli/pull/13994
- chore(ci): mark GitHub release as pre-release if not on "latest" npm channel
by @ljxfstorm in https://github.com/google-gemini/gemini-cli/pull/7386
- fix(patch): cherry-pick d284fa6 to release/v0.20.0-preview.0-pr-14545
[CONFLICTS] by @gemini-cli-robot in
https://github.com/google-gemini/gemini-cli/pull/14559
- fix(patch): cherry-pick 828afe1 to release/v0.20.0-preview.1-pr-14159 to patch
version v0.20.0-preview.1 and create version 0.20.0-preview.2 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14733
- fix(patch): cherry-pick 171103a to release/v0.20.0-preview.2-pr-14742 to patch
version v0.20.0-preview.2 and create version 0.20.0-preview.5 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/14752
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.19.4...v0.20.0
## Release v0.19.0 - v0.19.4
## Highlights
- **Zed integration:** Users can now leverage Gemini 3 within the Zed
integration after enabling "Preview Features" in their CLIs `/settings`.
- **Interactive shell:**
- **Click-to-Focus:** Go to `/settings` and enable **Use Alternate Buffer**
When "Use Alternate Buffer" setting is enabled users can click within the
embedded shell output to focus it for input.
- **Loading phrase:** Clearly indicates when the interactive shell is awaiting
user input. ([vid](https://imgur.com/a/kjK8bUK)
[pr](https://github.com/google-gemini/gemini-cli/pull/12535) by
[@jackwotherspoon](https://github.com/jackwotherspoon))
### What's Changed
- Use lenient MCP output schema validator by @cornmander in
https://github.com/google-gemini/gemini-cli/pull/13521
- Update persistence state to track counts of messages instead of times banner
has been displayed by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13428
- update docs for http proxy by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13538
- move stdio by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13528
- chore(release): bump version to 0.19.0-nightly.20251120.8e531dc02 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13540
- Skip pre-commit hooks for shadow repo (#13331) by @vishvananda in
https://github.com/google-gemini/gemini-cli/pull/13488
- fix(ui): Correct mouse click cursor positioning for wide characters by
@SandyTao520 in https://github.com/google-gemini/gemini-cli/pull/13537
- fix(core): correct bash @P prompt transformation detection by @pyrytakala in
https://github.com/google-gemini/gemini-cli/pull/13544
- Optimize and improve test coverage for cli/src/config by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13485
- Improve code coverage for cli/src/ui/privacy package by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13493
- docs: fix typos in source code and documentation by @fancive in
https://github.com/google-gemini/gemini-cli/pull/13577
- Improved code coverage for cli/src/zed-integration by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13570
- feat(ui): build interactive session browser component by @bl-ue in
https://github.com/google-gemini/gemini-cli/pull/13351
- Fix multiple bugs with auth flow including using the implemented but unused
restart support. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13565
- feat(core): add modelAvailabilityService for managing and tracking model
health by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/13426
- docs: fix grammar typo "a MCP" to "an MCP" by @noahacgn in
https://github.com/google-gemini/gemini-cli/pull/13595
- feat: custom loading phrase when interactive shell requires input by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/12535
- docs: Update uninstall command to reflect multiple extension support by
@JayadityaGit in https://github.com/google-gemini/gemini-cli/pull/13582
- bug(core): Ensure we use thinking budget on fallback to 2.5 by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13596
- Remove useModelRouter experimental flag by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13593
- feat(docs): Ensure multiline JS objects are rendered properly. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13535
- Fix exp id logging by @owenofbrien in
https://github.com/google-gemini/gemini-cli/pull/13430
- Moved client id logging into createBasicLogEvent by @owenofbrien in
https://github.com/google-gemini/gemini-cli/pull/13607
- Restore bracketed paste mode after external editor exit by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13606
- feat(core): Add support for custom aliases for model configs. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13546
- feat(core): Add `BaseLlmClient.generateContent`. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13591
- Turn off alternate buffer mode by default. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13623
- fix(cli): Prevent stdout/stderr patching for extension commands by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/13600
- Improve test coverage for cli/src/ui/components by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13598
- Update ink version to 6.4.6 by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13631
- chore/release: bump version to 0.19.0-nightly.20251122.42c2e1b21 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13637
- chore/release: bump version to 0.19.0-nightly.20251123.dadd606c0 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13675
- chore/release: bump version to 0.19.0-nightly.20251124.e177314a4 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13713
- fix(core): Fix context window overflow warning for PDF files by @kkitase in
https://github.com/google-gemini/gemini-cli/pull/13548
- feat :rephrasing the extension logging messages to run the explore command
when there are no extensions installed by @JayadityaGit in
https://github.com/google-gemini/gemini-cli/pull/13740
- Improve code coverage for cli package by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13724
- Add session subtask in /stats command by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13750
- feat(core): Migrate chatCompressionService to model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/12863
- feat(hooks): Hook Telemetry Infrastructure by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9082
- fix: (some minor improvements to configs and getPackageJson return behaviour)
by @grMLEqomlkkU5Eeinz4brIrOVCUCkJuN in
https://github.com/google-gemini/gemini-cli/pull/12510
- feat(hooks): Hook Event Handling by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9097
- feat(hooks): Hook Agent Lifecycle Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9105
- feat(core): Land bool for alternate system prompt. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13764
- bug(core): Add default chat compression config. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13766
- feat(model-availability): introduce ModelPolicy and PolicyCatalog by
@adamfweidman in https://github.com/google-gemini/gemini-cli/pull/13751
- feat(hooks): Hook System Orchestration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9102
- feat(config): add isModelAvailabilityServiceEnabled setting by @adamfweidman
in https://github.com/google-gemini/gemini-cli/pull/13777
- chore/release: bump version to 0.19.0-nightly.20251125.f6d97d448 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13782
- chore: remove console.error by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/13779
- fix: Add $schema property to settings.schema.json by @sacrosanctic in
https://github.com/google-gemini/gemini-cli/pull/12763
- fix(cli): allow non-GitHub SCP-styled URLs for extension installation by @m0ps
in https://github.com/google-gemini/gemini-cli/pull/13800
- fix(resume): allow passing a prompt via stdin while resuming using --resume by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13520
- feat(sessions): add /resume slash command to open the session browser by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13621
- docs(sessions): add documentation for chat recording and session management by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13667
- Fix TypeError: "URL.parse is not a function" for Node.js < v22 by @macarronesc
in https://github.com/google-gemini/gemini-cli/pull/13698
- fallback to flash for TerminalQuota errors by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/13791
- Update Code Wiki README badge by @PatoBeltran in
https://github.com/google-gemini/gemini-cli/pull/13768
- Add Databricks auth support and custom header option to gemini cli by
@AarushiShah in https://github.com/google-gemini/gemini-cli/pull/11893
- Update dependency for modelcontextprotocol/sdk to 1.23.0 by @bbiggs in
https://github.com/google-gemini/gemini-cli/pull/13827
- fix(patch): cherry-pick 576fda1 to release/v0.19.0-preview.0-pr-14099
[CONFLICTS] by @gemini-cli-robot in
https://github.com/google-gemini/gemini-cli/pull/14402
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.18.4...v0.19.0
## Release v0.19.0-preview.0
### What's Changed
- Use lenient MCP output schema validator by @cornmander in
https://github.com/google-gemini/gemini-cli/pull/13521
- Update persistence state to track counts of messages instead of times banner
has been displayed by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13428
- update docs for http proxy by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13538
- move stdio by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13528
- chore(release): bump version to 0.19.0-nightly.20251120.8e531dc02 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13540
- Skip pre-commit hooks for shadow repo (#13331) by @vishvananda in
https://github.com/google-gemini/gemini-cli/pull/13488
- fix(ui): Correct mouse click cursor positioning for wide characters by
@SandyTao520 in https://github.com/google-gemini/gemini-cli/pull/13537
- fix(core): correct bash @P prompt transformation detection by @pyrytakala in
https://github.com/google-gemini/gemini-cli/pull/13544
- Optimize and improve test coverage for cli/src/config by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13485
- Improve code coverage for cli/src/ui/privacy package by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13493
- docs: fix typos in source code and documentation by @fancive in
https://github.com/google-gemini/gemini-cli/pull/13577
- Improved code coverage for cli/src/zed-integration by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13570
- feat(ui): build interactive session browser component by @bl-ue in
https://github.com/google-gemini/gemini-cli/pull/13351
- Fix multiple bugs with auth flow including using the implemented but unused
restart support. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13565
- feat(core): add modelAvailabilityService for managing and tracking model
health by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/13426
- docs: fix grammar typo "a MCP" to "an MCP" by @noahacgn in
https://github.com/google-gemini/gemini-cli/pull/13595
- feat: custom loading phrase when interactive shell requires input by
@jackwotherspoon in https://github.com/google-gemini/gemini-cli/pull/12535
- docs: Update uninstall command to reflect multiple extension support by
@JayadityaGit in https://github.com/google-gemini/gemini-cli/pull/13582
- bug(core): Ensure we use thinking budget on fallback to 2.5 by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13596
- Remove useModelRouter experimental flag by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13593
- feat(docs): Ensure multiline JS objects are rendered properly. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13535
- Fix exp id logging by @owenofbrien in
https://github.com/google-gemini/gemini-cli/pull/13430
- Moved client id logging into createBasicLogEvent by @owenofbrien in
https://github.com/google-gemini/gemini-cli/pull/13607
- Restore bracketed paste mode after external editor exit by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13606
- feat(core): Add support for custom aliases for model configs. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13546
- feat(core): Add `BaseLlmClient.generateContent`. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13591
- Turn off alternate buffer mode by default. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13623
- fix(cli): Prevent stdout/stderr patching for extension commands by @chrstnb in
https://github.com/google-gemini/gemini-cli/pull/13600
- Improve test coverage for cli/src/ui/components by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13598
- Update ink version to 6.4.6 by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13631
- chore/release: bump version to 0.19.0-nightly.20251122.42c2e1b21 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13637
- chore/release: bump version to 0.19.0-nightly.20251123.dadd606c0 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13675
- chore/release: bump version to 0.19.0-nightly.20251124.e177314a4 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13713
- fix(core): Fix context window overflow warning for PDF files by @kkitase in
https://github.com/google-gemini/gemini-cli/pull/13548
- feat :rephrasing the extension logging messages to run the explore command
when there are no extensions installed by @JayadityaGit in
https://github.com/google-gemini/gemini-cli/pull/13740
- Improve code coverage for cli package by @megha1188 in
https://github.com/google-gemini/gemini-cli/pull/13724
- Add session subtask in /stats command by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13750
- feat(core): Migrate chatCompressionService to model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/12863
- feat(hooks): Hook Telemetry Infrastructure by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9082
- fix: (some minor improvements to configs and getPackageJson return behaviour)
by @grMLEqomlkkU5Eeinz4brIrOVCUCkJuN in
https://github.com/google-gemini/gemini-cli/pull/12510
- feat(hooks): Hook Event Handling by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9097
- feat(hooks): Hook Agent Lifecycle Integration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9105
- feat(core): Land bool for alternate system prompt. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13764
- bug(core): Add default chat compression config. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13766
- feat(model-availability): introduce ModelPolicy and PolicyCatalog by
@adamfweidman in https://github.com/google-gemini/gemini-cli/pull/13751
- feat(hooks): Hook System Orchestration by @Edilmo in
https://github.com/google-gemini/gemini-cli/pull/9102
- feat(config): add isModelAvailabilityServiceEnabled setting by @adamfweidman
in https://github.com/google-gemini/gemini-cli/pull/13777
- chore/release: bump version to 0.19.0-nightly.20251125.f6d97d448 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13782
- chore: remove console.error by @adamfweidman in
https://github.com/google-gemini/gemini-cli/pull/13779
- fix: Add $schema property to settings.schema.json by @sacrosanctic in
https://github.com/google-gemini/gemini-cli/pull/12763
- fix(cli): allow non-GitHub SCP-styled URLs for extension installation by @m0ps
in https://github.com/google-gemini/gemini-cli/pull/13800
- fix(resume): allow passing a prompt via stdin while resuming using --resume by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13520
- feat(sessions): add /resume slash command to open the session browser by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13621
- docs(sessions): add documentation for chat recording and session management by
@bl-ue in https://github.com/google-gemini/gemini-cli/pull/13667
- Fix TypeError: "URL.parse is not a function" for Node.js < v22 by @macarronesc
in https://github.com/google-gemini/gemini-cli/pull/13698
- fallback to flash for TerminalQuota errors by @sehoon38 in
https://github.com/google-gemini/gemini-cli/pull/13791
- Update Code Wiki README badge by @PatoBeltran in
https://github.com/google-gemini/gemini-cli/pull/13768
- Add Databricks auth support and custom header option to gemini cli by
@AarushiShah in https://github.com/google-gemini/gemini-cli/pull/11893
- Update dependency for modelcontextprotocol/sdk to 1.23.0 by @bbiggs in
https://github.com/google-gemini/gemini-cli/pull/13827
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.18.0-preview.4...v0.19.0-preview.0
## Release v0.18.0 - v0.18.4
### Highlights
- **Experimental permission improvements**: We're experimenting with a new
policy engine in Gemini CLI, letting users and administrators create
fine-grained policies for tool calls. This setting is currently behind a flag.
See our [policy engine documentation](../core/policy-engine.md) to learn how
to use this feature.
- **Gemini 3 support rolled out for some users**: Some users can now enable
Gemini 3 by using the `/settings` flag and toggling **Preview Features**. See
our [Gemini 3 on Gemini CLI documentation](../get-started/gemini-3.md) to find
out more about using Gemini 3.
- **Updated UI rollback:** We've temporarily rolled back a previous UI update,
which enabled embedded scrolling and mouse support. This can be re-enabled by
using the `/settings` command and setting **Use Alternate Screen Buffer** to
`true`.
- **Display your model in your chat history**: You can now go use `/settings`
and turn on **Show Model in Chat** to display the model in your chat history.
- **Uninstall multiple extensions**: You can uninstall multiple extensions with
a single command: `gemini extensions uninstall`.
![Uninstalling Gemini extensions with a single command](https://i.imgur.com/pi7nEBI.png)
### What's changed
- Remove obsolete reference to "help wanted" label in CONTRIBUTING.md by
@aswinashok44 in https://github.com/google-gemini/gemini-cli/pull/13291
- chore(release): v0.18.0-nightly.20251118.86828bb56 by @skeshive in
https://github.com/google-gemini/gemini-cli/pull/13309
- Docs: Access clarification. by @jkcinouye in
https://github.com/google-gemini/gemini-cli/pull/13304
- Fix links in Gemini 3 Pro documentation by @gmackall in
https://github.com/google-gemini/gemini-cli/pull/13312
- Improve keyboard code parsing by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13307
- fix(core): Ensure `read_many_files` tool is available to zed. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13338
- Support 3-parameter modifyOtherKeys sequences by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13342
- Improve pty resize error handling for Windows by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/13353
- fix(ui): Clear input prompt on Escape key press by @SandyTao520 in
https://github.com/google-gemini/gemini-cli/pull/13335
- bug(ui) showLineNumbers had the wrong default value. by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13356
- fix(cli): fix crash on startup in NO_COLOR mode (#13343) due to ungua… by
@avilladsen in https://github.com/google-gemini/gemini-cli/pull/13352
- fix: allow MCP prompts with spaces in name by @jackwotherspoon in
https://github.com/google-gemini/gemini-cli/pull/12910
- Refactor createTransport to duplicate less code by @davidmcwherter in
https://github.com/google-gemini/gemini-cli/pull/13010
- Followup from #10719 by @bl-ue in
https://github.com/google-gemini/gemini-cli/pull/13243
- Capturing github action workflow name if present and send it to clearcut by
@MJjainam in https://github.com/google-gemini/gemini-cli/pull/13132
- feat(sessions): record interactive-only errors and warnings to chat recording
JSON files by @bl-ue in https://github.com/google-gemini/gemini-cli/pull/13300
- fix(zed-integration): Correctly handle cancellation errors by @benbrandt in
https://github.com/google-gemini/gemini-cli/pull/13399
- docs: Add Code Wiki link to README by @holtskinner in
https://github.com/google-gemini/gemini-cli/pull/13289
- Restore keyboard mode when exiting the editor by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13350
- feat(core, cli): Bump genai version to 1.30.0 by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13435
- [cli-ui] Keep header ASCII art colored on non-gradient terminals (#13373) by
@bniladridas in https://github.com/google-gemini/gemini-cli/pull/13374
- Fix Copyright line in LICENSE by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13449
- Fix typo in write_todos methodology instructions by @Smetalo in
https://github.com/google-gemini/gemini-cli/pull/13411
- feat: update thinking mode support to exclude gemini-2.0 models and simplify
logic. by @kevin-ramdass in
https://github.com/google-gemini/gemini-cli/pull/13454
- remove unneeded log by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13456
- feat: add click-to-focus support for interactive shell by @galz10 in
https://github.com/google-gemini/gemini-cli/pull/13341
- Add User email detail to about box by @ptone in
https://github.com/google-gemini/gemini-cli/pull/13459
- feat(core): Wire up chat code path for model configs. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/12850
- chore/release: bump version to 0.18.0-nightly.20251120.2231497b1 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13476
- feat(core): Fix bug with incorrect model overriding. by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13477
- Use synchronous writes when detecting keyboard modes by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13478
- fix(cli): prevent race condition when restoring prompt after context overflow
by @SandyTao520 in https://github.com/google-gemini/gemini-cli/pull/13473
- Revert "feat(core): Fix bug with incorrect model overriding." by @adamfweidman
in https://github.com/google-gemini/gemini-cli/pull/13483
- Fix: Update system instruction when GEMINI.md memory is loaded or refreshed by
@lifefloating in https://github.com/google-gemini/gemini-cli/pull/12136
- fix(zed-integration): Ensure that the zed integration is classified as
interactive by @benbrandt in
https://github.com/google-gemini/gemini-cli/pull/13394
- Copy commands as part of setup-github by @gsehgal in
https://github.com/google-gemini/gemini-cli/pull/13464
- Update banner design by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13420
- Protect stdout and stderr so JavaScript code can't accidentally write to
stdout corrupting ink rendering by @jacob314 in
https://github.com/google-gemini/gemini-cli/pull/13247
- Enable switching preview features on/off without restart by @Adib234 in
https://github.com/google-gemini/gemini-cli/pull/13515
- feat(core): Use thinking level for Gemini 3 by @joshualitt in
https://github.com/google-gemini/gemini-cli/pull/13445
- Change default compress threshold to 0.5 for api key users by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13517
- remove duplicated mouse code by @scidomino in
https://github.com/google-gemini/gemini-cli/pull/13525
- feat(zed-integration): Use default model routing for Zed integration by
@benbrandt in https://github.com/google-gemini/gemini-cli/pull/13398
- feat(core): Incorporate Gemini 3 into model config hierarchy. by @joshualitt
in https://github.com/google-gemini/gemini-cli/pull/13447
- fix(patch): cherry-pick 5e218a5 to release/v0.18.0-preview.0-pr-13623 to patch
version v0.18.0-preview.0 and create version 0.18.0-preview.1 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13626
- fix(patch): cherry-pick d351f07 to release/v0.18.0-preview.1-pr-12535 to patch
version v0.18.0-preview.1 and create version 0.18.0-preview.2 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13813
- fix(patch): cherry-pick 3e50be1 to release/v0.18.0-preview.2-pr-13428 to patch
version v0.18.0-preview.2 and create version 0.18.0-preview.3 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13821
- fix(patch): cherry-pick d8a3d08 to release/v0.18.0-preview.3-pr-13791 to patch
version v0.18.0-preview.3 and create version 0.18.0-preview.4 by
@gemini-cli-robot in https://github.com/google-gemini/gemini-cli/pull/13826
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.17.1...v0.18.0
+1 -1
View File
@@ -1,3 +1,3 @@
# Authentication setup
# Authentication Setup
See: [Getting Started - Authentication Setup](../get-started/authentication.md).
+8 -8
View File
@@ -6,19 +6,19 @@ AI-powered tools. This allows you to safely experiment with and apply code
changes, knowing you can instantly revert back to the state before the tool was
run.
## How it works
## 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
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
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
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`
@@ -35,7 +35,7 @@ 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
## Enabling the Feature
The Checkpointing feature is disabled by default. To enable it, you need to edit
your `settings.json` file.
@@ -56,12 +56,12 @@ Add the following key to your `settings.json`:
}
```
## Using the `/restore` command
## Using the `/restore` Command
Once enabled, checkpoints are created automatically. To manage them, you use the
`/restore` command.
### List available checkpoints
### List Available Checkpoints
To see a list of all saved checkpoints for the current project, simply run:
@@ -74,7 +74,7 @@ typically composed of a timestamp, the name of the file being modified, and the
name of the tool that was about to be run (e.g.,
`2025-06-22T10-00-00_000Z-my-file.txt-write_file`).
### Restore a specific checkpoint
### Restore a Specific Checkpoint
To restore your project to a specific checkpoint, use the checkpoint file from
the list:
+6 -6
View File
@@ -1,4 +1,4 @@
# CLI commands
# CLI Commands
Gemini CLI supports several built-in commands to help you manage your session,
customize the interface, and control its behavior. These commands are prefixed
@@ -26,7 +26,7 @@ Slash commands provide meta-level control over the CLI itself.
- **Description:** Saves the current conversation history. You must add a
`<tag>` for identifying the conversation state.
- **Usage:** `/chat save <tag>`
- **Details on checkpoint location:** The default locations for saved chat
- **Details on Checkpoint Location:** The default locations for saved chat
checkpoints are:
- Linux/macOS: `~/.gemini/tmp/<project_hash>/`
- Windows: `C:\Users\<YourUsername>\.gemini\tmp\<project_hash>\`
@@ -256,13 +256,13 @@ Slash commands provide meta-level control over the CLI itself.
file, making it simpler for them to provide project-specific instructions to
the Gemini agent.
### Custom commands
### Custom Commands
Custom commands allow you to create personalized shortcuts for your most-used
prompts. For detailed instructions on how to create, manage, and use them,
please see the dedicated [Custom Commands documentation](./custom-commands.md).
## Input prompt shortcuts
## Input Prompt Shortcuts
These shortcuts apply directly to the input prompt for text manipulation.
@@ -320,7 +320,7 @@ your prompt to Gemini. These commands include git-aware filtering.
- If the `read_many_files` tool encounters an error (e.g., permission issues),
this will also be reported.
## Shell mode and passthrough commands (`!`)
## Shell mode & passthrough commands (`!`)
The `!` prefix lets you interact with your system's shell directly from within
Gemini CLI.
@@ -348,7 +348,7 @@ Gemini CLI.
- **Caution for all `!` usage:** Commands you execute in shell mode have the
same permissions and impact as if you ran them directly in your terminal.
- **Environment variable:** When a command is executed via `!` or in shell mode,
- **Environment Variable:** When a command is executed via `!` or in shell mode,
the `GEMINI_CLI=1` environment variable is set in the subprocess's
environment. This allows scripts or tools to detect if they are being run from
within the Gemini CLI.
+27 -27
View File
@@ -1,4 +1,4 @@
# Gemini CLI configuration
# Gemini CLI Configuration
Gemini CLI offers several ways to configure its behavior, including environment
variables, command-line arguments, and settings files. This document outlines
@@ -144,7 +144,7 @@ contain other project-specific files related to Gemini CLI's operation, such as:
be ignored if `--allowed-mcp-server-names` is set.
- **Default**: No MCP servers excluded.
- **Example:** `"excludeMCPServers": ["myNodeServer"]`.
- **Security note:** This uses simple string matching on MCP server names,
- **Security Note:** This uses simple string matching on MCP server names,
which can be modified. If you're a system administrator looking to prevent
users from bypassing this, consider configuring the `mcpServers` at the
system settings level such that the user will not be able to configure any
@@ -423,7 +423,7 @@ contain other project-specific files related to Gemini CLI's operation, such as:
}
```
## Shell history
## Shell History
The CLI keeps a history of shell commands you run. To avoid conflicts between
different projects, this history is stored in a project-specific directory
@@ -434,7 +434,7 @@ within your user's home folder.
path.
- The history is stored in a file named `shell_history`.
## Environment variables and `.env` files
## Environment Variables & `.env` Files
Environment variables are a common way to configure applications, especially for
sensitive information like API keys or for settings that might change between
@@ -449,7 +449,7 @@ loading order is:
the home directory.
3. If still not found, it looks for `~/.env` (in the user's home directory).
**Environment variable exclusion:** Some environment variables (like `DEBUG` and
**Environment Variable Exclusion:** Some environment variables (like `DEBUG` and
`DEBUG_MODE`) are automatically excluded from being loaded from project `.env`
files to prevent interference with gemini-cli behavior. Variables from
`.gemini/.env` files are never excluded. You can customize this behavior using
@@ -486,7 +486,7 @@ the `excludedProjectEnvVars` setting in your `settings.json` file.
- Required for using Code Assist or Vertex AI.
- If using Vertex AI, ensure you have the necessary permissions in this
project.
- **Cloud shell note:** When running in a Cloud Shell environment, this
- **Cloud Shell Note:** When running in a Cloud Shell environment, this
variable defaults to a special project allocated for Cloud Shell users. If
you have `GOOGLE_CLOUD_PROJECT` set in your global environment in Cloud
Shell, it will be overridden by this default. To use a different project in
@@ -547,7 +547,7 @@ the `excludedProjectEnvVars` setting in your `settings.json` file.
relative. `~` is supported for the home directory. **Note: This will
overwrite the file if it already exists.**
## Command-line arguments
## Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations
for that specific session.
@@ -606,7 +606,7 @@ for that specific session.
- **`--version`**:
- Displays the version of the CLI.
## Context files (hierarchical instructional context)
## Context Files (Hierarchical Instructional Context)
While not strictly configuration for the CLI's _behavior_, context files
(defaulting to `GEMINI.md` but configurable via the `contextFileName` setting)
@@ -622,7 +622,7 @@ context.
that you want the Gemini model to be aware of during your interactions. The
system is designed to manage this instructional context hierarchically.
### Example context file content (e.g., `GEMINI.md`)
### Example Context File Content (e.g., `GEMINI.md`)
Here's a conceptual example of what a context file at the root of a TypeScript
project might contain:
@@ -663,23 +663,23 @@ more relevant and precise your context files are, the better the AI can assist
you. Project-specific context files are highly encouraged to establish
conventions and context.
- **Hierarchical loading and precedence:** The CLI implements a sophisticated
- **Hierarchical Loading and Precedence:** The CLI implements a sophisticated
hierarchical memory system by loading context files (e.g., `GEMINI.md`) from
several locations. Content from files lower in this list (more specific)
typically overrides or supplements content from files higher up (more
general). The exact concatenation order and final context can be inspected
using the `/memory show` command. The typical loading order is:
1. **Global context file:**
1. **Global Context File:**
- Location: `~/.gemini/<contextFileName>` (e.g., `~/.gemini/GEMINI.md` in
your user home directory).
- Scope: Provides default instructions for all your projects.
2. **Project root and ancestors context files:**
2. **Project Root & Ancestors Context Files:**
- Location: The CLI searches for the configured context file in the
current working directory and then in each parent directory up to either
the project root (identified by a `.git` folder) or your home directory.
- Scope: Provides context relevant to the entire project or a significant
portion of it.
3. **Sub-directory context files (contextual/local):**
3. **Sub-directory Context Files (Contextual/Local):**
- Location: The CLI also scans for the configured context file in
subdirectories _below_ the current working directory (respecting common
ignore patterns like `node_modules`, `.git`, etc.). The breadth of this
@@ -687,15 +687,15 @@ conventions and context.
with a `memoryDiscoveryMaxDirs` field in your `settings.json` file.
- Scope: Allows for highly specific instructions relevant to a particular
component, module, or subsection of your project.
- **Concatenation and UI indication:** The contents of all found context files
are concatenated (with separators indicating their origin and path) and
provided as part of the system prompt to the Gemini model. The CLI footer
displays the count of loaded context files, giving you a quick visual cue
about the active instructional context.
- **Importing content:** You can modularize your context files by importing
- **Concatenation & UI Indication:** The contents of all found context files are
concatenated (with separators indicating their origin and path) and provided
as part of the system prompt to the Gemini model. The CLI footer displays the
count of loaded context files, giving you a quick visual cue about the active
instructional context.
- **Importing Content:** You can modularize your context files by importing
other Markdown files using the `@path/to/file.md` syntax. For more details,
see the [Memory Import Processor documentation](../core/memport.md).
- **Commands for memory management:**
- **Commands for Memory Management:**
- Use `/memory refresh` to force a re-scan and reload of all context files
from all configured locations. This updates the AI's instructional context.
- Use `/memory show` to display the combined instructional context currently
@@ -742,7 +742,7 @@ sandbox image:
BUILD_SANDBOX=1 gemini -s
```
## Usage statistics
## Usage Statistics
To help us improve the Gemini CLI, we collect anonymized usage statistics. This
data helps us understand how the CLI is used, identify common issues, and
@@ -750,22 +750,22 @@ prioritize new features.
**What we collect:**
- **Tool calls:** We log the names of the tools that are called, whether they
- **Tool Calls:** We log the names of the tools that are called, whether they
succeed or fail, and how long they take to execute. We do not collect the
arguments passed to the tools or any data returned by them.
- **API requests:** We log the Gemini model used for each request, the duration
- **API Requests:** We log the Gemini model used for each request, the duration
of the request, and whether it was successful. We do not collect the content
of the prompts or responses.
- **Session information:** We collect information about the configuration of the
- **Session Information:** We collect information about the configuration of the
CLI, such as the enabled tools and the approval mode.
**What we DON'T collect:**
- **Personally identifiable information (PII):** We do not collect any personal
- **Personally Identifiable Information (PII):** We do not collect any personal
information, such as your name, email address, or API keys.
- **Prompt and response content:** We do not log the content of your prompts or
- **Prompt and Response Content:** We do not log the content of your prompts or
the responses from the Gemini model.
- **File content:** We do not log the content of any files that are read or
- **File Content:** We do not log the content of any files that are read or
written by the CLI.
**How to opt out:**
+8 -8
View File
@@ -1,4 +1,4 @@
# Custom commands
# 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
@@ -9,9 +9,9 @@ all your projects, streamlining your workflow and ensuring consistency.
Gemini CLI discovers commands from two locations, loaded in a specific order:
1. **User commands (global):** Located in `~/.gemini/commands/`. These commands
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
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.
@@ -30,7 +30,7 @@ separator (`/` or `\`) being converted to a colon (`:`).
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced
command `/git:commit`.
## TOML file format (v1)
## TOML File Format (v1)
Your command definition files must be written in the TOML format and use the
`.toml` file extension.
@@ -60,7 +60,7 @@ 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)**
**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.
@@ -77,7 +77,7 @@ 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)**
**B. Using arguments in Shell commands (inside `!{...}` blocks)**
When you use `{{args}}` inside a shell injection block (`!{...}`), the arguments
are automatically **shell-escaped** before replacement. This allows you to
@@ -156,7 +156,7 @@ 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 `!{...}`
### 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
@@ -302,7 +302,7 @@ Your response should include:
"""
```
**3. Run the command:**
**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:
+23 -99
View File
@@ -1,11 +1,11 @@
# Gemini CLI for the enterprise
# 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.
> **A note on security:** The patterns described in this document are intended
> **A Note on Security:** The patterns described in this document are intended
> to help administrators create a more controlled and secure environment for
> using Gemini CLI. However, they should not be considered a foolproof security
> boundary. A determined user with sufficient privileges on their local machine
@@ -14,7 +14,7 @@ ensure a consistent experience for all users.
> managed environment, not to defend against a malicious actor with local
> administrative rights.
## Centralized configuration: The system settings file
## 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
@@ -33,11 +33,11 @@ settings (like `theme`) is:
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:**
**Example of Merging and Precedence:**
Here is how settings from different levels are combined.
- **System defaults `system-defaults.json`:**
- **System Defaults `system-defaults.json`:**
```json
{
@@ -89,7 +89,7 @@ Here is how settings from different levels are combined.
}
```
- **System overrides `settings.json`:**
- **System Overrides `settings.json`:**
```json
{
"ui": {
@@ -108,7 +108,7 @@ Here is how settings from different levels are combined.
This results in the following merged configuration:
- **Final merged configuration:**
- **Final Merged Configuration:**
```json
{
"ui": {
@@ -159,51 +159,7 @@ This results in the following merged configuration:
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
(e.g., `/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.
## Restricting tool access
## Restricting Tool Access
You can significantly enhance security by controlling which tools the Gemini
model can use. This is achieved through the `tools.core` and `tools.exclude`
@@ -241,12 +197,12 @@ environment to a blocklist.
}
```
**Security note:** Blocklisting with `excludeTools` is less secure than
**Security Note:** Blocklisting with `excludeTools` is less secure than
allowlisting with `coreTools`, as it relies on blocking known-bad commands, and
clever users may find ways to bypass simple string-based blocks. **Allowlisting
is the recommended approach.**
### Disabling YOLO mode
### 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
@@ -266,14 +222,14 @@ approval.
This setting is highly recommended in an enterprise environment to prevent
unintended tool execution.
## Managing custom tools (MCP servers)
## Managing Custom Tools (MCP Servers)
If your organization uses custom tools via
[Model-Context Protocol (MCP) servers](../core/tools-api.md), it is crucial to
understand how server configurations are managed to apply security policies
effectively.
### How MCP server configurations are merged
### 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
@@ -290,12 +246,12 @@ 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
### 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
### 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.
@@ -324,7 +280,7 @@ third-party MCP server, even if the server offers other tools like
}
```
#### More secure pattern: Define and add to allowlist in system settings
#### 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:
@@ -337,7 +293,7 @@ To create a secure, centrally-managed catalog of tools, the system administrator
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`:**
**Example System `settings.json`:**
1. Add the _names_ of all approved servers to an allowlist. This will prevent
users from adding their own servers.
@@ -366,12 +322,12 @@ 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
### 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`:**
**Example System `settings.json`:**
This configuration defines servers but does not enforce the allowlist. The
administrator has NOT included the "mcp.allowed" setting.
@@ -391,7 +347,7 @@ In this scenario, a user can add their own server in their local
results, the user's server will be added to the list of available tools and
allowed to run.
## Enforcing sandboxing for security
## 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
@@ -411,14 +367,14 @@ 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
## 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):**
**Example (for an MCP Server):**
```json
{
@@ -435,7 +391,7 @@ an environment variable, but it can also be enforced for custom tools via the
}
```
## Telemetry and auditing
## Telemetry and Auditing
For auditing and monitoring purposes, you can configure Gemini CLI to send
telemetry data to a central location. This allows you to track tool usage and
@@ -478,39 +434,7 @@ 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`
## 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
+1 -1
View File
@@ -1,4 +1,4 @@
# Ignoring files
# Ignoring Files
This document provides an overview of the Gemini Ignore (`.geminiignore`)
feature of the Gemini CLI.
+1 -1
View File
@@ -1,4 +1,4 @@
# Provide context with GEMINI.md files
# 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
-210
View File
@@ -1,210 +0,0 @@
# Advanced Model Configuration
This guide details the Model Configuration system within the Gemini CLI.
Designed for researchers, AI quality engineers, and advanced users, this system
provides a rigorous framework for managing generative model hyperparameters and
behaviors.
> **Warning**: This is a power-user feature. Configuration values are passed
> directly to the model provider with minimal validation. Incorrect settings
> (e.g., 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
(e.g., 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 (e.g., 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, e.g., `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 (e.g., `model` + `overrideScope`) override broad matches
(e.g., `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 (e.g., `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 (e.g., `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, e.g. 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"
}
}
]
}
```
+17 -17
View File
@@ -1,4 +1,4 @@
# Headless mode
# Headless Mode
Headless mode allows you to run Gemini CLI programmatically from command line
scripts and automation tools without any interactive UI. This is ideal for
@@ -45,9 +45,9 @@ The headless mode provides a headless interface to Gemini CLI that:
- Enables automation and scripting workflows
- Provides consistent exit codes for error handling
## Basic usage
## Basic Usage
### Direct prompts
### Direct Prompts
Use the `--prompt` (or `-p`) flag to run in headless mode:
@@ -55,7 +55,7 @@ Use the `--prompt` (or `-p`) flag to run in headless mode:
gemini --prompt "What is machine learning?"
```
### Stdin input
### Stdin Input
Pipe input to Gemini CLI from your terminal:
@@ -63,7 +63,7 @@ Pipe input to Gemini CLI from your terminal:
echo "Explain this code" | gemini
```
### Combining with file input
### Combining with File Input
Read from files and process with Gemini:
@@ -71,9 +71,9 @@ Read from files and process with Gemini:
cat README.md | gemini --prompt "Summarize this documentation"
```
## Output formats
## Output Formats
### Text output (default)
### Text Output (Default)
Standard human-readable output:
@@ -87,12 +87,12 @@ Response format:
The capital of France is Paris.
```
### JSON output
### JSON Output
Returns structured data including response, statistics, and metadata. This
format is ideal for programmatic processing and automation scripts.
#### Response schema
#### Response Schema
The JSON output follows this high-level structure:
@@ -140,7 +140,7 @@ The JSON output follows this high-level structure:
}
```
#### Example usage
#### Example Usage
```bash
gemini -p "What is the capital of France?" --output-format json
@@ -218,14 +218,14 @@ Response:
}
```
### Streaming JSON output
### Streaming JSON Output
Returns real-time events as newline-delimited JSON (JSONL). Each significant
action (initialization, messages, tool calls, results) emits immediately as it
occurs. This format is ideal for monitoring long-running operations, building
UIs with live progress, and creating automation pipelines that react to events.
#### When to use streaming JSON
#### When to Use Streaming JSON
Use `--output-format stream-json` when you need:
@@ -237,7 +237,7 @@ Use `--output-format stream-json` when you need:
timestamps
- **Pipeline integration** - Stream events to logging/monitoring systems
#### Event types
#### Event Types
The streaming format emits 6 event types:
@@ -248,7 +248,7 @@ The streaming format emits 6 event types:
5. **`error`** - Non-fatal errors and warnings
6. **`result`** - Final session outcome with aggregated stats
#### Basic usage
#### Basic Usage
```bash
# Stream events to console
@@ -261,7 +261,7 @@ gemini --output-format stream-json --prompt "Analyze this code" > events.jsonl
gemini --output-format stream-json --prompt "List files" | jq -r '.type'
```
#### Example output
#### Example Output
Each line is a complete JSON event:
@@ -274,7 +274,7 @@ Each line is a complete JSON event:
{"type":"result","status":"success","stats":{"total_tokens":250,"input_tokens":50,"output_tokens":200,"duration_ms":3000,"tool_calls":1},"timestamp":"2025-10-10T12:00:05.000Z"}
```
### File redirection
### File Redirection
Save output to files or pipe to other commands:
@@ -292,7 +292,7 @@ gemini -p "Explain microservices" | wc -w
gemini -p "List programming languages" | grep -i "python"
```
## Configuration options
## Configuration Options
Key command-line options for headless usage:
+10 -12
View File
@@ -7,17 +7,17 @@ overview of Gemini CLI, see the [main documentation page](../index.md).
## Basic features
- **[Commands](./commands.md):** A reference for all built-in slash commands
- **[Custom commands](./custom-commands.md):** Create your own commands and
- **[Custom Commands](./custom-commands.md):** Create your own commands and
shortcuts for frequently used prompts.
- **[Headless mode](./headless.md):** Use Gemini CLI programmatically for
- **[Headless Mode](./headless.md):** Use Gemini CLI programmatically for
scripting and automation.
- **[Model selection](./model.md):** Configure the Gemini AI model used by the
- **[Model Selection](./model.md):** Configure the Gemini AI model used by the
CLI.
- **[Settings](./settings.md):** Configure various aspects of the CLI's behavior
and appearance.
- **[Themes](./themes.md):** Customizing the CLI's appearance with different
themes.
- **[Keyboard shortcuts](./keyboard-shortcuts.md):** A reference for all
- **[Keyboard Shortcuts](./keyboard-shortcuts.md):** A reference for all
keyboard shortcuts to improve your workflow.
- **[Tutorials](./tutorials.md):** Step-by-step guides for common tasks.
@@ -25,21 +25,19 @@ overview of Gemini CLI, see the [main documentation page](../index.md).
- **[Checkpointing](./checkpointing.md):** Automatically save and restore
snapshots of your session and files.
- **[Enterprise configuration](./enterprise.md):** Deploying and manage Gemini
- **[Enterprise Configuration](./enterprise.md):** Deploying and manage Gemini
CLI in an enterprise environment.
- **[Sandboxing](./sandbox.md):** Isolate tool execution in a secure,
containerized environment.
- **[Telemetry](./telemetry.md):** Configure observability to monitor usage and
performance.
- **[Token caching](./token-caching.md):** Optimize API costs by caching tokens.
- **[Trusted folders](./trusted-folders.md):** A security feature to control
- **[Token Caching](./token-caching.md):** Optimize API costs by caching tokens.
- **[Trusted Folders](./trusted-folders.md):** A security feature to control
which projects can use the full capabilities of the CLI.
- **[Ignoring files (.geminiignore)](./gemini-ignore.md):** Exclude specific
- **[Ignoring Files (.geminiignore)](./gemini-ignore.md):** Exclude specific
files and directories from being accessed by tools.
- **[Context files (GEMINI.md)](./gemini-md.md):** Provide persistent,
- **[Context Files (GEMINI.md)](./gemini-md.md):** Provide persistent,
hierarchical context to the model.
- **[System prompt override](./system-prompt.md):** Replace the builtin system
instructions using `GEMINI_SYSTEM_MD`.
## Non-interactive mode
@@ -60,4 +58,4 @@ gemini -p "What is fine tuning?"
```
For comprehensive documentation on headless usage, scripting, automation, and
advanced examples, see the **[Headless mode](./headless.md)** guide.
advanced examples, see the **[Headless Mode](./headless.md)** guide.
+6 -6
View File
@@ -1,4 +1,4 @@
# Gemini CLI keyboard shortcuts
# Gemini CLI Keyboard Shortcuts
Gemini CLI ships with a set of default keyboard shortcuts for editing input,
navigating history, and controlling the UI. Use this reference to learn the
@@ -84,10 +84,10 @@ available combinations.
#### External Tools
| Action | Keys |
| ---------------------------------------------- | ------------------------- |
| Open the current prompt in an external editor. | `Ctrl + X` |
| Paste from the clipboard. | `Ctrl + V`<br />`Cmd + V` |
| Action | Keys |
| ---------------------------------------------- | ---------- |
| Open the current prompt in an external editor. | `Ctrl + X` |
| Paste from the clipboard. | `Ctrl + V` |
#### App Controls
@@ -110,7 +110,7 @@ available combinations.
<!-- KEYBINDINGS-AUTOGEN:END -->
## Additional context-specific shortcuts
## Additional Context-Specific Shortcuts
- `Ctrl+Y`: Toggle YOLO (auto-approval) mode for tool calls.
- `Shift+Tab`: Toggle Auto Edit (auto-accept edits) mode.
+19 -15
View File
@@ -1,27 +1,31 @@
## Model routing
## 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
## 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.
Model routing is not based on prompt complexity, but is a fallback mechanism.
Here's how it works:
1. **Model failure:** If the currently selected model fails (e.g., due to quota
or server errors), the CLI will iniate the fallback process.
1. **Model Failure:** If the currently selected model fails to respond (for
example, due to a server error or other issue), 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).
2. **User Consent:** The CLI will prompt you to ask if you want to switch to
the fallback model. This is handled by the `fallbackModelHandler`.
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.
3. **Fallback Activation:** If you consent, the CLI will activate the fallback
mode by calling `config.setFallbackMode(true)`.
### Model selection precedence
4. **Model Switch:** On the next request, the CLI will use the
`DEFAULT_GEMINI_FLASH_MODEL` as the fallback model. This is handled by the
`resolveModel` function in
`packages/cli/src/zed-integration/zedIntegration.ts` which checks if
`isInFallbackMode()` is true.
### Model Selection Precedence
The model used by Gemini CLI is determined by the following order of precedence:
@@ -33,5 +37,5 @@ The model used by Gemini CLI is determined by the following order of precedence:
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. **Default model:** If none of the above are set, the default model will be
4. **Default Model:** If none of the above are set, the default model will be
used. The default model is `auto`
+28 -32
View File
@@ -1,13 +1,8 @@
# Gemini CLI model selection (`/model` command)
# 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.
> **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.
Select your Gemini CLI model. The `/model` command opens a dialog where you can
configure the model used by Gemini CLI, giving you more control over your
results.
## How to use the `/model` command
@@ -17,25 +12,26 @@ Use the following command in Gemini CLI:
/model
```
Running this command will open a dialog with your options:
Running this command will open a dialog with your model options:
| Option | Description | Models |
| ----------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Auto (Gemini 3) | Let the system choose the best Gemini 3 model for your task. | gemini-3-pro-preview (if enabled), gemini-3-flash-preview (if enabled) |
| 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. |
| Option | Description | Models |
| ------------------ | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Auto (recommended) | Let the system choose the best model for your task. | gemini-3-pro-preview (if enabled), gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite |
| Pro | For complex tasks that require deep reasoning and creativity. | gemini-3-pro-preview (if enabled), gemini-2.5-pro |
| Flash | For tasks that need a balance of speed and reasoning. | gemini-2.5-flash |
| Flash-Lite | For simple tasks that need to be done quickly. | gemini-2.5-flash-lite |
We recommend selecting one of the above **Auto** options. However, you can
select **Manual** to select a specific model from those available.
### Gemini 3 Pro and Preview Features
### Gemini 3 and preview features
Note: Gemini 3 is not currently available on all account types. To learn more
about Gemini 3 access, refer to
[Gemini 3 Pro on Gemini CLI](../get-started/gemini-3.md).
> **Note:** Gemini 3 is not currently available on all account types. To learn
> more about Gemini 3 access, refer to
> [Gemini 3 on Gemini CLI](../get-started/gemini-3.md).
To enable Gemini 3 Pro and Gemini 3 Flash (if available), enable
[**Preview Features** by using the `settings` command](../cli/settings.md).
To enable Gemini 3 Pro (if available), enable
[**Preview features** by using the `settings` command](../cli/settings.md). Once
enabled, Gemini CLI will attempt to use Gemini 3 Pro when you select **Auto** or
**Pro**. Both **Auto** and **Pro** will try to use Gemini 3 Pro before falling
back to Gemini 2.5 Pro.
You can also use the `--model` flag to specify a particular Gemini model on
startup. For more details, refer to the
@@ -46,16 +42,16 @@ 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).
- **Default to Auto (recommended).** For most users, the _Auto (recommended)_
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.
need your model to be a little "smarter," use 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:
+1 -1
View File
@@ -87,7 +87,7 @@ Built-in profiles (set via `SEATBELT_PROFILE` env var):
- `restrictive-open`: Strict restrictions, network allowed
- `restrictive-closed`: Maximum restrictions
### Custom sandbox flags
### 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
+7 -9
View File
@@ -1,4 +1,4 @@
# Gemini CLI settings (`/settings` command)
# 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
@@ -94,16 +94,15 @@ they appear in the UI.
| Enable Tool Output Truncation | `tools.enableToolOutputTruncation` | Enable truncation of large tool outputs. | `true` |
| Tool Output Truncation Threshold | `tools.truncateToolOutputThreshold` | Truncate tool output if it is larger than this many characters. Set to -1 to disable. | `10000` |
| Tool Output Truncation Lines | `tools.truncateToolOutputLines` | The number of lines to keep when truncating tool output. | `100` |
| Enable Message Bus Integration | `tools.enableMessageBusIntegration` | Enable policy-based tool confirmation via message bus integration. | `false` |
### Security
| UI Label | Setting | Description | Default |
| ----------------------------- | ----------------------------------------------- | --------------------------------------------------------- | ------- |
| Disable YOLO Mode | `security.disableYoloMode` | Disable YOLO mode, even if enabled by a flag. | `false` |
| Blocks extensions from Git | `security.blockGitExtensions` | Blocks installing and loading extensions from Git. | `false` |
| Folder Trust | `security.folderTrust.enabled` | Setting to track whether Folder trust is enabled. | `false` |
| Allowed Environment Variables | `security.environmentVariableRedaction.allowed` | Environment variables to always allow (bypass redaction). | `[]` |
| Blocked Environment Variables | `security.environmentVariableRedaction.blocked` | Environment variables to always redact. | `[]` |
| UI Label | Setting | Description | Default |
| -------------------------- | ------------------------------ | -------------------------------------------------- | ------- |
| Disable YOLO Mode | `security.disableYoloMode` | Disable YOLO mode, even if enabled by a flag. | `false` |
| Blocks extensions from Git | `security.blockGitExtensions` | Blocks installing and loading extensions from Git. | `false` |
| Folder Trust | `security.folderTrust.enabled` | Setting to track whether Folder trust is enabled. | `false` |
### Experimental
@@ -111,4 +110,3 @@ they appear in the UI.
| ----------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | ------- |
| Enable Codebase Investigator | `experimental.codebaseInvestigatorSettings.enabled` | Enable the Codebase Investigator agent. | `true` |
| Codebase Investigator Max Num Turns | `experimental.codebaseInvestigatorSettings.maxNumTurns` | Maximum number of turns for the Codebase Investigator agent. | `10` |
| Agent Skills | `experimental.skills` | Enable Agent Skills (experimental). | `false` |
-156
View File
@@ -1,156 +0,0 @@
# Agent Skills
_Note: This is an experimental feature enabled via `experimental.skills`. You
can also search for "Skills" within the `/settings` interactive UI to toggle
this and manage other skill-related settings._
Agent Skills allow you to 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.
## Overview
Unlike general context files ([`GEMINI.md`](./gemini-md.md)), which provide
persistent project-wide background, Skills represent **on-demand expertise**.
This allows Gemini to maintain a vast library of specialized capabilities—such
as security auditing, cloud deployments, or codebase migrations—without
cluttering the model's immediate context window.
Gemini autonomously decides when to employ a skill based on your request and the
skill's description. When a relevant skill is identified, the model "pulls in"
the full instructions and resources required to complete the task using the
`activate_skill` tool.
## Key Benefits
- **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.
## Skill Discovery Tiers
Gemini CLI discovers skills from three primary locations:
1. **Project Skills** (`.gemini/skills/`): Project-specific skills that are
typically committed to version control and shared with the team.
2. **User Skills** (`~/.gemini/skills/`): Personal skills available across all
your projects.
3. **Extension Skills**: Skills bundled within installed
[extensions](../extensions/index.md).
**Precedence:** If multiple skills share the same name, higher-precedence
locations override lower ones: **Project > User > Extension**.
## Managing Skills
### In an Interactive Session
Use the `/skills` slash command to view and manage available expertise:
- `/skills list` (default): Shows all discovered skills and their status.
- `/skills disable <name>`: Prevents a specific skill from being used.
- `/skills enable <name>`: Re-enables a disabled skill.
- `/skills reload`: Refreshes the list of discovered skills from all tiers.
_Note: `/skills disable` and `/skills enable` default to the `user` scope. Use
`--scope project` to manage project-specific settings._
### From the Terminal
The `gemini skills` command provides management utilities:
```bash
# List all discovered skills
gemini skills list
# Enable/disable skills. Can use --scope to specify project or user
gemini skills enable my-expertise
gemini skills disable my-expertise
```
## Creating a Skill
A skill is a directory containing a `SKILL.md` file at its root. This file uses
YAML frontmatter for metadata and Markdown for instructions.
### Basic Structure
```markdown
---
name: <unique-name>
description: <what the skill does and when Gemini should use it>
---
<your instructions for how the agent should behave / use the skill>
```
- **`name`**: A unique identifier (lowercase, alphanumeric, and dashes).
- **`description`**: The most critical field. Gemini uses this to decide when
the skill is relevant. Be specific about the expertise provided.
- **Body**: Everything below the second `---` is injected as expert procedural
guidance for the model.
### Example: Team Code Reviewer
```markdown
---
name: code-reviewer
description:
Expertise in reviewing code for style, security, and performance. Use when the
user asks for "feedback," a "review," or to "check" their changes.
---
# Code Reviewer
You are an expert code reviewer. When reviewing code, follow this workflow:
1. **Analyze**: Review the staged changes or specific files provided. Ensure
that the changes are scoped properly and represent minimal changes required
to address the issue.
2. **Style**: Ensure code follows the project's conventions and idiomatic
patterns as described in the `GEMINI.md` file.
3. **Security**: Flag any potential security vulnerabilities.
4. **Tests**: Verify that new logic has corresponding test coverage and that
the test coverage adequately validates the changes.
Provide your feedback as a concise bulleted list of "Strengths" and
"Opportunities."
```
### Resource Conventions
While you can structure your skill directory however you like, the Agent Skills
standard encourages these conventions:
- **`scripts/`**: Executable scripts (bash, python, node) the agent can run.
- **`references/`**: Static documentation, schemas, or example data for the
agent to consult.
- **`assets/`**: Code templates, boilerplate, or binary resources.
When a skill is activated, Gemini CLI provides the model with a tree view of the
entire skill directory, allowing it to discover and utilize these assets.
## How it Works (Security & Privacy)
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.
-93
View File
@@ -1,93 +0,0 @@
# 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.
> 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.md#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 (e.g., `~/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.
## 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`.
+62 -86
View File
@@ -3,27 +3,27 @@
Learn how to enable and setup OpenTelemetry for Gemini CLI.
- [Observability with OpenTelemetry](#observability-with-opentelemetry)
- [Key benefits](#key-benefits)
- [OpenTelemetry integration](#opentelemetry-integration)
- [Key Benefits](#key-benefits)
- [OpenTelemetry Integration](#opentelemetry-integration)
- [Configuration](#configuration)
- [Google Cloud telemetry](#google-cloud-telemetry)
- [Google Cloud Telemetry](#google-cloud-telemetry)
- [Prerequisites](#prerequisites)
- [Direct export (recommended)](#direct-export-recommended)
- [Collector-based export (advanced)](#collector-based-export-advanced)
- [Local telemetry](#local-telemetry)
- [File-based output (recommended)](#file-based-output-recommended)
- [Collector-based export (advanced)](#collector-based-export-advanced-1)
- [Logs and metrics](#logs-and-metrics)
- [Direct Export (Recommended)](#direct-export-recommended)
- [Collector-Based Export (Advanced)](#collector-based-export-advanced)
- [Local Telemetry](#local-telemetry)
- [File-based Output (Recommended)](#file-based-output-recommended)
- [Collector-Based Export (Advanced)](#collector-based-export-advanced-1)
- [Logs and Metrics](#logs-and-metrics)
- [Logs](#logs)
- [Sessions](#sessions)
- [Tools](#tools)
- [Files](#files)
- [API](#api)
- [Model routing](#model-routing)
- [Chat and streaming](#chat-and-streaming)
- [Model Routing](#model-routing)
- [Chat and Streaming](#chat-and-streaming)
- [Resilience](#resilience)
- [Extensions](#extensions)
- [Agent runs](#agent-runs)
- [Agent Runs](#agent-runs)
- [IDE](#ide)
- [UI](#ui)
- [Metrics](#metrics)
@@ -31,40 +31,40 @@ Learn how to enable and setup OpenTelemetry for Gemini CLI.
- [Sessions](#sessions-1)
- [Tools](#tools-1)
- [API](#api-1)
- [Token usage](#token-usage)
- [Token Usage](#token-usage)
- [Files](#files-1)
- [Chat and streaming](#chat-and-streaming-1)
- [Model routing](#model-routing-1)
- [Agent runs](#agent-runs-1)
- [Chat and Streaming](#chat-and-streaming-1)
- [Model Routing](#model-routing-1)
- [Agent Runs](#agent-runs-1)
- [UI](#ui-1)
- [Performance](#performance)
- [GenAI semantic convention](#genai-semantic-convention)
- [GenAI Semantic Convention](#genai-semantic-convention)
## Key benefits
## Key Benefits
- **🔍 Usage analytics**: Understand interaction patterns and feature adoption
- **🔍 Usage Analytics**: Understand interaction patterns and feature adoption
across your team
- **⚡ Performance monitoring**: Track response times, token consumption, and
- **⚡ Performance Monitoring**: Track response times, token consumption, and
resource utilization
- **🐛 Real-time debugging**: Identify bottlenecks, failures, and error patterns
- **🐛 Real-time Debugging**: Identify bottlenecks, failures, and error patterns
as they occur
- **📊 Workflow optimization**: Make informed decisions to improve
- **📊 Workflow Optimization**: Make informed decisions to improve
configurations and processes
- **🏢 Enterprise governance**: Monitor usage across teams, track costs, ensure
- **🏢 Enterprise Governance**: Monitor usage across teams, track costs, ensure
compliance, and integrate with existing monitoring infrastructure
## OpenTelemetry integration
## OpenTelemetry Integration
Built on **[OpenTelemetry]** — the vendor-neutral, industry-standard
observability framework — Gemini CLI's observability system provides:
- **Universal compatibility**: Export to any OpenTelemetry backend (Google
- **Universal Compatibility**: Export to any OpenTelemetry backend (Google
Cloud, Jaeger, Prometheus, Datadog, etc.)
- **Standardized data**: Use consistent formats and collection methods across
- **Standardized Data**: Use consistent formats and collection methods across
your toolchain
- **Future-proof integration**: Connect with existing and future observability
- **Future-Proof Integration**: Connect with existing and future observability
infrastructure
- **No vendor lock-in**: Switch between backends without changing your
- **No Vendor Lock-in**: Switch between backends without changing your
instrumentation
[OpenTelemetry]: https://opentelemetry.io/
@@ -74,25 +74,24 @@ observability framework — Gemini CLI's observability system provides:
All telemetry behavior is controlled through your `.gemini/settings.json` file.
Environment variables can be used to override the settings in the file.
| Setting | Environment Variable | Description | Values | Default |
| -------------- | -------------------------------- | --------------------------------------------------- | ----------------- | ----------------------- |
| `enabled` | `GEMINI_TELEMETRY_ENABLED` | Enable or disable telemetry | `true`/`false` | `false` |
| `target` | `GEMINI_TELEMETRY_TARGET` | Where to send telemetry data | `"gcp"`/`"local"` | `"local"` |
| `otlpEndpoint` | `GEMINI_TELEMETRY_OTLP_ENDPOINT` | OTLP collector endpoint | URL string | `http://localhost:4317` |
| `otlpProtocol` | `GEMINI_TELEMETRY_OTLP_PROTOCOL` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
| `outfile` | `GEMINI_TELEMETRY_OUTFILE` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
| `logPrompts` | `GEMINI_TELEMETRY_LOG_PROMPTS` | Include prompts in telemetry logs | `true`/`false` | `true` |
| `useCollector` | `GEMINI_TELEMETRY_USE_COLLECTOR` | Use external OTLP collector (advanced) | `true`/`false` | `false` |
| `useCliAuth` | `GEMINI_TELEMETRY_USE_CLI_AUTH` | Use CLI credentials for telemetry (GCP target only) | `true`/`false` | `false` |
| Setting | Environment Variable | Description | Values | Default |
| -------------- | -------------------------------- | ------------------------------------------------- | ----------------- | ----------------------- |
| `enabled` | `GEMINI_TELEMETRY_ENABLED` | Enable or disable telemetry | `true`/`false` | `false` |
| `target` | `GEMINI_TELEMETRY_TARGET` | Where to send telemetry data | `"gcp"`/`"local"` | `"local"` |
| `otlpEndpoint` | `GEMINI_TELEMETRY_OTLP_ENDPOINT` | OTLP collector endpoint | URL string | `http://localhost:4317` |
| `otlpProtocol` | `GEMINI_TELEMETRY_OTLP_PROTOCOL` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
| `outfile` | `GEMINI_TELEMETRY_OUTFILE` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
| `logPrompts` | `GEMINI_TELEMETRY_LOG_PROMPTS` | Include prompts in telemetry logs | `true`/`false` | `true` |
| `useCollector` | `GEMINI_TELEMETRY_USE_COLLECTOR` | Use external OTLP collector (advanced) | `true`/`false` | `false` |
**Note on boolean environment variables:** For the boolean settings (`enabled`,
`logPrompts`, `useCollector`), setting the corresponding environment variable to
`true` or `1` will enable the feature. Any other value will disable it.
For detailed information about all configuration options, see the
[Configuration guide](../get-started/configuration.md).
[Configuration Guide](../get-started/configuration.md).
## Google Cloud telemetry
## Google Cloud Telemetry
### Prerequisites
@@ -131,35 +130,7 @@ Before using either method below, complete these steps:
--project="$OTLP_GOOGLE_CLOUD_PROJECT"
```
### Authenticating with CLI Credentials
By default, the telemetry collector for Google Cloud uses Application Default
Credentials (ADC). However, you can configure it to use the same OAuth
credentials that you use to log in to the Gemini CLI. This is useful in
environments where you don't have ADC set up.
To enable this, set the `useCliAuth` property in your `telemetry` settings to
`true`:
```json
{
"telemetry": {
"enabled": true,
"target": "gcp",
"useCliAuth": true
}
}
```
**Important:**
- This setting requires the use of **Direct Export** (in-process exporters).
- It **cannot** be used with `useCollector: true`. If you enable both, telemetry
will be disabled and an error will be logged.
- The CLI will automatically use your credentials to authenticate with Google
Cloud Trace, Metrics, and Logging APIs.
### Direct export (recommended)
### Direct Export (Recommended)
Sends telemetry directly to Google Cloud services. No collector needed.
@@ -179,7 +150,7 @@ Sends telemetry directly to Google Cloud services. No collector needed.
- Metrics: https://console.cloud.google.com/monitoring/metrics-explorer
- Traces: https://console.cloud.google.com/traces/list
### Collector-based export (advanced)
### Collector-Based Export (Advanced)
For custom processing, filtering, or routing, use an OpenTelemetry collector to
forward data to Google Cloud.
@@ -213,11 +184,11 @@ forward data to Google Cloud.
- Open `~/.gemini/tmp/<projectHash>/otel/collector-gcp.log` to view local
collector logs.
## Local telemetry
## Local Telemetry
For local development and debugging, you can capture telemetry data locally:
### File-based output (recommended)
### File-based Output (Recommended)
1. Enable telemetry in your `.gemini/settings.json`:
```json
@@ -233,7 +204,7 @@ For local development and debugging, you can capture telemetry data locally:
2. Run Gemini CLI and send prompts.
3. View logs and metrics in the specified file (e.g., `.gemini/telemetry.log`).
### Collector-based export (advanced)
### Collector-Based Export (Advanced)
1. Run the automation script:
```bash
@@ -249,7 +220,7 @@ For local development and debugging, you can capture telemetry data locally:
3. View traces at http://localhost:16686 and logs/metrics in the collector log
file.
## Logs and metrics
## Logs and Metrics
The following section describes the structure of logs and metrics generated for
Gemini CLI.
@@ -297,7 +268,7 @@ Captures startup configuration and user prompt submissions.
#### Tools
Captures tool executions, output truncation, and Edit behavior.
Captures tool executions, output truncation, and Smart Edit behavior.
- `gemini_cli.tool_call`: Emitted for each tool (function) call.
- **Attributes**:
@@ -325,11 +296,11 @@ Captures tool executions, output truncation, and Edit behavior.
- `lines` (int)
- `prompt_id` (string)
- `gemini_cli.edit_strategy`: Edit strategy chosen.
- `gemini_cli.smart_edit_strategy`: Smart Edit strategy chosen.
- **Attributes**:
- `strategy` (string)
- `gemini_cli.edit_correction`: Edit correction result.
- `gemini_cli.smart_edit_correction`: Smart Edit correction result.
- **Attributes**:
- `correction` ("success" | "failure")
@@ -390,7 +361,6 @@ Captures Gemini API requests, responses, and errors.
- `response_text` (string, optional)
- `prompt_id` (string)
- `auth_type` (string)
- `finish_reasons` (array of strings)
- `gemini_cli.api_error`: API request failed.
- **Attributes**:
@@ -407,7 +377,9 @@ Captures Gemini API requests, responses, and errors.
- **Attributes**:
- `model` (string)
#### Model routing
#### Model Routing
Tracks model selections via slash commands and router decisions.
- `gemini_cli.slash_command`: A slash command was executed.
- **Attributes**:
@@ -428,7 +400,9 @@ Captures Gemini API requests, responses, and errors.
- `failed` (boolean)
- `error_message` (string, optional)
#### Chat and streaming
#### Chat and Streaming
Observes streaming integrity, compression, and retry behavior.
- `gemini_cli.chat_compression`: Chat context was compressed.
- **Attributes**:
@@ -514,7 +488,9 @@ Tracks extension lifecycle and settings changes.
- `extension_source` (string)
- `status` (string)
#### Agent runs
#### Agent Runs
Tracks agent lifecycle and outcomes.
- `gemini_cli.agent.start`: Agent run started.
- **Attributes**:
@@ -590,7 +566,7 @@ Tracks API request volume and latency.
- `model`
- Note: Overlaps with `gen_ai.client.operation.duration` (GenAI conventions).
##### Token usage
##### Token Usage
Tracks tokens used by model and type.
@@ -618,7 +594,7 @@ Counts file operations with basic context.
- `function_name`
- `type` ("added" or "removed")
##### Chat and streaming
##### Chat and Streaming
Resilience counters for compression, invalid chunks, and retries.
@@ -637,7 +613,7 @@ Resilience counters for compression, invalid chunks, and retries.
- `gemini_cli.chat.content_retry_failure.count` (Counter, Int): Counts requests
where all content retries failed.
##### Model routing
##### Model Routing
Routing latency/failures and slash-command selections.
@@ -658,7 +634,7 @@ Routing latency/failures and slash-command selections.
- `routing.decision_source` (string)
- `routing.error_message` (string)
##### Agent runs
##### Agent Runs
Agent lifecycle metrics: runs, durations, and turns.
@@ -750,7 +726,7 @@ Optional performance monitoring for startup, CPU/memory, and phase timing.
- `current_value` (number)
- `baseline_value` (number)
#### GenAI semantic convention
#### GenAI Semantic Convention
The following metrics comply with [OpenTelemetry GenAI semantic conventions] for
standardized observability across GenAI applications:
+14 -14
View File
@@ -4,19 +4,19 @@ 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
## 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:**
- **Dark Themes:**
- `ANSI`
- `Atom One`
- `Ayu`
- `Default`
- `Dracula`
- `GitHub`
- **Light themes:**
- **Light Themes:**
- `ANSI Light`
- `Ayu Light`
- `Default Light`
@@ -24,7 +24,7 @@ using the `/theme` command within Gemini CLI:
- `Google Code`
- `Xcode`
### Changing themes
### Changing Themes
1. Enter `/theme` into Gemini CLI.
2. A dialog or selection prompt appears, listing the available themes.
@@ -36,7 +36,7 @@ using the `/theme` command within Gemini CLI:
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
### Theme Persistence
Selected themes are saved in Gemini CLI's
[configuration](../get-started/configuration.md) so your preference is
@@ -44,13 +44,13 @@ remembered across sessions.
---
## Custom color themes
## Custom Color Themes
Gemini CLI allows you to create your own custom color themes by specifying them
in your `settings.json` file. This gives you full control over the color palette
used in the CLI.
### How to define a custom theme
### 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
@@ -93,7 +93,7 @@ This object supports the keys `primary`, `secondary`, `link`, `accent`, and
`response`. When `text.response` is provided it takes precedence over
`text.primary` for rendering model responses in chat.
**Required properties:**
**Required Properties:**
- `name` (must match the key in the `customThemes` object and be a string)
- `type` (must be the string `"custom"`)
@@ -117,7 +117,7 @@ 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
### 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
@@ -162,17 +162,17 @@ custom theme defined in `settings.json`.
}
```
**Security note:** For your safety, Gemini CLI will only load theme files that
**Security Note:** For your safety, Gemini CLI will only load theme files that
are located within your home directory. If you attempt to load a theme from
outside your home directory, a warning will be displayed and the theme will not
be loaded. This is to prevent loading potentially malicious theme files from
untrusted sources.
### Example custom theme
### Example Custom Theme
<img src="../assets/theme-custom.png" alt="Custom theme example" width="600" />
### Using your custom theme
### 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.
@@ -184,7 +184,7 @@ untrusted sources.
---
## Dark themes
## Dark Themes
### ANSI
@@ -210,7 +210,7 @@ untrusted sources.
<img src="/assets/theme-github.png" alt="GitHub theme" width="600">
## Light themes
## Light Themes
### ANSI Light
+1 -1
View File
@@ -1,4 +1,4 @@
# Token caching and cost optimization
# 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
+16 -16
View File
@@ -5,7 +5,7 @@ which projects can use the full capabilities of the Gemini CLI. It prevents
potentially malicious code from running by asking you to approve a folder before
the CLI loads any project-specific configurations from it.
## Enabling the feature
## Enabling the Feature
The Trusted Folders feature is **disabled by default**. To use it, you must
first enable it in your settings.
@@ -22,7 +22,7 @@ Add the following to your user `settings.json` file:
}
```
## How it works: The trust dialog
## How It Works: The Trust Dialog
Once the feature is enabled, the first time you run the Gemini CLI from a
folder, a dialog will automatically appear, prompting you to make a choice:
@@ -38,58 +38,58 @@ folder, a dialog will automatically appear, prompting you to make a choice:
Your choice is saved in a central file (`~/.gemini/trustedFolders.json`), so you
will only be asked once per folder.
## Why trust matters: The impact of an untrusted workspace
## Why Trust Matters: The Impact of an Untrusted Workspace
When a folder is **untrusted**, the Gemini CLI runs in a restricted "safe mode"
to protect you. In this mode, the following features are disabled:
1. **Workspace settings are ignored**: The CLI will **not** load the
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`
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
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
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
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
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
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 the Gemini CLI for
that workspace.
## Managing your trust settings
## 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
- **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
- **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)
## 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
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
2. **Local Trust File**: If the IDE is not connected, the CLI checks the
central `~/.gemini/trustedFolders.json` file.
-4
View File
@@ -2,10 +2,6 @@
This page contains tutorials for interacting with Gemini CLI.
## Agent Skills
- [Getting Started with Agent Skills](./tutorials/skills-getting-started.md)
## Setting up a Model Context Protocol (MCP) server
> [!CAUTION] Before using a third-party MCP server, ensure you trust its source
@@ -1,124 +0,0 @@
# Getting Started with Agent Skills
Agent Skills allow you to extend Gemini CLI with specialized expertise. This
tutorial will guide you through creating your first skill, enabling it, and
using it in a session.
## 1. Enable Agent Skills
Agent Skills are currently an experimental feature and must be enabled in your
settings.
### Via the interactive UI
1. Start a Gemini CLI session by running `gemini`.
2. Type `/settings` to open the interactive settings dialog.
3. Search for "Skills".
4. Toggle **Agent Skills** to `true`.
5. Press `Esc` to save and exit. You may need to restart the CLI for the
changes to take effect.
### Via `settings.json`
Alternatively, you can manually edit your global settings file at
`~/.gemini/settings.json` (create it if it doesn't exist):
```json
{
"experimental": {
"skills": true
}
}
```
## 2. Create Your First Skill
A skill is a directory containing a `SKILL.md` file. Let's create an **API
Auditor** skill that helps you verify if local or remote endpoints are
responding correctly.
1. **Create the skill directory structure:**
```bash
mkdir -p .gemini/skills/api-auditor/scripts
```
2. **Create the `SKILL.md` file:** Create a file at
`.gemini/skills/api-auditor/SKILL.md` with the following content:
```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. **Create the bundled Node.js script:** Create a file at
`.gemini/skills/api-auditor/scripts/audit.js`. This script will be used by
the agent to perform the actual check:
```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})`));
```
## 3. Verify the Skill is Discovered
Use the `/skills` slash command (or `gemini skills list` from your terminal) to
see if Gemini CLI has found your new skill.
In a Gemini CLI session:
```
/skills list
```
You should see `api-auditor` in the list of available skills.
## 4. Use the Skill in a Chat
Now, let's see the skill in action. Start a new session and ask a question about
an endpoint.
**User:** "Can you audit http://geminili.com"
Gemini will recognize the request matches the `api-auditor` description and will
ask for your permission to activate it.
**Model:** (After calling `activate_skill`) "I've activated the **api-auditor**
skill. I'll run the audit script now..."
Gemini will then use the `run_shell_command` tool to execute your bundled Node
script:
`node .gemini/skills/api-auditor/scripts/audit.js http://geminili.com`
## Next Steps
- Explore [Agent Skills Authoring Guide](../skills.md#creating-a-skill) to learn
about more advanced skill features.
- Learn how to share skills via [Extensions](../../extensions/index.md).
+1 -1
View File
@@ -35,7 +35,7 @@ _PowerShell_
Remove-Item -Path (Join-Path $env:LocalAppData "npm-cache\_npx") -Recurse -Force
```
## Method 2: Using npm (global install)
## Method 2: Using npm (Global Install)
If you installed the CLI globally (e.g., `npm install -g @google/gemini-cli`),
use the `npm uninstall` command with the `-g` flag to remove it.
+1 -1
View File
@@ -1,4 +1,4 @@
# Gemini CLI core
# Gemini CLI Core
Gemini CLI's core package (`packages/core`) is the backend portion of Gemini
CLI, handling communication with the Gemini API, managing tools, and processing
+18 -18
View File
@@ -27,21 +27,21 @@ More content here.
@./shared/configuration.md
```
## Supported path formats
## Supported Path Formats
### Relative paths
### Relative Paths
- `@./file.md` - Import from the same directory
- `@../file.md` - Import from parent directory
- `@./components/file.md` - Import from subdirectory
### Absolute paths
### Absolute Paths
- `@/absolute/path/to/file.md` - Import using absolute path
## Examples
### Basic import
### Basic Import
```markdown
# My GEMINI.md
@@ -55,7 +55,7 @@ Welcome to my project!
@./features/overview.md
```
### Nested imports
### Nested Imports
The imported files can themselves contain imports, creating a nested structure:
@@ -73,9 +73,9 @@ The imported files can themselves contain imports, creating a nested structure:
@./shared/title.md
```
## Safety features
## Safety Features
### Circular import detection
### Circular Import Detection
The processor automatically detects and prevents circular imports:
@@ -89,37 +89,37 @@ The processor automatically detects and prevents circular imports:
@./file-a.md <!-- This will be detected and prevented -->
```
### File access security
### File Access Security
The `validateImportPath` function ensures that imports are only allowed from
specified directories, preventing access to sensitive files outside the allowed
scope.
### Maximum import depth
### Maximum Import Depth
To prevent infinite recursion, there's a configurable maximum import depth
(default: 5 levels).
## Error handling
## Error Handling
### Missing files
### Missing Files
If a referenced file doesn't exist, the import will fail gracefully with an
error comment in the output.
### File access errors
### File Access Errors
Permission issues or other file system errors are handled gracefully with
appropriate error messages.
## Code region detection
## Code Region Detection
The import processor uses the `marked` library to detect code blocks and inline
code spans, ensuring that `@` imports inside these regions are properly ignored.
This provides robust handling of nested code blocks and complex Markdown
structures.
## Import tree structure
## Import Tree Structure
The processor returns an import tree that shows the hierarchy of imported files,
similar to Claude's `/memory` feature. This helps users debug problems with
@@ -143,7 +143,7 @@ Memory Files
The tree preserves the order that files were imported and shows the complete
import chain for debugging purposes.
## Comparison to Claude Code's `/memory` (`claude.md`) approach
## Comparison to Claude Code's `/memory` (`claude.md`) Approach
Claude Code's `/memory` feature (as seen in `claude.md`) produces a flat, linear
document by concatenating all included files, always marking file boundaries
@@ -154,7 +154,7 @@ for reconstructing the hierarchy if needed.
> [!NOTE] The import tree is mainly for clarity during development and has
> limited relevance to LLM consumption.
## API reference
## API Reference
### `processImports(content, basePath, debugMode?, importState?)`
@@ -225,7 +225,7 @@ directory if no `.git` is found)
## Troubleshooting
### Common issues
### Common Issues
1. **Import not working**: Check that the file exists and the path is correct
2. **Circular import warnings**: Review your import structure for circular
@@ -235,7 +235,7 @@ directory if no `.git` is found)
4. **Path resolution issues**: Use absolute paths if relative paths aren't
resolving correctly
### Debug mode
### Debug Mode
Enable debug mode to see detailed logging of the import process:
+9 -30
View File
@@ -1,32 +1,13 @@
# Policy engine
# Policy Engine
:::note This feature is currently in testing. To enable it, set
`tools.enableMessageBusIntegration` to `true` in your `settings.json` file. :::
The Gemini CLI includes a powerful policy engine that provides fine-grained
control over tool execution. It allows users and administrators to define rules
that determine whether a tool call should be allowed, denied, or require user
confirmation.
## Quick start
To create your first policy:
1. **Create the policy directory** if it doesn't exist:
```bash
mkdir -p ~/.gemini/policies
```
2. **Create a new policy file** (e.g., `~/.gemini/policies/my-rules.toml`). You
can use any filename ending in `.toml`; all such files in this directory
will be loaded and combined:
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git status"
decision = "allow"
priority = 100
```
3. **Run a command** that triggers the policy (e.g., ask Gemini CLI to
`git status`). The tool will now execute automatically without prompting for
confirmation.
## Core concepts
The policy engine operates on a set of rules. Each rule is a combination of
@@ -68,7 +49,7 @@ The `toolName` in the rule must match the name of the tool being called.
wildcard. A `toolName` of `my-server__*` will match any tool from the
`my-server` MCP.
#### Arguments pattern
#### Arguments Pattern
If `argsPattern` is specified, the tool's arguments are converted to a stable
JSON string, which is then tested against the provided regular expression. If
@@ -83,7 +64,7 @@ There are three possible decisions a rule can enforce:
- `ask_user`: The user is prompted to approve or deny the tool call. (In
non-interactive mode, this is treated as `deny`.)
### Priority system and tiers
### Priority system & tiers
The policy engine uses a sophisticated priority system to resolve conflicts when
multiple rules match a single tool call. The core principle is simple: **the
@@ -131,12 +112,12 @@ outcome.
A rule matches a tool call if all of its conditions are met:
1. **Tool name**: The `toolName` in the rule must match the name of the tool
1. **Tool Name**: The `toolName` in the rule must match the name of the tool
being called.
- **Wildcards**: For Model-hosting-protocol (MCP) servers, you can use a
wildcard. A `toolName` of `my-server__*` will match any tool from the
`my-server` MCP.
2. **Arguments pattern**: If `argsPattern` is specified, the tool's arguments
2. **Arguments Pattern**: If `argsPattern` is specified, the tool's arguments
are converted to a stable JSON string, which is then tested against the
provided regular expression. If the arguments don't match the pattern, the
rule does not apply.
@@ -239,7 +220,7 @@ decision = "allow"
priority = 200
```
**2. Using a wildcard**
**2. Using a Wildcard**
To create a rule that applies to _all_ tools on a specific MCP server, specify
only the `mcpName`.
@@ -258,8 +239,6 @@ The Gemini CLI ships with a set of default policies to provide a safe
out-of-the-box experience.
- **Read-only tools** (like `read_file`, `glob`) are generally **allowed**.
- **Agent delegation** (like `delegate_to_agent`) is **allowed** (sub-agent
actions are checked individually).
- **Write tools** (like `write_file`, `run_shell_command`) default to
**`ask_user`**.
- In **`yolo`** mode, a high-priority rule allows all tools.
+26 -26
View File
@@ -1,11 +1,11 @@
# Gemini CLI core: Tools API
# Gemini CLI Core: Tools API
The Gemini CLI core (`packages/core`) features a robust system for defining,
registering, and executing tools. These tools extend the capabilities of the
Gemini model, allowing it to interact with the local environment, fetch web
content, and perform various actions beyond simple text generation.
## Core concepts
## Core Concepts
- **Tool (`tools.ts`):** An interface and base class (`BaseTool`) that defines
the contract for all tools. Each tool must have:
@@ -32,35 +32,35 @@ content, and perform various actions beyond simple text generation.
- `returnDisplay`: A user-friendly string (often Markdown) or a special object
(like `FileDiff`) for display in the CLI.
- **Returning rich content:** Tools are not limited to returning simple text.
- **Returning Rich Content:** Tools are not limited to returning simple text.
The `llmContent` can be a `PartListUnion`, which is an array that can contain
a mix of `Part` objects (for images, audio, etc.) and `string`s. This allows a
single tool execution to return multiple pieces of rich content.
- **Tool registry (`tool-registry.ts`):** A class (`ToolRegistry`) responsible
- **Tool Registry (`tool-registry.ts`):** A class (`ToolRegistry`) responsible
for:
- **Registering tools:** Holding a collection of all available built-in tools
- **Registering Tools:** Holding a collection of all available built-in tools
(e.g., `ReadFileTool`, `ShellTool`).
- **Discovering tools:** It can also discover tools dynamically:
- **Command-based discovery:** If `tools.discoveryCommand` is configured in
- **Discovering Tools:** It can also discover tools dynamically:
- **Command-based Discovery:** If `tools.discoveryCommand` is configured in
settings, this command is executed. It's expected to output JSON
describing custom tools, which are then registered as `DiscoveredTool`
instances.
- **MCP-based discovery:** If `mcp.serverCommand` is configured, the
- **MCP-based Discovery:** If `mcp.serverCommand` is configured, the
registry can connect to a Model Context Protocol (MCP) server to list and
register tools (`DiscoveredMCPTool`).
- **Providing schemas:** Exposing the `FunctionDeclaration` schemas of all
- **Providing Schemas:** Exposing the `FunctionDeclaration` schemas of all
registered tools to the Gemini model, so it knows what tools are available
and how to use them.
- **Retrieving tools:** Allowing the core to get a specific tool by name for
- **Retrieving Tools:** Allowing the core to get a specific tool by name for
execution.
## Built-in tools
## Built-in Tools
The core comes with a suite of pre-defined tools, typically found in
`packages/core/src/tools/`. These include:
- **File system tools:**
- **File System Tools:**
- `LSTool` (`ls.ts`): Lists directory contents.
- `ReadFileTool` (`read-file.ts`): Reads the content of a single file.
- `WriteFileTool` (`write-file.ts`): Writes content to a file.
@@ -70,26 +70,26 @@ The core comes with a suite of pre-defined tools, typically found in
requiring confirmation).
- `ReadManyFilesTool` (`read-many-files.ts`): Reads and concatenates content
from multiple files or glob patterns (used by the `@` command in CLI).
- **Execution tools:**
- **Execution Tools:**
- `ShellTool` (`shell.ts`): Executes arbitrary shell commands (requires
careful sandboxing and user confirmation).
- **Web tools:**
- **Web Tools:**
- `WebFetchTool` (`web-fetch.ts`): Fetches content from a URL.
- `WebSearchTool` (`web-search.ts`): Performs a web search.
- **Memory tools:**
- **Memory Tools:**
- `MemoryTool` (`memoryTool.ts`): Interacts with the AI's memory.
Each of these tools extends `BaseTool` and implements the required methods for
its specific functionality.
## Tool execution flow
## Tool Execution Flow
1. **Model request:** The Gemini model, based on the user's prompt and the
1. **Model Request:** The Gemini model, based on the user's prompt and the
provided tool schemas, decides to use a tool and returns a `FunctionCall`
part in its response, specifying the tool name and arguments.
2. **Core receives request:** The core parses this `FunctionCall`.
3. **Tool retrieval:** It looks up the requested tool in the `ToolRegistry`.
4. **Parameter validation:** The tool's `validateToolParams()` method is
2. **Core Receives Request:** The core parses this `FunctionCall`.
3. **Tool Retrieval:** It looks up the requested tool in the `ToolRegistry`.
4. **Parameter Validation:** The tool's `validateToolParams()` method is
called.
5. **Confirmation (if needed):**
- The tool's `shouldConfirmExecute()` method is called.
@@ -99,27 +99,27 @@ its specific functionality.
6. **Execution:** If validated and confirmed (or if no confirmation is needed),
the core calls the tool's `execute()` method with the provided arguments and
an `AbortSignal` (for potential cancellation).
7. **Result processing:** The `ToolResult` from `execute()` is received by the
7. **Result Processing:** The `ToolResult` from `execute()` is received by the
core.
8. **Response to model:** The `llmContent` from the `ToolResult` is packaged as
8. **Response to Model:** The `llmContent` from the `ToolResult` is packaged as
a `FunctionResponse` and sent back to the Gemini model so it can continue
generating a user-facing response.
9. **Display to user:** The `returnDisplay` from the `ToolResult` is sent to
9. **Display to User:** The `returnDisplay` from the `ToolResult` is sent to
the CLI to show the user what the tool did.
## Extending with custom tools
## Extending with Custom Tools
While direct programmatic registration of new tools by users isn't explicitly
detailed as a primary workflow in the provided files for typical end-users, the
architecture supports extension through:
- **Command-based discovery:** Advanced users or project administrators can
- **Command-based Discovery:** Advanced users or project administrators can
define a `tools.discoveryCommand` in `settings.json`. This command, when run
by the Gemini CLI core, should output a JSON array of `FunctionDeclaration`
objects. The core will then make these available as `DiscoveredTool`
instances. The corresponding `tools.callCommand` would then be responsible for
actually executing these custom tools.
- **MCP server(s):** For more complex scenarios, one or more MCP servers can be
- **MCP Server(s):** For more complex scenarios, one or more MCP servers can be
set up and configured via the `mcpServers` setting in `settings.json`. The
Gemini CLI core can then discover and use tools exposed by these servers. As
mentioned, if you have multiple MCP servers, the tool names will be prefixed
+1 -1
View File
@@ -1,4 +1,4 @@
# Example proxy script
# Example Proxy Script
The following is an example of a proxy script that can be used with the
`GEMINI_SANDBOX_PROXY_COMMAND` environment variable. This script only allows
+4 -4
View File
@@ -1,4 +1,4 @@
# Extension releasing
# Extension Releasing
There are two primary ways of releasing extensions to users:
@@ -64,7 +64,7 @@ If you plan on doing cherry picks, you may want to avoid having your default
branch be the stable branch to avoid force-pushing to the default branch which
should generally be avoided.
## Releasing through GitHub releases
## Releasing through Github releases
Gemini CLI extensions can be distributed through
[GitHub Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases).
@@ -105,9 +105,9 @@ To ensure Gemini CLI can automatically find the correct release asset for each
platform, you must follow this naming convention. The CLI will search for assets
in the following order:
1. **Platform and architecture-Specific:**
1. **Platform and Architecture-Specific:**
`{platform}.{arch}.{name}.{extension}`
2. **Platform-specific:** `{platform}.{name}.{extension}`
2. **Platform-Specific:** `{platform}.{name}.{extension}`
3. **Generic:** If only one asset is provided, it will be used as a generic
fallback.
@@ -1,4 +1,4 @@
# Getting started with Gemini CLI extensions
# Getting Started with Gemini CLI Extensions
This guide will walk you through creating your first Gemini CLI extension.
You'll learn how to set up a new extension, add a custom tool via an MCP server,
@@ -10,7 +10,7 @@ file.
Before you start, make sure you have the Gemini CLI installed and a basic
understanding of Node.js and TypeScript.
## Step 1: Create a new extension
## Step 1: Create a New Extension
The easiest way to start is by using one of the built-in templates. We'll use
the `mcp-server` example as our foundation.
@@ -32,7 +32,7 @@ my-first-extension/
└── tsconfig.json
```
## Step 2: Understand the extension files
## Step 2: Understand the Extension Files
Let's look at the key files in your new extension.
@@ -124,7 +124,7 @@ These are standard configuration files for a TypeScript project. The
`package.json` file defines dependencies and a `build` script, and
`tsconfig.json` configures the TypeScript compiler.
## Step 3: Build and link your extension
## Step 3: Build and Link Your Extension
Before you can use the extension, you need to compile the TypeScript code and
link the extension to your Gemini CLI installation for local development.
@@ -158,7 +158,7 @@ link the extension to your Gemini CLI installation for local development.
Now, restart your Gemini CLI session. The new `fetch_posts` tool will be
available. You can test it by asking: "fetch posts".
## Step 4: Add a custom command
## Step 4: Add a Custom Command
Custom commands provide a way to create shortcuts for complex prompts. Let's add
a command that searches for a pattern in your code.
@@ -186,7 +186,7 @@ a command that searches for a pattern in your code.
After saving the file, restart the Gemini CLI. You can now run
`/fs:grep-code "some pattern"` to use your new command.
## Step 5: Add a custom `GEMINI.md`
## Step 5: Add a Custom `GEMINI.md`
You can provide persistent context to the model by adding a `GEMINI.md` file to
your extension. This is useful for giving the model instructions on how to
@@ -222,7 +222,7 @@ need this for extensions built to expose commands and prompts.
Restart the CLI again. The model will now have the context from your `GEMINI.md`
file in every session where the extension is active.
## Step 6: Releasing your extension
## Step 6: Releasing Your Extension
Once you are happy with your extension, you can share it with others. The two
primary ways of releasing extensions are via a Git repository or through GitHub
+4 -19
View File
@@ -1,4 +1,4 @@
# Gemini CLI extensions
# Gemini CLI Extensions
_This documentation is up-to-date with the v0.4.0 release._
@@ -163,11 +163,11 @@ The file has the following structure:
your extension in the CLI. Note that we expect this name to match the
extension directory name.
- `version`: The version of the extension.
- `mcpServers`: A map of MCP servers to settings. The key is the name of the
- `mcpServers`: A map of MCP servers to configure. The key is the name of the
server, and the value is the server configuration. These servers will be
loaded on startup just like MCP servers settingsd in a
loaded on startup just like MCP servers configured in a
[`settings.json` file](../get-started/configuration.md). If both an extension
and a `settings.json` file settings an MCP server with the same name, the
and a `settings.json` file configure an MCP server with the same name, the
server defined in the `settings.json` file takes precedence.
- Note that all MCP server configuration options are supported except for
`trust`.
@@ -223,21 +223,6 @@ When a user installs this extension, they will be prompted to enter their API
key. The value will be saved to a `.env` file in the extension's directory
(e.g., `<home>/.gemini/extensions/my-api-extension/.env`).
You can view a list of an extension's settings by running:
```
gemini extensions settings list <extension name>
```
and you can update a given setting using:
```
gemini extensions settings set <extension name> <setting name> [--scope <scope>]
```
- `--scope`: The scope to set the setting in (`user` or `workspace`). This is
optional and will default to `user`.
### Custom commands
Extensions can provide [custom commands](../cli/custom-commands.md) by placing
+1 -1
View File
@@ -1,4 +1,4 @@
# Frequently asked questions (FAQ)
# Frequently Asked Questions (FAQ)
This page provides answers to common questions and solutions to frequent
problems encountered while using Gemini CLI.
+157 -195
View File
@@ -1,198 +1,206 @@
# Gemini CLI authentication setup
# Gemini CLI Authentication Setup
To use Gemini CLI, you'll need to authenticate with Google. This guide helps you
quickly find the best way to sign in based on your account type and how you're
using the CLI.
Gemini CLI requires authentication using Google's services. Before using Gemini
CLI, configure **one** of the following authentication methods:
For most users, we recommend starting Gemini CLI and logging in with your
personal Google account.
- Interactive mode:
- Recommended: Login with Google
- Use Gemini API key
- Use Vertex AI
- Headless (non-interactive) mode
- Google Cloud Environments (Cloud Shell, Compute Engine, etc.)
## Choose your authentication method <a id="auth-methods"></a>
## Quick Check: Running in Google Cloud Shell?
Select the authentication method that matches your situation in the table below:
If you are running the Gemini CLI within a Google Cloud Shell environment,
authentication is typically automatic using your Cloud Shell credentials.
| User Type / Scenario | Recommended Authentication Method | Google Cloud Project Required |
| :--------------------------------------------------------------------- | :--------------------------------------------------------------- | :---------------------------------------------------------- |
| Individual Google accounts | [Login with Google](#login-google) | No, with exceptions |
| Organization users with a company, school, or Google Workspace account | [Login with Google](#login-google) | [Yes](#set-gcp) |
| AI Studio user with a Gemini API key | [Use Gemini API Key](#gemini-api) | No |
| Google Cloud Vertex AI user | [Vertex AI](#vertex-ai) | [Yes](#set-gcp) |
| [Headless mode](#headless) | [Use Gemini API Key](#gemini-api) or<br> [Vertex AI](#vertex-ai) | No (for Gemini API Key)<br> [Yes](#set-gcp) (for Vertex AI) |
### Other Google Cloud Environments (e.g., Compute Engine)
### What is my Google account type?
Some other Google Cloud environments, such as Compute Engine VMs, might also
support automatic authentication. In these environments, Gemini CLI can
automatically use Application Default Credentials (ADC) sourced from the
environment's metadata server.
- **Individual Google accounts:** Includes all
[free tier accounts](../quota-and-pricing/#free-usage) such as Gemini Code
Assist for individuals, as well as paid subscriptions for
[Google AI Pro and Ultra](https://gemini.google/subscriptions/).
If automatic authentication does not occur in your environment, you will need to
use one of the interactive methods described below.
- **Organization accounts:** Accounts using paid licenses through an
organization such as a company, school, or
[Google Workspace](https://workspace.google.com/). Includes
[Google AI Ultra for Business](https://support.google.com/a/answer/16345165)
subscriptions.
## Authenticate in Interactive mode
## (Recommended) Login with Google <a id="login-google"></a>
When you run Gemini CLI through the command-line, Gemini CLI will provide the
following options:
If you run Gemini CLI on your local machine, the simplest authentication method
is logging in with your Google account. This method requires a web browser on a
machine that can communicate with the terminal running Gemini CLI (e.g., your
local machine).
```bash
> 1. Login with Google
> 2. Use Gemini API key
> 3. Vertex AI
```
> **Important:** If you are a **Google AI Pro** or **Google AI Ultra**
> subscriber, use the Google account associated with your subscription.
The following sections provide instructions for each of these authentication
options.
To authenticate and use Gemini CLI:
### Recommended: Login with Google
1. Start the CLI:
If you are running Gemini CLI on your local machine, the simplest method is
logging in with your Google account.
```bash
gemini
```
> **Important:** Use this method if you are a **Google AI Pro** or **Google AI
> Ultra** subscriber.
2. Select **Login with Google**. Gemini CLI opens a login prompt using your web
browser. Follow the on-screen instructions. Your credentials will be cached
locally for future sessions.
1. Select **Login with Google**. Gemini CLI will open a login prompt using your
web browser.
### Do I need to set my Google Cloud project?
If you are a **Google AI Pro** or **Google AI Ultra** subscriber, login with
the Google account associated with your subscription.
Most individual Google accounts (free and paid) don't require a Google Cloud
project for authentication. However, you'll need to set a Google Cloud project
when you meet at least one of the following conditions:
2. Follow the on-screen instructions. Your credentials will be cached locally
for future sessions.
- You are using a company, school, or Google Workspace account.
- You are using a Gemini Code Assist license from the Google Developer Program.
- You are using a license from a Gemini Code Assist subscription.
> **Note:** This method requires a web browser on a machine that can
> communicate with the terminal running the CLI (e.g., your local machine).
> The browser will be redirected to a `localhost` URL that the CLI listens on
> during setup.
For instructions, see [Set your Google Cloud Project](#set-gcp).
#### (Optional) Set your Google Cloud Project
## Use Gemini API key <a id="gemini-api"></a>
When you log in using a Google account, you may be prompted to select a
`GOOGLE_CLOUD_PROJECT`.
This can be necessary if you are:
- Using a Google Workspace account.
- Using a Gemini Code Assist license from the Google Developer Program.
- Using a license from a Gemini Code Assist subscription.
- Using the product outside the
[supported regions](https://developers.google.com/gemini-code-assist/resources/available-locations)
for free individual usage.
- A Google account holder under the age of 18.
If you fall into one of these categories, you must:
1. Have a Google Cloud Project ID.
2. [Enable the Gemini for Cloud API](https://cloud.google.com/gemini/docs/discover/set-up-gemini#enable-api).
3. [Configure necessary IAM access permissions](https://cloud.google.com/gemini/docs/discover/set-up-gemini#grant-iam).
To set the project ID, you can export either the `GOOGLE_CLOUD_PROJECT` or
`GOOGLE_CLOUD_PROJECT_ID` environment variable. The CLI checks for
`GOOGLE_CLOUD_PROJECT` first, then falls back to `GOOGLE_CLOUD_PROJECT_ID` :
```bash
# Replace YOUR_PROJECT_ID with your actual Google Cloud Project ID
# Using the standard variable:
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
# Or, using the fallback variable:
export GOOGLE_CLOUD_PROJECT_ID="YOUR_PROJECT_ID"
```
To make this setting persistent, see
[Persisting Environment Variables](#persisting-environment-variables).
### Use Gemini API Key
If you don't want to authenticate using your Google account, you can use an API
key from Google AI Studio.
To authenticate and use Gemini CLI with a Gemini API key:
1. Obtain your API key from
[Google AI Studio](https://aistudio.google.com/app/apikey).
2. Set the `GEMINI_API_KEY` environment variable:
1. Obtain your API key from
[Google AI Studio](https://aistudio.google.com/app/apikey).
```bash
# Replace YOUR_GEMINI_API_KEY with the key from AI Studio
export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
```
2. Set the `GEMINI_API_KEY` environment variable to your key. For example:
```bash
# Replace YOUR_GEMINI_API_KEY with the key from AI Studio
export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
```
To make this setting persistent, see
[Persisting Environment Variables](#persisting-vars).
3. Start the CLI:
```bash
gemini
```
4. Select **Use Gemini API key**.
To make this setting persistent, see
[Persisting Environment Variables](#persisting-environment-variables).
> **Warning:** Treat API keys, especially for services like Gemini, as sensitive
> credentials. Protect them to prevent unauthorized access and potential misuse
> of the service under your account.
## Use Vertex AI <a id="vertex-ai"></a>
### Use Vertex AI
To use Gemini CLI with Google Cloud's Vertex AI platform, choose from the
following authentication options:
If you intend to use Google Cloud's Vertex AI platform, you have several
authentication options:
- A. Application Default Credentials (ADC) using `gcloud`.
- B. Service account JSON key.
- C. Google Cloud API key.
- Application Default Credentials (ADC) and `gcloud`.
- A Service Account JSON key.
- A Google Cloud API key.
Regardless of your authentication method for Vertex AI, you'll need to set
`GOOGLE_CLOUD_PROJECT` to your Google Cloud project ID with the Vertex AI API
enabled, and `GOOGLE_CLOUD_LOCATION` to the location of your Vertex AI resources
or the location where you want to run your jobs.
#### First: Set required environment variables
For example:
Regardless of your method of authentication, you'll typically need to set the
following variables: `GOOGLE_CLOUD_PROJECT` (or `GOOGLE_CLOUD_PROJECT_ID`) and
`GOOGLE_CLOUD_LOCATION`.
To set these variables:
```bash
# Replace with your project ID and desired location (e.g., us-central1)
# You can use GOOGLE_CLOUD_PROJECT_ID as a fallback for GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"
```
To make any Vertex AI environment variable settings persistent, see
[Persisting Environment Variables](#persisting-vars).
#### A. Vertex AI - Application Default Credentials (ADC) using `gcloud`
#### A. Vertex AI - application default credentials (ADC) using `gcloud`
Consider this authentication method if you have Google Cloud CLI installed.
Consider this method of authentication if you have Google Cloud CLI installed.
> **Note:** If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you
> must unset them to use ADC:
>
> ```bash
> unset GOOGLE_API_KEY GEMINI_API_KEY
> ```
1. Verify you have a Google Cloud project and Vertex AI API is enabled.
```bash
unset GOOGLE_API_KEY GEMINI_API_KEY
```
2. Log in to Google Cloud:
1. Ensure you have a Google Cloud project and Vertex AI API is enabled.
2. Log in to Google Cloud:
```bash
gcloud auth application-default login
```
```bash
gcloud auth application-default login
```
3. [Configure your Google Cloud Project](#set-gcp).
See
[Set up Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc)
for details.
4. Start the CLI:
3. Ensure `GOOGLE_CLOUD_PROJECT` (or `GOOGLE_CLOUD_PROJECT_ID`) and
`GOOGLE_CLOUD_LOCATION` are set.
```bash
gemini
```
#### B. Vertex AI - Service Account JSON key
5. Select **Vertex AI**.
#### B. Vertex AI - service account JSON key
Consider this method of authentication in non-interactive environments, CI/CD
pipelines, or if your organization restricts user-based ADC or API key creation.
Consider this method of authentication in non-interactive environments, CI/CD,
or if your organization restricts user-based ADC or API key creation.
> **Note:** If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you
> must unset them:
>
> ```bash
> unset GOOGLE_API_KEY GEMINI_API_KEY
> ```
```bash
unset GOOGLE_API_KEY GEMINI_API_KEY
```
1. [Create a service account and key](https://cloud.google.com/iam/docs/keys-create-delete)
and download the provided JSON file. Assign the "Vertex AI User" role to the
service account.
2. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the JSON
file's absolute path. For example:
file's absolute path:
```bash
# Replace /path/to/your/keyfile.json with the actual path
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
```
3. [Configure your Google Cloud Project](#set-gcp).
3. Ensure `GOOGLE_CLOUD_PROJECT` (or `GOOGLE_CLOUD_PROJECT_ID`) and
`GOOGLE_CLOUD_LOCATION` are set.
4. Start the CLI:
```bash
gemini
```
5. Select **Vertex AI**.
> **Warning:** Protect your service account key file as it gives access to
> your resources.
> **Warning:** Protect your service account key file as it provides access to
> your resources.
#### C. Vertex AI - Google Cloud API key
1. Obtain a Google Cloud API key:
[Get an API Key](https://cloud.google.com/vertex-ai/generative-ai/docs/start/api-keys?usertype=newuser).
2. Set the `GOOGLE_API_KEY` environment variable:
```bash
@@ -202,59 +210,17 @@ pipelines, or if your organization restricts user-based ADC or API key creation.
> **Note:** If you see errors like
> `"API keys are not supported by this API..."`, your organization might
> restrict API key usage for this service. Try the other Vertex AI
> authentication methods instead.
> restrict API key usage for this service. Try the
> [Service Account JSON Key](#b-vertex-ai-service-account-json-key) or
> [ADC](#a-vertex-ai-application-default-credentials-adc-using-gcloud)
> methods instead.
3. [Configure your Google Cloud Project](#set-gcp).
To make any of these Vertex AI environment variable settings persistent, see
[Persisting Environment Variables](#persisting-environment-variables).
4. Start the CLI:
## Persisting Environment Variables
```bash
gemini
```
5. Select **Vertex AI**.
## Set your Google Cloud project <a id="set-gcp"></a>
> **Important:** Most individual Google accounts (free and paid) don't require a
> Google Cloud project for authentication.
When you sign in using your Google account, you may need to configure a Google
Cloud project for Gemini CLI to use. This applies when you meet at least one of
the following conditions:
- You are using a Company, School, or Google Workspace account.
- You are using a Gemini Code Assist license from the Google Developer Program.
- You are using a license from a Gemini Code Assist subscription.
To configure Gemini CLI to use a Google Cloud project, do the following:
1. [Find your Google Cloud Project ID](https://support.google.com/googleapi/answer/7014113).
2. [Enable the Gemini for Cloud API](https://cloud.google.com/gemini/docs/discover/set-up-gemini#enable-api).
3. [Configure necessary IAM access permissions](https://cloud.google.com/gemini/docs/discover/set-up-gemini#grant-iam).
4. Configure your environment variables. Set either the `GOOGLE_CLOUD_PROJECT`
or `GOOGLE_CLOUD_PROJECT_ID` variable to the project ID to use with Gemini
CLI. Gemini CLI checks for `GOOGLE_CLOUD_PROJECT` first, then falls back to
`GOOGLE_CLOUD_PROJECT_ID`.
For example, to set the `GOOGLE_CLOUD_PROJECT_ID` variable:
```bash
# Replace YOUR_PROJECT_ID with your actual Google Cloud project ID
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
```
To make this setting persistent, see
[Persisting Environment Variables](#persisting-vars).
## Persisting environment variables <a id="persisting-vars"></a>
To avoid setting environment variables for every terminal session, you can
persist them with the following methods:
To avoid setting environment variables in every terminal session, you can:
1. **Add your environment variables to your shell configuration file:** Append
the `export ...` commands to your shell's startup file (e.g., `~/.bashrc`,
@@ -267,9 +233,9 @@ persist them with the following methods:
source ~/.bashrc
```
> **Warning:** Be aware that when you export API keys or service account
> paths in your shell configuration file, any process launched from that
> shell can read them.
> **Warning:** Be advised that when you export API keys or service account
> paths in your shell configuration file, any process executed from the
> shell can potentially read them.
2. **Use a `.env` file:** Create a `.gemini/.env` file in your project
directory or home directory. Gemini CLI automatically loads variables from
@@ -286,31 +252,27 @@ persist them with the following methods:
EOF
```
Variables are loaded from the first file found, not merged.
Variables are loaded from the first file found, not merged.
## Running in Google Cloud environments <a id="cloud-env"></a>
## Non-interactive mode / headless environments
When running Gemini CLI within certain Google Cloud environments, authentication
is automatic.
Non-interactive mode / headless environments will use your existing
authentication method, if an existing authentication credential is cached.
In a Google Cloud Shell environment, Gemini CLI typically authenticates
automatically using your Cloud Shell credentials. In Compute Engine
environments, Gemini CLI automatically uses Application Default Credentials
(ADC) from the environment's metadata server.
If you have not already logged in with an authentication credential (such as a
Google account), you **must** configure authentication using environment
variables:
If automatic authentication fails, use one of the interactive methods described
on this page.
1. **Gemini API Key:** Set `GEMINI_API_KEY`.
2. **Vertex AI:**
- Set `GOOGLE_GENAI_USE_VERTEXAI=true`.
- **With Google Cloud API Key:** Set `GOOGLE_API_KEY`.
- **With ADC:** Ensure ADC is configured (e.g., via a service account with
`GOOGLE_APPLICATION_CREDENTIALS`) and set `GOOGLE_CLOUD_PROJECT` (or
`GOOGLE_CLOUD_PROJECT_ID`) and `GOOGLE_CLOUD_LOCATION`.
## Running in headless mode <a id="headless"></a>
[Headless mode](../cli/headless) will use your existing authentication method,
if an existing authentication credential is cached.
If you have not already logged in with an authentication credential, you must
configure authentication using environment variables:
- [Use Gemini API Key](#gemini-api)
- [Vertex AI](#vertex-ai)
The CLI will exit with an error in non-interactive mode if no suitable
environment variables are found.
## What's next?
+32 -32
View File
@@ -1,6 +1,6 @@
# Gemini CLI configuration
# Gemini CLI Configuration
**Note on deprecated configuration format**
**Note on Deprecated Configuration Format**
This document describes the legacy v1 format for the `settings.json` file. This
format is now deprecated.
@@ -132,7 +132,7 @@ contain other project-specific files related to Gemini CLI's operation, such as:
}
```
### Troubleshooting file search performance
### Troubleshooting File Search Performance
If you are experiencing performance issues with file searching (e.g., with `@`
completions), especially in projects with a very large number of files, here are
@@ -144,12 +144,12 @@ a few things you can try in order of recommendation:
the total number of files crawled is the most effective way to improve
performance.
2. **Disable fuzzy search:** If ignoring files is not enough, you can disable
2. **Disable Fuzzy Search:** If ignoring files is not enough, you can disable
fuzzy search by setting `disableFuzzySearch` to `true` in your
`settings.json` file. This will use a simpler, non-fuzzy matching algorithm,
which can be faster.
3. **Disable recursive file search:** As a last resort, you can disable
3. **Disable Recursive File Search:** As a last resort, you can disable
recursive file search entirely by setting `enableRecursiveFileSearch` to
`false`. This will be the fastest option as it avoids a recursive crawl of
your project. However, it means you will need to type the full path to files
@@ -194,7 +194,7 @@ a few things you can try in order of recommendation:
`--allowed-mcp-server-names` is set.
- **Default:** All MCP servers are available for use by the Gemini model.
- **Example:** `"allowMCPServers": ["myPythonServer"]`.
- **Security note:** This uses simple string matching on MCP server names,
- **Security Note:** This uses simple string matching on MCP server names,
which can be modified. If you're a system administrator looking to prevent
users from bypassing this, consider configuring the `mcpServers` at the
system settings level such that the user will not be able to configure any
@@ -208,7 +208,7 @@ a few things you can try in order of recommendation:
be ignored if `--allowed-mcp-server-names` is set.
- **Default**: No MCP servers excluded.
- **Example:** `"excludeMCPServers": ["myNodeServer"]`.
- **Security note:** This uses simple string matching on MCP server names,
- **Security Note:** This uses simple string matching on MCP server names,
which can be modified. If you're a system administrator looking to prevent
users from bypassing this, consider configuring the `mcpServers` at the
system settings level such that the user will not be able to configure any
@@ -538,7 +538,7 @@ a few things you can try in order of recommendation:
}
```
## Shell history
## Shell History
The CLI keeps a history of shell commands you run. To avoid conflicts between
different projects, this history is stored in a project-specific directory
@@ -549,7 +549,7 @@ within your user's home folder.
path.
- The history is stored in a file named `shell_history`.
## Environment variables and `.env` files
## Environment Variables & `.env` Files
Environment variables are a common way to configure applications, especially for
sensitive information like API keys or for settings that might change between
@@ -566,7 +566,7 @@ loading order is:
the home directory.
3. If still not found, it looks for `~/.env` (in the user's home directory).
**Environment variable exclusion:** Some environment variables (like `DEBUG` and
**Environment Variable Exclusion:** Some environment variables (like `DEBUG` and
`DEBUG_MODE`) are automatically excluded from being loaded from project `.env`
files to prevent interference with gemini-cli behavior. Variables from
`.gemini/.env` files are never excluded. You can customize this behavior using
@@ -591,7 +591,7 @@ the `excludedProjectEnvVars` setting in your `settings.json` file.
- Required for using Code Assist or Vertex AI.
- If using Vertex AI, ensure you have the necessary permissions in this
project.
- **Cloud Shell note:** When running in a Cloud Shell environment, this
- **Cloud Shell Note:** When running in a Cloud Shell environment, this
variable defaults to a special project allocated for Cloud Shell users. If
you have `GOOGLE_CLOUD_PROJECT` set in your global environment in Cloud
Shell, it will be overridden by this default. To use a different project in
@@ -639,7 +639,7 @@ the `excludedProjectEnvVars` setting in your `settings.json` file.
- Specifies the endpoint for the code assist server.
- This is useful for development and testing.
## Command-line arguments
## Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations
for that specific session.
@@ -714,7 +714,7 @@ for that specific session.
- **`--version`**:
- Displays the version of the CLI.
## Context files (hierarchical instructional context)
## Context Files (Hierarchical Instructional Context)
While not strictly configuration for the CLI's _behavior_, context files
(defaulting to `GEMINI.md` but configurable via the `contextFileName` setting)
@@ -730,7 +730,7 @@ context.
that you want the Gemini model to be aware of during your interactions. The
system is designed to manage this instructional context hierarchically.
### Example context file content (e.g., `GEMINI.md`)
### Example Context File Content (e.g., `GEMINI.md`)
Here's a conceptual example of what a context file at the root of a TypeScript
project might contain:
@@ -771,23 +771,23 @@ more relevant and precise your context files are, the better the AI can assist
you. Project-specific context files are highly encouraged to establish
conventions and context.
- **Hierarchical loading and precedence:** The CLI implements a sophisticated
- **Hierarchical Loading and Precedence:** The CLI implements a sophisticated
hierarchical memory system by loading context files (e.g., `GEMINI.md`) from
several locations. Content from files lower in this list (more specific)
typically overrides or supplements content from files higher up (more
general). The exact concatenation order and final context can be inspected
using the `/memory show` command. The typical loading order is:
1. **Global context file:**
1. **Global Context File:**
- Location: `~/.gemini/<contextFileName>` (e.g., `~/.gemini/GEMINI.md` in
your user home directory).
- Scope: Provides default instructions for all your projects.
2. **Project root and ancestors context files:**
2. **Project Root & Ancestors Context Files:**
- Location: The CLI searches for the configured context file in the
current working directory and then in each parent directory up to either
the project root (identified by a `.git` folder) or your home directory.
- Scope: Provides context relevant to the entire project or a significant
portion of it.
3. **Sub-directory context files (contextual/local):**
3. **Sub-directory Context Files (Contextual/Local):**
- Location: The CLI also scans for the configured context file in
subdirectories _below_ the current working directory (respecting common
ignore patterns like `node_modules`, `.git`, etc.). The breadth of this
@@ -795,15 +795,15 @@ conventions and context.
with a `memoryDiscoveryMaxDirs` field in your `settings.json` file.
- Scope: Allows for highly specific instructions relevant to a particular
component, module, or subsection of your project.
- **Concatenation and UI indication:** The contents of all found context files
are concatenated (with separators indicating their origin and path) and
provided as part of the system prompt to the Gemini model. The CLI footer
displays the count of loaded context files, giving you a quick visual cue
about the active instructional context.
- **Importing content:** You can modularize your context files by importing
- **Concatenation & UI Indication:** The contents of all found context files are
concatenated (with separators indicating their origin and path) and provided
as part of the system prompt to the Gemini model. The CLI footer displays the
count of loaded context files, giving you a quick visual cue about the active
instructional context.
- **Importing Content:** You can modularize your context files by importing
other Markdown files using the `@path/to/file.md` syntax. For more details,
see the [Memory Import Processor documentation](../core/memport.md).
- **Commands for memory management:**
- **Commands for Memory Management:**
- Use `/memory refresh` to force a re-scan and reload of all context files
from all configured locations. This updates the AI's instructional context.
- Use `/memory show` to display the combined instructional context currently
@@ -850,7 +850,7 @@ sandbox image:
BUILD_SANDBOX=1 gemini -s
```
## Usage statistics
## Usage Statistics
To help us improve the Gemini CLI, we collect anonymized usage statistics. This
data helps us understand how the CLI is used, identify common issues, and
@@ -858,22 +858,22 @@ prioritize new features.
**What we collect:**
- **Tool calls:** We log the names of the tools that are called, whether they
- **Tool Calls:** We log the names of the tools that are called, whether they
succeed or fail, and how long they take to execute. We do not collect the
arguments passed to the tools or any data returned by them.
- **API requests:** We log the Gemini model used for each request, the duration
- **API Requests:** We log the Gemini model used for each request, the duration
of the request, and whether it was successful. We do not collect the content
of the prompts or responses.
- **Session information:** We collect information about the configuration of the
- **Session Information:** We collect information about the configuration of the
CLI, such as the enabled tools and the approval mode.
**What we DON'T collect:**
- **Personally identifiable information (PII):** We do not collect any personal
- **Personally Identifiable Information (PII):** We do not collect any personal
information, such as your name, email address, or API keys.
- **Prompt and response content:** We do not log the content of your prompts or
- **Prompt and Response Content:** We do not log the content of your prompts or
the responses from the Gemini model.
- **File content:** We do not log the content of any files that are read or
- **File Content:** We do not log the content of any files that are read or
written by the CLI.
**How to opt out:**
+53 -249
View File
@@ -1,6 +1,6 @@
# Gemini CLI configuration
# Gemini CLI Configuration
> **Note on configuration format, 9/17/25:** The format of the `settings.json`
> **Note on Configuration Format, 9/17/25:** The format of the `settings.json`
> file has been updated to a new, more organized structure.
>
> - The new format will be supported in the stable release starting
@@ -367,12 +367,6 @@ their corresponding top-level category object in your `settings.json` file.
"model": "gemini-3-pro-preview"
}
},
"gemini-3-flash-preview": {
"extends": "chat-base-3",
"modelConfig": {
"model": "gemini-3-flash-preview"
}
},
"gemini-2.5-pro": {
"extends": "chat-base-2.5",
"modelConfig": {
@@ -502,11 +496,6 @@ their corresponding top-level category object in your `settings.json` file.
"model": "gemini-3-pro-preview"
}
},
"chat-compression-3-flash": {
"modelConfig": {
"model": "gemini-3-flash-preview"
}
},
"chat-compression-2.5-pro": {
"modelConfig": {
"model": "gemini-2.5-pro"
@@ -535,11 +524,6 @@ their corresponding top-level category object in your `settings.json` file.
with (and override) the built-in aliases.
- **Default:** `{}`
- **`modelConfigs.customOverrides`** (array):
- **Description:** Custom model config overrides. These are merged with (and
added to) the built-in overrides.
- **Default:** `[]`
- **`modelConfigs.overrides`** (array):
- **Description:** Apply specific configuration overrides based on matches,
with a primary key of model (or alias). The most specific match will be
@@ -616,16 +600,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Description:** Show color in shell output.
- **Default:** `false`
- **`tools.shell.inactivityTimeout`** (number):
- **Description:** The maximum time in seconds allowed without output from the
shell command. Defaults to 5 minutes.
- **Default:** `300`
- **`tools.shell.enableShellOutputEfficiency`** (boolean):
- **Description:** Enable shell output efficiency optimizations for better
performance.
- **Default:** `true`
- **`tools.autoAccept`** (boolean):
- **Description:** Automatically accept and execute tool calls that are
considered safe (e.g., read-only operations).
@@ -684,10 +658,20 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `1000`
- **Requires restart:** Yes
- **`tools.enableMessageBusIntegration`** (boolean):
- **Description:** Enable policy-based tool confirmation via message bus
integration. When enabled, tools automatically respect policy engine
decisions (ALLOW/DENY/ASK_USER) without requiring individual tool
implementations.
- **Default:** `false`
- **Requires restart:** Yes
- **`tools.enableHooks`** (boolean):
- **Description:** Enables the hooks system experiment. When disabled, the
hooks system is completely deactivated regardless of other settings.
- **Default:** `true`
- **Description:** Enable the hooks system for intercepting and customizing
Gemini CLI behavior. When enabled, hooks configured in settings will execute
at appropriate lifecycle events (BeforeTool, AfterTool, BeforeModel, etc.).
Requires MessageBus integration.
- **Default:** `false`
- **Requires restart:** Yes
#### `mcp`
@@ -707,6 +691,12 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `undefined`
- **Requires restart:** Yes
#### `useSmartEdit`
- **`useSmartEdit`** (boolean):
- **Description:** Enable the smart-edit tool instead of the replace tool.
- **Default:** `true`
#### `useWriteTodos`
- **`useWriteTodos`** (boolean):
@@ -720,11 +710,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `false`
- **Requires restart:** Yes
- **`security.enablePermanentToolApproval`** (boolean):
- **Description:** Enable the "Allow for all future sessions" option in tool
confirmation dialogs.
- **Default:** `false`
- **`security.blockGitExtensions`** (boolean):
- **Description:** Blocks installing and loading extensions from Git.
- **Default:** `false`
@@ -735,22 +720,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `false`
- **Requires restart:** Yes
- **`security.environmentVariableRedaction.allowed`** (array):
- **Description:** Environment variables to always allow (bypass redaction).
- **Default:** `[]`
- **Requires restart:** Yes
- **`security.environmentVariableRedaction.blocked`** (array):
- **Description:** Environment variables to always redact.
- **Default:** `[]`
- **Requires restart:** Yes
- **`security.environmentVariableRedaction.enabled`** (boolean):
- **Description:** Enable redaction of environment variables that may contain
secrets.
- **Default:** `false`
- **Requires restart:** Yes
- **`security.auth.selectedType`** (string):
- **Description:** The currently selected authentication type.
- **Default:** `undefined`
@@ -793,12 +762,6 @@ their corresponding top-level category object in your `settings.json` file.
#### `experimental`
- **`experimental.enableAgents`** (boolean):
- **Description:** Enable local and remote subagents. Warning: Experimental
feature, uses YOLO mode for subagents
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.extensionManagement`** (boolean):
- **Description:** Enable extension management features.
- **Default:** `true`
@@ -809,13 +772,8 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.jitContext`** (boolean):
- **Description:** Enable Just-In-Time (JIT) context loading.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.skills`** (boolean):
- **Description:** Enable Agent Skills (experimental).
- **`experimental.isModelAvailabilityServiceEnabled`** (boolean):
- **Description:** Enable model routing using new availability service.
- **Default:** `false`
- **Requires restart:** Yes
@@ -843,111 +801,15 @@ their corresponding top-level category object in your `settings.json` file.
- **`experimental.codebaseInvestigatorSettings.model`** (string):
- **Description:** The model to use for the Codebase Investigator agent.
- **Default:** `"auto"`
- **Requires restart:** Yes
- **`experimental.useOSC52Paste`** (boolean):
- **Description:** Use OSC 52 sequence for pasting instead of clipboardy
(useful for remote sessions).
- **Default:** `false`
- **`experimental.introspectionAgentSettings.enabled`** (boolean):
- **Description:** Enable the Introspection Agent.
- **Default:** `false`
- **Requires restart:** Yes
#### `skills`
- **`skills.disabled`** (array):
- **Description:** List of disabled skills.
- **Default:** `[]`
- **Default:** `"gemini-2.5-pro"`
- **Requires restart:** Yes
#### `hooks`
- **`hooks.enabled`** (boolean):
- **Description:** Canonical toggle for the hooks system. When disabled, no
hooks will be executed.
- **Default:** `false`
- **`hooks.disabled`** (array):
- **Description:** List of hook names (commands) that should be disabled.
Hooks in this list will not execute even if configured.
- **Default:** `[]`
- **`hooks.notifications`** (boolean):
- **Description:** Show visual indicators when hooks are executing.
- **Default:** `true`
- **`hooks.BeforeTool`** (array):
- **Description:** Hooks that execute before tool execution. Can intercept,
validate, or modify tool calls.
- **Default:** `[]`
- **`hooks.AfterTool`** (array):
- **Description:** Hooks that execute after tool execution. Can process
results, log outputs, or trigger follow-up actions.
- **Default:** `[]`
- **`hooks.BeforeAgent`** (array):
- **Description:** Hooks that execute before agent loop starts. Can set up
context or initialize resources.
- **Default:** `[]`
- **`hooks.AfterAgent`** (array):
- **Description:** Hooks that execute after agent loop completes. Can perform
cleanup or summarize results.
- **Default:** `[]`
- **`hooks.Notification`** (array):
- **Description:** Hooks that execute on notification events (errors,
warnings, info). Can log or alert on specific conditions.
- **Default:** `[]`
- **`hooks.SessionStart`** (array):
- **Description:** Hooks that execute when a session starts. Can initialize
session-specific resources or state.
- **Default:** `[]`
- **`hooks.SessionEnd`** (array):
- **Description:** Hooks that execute when a session ends. Can perform cleanup
or persist session data.
- **Default:** `[]`
- **`hooks.PreCompress`** (array):
- **Description:** Hooks that execute before chat history compression. Can
back up or analyze conversation before compression.
- **Default:** `[]`
- **`hooks.BeforeModel`** (array):
- **Description:** Hooks that execute before LLM requests. Can modify prompts,
inject context, or control model parameters.
- **Default:** `[]`
- **`hooks.AfterModel`** (array):
- **Description:** Hooks that execute after LLM responses. Can process
outputs, extract information, or log interactions.
- **Default:** `[]`
- **`hooks.BeforeToolSelection`** (array):
- **Description:** Hooks that execute before tool selection. Can filter or
prioritize available tools dynamically.
- **Default:** `[]`
#### `admin`
- **`admin.secureModeEnabled`** (boolean):
- **Description:** If true, disallows yolo mode from being used.
- **Default:** `false`
- **`admin.extensions.enabled`** (boolean):
- **Description:** If false, disallows extensions from being installed or
used.
- **Default:** `true`
- **`admin.mcp.enabled`** (boolean):
- **Description:** If false, disallows MCP servers from being used.
- **Default:** `true`
- **`hooks`** (object):
- **Description:** Hook configurations for intercepting and customizing agent
behavior.
- **Default:** `{}`
<!-- SETTINGS-AUTOGEN:END -->
#### `mcpServers`
@@ -1083,7 +945,7 @@ of v0.3.0:
}
```
## Shell history
## Shell History
The CLI keeps a history of shell commands you run. To avoid conflicts between
different projects, this history is stored in a project-specific directory
@@ -1094,7 +956,7 @@ within your user's home folder.
path.
- The history is stored in a file named `shell_history`.
## Environment variables and `.env` files
## Environment Variables & `.env` Files
Environment variables are a common way to configure applications, especially for
sensitive information like API keys or for settings that might change between
@@ -1111,7 +973,7 @@ loading order is:
the home directory.
3. If still not found, it looks for `~/.env` (in the user's home directory).
**Environment variable exclusion:** Some environment variables (like `DEBUG` and
**Environment Variable Exclusion:** Some environment variables (like `DEBUG` and
`DEBUG_MODE`) are automatically excluded from being loaded from project `.env`
files to prevent interference with gemini-cli behavior. Variables from
`.gemini/.env` files are never excluded. You can customize this behavior using
@@ -1136,7 +998,7 @@ the `advanced.excludedEnvVars` setting in your `settings.json` file.
- Required for using Code Assist or Vertex AI.
- If using Vertex AI, ensure you have the necessary permissions in this
project.
- **Cloud Shell note:** When running in a Cloud Shell environment, this
- **Cloud Shell Note:** When running in a Cloud Shell environment, this
variable defaults to a special project allocated for Cloud Shell users. If
you have `GOOGLE_CLOUD_PROJECT` set in your global environment in Cloud
Shell, it will be overridden by this default. To use a different project in
@@ -1180,18 +1042,6 @@ the `advanced.excludedEnvVars` setting in your `settings.json` file.
- **`GEMINI_SANDBOX`**:
- Alternative to the `sandbox` setting in `settings.json`.
- Accepts `true`, `false`, `docker`, `podman`, or a custom command string.
- **`GEMINI_SYSTEM_MD`**:
- Replaces the builtin system prompt with content from a Markdown file.
- `true`/`1`: Use project default path `./.gemini/system.md`.
- Any other string: Treat as a path (relative/absolute supported, `~`
expands).
- `false`/`0` or unset: Use the builtin prompt. See
[System Prompt Override](../cli/system-prompt.md).
- **`GEMINI_WRITE_SYSTEM_MD`**:
- Writes the current builtin system prompt to a file for review.
- `true`/`1`: Write to `./.gemini/system.md`. Otherwise treat the value as a
path.
- Run the CLI once with this set to generate the file.
- **`SEATBELT_PROFILE`** (macOS specific):
- Switches the Seatbelt (`sandbox-exec`) profile on macOS.
- `permissive-open`: (Default) Restricts writes to the project folder (and a
@@ -1217,53 +1067,7 @@ the `advanced.excludedEnvVars` setting in your `settings.json` file.
- Specifies the endpoint for the code assist server.
- This is useful for development and testing.
### Environment variable redaction
To prevent accidental leakage of sensitive information, Gemini CLI automatically
redacts potential secrets from environment variables when executing tools (such
as shell commands). This "best effort" redaction applies to variables inherited
from the system or loaded from `.env` files.
**Default Redaction Rules:**
- **By Name:** Variables are redacted if their names contain sensitive terms
like `TOKEN`, `SECRET`, `PASSWORD`, `KEY`, `AUTH`, `CREDENTIAL`, `PRIVATE`, or
`CERT`.
- **By Value:** Variables are redacted if their values match known secret
patterns, such as:
- Private keys (RSA, OpenSSH, PGP, etc.)
- Certificates
- URLs containing credentials
- API keys and tokens (GitHub, Google, AWS, Stripe, Slack, etc.)
- **Specific Blocklist:** Certain variables like `CLIENT_ID`, `DB_URI`,
`DATABASE_URL`, and `CONNECTION_STRING` are always redacted by default.
**Allowlist (Never Redacted):**
- Common system variables (e.g., `PATH`, `HOME`, `USER`, `SHELL`, `TERM`,
`LANG`).
- Variables starting with `GEMINI_CLI_`.
- GitHub Action specific variables.
**Configuration:**
You can customize this behavior in your `settings.json` file:
- **`security.allowedEnvironmentVariables`**: A list of variable names to
_never_ redact, even if they match sensitive patterns.
- **`security.blockedEnvironmentVariables`**: A list of variable names to
_always_ redact, even if they don't match sensitive patterns.
```json
{
"security": {
"allowedEnvironmentVariables": ["MY_PUBLIC_KEY", "NOT_A_SECRET_TOKEN"],
"blockedEnvironmentVariables": ["INTERNAL_IP_ADDRESS"]
}
}
```
## Command-line arguments
## Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations
for that specific session.
@@ -1358,7 +1162,7 @@ for that specific session.
- **`--record-responses`**:
- Path to a file to record model responses for testing.
## Context files (hierarchical instructional context)
## Context Files (Hierarchical Instructional Context)
While not strictly configuration for the CLI's _behavior_, context files
(defaulting to `GEMINI.md` but configurable via the `context.fileName` setting)
@@ -1374,7 +1178,7 @@ context.
that you want the Gemini model to be aware of during your interactions. The
system is designed to manage this instructional context hierarchically.
### Example context file content (e.g., `GEMINI.md`)
### Example Context File Content (e.g., `GEMINI.md`)
Here's a conceptual example of what a context file at the root of a TypeScript
project might contain:
@@ -1415,23 +1219,23 @@ more relevant and precise your context files are, the better the AI can assist
you. Project-specific context files are highly encouraged to establish
conventions and context.
- **Hierarchical loading and precedence:** The CLI implements a sophisticated
- **Hierarchical Loading and Precedence:** The CLI implements a sophisticated
hierarchical memory system by loading context files (e.g., `GEMINI.md`) from
several locations. Content from files lower in this list (more specific)
typically overrides or supplements content from files higher up (more
general). The exact concatenation order and final context can be inspected
using the `/memory show` command. The typical loading order is:
1. **Global context file:**
1. **Global Context File:**
- Location: `~/.gemini/<configured-context-filename>` (e.g.,
`~/.gemini/GEMINI.md` in your user home directory).
- Scope: Provides default instructions for all your projects.
2. **Project root and ancestors context files:**
2. **Project Root & Ancestors Context Files:**
- Location: The CLI searches for the configured context file in the
current working directory and then in each parent directory up to either
the project root (identified by a `.git` folder) or your home directory.
- Scope: Provides context relevant to the entire project or a significant
portion of it.
3. **Sub-directory context files (contextual/local):**
3. **Sub-directory Context Files (Contextual/Local):**
- Location: The CLI also scans for the configured context file in
subdirectories _below_ the current working directory (respecting common
ignore patterns like `node_modules`, `.git`, etc.). The breadth of this
@@ -1440,15 +1244,15 @@ conventions and context.
file.
- Scope: Allows for highly specific instructions relevant to a particular
component, module, or subsection of your project.
- **Concatenation and UI indication:** The contents of all found context files
are concatenated (with separators indicating their origin and path) and
provided as part of the system prompt to the Gemini model. The CLI footer
displays the count of loaded context files, giving you a quick visual cue
about the active instructional context.
- **Importing content:** You can modularize your context files by importing
- **Concatenation & UI Indication:** The contents of all found context files are
concatenated (with separators indicating their origin and path) and provided
as part of the system prompt to the Gemini model. The CLI footer displays the
count of loaded context files, giving you a quick visual cue about the active
instructional context.
- **Importing Content:** You can modularize your context files by importing
other Markdown files using the `@path/to/file.md` syntax. For more details,
see the [Memory Import Processor documentation](../core/memport.md).
- **Commands for memory management:**
- **Commands for Memory Management:**
- Use `/memory refresh` to force a re-scan and reload of all context files
from all configured locations. This updates the AI's instructional context.
- Use `/memory show` to display the combined instructional context currently
@@ -1495,7 +1299,7 @@ sandbox image:
BUILD_SANDBOX=1 gemini -s
```
## Usage statistics
## Usage Statistics
To help us improve the Gemini CLI, we collect anonymized usage statistics. This
data helps us understand how the CLI is used, identify common issues, and
@@ -1503,22 +1307,22 @@ prioritize new features.
**What we collect:**
- **Tool calls:** We log the names of the tools that are called, whether they
- **Tool Calls:** We log the names of the tools that are called, whether they
succeed or fail, and how long they take to execute. We do not collect the
arguments passed to the tools or any data returned by them.
- **API requests:** We log the Gemini model used for each request, the duration
- **API Requests:** We log the Gemini model used for each request, the duration
of the request, and whether it was successful. We do not collect the content
of the prompts or responses.
- **Session information:** We collect information about the configuration of the
- **Session Information:** We collect information about the configuration of the
CLI, such as the enabled tools and the approval mode.
**What we DON'T collect:**
- **Personally identifiable information (PII):** We do not collect any personal
- **Personally Identifiable Information (PII):** We do not collect any personal
information, such as your name, email address, or API keys.
- **Prompt and response content:** We do not log the content of your prompts or
- **Prompt and Response Content:** We do not log the content of your prompts or
the responses from the Gemini model.
- **File content:** We do not log the content of any files that are read or
- **File Content:** We do not log the content of any files that are read or
written by the CLI.
**How to opt out:**
+3 -3
View File
@@ -1,6 +1,6 @@
Note: This page will be replaced by [installation.md](installation.md).
# Gemini CLI installation, execution, and deployment
# Gemini CLI Installation, Execution, and Deployment
Install and run Gemini CLI. This document provides an overview of Gemini CLI's
installation methods and deployment architecture.
@@ -44,7 +44,7 @@ downloading the Gemini CLI package from the NPM registry.
For security and isolation, Gemini CLI can be run inside a container. This is
the default way that the CLI executes tools that might have side effects.
- **Directly from the registry:** You can run the published sandbox image
- **Directly from the Registry:** You can run the published sandbox image
directly. This is useful for environments where you only have Docker and want
to run the CLI.
```bash
@@ -63,7 +63,7 @@ the default way that the CLI executes tools that might have side effects.
Contributors to the project will want to run the CLI directly from the source
code.
- **Development mode:** This method provides hot-reloading and is useful for
- **Development Mode:** This method provides hot-reloading and is useful for
active development.
```bash
# From the root of the repository
+4 -4
View File
@@ -1,4 +1,4 @@
# Gemini CLI examples
# Gemini CLI Examples
Not sure where to get started with Gemini CLI? This document covers examples on
how to use Gemini CLI for a variety of tasks.
@@ -24,7 +24,7 @@ Rename the photos in my "photos" directory based on their contents.
Result: Gemini will ask for permission to rename your files.
Select **Allow once** and your files will be renamed:
Select **Yes, allow once.** and your files will be renamed:
```bash
photos/yellow_flowers.png
@@ -57,7 +57,7 @@ Gemini CLI will return an explanation based on the actual source code:
The `chalk` library is a popular npm package for styling terminal output with
colors. After analyzing the source code, here's how it works:
- **Core functionality:** The main file sets up a chainable API. Each color or
- **Core Functionality:** The main file sets up a chainable API. Each color or
modifier (like `bold` or `italic`) is a getter that appends the corresponding
ANSI escape code to an internal stack.
@@ -65,7 +65,7 @@ colors. After analyzing the source code, here's how it works:
getters. The `red` getter adds the red color code, and the `bold` getter adds
the bold code.
- **Output generation:** When the chain is treated as a string (e.g., in
- **Output Generation:** When the chain is treated as a string (e.g., in
`console.log`), a final `toString()` method is called. This method joins all
the stored ANSI codes, wraps them around the input string ('Hello'), and adds
a reset code at the end. This produces the final, styled string that the
+56 -62
View File
@@ -1,37 +1,64 @@
# Gemini 3 Pro and Gemini 3 Flash on Gemini CLI
# Gemini 3 Pro on Gemini CLI (Join the Waitlist)
Gemini 3 Pro and Gemini 3 Flash are now available on Gemini CLI! Currently, most
paid customers of Gemini CLI will have access to both Gemini 3 Pro and Gemini 3
Flash, including the following subscribers:
Were excited to bring Gemini 3 Pro to Gemini CLI. For Google AI Ultra users
(Google AI Ultra for Business is not currently supported) and paid Gemini and
Vertex API key holders, Gemini 3 Pro is already available and ready to enable.
For everyone else, we're gradually expanding access
[through a waitlist](https://goo.gle/geminicli-waitlist-signup). Sign up for the
waitlist now to access Gemini 3 Pro once approved.
- Google AI Pro and Google AI Ultra (excluding business customers).
- Gemini Code Assist Standard and Enterprise (requires
[administrative enablement](#administrator-instructions)).
- Paid Gemini API and Vertex API key holders.
**Note:** Please wait until you have been approved to use Gemini 3 Pro to enable
**Preview Features**. If enabled early, the CLI will fallback to Gemini 2.5 Pro.
For free tier users:
## Do I need to join the waitlist?
- If you signed up for the waitlist, please check your email for details. Weve
onboarded everyone who signed up to the previously available waitlist.
- If you were not on our waitlist, were rolling out additional access gradually
to ensure the experience remains fast and reliable. Stay tuned for more
details.
The following users will be **automatically granted access** to Gemini 3 Pro on
Gemini CLI:
## How to get started with Gemini 3 on Gemini CLI
- Google AI Ultra subscribers (excluding Google AI Ultra for Business, which is
on the roadmap).
- Gemini API key users
[with access to Gemini 3](https://ai.google.dev/gemini-api/docs/rate-limits).
- Vertex API key users
[with access to Gemini 3](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/quotas).
Get started by upgrading Gemini CLI to the latest version (0.21.1):
For **Gemini Code Assist Enterprise users**, access is coming soon.
```bash
npm install -g @google/gemini-cli@latest
```
Users not automatically granted access through one of these account types will
need to join the waitlist. This includes Google AI Pro, Gemini Code Assist
standard, and free tier users.
After youve confirmed your version is 0.21.1 or later:
Note: Whether youre automatically granted access or accepted from the waitlist,
youll still need to enable Gemini 3 Pro
[using the `/settings` command](../cli/settings.md).
1. Use the `/settings` command in Gemini CLI.
2. Toggle **Preview Features** to `true`.
3. Run `/model` and select **Auto (Gemini 3)**.
## How to join the waitlist
For more information, see [Gemini CLI model selection](../cli/model.md).
Users not automatically granted access will need to join the waitlist. Follow
these instructions to sign up:
- Install Gemini CLI.
- Authenticate using the **Login with Google** option. Youll see a banner that
says “Gemini 3 is now available.” If you do not see this banner, update your
installation of Gemini CLI to the most recent version.
- Fill out this Google form:
[Access Gemini 3 in Gemini CLI](https://goo.gle/geminicli-waitlist-signup).
Provide the email address of the account you used to authenticate with Gemini
CLI.
Users will be onboarded in batches, subject to availability. When youve been
granted access to Gemini 3 Pro, youll receive an acceptance email to your
submitted email address.
## How to use Gemini 3 Pro with Gemini CLI
Once you receive your acceptance emailor if you are automatically granted
accessyou still need to enable Gemini 3 Pro within Gemini CLI.
To enable Gemini 3 Pro, use the `/settings` command in Gemini CLI and set
**Preview Features** to `true`.
For more information, see [Gemini CLI Settings](../cli/settings.md).
### Usage limits and fallback
@@ -49,12 +76,12 @@ There may be times when the Gemini 3 Pro model is overloaded. When that happens,
Gemini CLI will ask you to decide whether you want to keep trying Gemini 3 Pro
or fallback to Gemini 2.5 Pro.
> **Note:** The **Keep trying** option uses exponential backoff, in which Gemini
> CLI waits longer between each retry, when the system is busy. If the retry
> doesn't happen immediately, please wait a few minutes for the request to
> process.
**Note:** The **Keep trying** option uses exponential backoff, in which Gemini
CLI waits longer between each retry, when the system is busy. If the retry
doesn't happen immediately, please wait a few minutes for the request to
process.
### Model selection and routing types
## Model selection & routing types
When using Gemini CLI, you may want to control how your requests are routed
between models. By default, Gemini CLI uses **Auto** routing.
@@ -73,39 +100,6 @@ manage your usage limits:
To learn more about selecting a model and routing, refer to
[Gemini CLI Model Selection](../cli/model.md).
## How to enable Gemini 3 with Gemini CLI on Gemini Code Assist
If you're using Gemini Code Assist Standard or Gemini Code Assist Enterprise,
enabling Gemini 3 Pro on Gemini CLI requires configuring your release channels.
Using Gemini 3 Pro will require two steps: administrative enablement and user
enablement.
To learn more about these settings, refer to
[Configure Gemini Code Assist release channels](https://developers.google.com/gemini-code-assist/docs/configure-release-channels).
### Administrator instructions
An administrator with **Google Cloud Settings Admin** permissions must follow
these directions:
- Navigate to the Google Cloud Project you're using with Gemini CLI for Code
Assist.
- Go to **Admin for Gemini** > **Settings**.
- Under **Release channels for Gemini Code Assist in local IDEs** select
**Preview**.
- Click **Save changes**.
### User instructions
Wait for two to three minutes after your administrator has enabled **Preview**,
then:
- Open Gemini CLI.
- Use the `/settings` command.
- Set **Preview Features** to `true`.
Restart Gemini CLI and you should have access to Gemini 3.
## Need help?
If you need help, we recommend searching for an existing
+4 -9
View File
@@ -1,4 +1,4 @@
# Get started with Gemini CLI
# Get Started with Gemini CLI
Welcome to Gemini CLI! This guide will help you install, configure, and start
using the Gemini CLI to enhance your workflow right from your terminal.
@@ -28,24 +28,19 @@ For more installation options, see [Gemini CLI Installation](./installation.md).
## Authenticate
To begin using Gemini CLI, you must authenticate with a Google service. In most
cases, you can log in with your existing Google account:
To begin using Gemini CLI, you must authenticate with a Google service. The most
straightforward authentication method uses your existing Google account:
1. Run Gemini CLI after installation:
```bash
gemini
```
2. When asked "How would you like to authenticate for this project?" select **1.
Login with Google**.
3. Select your Google account.
4. Click on **Sign in**.
Certain account types may require you to configure a Google Cloud project. For
more information, including other authentication methods, see
For other authentication options and information, see
[Gemini CLI Authentication Setup](./authentication.md).
## Configure
+4 -4
View File
@@ -1,4 +1,4 @@
# Gemini CLI installation, execution, and deployment
# Gemini CLI Installation, Execution, and Deployment
Install and run Gemini CLI. This document provides an overview of Gemini CLI's
installation methods and deployment architecture.
@@ -42,7 +42,7 @@ downloading the Gemini CLI package from the NPM registry.
For security and isolation, Gemini CLI can be run inside a container. This is
the default way that the CLI executes tools that might have side effects.
- **Directly from the registry:** You can run the published sandbox image
- **Directly from the Registry:** You can run the published sandbox image
directly. This is useful for environments where you only have Docker and want
to run the CLI.
```bash
@@ -61,13 +61,13 @@ the default way that the CLI executes tools that might have side effects.
Contributors to the project will want to run the CLI directly from the source
code.
- **Development mode:** This method provides hot-reloading and is useful for
- **Development Mode:** This method provides hot-reloading and is useful for
active development.
```bash
# From the root of the repository
npm run start
```
- **Production-like mode (linked package):** This method simulates a global
- **Production-like mode (Linked package):** This method simulates a global
installation by linking your local package. It's useful for testing a local
build in a production workflow.
-856
View File
@@ -1,856 +0,0 @@
# Hooks on Gemini CLI: Best practices
This guide covers security considerations, performance optimization, debugging
techniques, and privacy considerations for developing and deploying hooks in
Gemini CLI.
## Performance
### Keep hooks fast
Hooks run synchronously—slow hooks delay the agent loop. Optimize for speed by
using parallel operations:
```javascript
// Sequential operations are slower
const data1 = await fetch(url1).then((r) => r.json());
const data2 = await fetch(url2).then((r) => r.json());
const data3 = await fetch(url3).then((r) => r.json());
// Prefer parallel operations for better performance
// Start requests concurrently
const p1 = fetch(url1).then((r) => r.json());
const p2 = fetch(url2).then((r) => r.json());
const p3 = fetch(url3).then((r) => r.json());
// Wait for all results
const [data1, data2, data3] = await Promise.all([p1, p2, p3]);
```
### Cache expensive operations
Store results between invocations to avoid repeated computation:
```javascript
const fs = require('fs');
const path = require('path');
const CACHE_FILE = '.gemini/hook-cache.json';
function readCache() {
try {
return JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
} catch {
return {};
}
}
function writeCache(data) {
fs.writeFileSync(CACHE_FILE, JSON.stringify(data, null, 2));
}
async function main() {
const cache = readCache();
const cacheKey = `tool-list-${(Date.now() / 3600000) | 0}`; // Hourly cache
if (cache[cacheKey]) {
console.log(JSON.stringify(cache[cacheKey]));
return;
}
// Expensive operation
const result = await computeExpensiveResult();
cache[cacheKey] = result;
writeCache(cache);
console.log(JSON.stringify(result));
}
```
### Use appropriate events
Choose hook events that match your use case to avoid unnecessary execution.
`AfterAgent` fires once per agent loop completion, while `AfterModel` fires
after every LLM call (potentially multiple times per loop):
```json
// If checking final completion, use AfterAgent instead of AfterModel
{
"hooks": {
"AfterAgent": [
{
"matcher": "*",
"hooks": [
{
"name": "final-checker",
"command": "./check-completion.sh"
}
]
}
]
}
}
```
### Filter with matchers
Use specific matchers to avoid unnecessary hook execution. Instead of matching
all tools with `*`, specify only the tools you need:
```json
{
"matcher": "write_file|replace",
"hooks": [
{
"name": "validate-writes",
"command": "./validate.sh"
}
]
}
```
### Optimize JSON parsing
For large inputs, use streaming JSON parsers to avoid loading everything into
memory:
```javascript
// Standard approach: parse entire input
const input = JSON.parse(await readStdin());
const content = input.tool_input.content;
// For very large inputs: stream and extract only needed fields
const { createReadStream } = require('fs');
const JSONStream = require('JSONStream');
const stream = createReadStream(0).pipe(JSONStream.parse('tool_input.content'));
let content = '';
stream.on('data', (chunk) => {
content += chunk;
});
```
## Debugging
### Log to files
Write debug information to dedicated log files:
```bash
#!/usr/bin/env bash
LOG_FILE=".gemini/hooks/debug.log"
# Log with timestamp
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}
input=$(cat)
log "Received input: ${input:0:100}..."
# Hook logic here
log "Hook completed successfully"
```
### Use stderr for errors
Error messages on stderr are surfaced appropriately based on exit codes:
```javascript
try {
const result = dangerousOperation();
console.log(JSON.stringify({ result }));
} catch (error) {
console.error(`Hook error: ${error.message}`);
process.exit(2); // Blocking error
}
```
### Test hooks independently
Run hook scripts manually with sample JSON input:
```bash
# Create test input
cat > test-input.json << 'EOF'
{
"session_id": "test-123",
"cwd": "/tmp/test",
"hook_event_name": "BeforeTool",
"tool_name": "write_file",
"tool_input": {
"file_path": "test.txt",
"content": "Test content"
}
}
EOF
# Test the hook
cat test-input.json | .gemini/hooks/my-hook.sh
# Check exit code
echo "Exit code: $?"
```
### Check exit codes
Ensure your script returns the correct exit code:
```bash
#!/usr/bin/env bash
set -e # Exit on error
# Hook logic
process_input() {
# ...
}
if process_input; then
echo "Success message"
exit 0
else
echo "Error message" >&2
exit 2
fi
```
### Enable telemetry
Hook execution is logged when `telemetry.logPrompts` is enabled:
```json
{
"telemetry": {
"logPrompts": true
}
}
```
View hook telemetry in logs to debug execution issues.
### Use hook panel
The `/hooks panel` command shows execution status and recent output:
```bash
/hooks panel
```
Check for:
- Hook execution counts
- Recent successes/failures
- Error messages
- Execution timing
## Development
### Start simple
Begin with basic logging hooks before implementing complex logic:
```bash
#!/usr/bin/env bash
# Simple logging hook to understand input structure
input=$(cat)
echo "$input" >> .gemini/hook-inputs.log
echo "Logged input"
```
### Use JSON libraries
Parse JSON with proper libraries instead of text processing:
**Bad:**
```bash
# Fragile text parsing
tool_name=$(echo "$input" | grep -oP '"tool_name":\s*"\K[^"]+')
```
**Good:**
```bash
# Robust JSON parsing
tool_name=$(echo "$input" | jq -r '.tool_name')
```
### Make scripts executable
Always make hook scripts executable:
```bash
chmod +x .gemini/hooks/*.sh
chmod +x .gemini/hooks/*.js
```
### Version control
Commit hooks to share with your team:
```bash
git add .gemini/hooks/
git add .gemini/settings.json
git commit -m "Add project hooks for security and testing"
```
**`.gitignore` considerations:**
```gitignore
# Ignore hook cache and logs
.gemini/hook-cache.json
.gemini/hook-debug.log
.gemini/memory/session-*.jsonl
# Keep hook scripts
!.gemini/hooks/*.sh
!.gemini/hooks/*.js
```
### Document behavior
Add descriptions to help others understand your hooks:
```json
{
"hooks": {
"BeforeTool": [
{
"matcher": "write_file|replace",
"hooks": [
{
"name": "secret-scanner",
"type": "command",
"command": "$GEMINI_PROJECT_DIR/.gemini/hooks/block-secrets.sh",
"description": "Scans code changes for API keys, passwords, and other secrets before writing"
}
]
}
]
}
}
```
Add comments in hook scripts:
```javascript
#!/usr/bin/env node
/**
* RAG Tool Filter Hook
*
* This hook reduces the tool space from 100+ tools to ~15 relevant ones
* by extracting keywords from the user's request and filtering tools
* based on semantic similarity.
*
* Performance: ~500ms average, cached tool embeddings
* Dependencies: @google/generative-ai
*/
```
## Troubleshooting
### Hook not executing
**Check hook name in `/hooks panel`:**
```bash
/hooks panel
```
Verify the hook appears in the list and is enabled.
**Verify matcher pattern:**
```bash
# Test regex pattern
echo "write_file|replace" | grep -E "write_.*|replace"
```
**Check disabled list:**
```json
{
"hooks": {
"disabled": ["my-hook-name"]
}
}
```
**Ensure script is executable:**
```bash
ls -la .gemini/hooks/my-hook.sh
chmod +x .gemini/hooks/my-hook.sh
```
**Verify script path:**
```bash
# Check path expansion
echo "$GEMINI_PROJECT_DIR/.gemini/hooks/my-hook.sh"
# Verify file exists
test -f "$GEMINI_PROJECT_DIR/.gemini/hooks/my-hook.sh" && echo "File exists"
```
### Hook timing out
**Check configured timeout:**
```json
{
"name": "slow-hook",
"timeout": 60000
}
```
**Optimize slow operations:**
```javascript
// Before: Sequential operations (slow)
for (const item of items) {
await processItem(item);
}
// After: Parallel operations (fast)
await Promise.all(items.map((item) => processItem(item)));
```
**Use caching:**
```javascript
const cache = new Map();
async function getCachedData(key) {
if (cache.has(key)) {
return cache.get(key);
}
const data = await fetchData(key);
cache.set(key, data);
return data;
}
```
**Consider splitting into multiple faster hooks:**
```json
{
"hooks": {
"BeforeTool": [
{
"matcher": "write_file",
"hooks": [
{
"name": "quick-check",
"command": "./quick-validation.sh",
"timeout": 1000
}
]
},
{
"matcher": "write_file",
"hooks": [
{
"name": "deep-check",
"command": "./deep-analysis.sh",
"timeout": 30000
}
]
}
]
}
}
```
### Invalid JSON output
**Validate JSON before outputting:**
```bash
#!/usr/bin/env bash
output='{"decision": "allow"}'
# Validate JSON
if echo "$output" | jq empty 2>/dev/null; then
echo "$output"
else
echo "Invalid JSON generated" >&2
exit 1
fi
```
**Ensure proper quoting and escaping:**
```javascript
// Bad: Unescaped string interpolation
const message = `User said: ${userInput}`;
console.log(JSON.stringify({ message }));
// Good: Automatic escaping
console.log(JSON.stringify({ message: `User said: ${userInput}` }));
```
**Check for binary data or control characters:**
```javascript
function sanitizeForJSON(str) {
return str.replace(/[\x00-\x1F\x7F-\x9F]/g, ''); // Remove control chars
}
const cleanContent = sanitizeForJSON(content);
console.log(JSON.stringify({ content: cleanContent }));
```
### Exit code issues
**Verify script returns correct codes:**
```bash
#!/usr/bin/env bash
set -e # Exit on error
# Processing logic
if validate_input; then
echo "Success"
exit 0
else
echo "Validation failed" >&2
exit 2
fi
```
**Check for unintended errors:**
```bash
#!/usr/bin/env bash
# Don't use 'set -e' if you want to handle errors explicitly
# set -e
if ! command_that_might_fail; then
# Handle error
echo "Command failed but continuing" >&2
fi
# Always exit explicitly
exit 0
```
**Use trap for cleanup:**
```bash
#!/usr/bin/env bash
cleanup() {
# Cleanup logic
rm -f /tmp/hook-temp-*
}
trap cleanup EXIT
# Hook logic here
```
### Environment variables not available
**Check if variable is set:**
```bash
#!/usr/bin/env bash
if [ -z "$GEMINI_PROJECT_DIR" ]; then
echo "GEMINI_PROJECT_DIR not set" >&2
exit 1
fi
if [ -z "$CUSTOM_VAR" ]; then
echo "Warning: CUSTOM_VAR not set, using default" >&2
CUSTOM_VAR="default-value"
fi
```
**Debug available variables:**
```bash
#!/usr/bin/env bash
# List all environment variables
env > .gemini/hook-env.log
# Check specific variables
echo "GEMINI_PROJECT_DIR: $GEMINI_PROJECT_DIR" >> .gemini/hook-env.log
echo "GEMINI_SESSION_ID: $GEMINI_SESSION_ID" >> .gemini/hook-env.log
echo "GEMINI_API_KEY: ${GEMINI_API_KEY:+<set>}" >> .gemini/hook-env.log
```
**Use .env files:**
```bash
#!/usr/bin/env bash
# Load .env file if it exists
if [ -f "$GEMINI_PROJECT_DIR/.env" ]; then
source "$GEMINI_PROJECT_DIR/.env"
fi
```
## Using Hooks Securely
### Threat Model
Understanding where hooks come from and what they can do is critical for secure
usage.
| Hook Source | Description |
| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
| **System** | Configured by system administrators (e.g., `/etc/gemini-cli/settings.json`, `/Library/...`). Assumed to be the **safest**. |
| **User** (`~/.gemini/...`) | Configured by you. You are responsible for ensuring they are safe. |
| **Extensions** | You explicitly approve and install these. Security depends on the extension source (integrity). |
| **Project** (`./.gemini/...`) | **Untrusted by default.** Safest in trusted internal repos; higher risk in third-party/public repos. |
#### Project Hook Security
When you open a project with hooks defined in `.gemini/settings.json`:
1. **Detection**: Gemini CLI detects the hooks.
2. **Identification**: A unique identity is generated for each hook based on its
`name` and `command`.
3. **Warning**: If this specific hook identity has not been seen before, a
**warning** is displayed.
4. **Execution**: The hook is executed (unless specific security settings block
it).
5. **Trust**: The hook is marked as "trusted" for this project.
> [!IMPORTANT] **Modification Detection**: If the `command` string of a project
> hook is changed (e.g., by a `git pull`), its identity changes. Gemini CLI will
> treat it as a **new, untrusted hook** and warn you again. This prevents
> malicious actors from silently swapping a verified command for a malicious
> one.
### Risks
| Risk | Description |
| :--------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
| **Arbitrary Code Execution** | Hooks run as your user. They can do anything you can do (delete files, install software). |
| **Data Exfiltration** | A hook could read your input (prompts), output (code), or environment variables (`GEMINI_API_KEY`) and send them to a remote server. |
| **Prompt Injection** | Malicious content in a file or web page could trick an LLM into running a tool that triggers a hook in an unexpected way. |
### Mitigation Strategies
#### Verify the source
**Verify the source** of any project hooks or extensions before enabling them.
- For open-source projects, a quick review of the hook scripts is recommended.
- For extensions, ensure you trust the author or publisher (e.g., verified
publishers, well-known community members).
- Be cautious with obfuscated scripts or compiled binaries from unknown sources.
#### Sanitize Environment
Hooks inherit the environment of the Gemini CLI process, which may include
sensitive API keys. Gemini CLI attempts to sanitize sensitive variables, but you
should be cautious.
- **Avoid printing environment variables** to stdout/stderr unless necessary.
- **Use `.env` files** to securely manage sensitive variables, ensuring they are
excluded from version control.
**System Administrators:** You can enforce environment variable redaction by
default in the system configuration (e.g., `/etc/gemini-cli/settings.json`):
```json
{
"security": {
"environmentVariableRedaction": {
"enabled": true,
"blocked": ["MY_SECRET_KEY"],
"allowed": ["SAFE_VAR"]
}
}
}
```
## Authoring Secure Hooks
When writing your own hooks, follow these practices to ensure they are robust
and secure.
### Validate all inputs
Never trust data from hooks without validation. Hook inputs often come from the
LLM or user prompts, which can be manipulated.
```bash
#!/usr/bin/env bash
input=$(cat)
# Validate JSON structure
if ! echo "$input" | jq empty 2>/dev/null; then
echo "Invalid JSON input" >&2
exit 1
fi
# Validate tool_name explicitly
tool_name=$(echo "$input" | jq -r '.tool_name // empty')
if [[ "$tool_name" != "write_file" && "$tool_name" != "read_file" ]]; then
echo "Unexpected tool: $tool_name" >&2
exit 1
fi
```
### Use timeouts
Prevent denial-of-service (hanging agents) by enforcing timeouts. Gemini CLI
defaults to 60 seconds, but you should set stricter limits for fast hooks.
```json
{
"hooks": {
"BeforeTool": [
{
"matcher": "*",
"hooks": [
{
"name": "fast-validator",
"command": "./hooks/validate.sh",
"timeout": 5000 // 5 seconds
}
]
}
]
}
}
```
### Limit permissions
Run hooks with minimal required permissions:
```bash
#!/usr/bin/env bash
# Don't run as root
if [ "$EUID" -eq 0 ]; then
echo "Hook should not run as root" >&2
exit 1
fi
# Check file permissions before writing
if [ -w "$file_path" ]; then
# Safe to write
else
echo "Insufficient permissions" >&2
exit 1
fi
```
### Example: Secret Scanner
Use `BeforeTool` hooks to prevent committing sensitive data. This is a powerful
pattern for enhancing security in your workflow.
```javascript
const SECRET_PATTERNS = [
/api[_-]?key\s*[:=]\s*['"]?[a-zA-Z0-9_-]{20,}['"]?/i,
/password\s*[:=]\s*['"]?[^\s'"]{8,}['"]?/i,
/secret\s*[:=]\s*['"]?[a-zA-Z0-9_-]{20,}['"]?/i,
/AKIA[0-9A-Z]{16}/, // AWS access key
/ghp_[a-zA-Z0-9]{36}/, // GitHub personal access token
/sk-[a-zA-Z0-9]{48}/, // OpenAI API key
];
function containsSecret(content) {
return SECRET_PATTERNS.some((pattern) => pattern.test(content));
}
```
## Privacy considerations
Hook inputs and outputs may contain sensitive information. Gemini CLI respects
the `telemetry.logPrompts` setting for hook data logging.
### What data is collected
Hook telemetry may include:
- **Hook inputs:** User prompts, tool arguments, file contents
- **Hook outputs:** Hook responses, decision reasons, added context
- **Standard streams:** stdout and stderr from hook processes
- **Execution metadata:** Hook name, event type, duration, success/failure
### Privacy settings
**Enabled (default):**
Full hook I/O is logged to telemetry. Use this when:
- Developing and debugging hooks
- Telemetry is redirected to a trusted enterprise system
- You understand and accept the privacy implications
**Disabled:**
Only metadata is logged (event name, duration, success/failure). Hook inputs and
outputs are excluded. Use this when:
- Sending telemetry to third-party systems
- Working with sensitive data
- Privacy regulations require minimizing data collection
### Configuration
**Disable PII logging in settings:**
```json
{
"telemetry": {
"logPrompts": false
}
}
```
**Disable via environment variable:**
```bash
export GEMINI_TELEMETRY_LOG_PROMPTS=false
```
### Sensitive data in hooks
If your hooks process sensitive data:
1. **Minimize logging:** Don't write sensitive data to log files
2. **Sanitize outputs:** Remove sensitive data before outputting
3. **Use secure storage:** Encrypt sensitive data at rest
4. **Limit access:** Restrict hook script permissions
**Example sanitization:**
```javascript
function sanitizeOutput(data) {
const sanitized = { ...data };
// Remove sensitive fields
delete sanitized.apiKey;
delete sanitized.password;
// Redact sensitive strings
if (sanitized.content) {
sanitized.content = sanitized.content.replace(
/api[_-]?key\s*[:=]\s*['"]?[a-zA-Z0-9_-]{20,}['"]?/gi,
'[REDACTED]',
);
}
return sanitized;
}
console.log(JSON.stringify(sanitizeOutput(hookOutput)));
```
## Learn more
- [Hooks Reference](index.md) - Complete API reference
- [Writing Hooks](writing-hooks.md) - Tutorial and examples
- [Configuration](../cli/configuration.md) - Gemini CLI settings
- [Hooks Design Document](../hooks-design.md) - Technical architecture
-687
View File
@@ -1,687 +0,0 @@
# Gemini CLI hooks
Hooks are scripts or programs that Gemini CLI executes at specific points in the
agentic loop, allowing you to intercept and customize behavior without modifying
the CLI's source code.
See [writing hooks guide](writing-hooks.md) for a tutorial on creating your
first hook and a comprehensive example.
See [hooks reference](reference.md) for the technical specification of the I/O
schemas.
See [best practices](best-practices.md) for guidelines on security, performance,
and debugging.
## What are hooks?
With hooks, you can:
- **Add context:** Inject relevant information before the model processes a
request
- **Validate actions:** Review and block potentially dangerous operations
- **Enforce policies:** Implement security and compliance requirements
- **Log interactions:** Track tool usage and model responses
- **Optimize behavior:** Dynamically adjust tool selection or model parameters
Hooks run synchronously as part of the agent loop—when a hook event fires,
Gemini CLI waits for all matching hooks to complete before continuing.
## Security and Risks
> [!WARNING] **Hooks execute arbitrary code with your user privileges.**
By configuring hooks, you are explicitly allowing Gemini CLI to run shell
commands on your machine. Malicious or poorly configured hooks can:
- **Exfiltrate data**: Read sensitive files (`.env`, ssh keys) and send them to
remote servers.
- **Modify system**: Delete files, install malware, or change system settings.
- **Consume resources**: Run infinite loops or crash your system.
**Project-level hooks** (in `.gemini/settings.json`) and **Extension hooks** are
particularly risky when opening third-party projects or extensions from
untrusted authors. Gemini CLI will **warn you** the first time it detects a new
project hook (identified by its name and command), but it is **your
responsibility** to review these hooks (and any installed extensions) before
trusting them.
See [Security Considerations](best-practices.md#using-hooks-securely) for a
detailed threat model and mitigation strategies.
## Core concepts
### Hook events
Hooks are triggered by specific events in Gemini CLI's lifecycle. The following
table lists all available hook events:
| Event | When It Fires | Common Use Cases |
| --------------------- | --------------------------------------------- | ------------------------------------------ |
| `SessionStart` | When a session begins | Initialize resources, load context |
| `SessionEnd` | When a session ends | Clean up, save state |
| `BeforeAgent` | After user submits prompt, before planning | Add context, validate prompts |
| `AfterAgent` | When agent loop ends | Review output, force continuation |
| `BeforeModel` | Before sending request to LLM | Modify prompts, add instructions |
| `AfterModel` | After receiving LLM response | Filter responses, log interactions |
| `BeforeToolSelection` | Before LLM selects tools (after BeforeModel) | Filter available tools, optimize selection |
| `BeforeTool` | Before a tool executes | Validate arguments, block dangerous ops |
| `AfterTool` | After a tool executes | Process results, run tests |
| `PreCompress` | Before context compression | Save state, notify user |
| `Notification` | When a notification occurs (e.g., permission) | Auto-approve, log decisions |
### Hook types
Gemini CLI currently supports **command hooks** that run shell commands or
scripts:
```json
{
"type": "command",
"command": "$GEMINI_PROJECT_DIR/.gemini/hooks/my-hook.sh",
"timeout": 30000
}
```
**Note:** Plugin hooks (npm packages) are planned for a future release.
### Matchers
For tool-related events (`BeforeTool`, `AfterTool`), you can filter which tools
trigger the hook:
```json
{
"hooks": {
"BeforeTool": [
{
"matcher": "write_file|replace",
"hooks": [
/* hooks for write operations */
]
}
]
}
}
```
**Matcher patterns:**
- **Exact match:** `"read_file"` matches only `read_file`
- **Regex:** `"write_.*|replace"` matches `write_file`, `replace`
- **Wildcard:** `"*"` or `""` matches all tools
**Session event matchers:**
- **SessionStart:** `startup`, `resume`, `clear`
- **SessionEnd:** `exit`, `clear`, `logout`, `prompt_input_exit`
- **PreCompress:** `manual`, `auto`
- **Notification:** `ToolPermission`
## Hook input/output contract
### Command hook communication
Hooks communicate via:
- **Input:** JSON on stdin
- **Output:** Exit code + stdout/stderr
### Exit codes
- **0:** Success - stdout shown to user (or injected as context for some events)
- **2:** Blocking error - stderr shown to agent/user, operation may be blocked
- **Other:** Non-blocking warning - logged but execution continues
### Common input fields
Every hook receives these base fields:
```json
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/path/to/project",
"hook_event_name": "BeforeTool",
"timestamp": "2025-12-01T10:30:00Z"
// ... event-specific fields
}
```
### Event-specific fields
#### BeforeTool
**Input:**
```json
{
"tool_name": "write_file",
"tool_input": {
"file_path": "/path/to/file.ts",
"content": "..."
}
}
```
**Output (JSON on stdout):**
```json
{
"decision": "allow|deny|ask|block",
"reason": "Explanation shown to agent",
"systemMessage": "Message shown to user"
}
```
Or simple exit codes:
- Exit 0 = allow (stdout shown to user)
- Exit 2 = deny (stderr shown to agent)
#### AfterTool
**Input:**
```json
{
"tool_name": "read_file",
"tool_input": { "file_path": "..." },
"tool_response": "file contents..."
}
```
**Output:**
```json
{
"decision": "allow|deny",
"hookSpecificOutput": {
"hookEventName": "AfterTool",
"additionalContext": "Extra context for agent"
}
}
```
#### BeforeAgent
**Input:**
```json
{
"prompt": "Fix the authentication bug"
}
```
**Output:**
```json
{
"decision": "allow|deny",
"hookSpecificOutput": {
"hookEventName": "BeforeAgent",
"additionalContext": "Recent project decisions: ..."
}
}
```
#### BeforeModel
**Input:**
```json
{
"llm_request": {
"model": "gemini-2.0-flash-exp",
"messages": [{ "role": "user", "content": "Hello" }],
"config": { "temperature": 0.7 },
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO",
"allowedFunctionNames": ["read_file", "write_file"]
}
}
}
}
```
**Output:**
```json
{
"decision": "allow",
"hookSpecificOutput": {
"hookEventName": "BeforeModel",
"llm_request": {
"messages": [
{ "role": "system", "content": "Additional instructions..." },
{ "role": "user", "content": "Hello" }
]
}
}
}
```
#### AfterModel
**Input:**
```json
{
"llm_request": {
"model": "gemini-2.0-flash-exp",
"messages": [
/* ... */
],
"config": {
/* ... */
},
"toolConfig": {
/* ... */
}
},
"llm_response": {
"text": "string",
"candidates": [
{
"content": {
"role": "model",
"parts": ["array of content parts"]
},
"finishReason": "STOP"
}
]
}
}
```
**Output:**
```json
{
"hookSpecificOutput": {
"hookEventName": "AfterModel",
"llm_response": {
"candidate": {
/* modified response */
}
}
}
}
```
#### BeforeToolSelection
**Input:**
```json
{
"llm_request": {
"model": "gemini-2.0-flash-exp",
"messages": [
/* ... */
],
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO",
"allowedFunctionNames": [
/* 100+ tools */
]
}
}
}
}
```
**Output:**
```json
{
"hookSpecificOutput": {
"hookEventName": "BeforeToolSelection",
"toolConfig": {
"functionCallingConfig": {
"mode": "ANY",
"allowedFunctionNames": ["read_file", "write_file", "replace"]
}
}
}
}
```
Or simple output (comma-separated tool names sets mode to ANY):
```bash
echo "read_file,write_file,replace"
```
#### SessionStart
**Input:**
```json
{
"source": "startup|resume|clear"
}
```
**Output:**
```json
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "Loaded 5 project memories"
}
}
```
#### SessionEnd
**Input:**
```json
{
"reason": "exit|clear|logout|prompt_input_exit|other"
}
```
No structured output expected (but stdout/stderr logged).
#### PreCompress
**Input:**
```json
{
"trigger": "manual|auto"
}
```
**Output:**
```json
{
"systemMessage": "Compression starting..."
}
```
#### Notification
**Input:**
```json
{
"notification_type": "ToolPermission",
"message": "string",
"details": {
/* notification details */
}
}
```
**Output:**
```json
{
"systemMessage": "Notification logged"
}
```
## Configuration
Hook definitions are configured in `settings.json` files using the `hooks`
object. Configuration can be specified at multiple levels with defined
precedence rules.
### Configuration layers
Hook configurations are applied in the following order of execution (lower
numbers run first):
1. **Project settings:** `.gemini/settings.json` in your project directory
(highest priority)
2. **User settings:** `~/.gemini/settings.json`
3. **System settings:** `/etc/gemini-cli/settings.json`
4. **Extensions:** Internal hooks defined by installed extensions (lowest
priority)
#### Deduplication and shadowing
If multiple hooks with the identical **name** and **command** are discovered
across different configuration layers, Gemini CLI deduplicates them. The hook
from the higher-priority layer (e.g., Project) will be kept, and others will be
ignored.
Within each level, hooks run in the order they are declared in the
configuration.
### Configuration schema
```json
{
"hooks": {
"EventName": [
{
"matcher": "pattern",
"hooks": [
{
"name": "hook-identifier",
"type": "command",
"command": "./path/to/script.sh",
"description": "What this hook does",
"timeout": 30000
}
]
}
]
}
}
```
**Configuration properties:**
- **`name`** (string, recommended): Unique identifier for the hook used in
`/hooks enable/disable` commands. If omitted, the `command` path is used as
the identifier.
- **`type`** (string, required): Hook type - currently only `"command"` is
supported
- **`command`** (string, required): Path to the script or command to execute
- **`description`** (string, optional): Human-readable description shown in
`/hooks panel`
- **`timeout`** (number, optional): Timeout in milliseconds (default: 60000)
- **`matcher`** (string, optional): Pattern to filter when hook runs (event
matchers only)
### Environment variables
Hooks have access to:
- `GEMINI_PROJECT_DIR`: Project root directory
- `GEMINI_SESSION_ID`: Current session ID
- `GEMINI_API_KEY`: Gemini API key (if configured)
- All other environment variables from the parent process
## Managing hooks
### View registered hooks
Use the `/hooks panel` command to view all registered hooks:
```bash
/hooks panel
```
This command displays:
- All active hooks organized by event
- Hook source (user, project, system)
- Hook type (command or plugin)
- Execution status and recent output
### Enable and disable hooks
You can temporarily enable or disable individual hooks using commands:
```bash
/hooks enable hook-name
/hooks disable hook-name
```
These commands allow you to control hook execution without editing configuration
files. The hook name should match the `name` field in your hook configuration.
Changes made via these commands are persisted to your global User settings
(`~/.gemini/settings.json`).
### Disabled hooks configuration
To permanently disable hooks, add them to the `hooks.disabled` array in your
`settings.json`:
```json
{
"hooks": {
"disabled": ["secret-scanner", "auto-test"]
}
}
```
**Note:** The `hooks.disabled` array uses a UNION merge strategy. Disabled hooks
from all configuration levels (user, project, system) are combined and
deduplicated, meaning a hook disabled at any level remains disabled.
## Migration from Claude Code
If you have hooks configured for Claude Code, you can migrate them:
```bash
gemini hooks migrate --from-claude
```
This command:
- Reads `.claude/settings.json`
- Converts event names (`PreToolUse``BeforeTool`, etc.)
- Translates tool names (`Bash``run_shell_command`, `replace``replace`)
- Updates matcher patterns
- Writes to `.gemini/settings.json`
### Event name mapping
| Claude Code | Gemini CLI |
| ------------------ | -------------- |
| `PreToolUse` | `BeforeTool` |
| `PostToolUse` | `AfterTool` |
| `UserPromptSubmit` | `BeforeAgent` |
| `Stop` | `AfterAgent` |
| `Notification` | `Notification` |
| `SessionStart` | `SessionStart` |
| `SessionEnd` | `SessionEnd` |
| `PreCompact` | `PreCompress` |
### Tool name mapping
| Claude Code | Gemini CLI |
| ----------- | --------------------- |
| `Bash` | `run_shell_command` |
| `Edit` | `replace` |
| `Read` | `read_file` |
| `Write` | `write_file` |
| `Glob` | `glob` |
| `Grep` | `search_file_content` |
| `LS` | `list_directory` |
## Tool and Event Matchers Reference
### Available tool names for matchers
The following built-in tools can be used in `BeforeTool` and `AfterTool` hook
matchers:
#### File operations
- `read_file` - Read a single file
- `read_many_files` - Read multiple files at once
- `write_file` - Create or overwrite a file
- `replace` - Edit file content with find/replace
#### File system
- `list_directory` - List directory contents
- `glob` - Find files matching a pattern
- `search_file_content` - Search within file contents
#### Execution
- `run_shell_command` - Execute shell commands
#### Web and external
- `google_web_search` - Google Search with grounding
- `web_fetch` - Fetch web page content
#### Agent features
- `write_todos` - Manage TODO items
- `save_memory` - Save information to memory
- `delegate_to_agent` - Delegate tasks to sub-agents
#### Example matchers
```json
{
"matcher": "write_file|replace" // File editing tools
}
```
```json
{
"matcher": "read_.*" // All read operations
}
```
```json
{
"matcher": "run_shell_command" // Only shell commands
}
```
```json
{
"matcher": "*" // All tools
}
```
### Event-specific matchers
#### SessionStart event matchers
- `startup` - Fresh session start
- `resume` - Resuming a previous session
- `clear` - Session cleared
#### SessionEnd event matchers
- `exit` - Normal exit
- `clear` - Session cleared
- `logout` - User logged out
- `prompt_input_exit` - Exit from prompt input
- `other` - Other reasons
#### PreCompress event matchers
- `manual` - Manually triggered compression
- `auto` - Automatically triggered compression
#### Notification event matchers
- `ToolPermission` - Tool permission notifications
## Learn more
- [Writing Hooks](writing-hooks.md) - Tutorial and comprehensive example
- [Best Practices](best-practices.md) - Security, performance, and debugging
- [Custom Commands](../cli/custom-commands.md) - Create reusable prompt
shortcuts
- [Configuration](../cli/configuration.md) - Gemini CLI configuration options
- [Hooks Design Document](../hooks-design.md) - Technical architecture details
-168
View File
@@ -1,168 +0,0 @@
# Hooks Reference
This document provides the technical specification for Gemini CLI hooks,
including the JSON schemas for input and output, exit code behaviors, and the
stable model API.
## Communication Protocol
Hooks communicate with Gemini CLI via standard streams and exit codes:
- **Input**: Gemini CLI sends a JSON object to the hook's `stdin`.
- **Output**: The hook sends a JSON object (or plain text) to `stdout`.
- **Exit Codes**: Used to signal success or blocking errors.
### Exit Code Behavior
| Exit Code | Meaning | Behavior |
| :-------- | :----------------- | :---------------------------------------------------------------------------------------------- |
| `0` | **Success** | `stdout` is parsed as JSON. If parsing fails, it's treated as a `systemMessage`. |
| `2` | **Blocking Error** | Interrupts the current operation. `stderr` is shown to the agent (for tool events) or the user. |
| Other | **Warning** | Execution continues. `stderr` is logged as a non-blocking warning. |
---
## Input Schema (`stdin`)
Every hook receives a base JSON object. Extra fields are added depending on the
specific event.
### Base Fields (All Events)
| Field | Type | Description |
| :---------------- | :------- | :---------------------------------------------------- |
| `session_id` | `string` | Unique identifier for the current CLI session. |
| `transcript_path` | `string` | Path to the session's JSON transcript (if available). |
| `cwd` | `string` | The current working directory. |
| `hook_event_name` | `string` | The name of the firing event (e.g., `BeforeTool`). |
| `timestamp` | `string` | ISO 8601 timestamp of the event. |
### Event-Specific Fields
#### Tool Events (`BeforeTool`, `AfterTool`)
- `tool_name`: (`string`) The internal name of the tool (e.g., `write_file`,
`run_shell_command`).
- `tool_input`: (`object`) The arguments passed to the tool.
- `tool_response`: (`object`, **AfterTool only**) The raw output from the tool
execution.
#### Agent Events (`BeforeAgent`, `AfterAgent`)
- `prompt`: (`string`) The user's submitted prompt.
- `prompt_response`: (`string`, **AfterAgent only**) The final response text
from the model.
- `stop_hook_active`: (`boolean`, **AfterAgent only**) Indicates if a stop hook
is already handling a continuation.
#### Model Events (`BeforeModel`, `AfterModel`, `BeforeToolSelection`)
- `llm_request`: (`LLMRequest`) A stable representation of the outgoing request.
See [Stable Model API](#stable-model-api).
- `llm_response`: (`LLMResponse`, **AfterModel only**) A stable representation
of the incoming response.
#### Session & Notification Events
- `source`: (`startup` | `resume` | `clear`, **SessionStart only**) The trigger
source.
- `reason`: (`exit` | `clear` | `logout` | `prompt_input_exit` | `other`,
**SessionEnd only**) The reason for session end.
- `trigger`: (`manual` | `auto`, **PreCompress only**) What triggered the
compression event.
- `notification_type`: (`ToolPermission`, **Notification only**) The type of
notification being fired.
- `message`: (`string`, **Notification only**) The notification message.
- `details`: (`object`, **Notification only**) Payload-specific details for the
notification.
---
## Output Schema (`stdout`)
If the hook exits with `0`, the CLI attempts to parse `stdout` as JSON.
### Common Output Fields
| Field | Type | Description |
| :------------------- | :-------- | :----------------------------------------------------------------------- |
| `decision` | `string` | One of: `allow`, `deny`, `block`, `ask`, `approve`. |
| `reason` | `string` | Explanation shown to the **agent** when a decision is `deny` or `block`. |
| `systemMessage` | `string` | Message displayed to the **user** in the CLI terminal. |
| `continue` | `boolean` | If `false`, immediately terminates the agent loop for this turn. |
| `stopReason` | `string` | Message shown to the user when `continue` is `false`. |
| `suppressOutput` | `boolean` | If `true`, the hook execution is hidden from the CLI transcript. |
| `hookSpecificOutput` | `object` | Container for event-specific data (see below). |
### `hookSpecificOutput` Reference
| Field | Supported Events | Description |
| :------------------ | :----------------------------------------- | :-------------------------------------------------------------------------------- |
| `additionalContext` | `SessionStart`, `BeforeAgent`, `AfterTool` | Appends text directly to the agent's context. |
| `llm_request` | `BeforeModel` | A `Partial<LLMRequest>` to override parameters of the outgoing call. |
| `llm_response` | `BeforeModel` | A **full** `LLMResponse` to bypass the model and provide a synthetic result. |
| `llm_response` | `AfterModel` | A `Partial<LLMResponse>` to modify the model's response before the agent sees it. |
| `toolConfig` | `BeforeToolSelection` | Object containing `mode` (`AUTO`/`ANY`/`NONE`) and `allowedFunctionNames`. |
---
## Stable Model API
Gemini CLI uses a decoupled format for model interactions to ensure hooks remain
stable even if the underlying Gemini SDK changes.
### `LLMRequest` Object
Used in `BeforeModel` and `BeforeToolSelection`.
> 💡 **Note**: In v1, model hooks are primarily text-focused. Non-text parts
> (like images or function calls) provided in the `content` array will be
> simplified to their string representation by the translator.
```typescript
{
"model": string,
"messages": Array<{
"role": "user" | "model" | "system",
"content": string | Array<{ "type": string, [key: string]: any }>
}>,
"config"?: {
"temperature"?: number,
"maxOutputTokens"?: number,
"topP"?: number,
"topK"?: number
},
"toolConfig"?: {
"mode"?: "AUTO" | "ANY" | "NONE",
"allowedFunctionNames"?: string[]
}
}
```
### `LLMResponse` Object
Used in `AfterModel` and as a synthetic response in `BeforeModel`.
```typescript
{
"text"?: string,
"candidates": Array<{
"content": {
"role": "model",
"parts": string[]
},
"finishReason"?: "STOP" | "MAX_TOKENS" | "SAFETY" | "RECITATION" | "OTHER",
"index"?: number,
"safetyRatings"?: Array<{
"category": string,
"probability": string,
"blocked"?: boolean
}>
}>,
"usageMetadata"?: {
"promptTokenCount"?: number,
"candidatesTokenCount"?: number,
"totalTokenCount"?: number
}
}
```
File diff suppressed because it is too large Load Diff
+23 -23
View File
@@ -1,4 +1,4 @@
# Gemini CLI companion plugin: Interface specification
# Gemini CLI Companion Plugin: Interface Specification
> Last Updated: September 15, 2025
@@ -9,11 +9,11 @@ awareness) are provided by the official extension
This specification is for contributors who wish to bring similar functionality
to other editors like JetBrains IDEs, Sublime Text, etc.
## I. The communication interface
## I. The Communication Interface
Gemini CLI and the IDE plugin communicate through a local communication channel.
### 1. Transport layer: MCP over HTTP
### 1. Transport Layer: MCP over HTTP
The plugin **MUST** run a local HTTP server that implements the **Model Context
Protocol (MCP)**.
@@ -25,24 +25,24 @@ Protocol (MCP)**.
- **Port:** The server **MUST** listen on a dynamically assigned port (i.e.,
listen on port `0`).
### 2. Discovery mechanism: The port file
### 2. Discovery Mechanism: The Port File
For Gemini CLI to connect, it needs to discover which IDE instance it's running
in and what port your server is using. The plugin **MUST** facilitate this by
creating a "discovery file."
- **How the CLI finds the file:** The CLI determines the Process ID (PID) of the
- **How the CLI Finds the File:** The CLI determines the Process ID (PID) of the
IDE it's running in by traversing the process tree. It then looks for a
discovery file that contains this PID in its name.
- **File location:** The file must be created in a specific directory:
- **File Location:** The file must be created in a specific directory:
`os.tmpdir()/gemini/ide/`. Your plugin must create this directory if it
doesn't exist.
- **File naming convention:** The filename is critical and **MUST** follow the
- **File Naming Convention:** The filename is critical and **MUST** follow the
pattern: `gemini-ide-server-${PID}-${PORT}.json`
- `${PID}`: The process ID of the parent IDE process. Your plugin must
determine this PID and include it in the filename.
- `${PORT}`: The port your MCP server is listening on.
- **File content and workspace validation:** The file **MUST** contain a JSON
- **File Content & Workspace Validation:** The file **MUST** contain a JSON
object with the following structure:
```json
@@ -79,7 +79,7 @@ creating a "discovery file."
server (e.g., `Authorization: Bearer a-very-secret-token`). Your server
**MUST** validate this token on every request and reject any that are
unauthorized.
- **Tie-breaking with environment variables (recommended):** For the most
- **Tie-Breaking with Environment Variables (Recommended):** For the most
reliable experience, your plugin **SHOULD** both create the discovery file and
set the `GEMINI_CLI_IDE_SERVER_PORT` environment variable in the integrated
terminal. The file serves as the primary discovery mechanism, but the
@@ -88,18 +88,18 @@ creating a "discovery file."
`GEMINI_CLI_IDE_SERVER_PORT` variable to identify and connect to the correct
window's server.
## II. The context interface
## II. The Context Interface
To enable context awareness, the plugin **MAY** provide the CLI with real-time
information about the user's activity in the IDE.
### `ide/contextUpdate` notification
### `ide/contextUpdate` Notification
The plugin **MAY** send an `ide/contextUpdate`
[notification](https://modelcontextprotocol.io/specification/2025-06-18/basic/index#notifications)
to the CLI whenever the user's context changes.
- **Triggering events:** This notification should be sent (with a recommended
- **Triggering Events:** This notification should be sent (with a recommended
debounce of 50ms) when:
- A file is opened, closed, or focused.
- The user's cursor position or text selection changes in the active file.
@@ -136,16 +136,16 @@ to the CLI whenever the user's context changes.
Virtual files (e.g., unsaved files without a path, editor settings pages)
**MUST** be excluded.
### How the CLI uses this context
### How the CLI Uses This Context
After receiving the `IdeContext` object, the CLI performs several normalization
and truncation steps before sending the information to the model.
- **File ordering:** The CLI uses the `timestamp` field to determine the most
- **File Ordering:** The CLI uses the `timestamp` field to determine the most
recently used files. It sorts the `openFiles` list based on this value.
Therefore, your plugin **MUST** provide an accurate Unix timestamp for when a
file was last focused.
- **Active file:** The CLI considers only the most recent file (after sorting)
- **Active File:** The CLI considers only the most recent file (after sorting)
to be the "active" file. It will ignore the `isActive` flag on all other files
and clear their `cursor` and `selectedText` fields. Your plugin should focus
on setting `isActive: true` and providing cursor/selection details only for
@@ -156,14 +156,14 @@ and truncation steps before sending the information to the model.
While the CLI handles the final truncation, it is highly recommended that your
plugin also limits the amount of context it sends.
## III. The diffing interface
## III. The Diffing Interface
To enable interactive code modifications, the plugin **MAY** expose a diffing
interface. This allows the CLI to request that the IDE open a diff view, showing
proposed changes to a file. The user can then review, edit, and ultimately
accept or reject these changes directly within the IDE.
### `openDiff` tool
### `openDiff` Tool
The plugin **MUST** register an `openDiff` tool on its MCP server.
@@ -194,7 +194,7 @@ The plugin **MUST** register an `openDiff` tool on its MCP server.
The actual outcome of the diff (acceptance or rejection) is communicated
asynchronously via notifications.
### `closeDiff` tool
### `closeDiff` Tool
The plugin **MUST** register a `closeDiff` tool on its MCP server.
@@ -219,7 +219,7 @@ The plugin **MUST** register a `closeDiff` tool on its MCP server.
**MUST** have `isError: true` and include a `TextContent` block in the
`content` array describing the error.
### `ide/diffAccepted` notification
### `ide/diffAccepted` Notification
When the user accepts the changes in a diff view (e.g., by clicking an "Apply"
or "Save" button), the plugin **MUST** send an `ide/diffAccepted` notification
@@ -238,7 +238,7 @@ to the CLI.
}
```
### `ide/diffRejected` notification
### `ide/diffRejected` Notification
When the user rejects the changes (e.g., by closing the diff view without
accepting), the plugin **MUST** send an `ide/diffRejected` notification to the
@@ -254,14 +254,14 @@ CLI.
}
```
## IV. The lifecycle interface
## IV. The Lifecycle Interface
The plugin **MUST** manage its resources and the discovery file correctly based
on the IDE's lifecycle.
- **On activation (IDE startup/plugin enabled):**
- **On Activation (IDE startup/plugin enabled):**
1. Start the MCP server.
2. Create the discovery file.
- **On deactivation (IDE shutdown/plugin disabled):**
- **On Deactivation (IDE shutdown/plugin disabled):**
1. Stop the MCP server.
2. Delete the discovery file.
+19 -19
View File
@@ -1,4 +1,4 @@
# IDE integration
# IDE Integration
Gemini CLI can integrate with your IDE to provide a more seamless and
context-aware experience. This integration allows the CLI to understand your
@@ -11,18 +11,18 @@ support VS Code extensions. To build support for other editors, see the
## Features
- **Workspace context:** The CLI automatically gains awareness of your workspace
- **Workspace Context:** The CLI automatically gains awareness of your workspace
to provide more relevant and accurate responses. This context includes:
- The **10 most recently accessed files** in your workspace.
- Your active cursor position.
- Any text you have selected (up to a 16KB limit; longer selections will be
truncated).
- **Native diffing:** When Gemini suggests code modifications, you can view the
- **Native Diffing:** When Gemini suggests code modifications, you can view the
changes directly within your IDE's native diff viewer. This allows you to
review, edit, and accept or reject the suggested changes seamlessly.
- **VS Code commands:** You can access Gemini CLI features directly from the VS
- **VS Code Commands:** You can access Gemini CLI features directly from the VS
Code Command Palette (`Cmd+Shift+P` or `Ctrl+Shift+P`):
- `Gemini CLI: Run`: Starts a new Gemini CLI session in the integrated
terminal.
@@ -32,18 +32,18 @@ support VS Code extensions. To build support for other editors, see the
- `Gemini CLI: View Third-Party Notices`: Displays the third-party notices for
the extension.
## Installation and setup
## Installation and Setup
There are three ways to set up the IDE integration:
### 1. Automatic nudge (recommended)
### 1. Automatic Nudge (Recommended)
When you run Gemini CLI inside a supported editor, it will automatically detect
your environment and prompt you to connect. Answering "Yes" will automatically
run the necessary setup, which includes installing the companion extension and
enabling the connection.
### 2. Manual installation from CLI
### 2. Manual Installation from CLI
If you previously dismissed the prompt or want to install the extension
manually, you can run the following command inside Gemini CLI:
@@ -54,13 +54,13 @@ manually, you can run the following command inside Gemini CLI:
This will find the correct extension for your IDE and install it.
### 3. Manual installation from a marketplace
### 3. Manual Installation from a Marketplace
You can also install the extension directly from a marketplace.
- **For Visual Studio Code:** Install from the
[VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=google.gemini-cli-vscode-ide-companion).
- **For VS Code forks:** To support forks of VS Code, the extension is also
- **For VS Code Forks:** To support forks of VS Code, the extension is also
published on the
[Open VSX Registry](https://open-vsx.org/extension/google/gemini-cli-vscode-ide-companion).
Follow your editor's instructions for installing extensions from this
@@ -75,7 +75,7 @@ You can also install the extension directly from a marketplace.
## Usage
### Enabling and disabling
### Enabling and Disabling
You can control the IDE integration from within the CLI:
@@ -91,7 +91,7 @@ You can control the IDE integration from within the CLI:
When enabled, Gemini CLI will automatically attempt to connect to the IDE
companion extension.
### Checking the status
### Checking the Status
To check the connection status and see the context the CLI has received from the
IDE, run:
@@ -106,7 +106,7 @@ recently opened files it is aware of.
> [!NOTE] The file list is limited to 10 recently accessed files within your
> workspace and only includes local files on disk.)
### Working with diffs
### Working with Diffs
When you ask Gemini to modify a file, it can open a diff view directly in your
editor.
@@ -128,17 +128,17 @@ editor.
You can also **modify the suggested changes** directly in the diff view before
accepting them.
If you select Allow for this session in the CLI, changes will no longer show
up in the IDE as they will be auto-accepted.
If you select Yes, allow always in the CLI, changes will no longer show up in
the IDE as they will be auto-accepted.
## Using with sandboxing
## Using with Sandboxing
If you are using Gemini CLI within a sandbox, please be aware of the following:
- **On macOS:** The IDE integration requires network access to communicate with
the IDE companion extension. You must use a Seatbelt profile that allows
network access.
- **In a Docker container:** If you run Gemini CLI inside a Docker (or Podman)
- **In a Docker Container:** If you run Gemini CLI inside a Docker (or Podman)
container, the IDE integration can still connect to the VS Code extension
running on your host machine. The CLI is configured to automatically find the
IDE server on `host.docker.internal`. No special configuration is usually
@@ -150,7 +150,7 @@ If you are using Gemini CLI within a sandbox, please be aware of the following:
If you encounter issues with IDE integration, here are some common error
messages and how to resolve them.
### Connection errors
### Connection Errors
- **Message:**
`🔴 Disconnected: Failed to connect to IDE companion extension in [IDE Name]. Please ensure the extension is running. To install the extension, run /ide install.`
@@ -170,7 +170,7 @@ messages and how to resolve them.
- **Solution:** Run `/ide enable` to try and reconnect. If the issue
continues, open a new terminal window or restart your IDE.
### Configuration errors
### Configuration Errors
- **Message:**
`🔴 Disconnected: Directory mismatch. Gemini CLI is running in a different location than the open workspace in [IDE Name]. Please run the CLI from one of the following directories: [List of directories]`
@@ -184,7 +184,7 @@ messages and how to resolve them.
- **Cause:** You have no workspace open in your IDE.
- **Solution:** Open a workspace in your IDE and restart the CLI.
### General errors
### General Errors
- **Message:**
`IDE integration is not supported in your current environment. To use this feature, run Gemini CLI in one of these supported IDEs: [List of IDEs]`
+49 -85
View File
@@ -1,10 +1,10 @@
# Welcome to Gemini CLI documentation
This documentation provides a comprehensive guide to installing, using, and
developing Gemini CLI, a tool that lets you interact with Gemini models through
a command-line interface.
developing Gemini CLI. This tool lets you interact with Gemini models through a
command-line interface.
## Gemini CLI overview
## Overview
Gemini CLI brings the capabilities of Gemini models to your terminal in an
interactive Read-Eval-Print Loop (REPL) environment. Gemini CLI consists of a
@@ -18,130 +18,94 @@ file system operations, running shells, and web fetching, which are managed by
This documentation is organized into the following sections:
### Overview
- **[Architecture overview](./architecture.md):** Understand the high-level
design of Gemini CLI, including its components and how they interact.
- **[Contribution guide](../CONTRIBUTING.md):** Information for contributors and
developers, including setup, building, testing, and coding conventions.
### Get started
- **[Gemini CLI quickstart](./get-started/index.md):** Let's get started with
- **[Gemini CLI Quickstart](./get-started/index.md):** Let's get started with
Gemini CLI.
- **[Gemini 3 Pro on Gemini CLI](./get-started/gemini-3.md):** Learn how to
enable and use Gemini 3.
- **[Authentication](./get-started/authentication.md):** Authenticate to Gemini
CLI.
- **[Configuration](./get-started/configuration.md):** Learn how to configure
the CLI.
- **[Installation](./get-started/installation.md):** Install and run Gemini CLI.
- **[Authentication](./get-started/authentication.md):** Authenticate Gemini
CLI.
- **[Configuration](./get-started/configuration.md):** Information on
configuring the CLI.
- **[Examples](./get-started/examples.md):** Example usage of Gemini CLI.
- **[Get started with Gemini 3](./get-started/gemini-3.md):** Learn how to
enable and use Gemini 3.
### CLI
- **[Introduction: Gemini CLI](./cli/index.md):** Overview of the command-line
interface.
- **[CLI overview](./cli/index.md):** Overview of the command-line interface.
- **[Commands](./cli/commands.md):** Description of available CLI commands.
- **[Checkpointing](./cli/checkpointing.md):** Documentation for the
checkpointing feature.
- **[Custom commands](./cli/custom-commands.md):** Create your own commands and
shortcuts for frequently used prompts.
- **[Enterprise](./cli/enterprise.md):** Gemini CLI for enterprise.
- **[Headless mode](./cli/headless.md):** Use Gemini CLI programmatically for
scripting and automation.
- **[Keyboard shortcuts](./cli/keyboard-shortcuts.md):** A reference for all
keyboard shortcuts to improve your workflow.
- **[Model selection](./cli/model.md):** Select the model used to process your
- **[Model Selection](./cli/model.md):** Select the model used to process your
commands with `/model`.
- **[Sandbox](./cli/sandbox.md):** Isolate tool execution in a secure,
containerized environment.
- **[Settings](./cli/settings.md):** Configure various aspects of the CLI's
behavior and appearance with `/settings`.
- **[Telemetry](./cli/telemetry.md):** Overview of telemetry in the CLI.
- **[Themes](./cli/themes.md):** Themes for Gemini CLI.
- **[Token caching](./cli/token-caching.md):** Token caching and optimization.
- **[Token Caching](./cli/token-caching.md):** Token caching and optimization.
- **[Tutorials](./cli/tutorials.md):** Tutorials for Gemini CLI.
- **[Checkpointing](./cli/checkpointing.md):** Documentation for the
checkpointing feature.
- **[Telemetry](./cli/telemetry.md):** Overview of telemetry in the CLI.
- **[Trusted Folders](./cli/trusted-folders.md):** An overview of the Trusted
Folders security feature.
- **[Tutorials](./cli/tutorials.md):** Tutorials for Gemini CLI.
- **[Uninstall](./cli/uninstall.md):** Methods for uninstalling the Gemini CLI.
### Core
- **[Introduction: Gemini CLI core](./core/index.md):** Information about Gemini
CLI core.
- **[Gemini CLI core overview](./core/index.md):** Information about Gemini CLI
core.
- **[Memport](./core/memport.md):** Using the Memory Import Processor.
- **[Tools API](./core/tools-api.md):** Information on how the core manages and
exposes tools.
- **[System Prompt Override](./cli/system-prompt.md):** Replace built-in system
instructions using `GEMINI_SYSTEM_MD`.
- **[Policy Engine](./core/policy-engine.md):** Use the Policy Engine for
fine-grained control over tool execution.
### Tools
- **[Introduction: Gemini CLI tools](./tools/index.md):** Information about
Gemini CLI's tools.
- **[File system tools](./tools/file-system.md):** Documentation for the
- **[Gemini CLI tools overview](./tools/index.md):** Information about Gemini
CLI's tools.
- **[File System Tools](./tools/file-system.md):** Documentation for the
`read_file` and `write_file` tools.
- **[Shell tool](./tools/shell.md):** Documentation for the `run_shell_command`
tool.
- **[Web fetch tool](./tools/web-fetch.md):** Documentation for the `web_fetch`
tool.
- **[Web search tool](./tools/web-search.md):** Documentation for the
`google_web_search` tool.
- **[Memory tool](./tools/memory.md):** Documentation for the `save_memory`
tool.
- **[Todo tool](./tools/todos.md):** Documentation for the `write_todos` tool.
- **[MCP servers](./tools/mcp-server.md):** Using MCP servers with Gemini CLI.
- **[Shell Tool](./tools/shell.md):** Documentation for the `run_shell_command`
tool.
- **[Web Fetch Tool](./tools/web-fetch.md):** Documentation for the `web_fetch`
tool.
- **[Web Search Tool](./tools/web-search.md):** Documentation for the
`google_web_search` tool.
- **[Memory Tool](./tools/memory.md):** Documentation for the `save_memory`
tool.
- **[Todo Tool](./tools/todos.md):** Documentation for the `write_todos` tool.
### Extensions
- **[Introduction: Extensions](./extensions/index.md):** How to extend the CLI
with new functionality.
- **[Get Started with extensions](./extensions/getting-started-extensions.md):**
- **[Extensions](./extensions/index.md):** How to extend the CLI with new
functionality.
- **[Get Started with Extensions](./extensions/getting-started-extensions.md):**
Learn how to build your own extension.
- **[Extension releasing](./extensions/extension-releasing.md):** How to release
- **[Extension Releasing](./extensions/extension-releasing.md):** How to release
Gemini CLI extensions.
### Hooks
- **[Hooks](./hooks/index.md):** Intercept and customize Gemini CLI behavior at
key lifecycle points.
- **[Writing Hooks](./hooks/writing-hooks.md):** Learn how to create your first
hook with a comprehensive example.
- **[Best Practices](./hooks/best-practices.md):** Security, performance, and
debugging guidelines for hooks.
### IDE integration
- **[Introduction to IDE integration](./ide-integration/index.md):** Connect the
CLI to your editor.
- **[IDE companion extension spec](./ide-integration/ide-companion-spec.md):**
- **[IDE Integration](./ide-integration/index.md):** Connect the CLI to your
editor.
- **[IDE Companion Extension Spec](./ide-integration/ide-companion-spec.md):**
Spec for building IDE companion extensions.
### Development
### About the Gemini CLI project
- **[Architecture Overview](./architecture.md):** Understand the high-level
design of Gemini CLI, including its components and how they interact.
- **[Contributing & Development Guide](../CONTRIBUTING.md):** Information for
contributors and developers, including setup, building, testing, and coding
conventions.
- **[NPM](./npm.md):** Details on how the project's packages are structured.
- **[Troubleshooting Guide](./troubleshooting.md):** Find solutions to common
problems.
- **[FAQ](./faq.md):** Frequently asked questions.
- **[Terms of Service and Privacy Notice](./tos-privacy.md):** Information on
the terms of service and privacy notices applicable to your use of Gemini CLI.
- **[Releases](./releases.md):** Information on the project's releases and
deployment cadence.
- **[Changelog](./changelogs/index.md):** Highlights and notable changes to
Gemini CLI.
- **[Integration tests](./integration-tests.md):** Information about the
integration testing framework used in this project.
- **[Issue and PR automation](./issue-and-pr-automation.md):** A detailed
overview of the automated processes we use to manage and triage issues and
pull requests.
### Support
- **[FAQ](./faq.md):** Frequently asked questions.
- **[Troubleshooting guide](./troubleshooting.md):** Find solutions to common
problems.
- **[Quota and pricing](./quota-and-pricing.md):** Learn about the free tier and
paid options.
- **[Terms of service and privacy notice](./tos-privacy.md):** Information on
the terms of service and privacy notices applicable to your use of Gemini CLI.
We hope this documentation helps you make the most of Gemini CLI!
+5 -5
View File
@@ -1,4 +1,4 @@
# Integration tests
# Integration Tests
This document provides information about the integration testing framework used
in this project.
@@ -86,7 +86,7 @@ with the deflake script or workflow to make sure that it is not flaky.
npm run deflake -- --runs=5 --command="npm run test:e2e -- -- --test-name-pattern '<your-new-test-name>'"
```
#### Deflake workflow
#### Deflake Workflow
```bash
gh workflow run deflake.yml --ref <your-branch> -f test_name_pattern="<your-test-name-pattern>"
@@ -199,9 +199,9 @@ file, or case.
## Continuous integration
To ensure the integration tests are always run, a GitHub Actions workflow is
defined in `.github/workflows/chained_e2e.yml`. This workflow automatically runs
the integrations tests for pull requests against the `main` branch, or when a
pull request is added to a merge queue.
defined in `.github/workflows/e2e.yml`. This workflow automatically runs the
integrations tests for pull requests against the `main` branch, or when a pull
request is added to a merge queue.
The workflow runs the tests in different sandboxing environments to ensure
Gemini CLI is tested across each:
+8 -11
View File
@@ -1,4 +1,4 @@
# Automation and triage processes
# Automation and Triage Processes
This document provides a detailed overview of the automated processes we use to
manage and triage issues and pull requests. Our goal is to provide prompt
@@ -6,7 +6,7 @@ feedback and ensure that contributions are reviewed and integrated efficiently.
Understanding this automation will help you as a contributor know what to expect
and how to best interact with our repository bots.
## Guiding principle: Issues and pull requests
## Guiding Principle: Issues and Pull Requests
First and foremost, almost every Pull Request (PR) should be linked to a
corresponding Issue. The issue describes the "what" and the "why" (the bug or
@@ -14,17 +14,14 @@ feature), while the PR is the "how" (the implementation). This separation helps
us track work, prioritize features, and maintain clear historical context. Our
automation is built around this principle.
> **Note:** Issues tagged as "🔒Maintainers only" are reserved for project
> maintainers. We will not accept pull requests related to these issues.
---
## Detailed automation workflows
## Detailed Automation Workflows
Here is a breakdown of the specific automation workflows that run in our
repository.
### 1. When you open an issue: `Automated Issue Triage`
### 1. When you open an Issue: `Automated Issue Triage`
This is the first bot you will interact with when you create an issue. Its job
is to perform an initial analysis and apply the correct labels.
@@ -51,7 +48,7 @@ is to perform an initial analysis and apply the correct labels.
- If the `status/need-information` label is added, please provide the
requested details in a comment.
### 2. When you open a pull request: `Continuous Integration (CI)`
### 2. When you open a Pull Request: `Continuous Integration (CI)`
This workflow ensures that all changes meet our quality standards before they
can be merged.
@@ -73,7 +70,7 @@ can be merged.
- If a check fails (a red "X" ❌), click the "Details" link next to the failed
check to view the logs, identify the problem, and push a fix.
### 3. Ongoing triage for pull requests: `PR Auditing and Label Sync`
### 3. Ongoing Triage for Pull Requests: `PR Auditing and Label Sync`
This workflow runs periodically to ensure all open PRs are correctly linked to
issues and have consistent labels.
@@ -96,7 +93,7 @@ issues and have consistent labels.
- This will ensure your PR is correctly categorized and moves through the
review process smoothly.
### 4. Ongoing triage for issues: `Scheduled Issue Triage`
### 4. Ongoing Triage for Issues: `Scheduled Issue Triage`
This is a fallback workflow to ensure that no issue gets missed by the triage
process.
@@ -113,7 +110,7 @@ process.
ensure every issue is eventually categorized, even if the initial triage
fails.
### 5. Release automation
### 5. Release Automation
This workflow handles the process of packaging and publishing new versions of
the Gemini CLI.
+7 -7
View File
@@ -1,9 +1,9 @@
# Local development guide
# Local Development Guide
This guide provides instructions for setting up and using local development
features, such as development tracing.
## Development tracing
## Development Tracing
Development traces (dev traces) are OpenTelemetry (OTel) traces that help you
debug your code by instrumenting interesting events like model calls, tool
@@ -15,7 +15,7 @@ behaviour and debugging issues. They are disabled by default.
To enable dev traces, set the `GEMINI_DEV_TRACING=true` environment variable
when running Gemini CLI.
### Viewing dev traces
### Viewing Dev Traces
You can view dev traces using either Jaeger or the Genkit Developer UI.
@@ -23,7 +23,7 @@ You can view dev traces using either Jaeger or the Genkit Developer UI.
Genkit provides a web-based UI for viewing traces and other telemetry data.
1. **Start the Genkit telemetry server:**
1. **Start the Genkit Telemetry Server:**
Run the following command to start the Genkit server:
@@ -37,7 +37,7 @@ Genkit provides a web-based UI for viewing traces and other telemetry data.
Genkit Developer UI: http://localhost:4000
```
2. **Run Gemini CLI with dev tracing:**
2. **Run Gemini CLI with Dev Tracing:**
In a separate terminal, run your Gemini CLI command with the
`GEMINI_DEV_TRACING` environment variable:
@@ -46,7 +46,7 @@ Genkit provides a web-based UI for viewing traces and other telemetry data.
GEMINI_DEV_TRACING=true gemini
```
3. **View the traces:**
3. **View the Traces:**
Open the Genkit Developer UI URL in your browser and navigate to the
**Traces** tab to view the traces.
@@ -84,7 +84,7 @@ You can view dev traces in the Jaeger UI. To get started, follow these steps:
For more detailed information on telemetry, see the
[telemetry documentation](./cli/telemetry.md).
### Instrumenting code with dev traces
### Instrumenting Code with Dev Traces
You can add dev traces to your own code for more detailed instrumentation. This
is useful for debugging and understanding the flow of execution.
+7 -7
View File
@@ -1,4 +1,4 @@
# Package overview
# Package Overview
This monorepo contains two main packages: `@google/gemini-cli` and
`@google/gemini-cli-core`.
@@ -25,7 +25,7 @@ Node.js package with its own dependencies. This allows it to be used as a
standalone package in other projects, if needed. All transpiled js code in the
`dist` folder is included in the package.
## NPM workspaces
## NPM Workspaces
This project uses
[NPM Workspaces](https://docs.npmjs.com/cli/v10/using-npm/workspaces) to manage
@@ -33,7 +33,7 @@ the packages within this monorepo. This simplifies development by allowing us to
manage dependencies and run scripts across multiple packages from the root of
the project.
### How it works
### How it Works
The root `package.json` file defines the workspaces for this project:
@@ -46,17 +46,17 @@ The root `package.json` file defines the workspaces for this project:
This tells NPM that any folder inside the `packages` directory is a separate
package that should be managed as part of the workspace.
### Benefits of workspaces
### Benefits of Workspaces
- **Simplified dependency management**: Running `npm install` from the root of
- **Simplified Dependency Management**: Running `npm install` from the root of
the project will install all dependencies for all packages in the workspace
and link them together. This means you don't need to run `npm install` in each
package's directory.
- **Automatic linking**: Packages within the workspace can depend on each other.
- **Automatic Linking**: Packages within the workspace can depend on each other.
When you run `npm install`, NPM will automatically create symlinks between the
packages. This means that when you make changes to one package, the changes
are immediately available to other packages that depend on it.
- **Simplified script execution**: You can run scripts in any package from the
- **Simplified Script Execution**: You can run scripts in any package from the
root of the project using the `--workspace` flag. For example, to run the
`build` script in the `cli` package, you can run
`npm run build --workspace @google/gemini-cli`.
+23 -19
View File
@@ -1,17 +1,20 @@
# Gemini CLI: Quotas and pricing
# Gemini CLI: Quotas and Pricing
Gemini CLI offers a generous free tier that covers many individual developers'
use cases. For enterprise or professional usage, or if you need higher limits,
several options are available depending on your authentication account type.
Gemini CLI offers a generous free tier that covers the use cases for many
individual developers. For enterprise / professional usage, or if you need
higher limits, there are multiple possible avenues depending on what type of
account you use to authenticate.
See [privacy and terms](./tos-privacy.md) for details on the Privacy Policy and
See [privacy and terms](./tos-privacy.md) for details on Privacy policy and
Terms of Service.
> **Note:** Published prices are list price; additional negotiated commercial
> discounting may apply.
> [!NOTE]
>
> Published prices are list price; additional negotiated commercial discounting
> may apply.
This article outlines the specific quotas and pricing applicable to Gemini CLI
when using different authentication methods.
This article outlines the specific quotas and pricing applicable to the Gemini
CLI when using different authentication methods.
Generally, there are three categories to choose from:
@@ -21,7 +24,7 @@ Generally, there are three categories to choose from:
- Pay-As-You-Go: The most flexible option for professional use, long-running
tasks, or when you need full control over your usage.
## Free usage
## Free Usage
Your journey begins with a generous free tier, perfect for experimentation and
light use.
@@ -41,7 +44,7 @@ Assist for individuals. This includes:
Learn more at
[Gemini Code Assist for Individuals Limits](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli).
### Log in with Gemini API Key (unpaid)
### Log in with Gemini API Key (Unpaid)
If you are using a Gemini API key, you can also benefit from a free tier. This
includes:
@@ -69,9 +72,11 @@ Learn more at
If you use up your initial number of requests, you can continue to benefit from
Gemini CLI by upgrading to one of the following subscriptions:
- [Google AI Pro and AI Ultra](https://gemini.google/subscriptions/). This is
recommended for individual developers. Quotas and pricing are based on a fixed
price subscription.
- [Google AI Pro and AI Ultra](https://cloud.google.com/products/gemini/pricing)
by signing up at
[Set up Gemini Code Assist](https://goo.gle/set-up-gemini-code-assist). This
is recommended for individual developers. Quotas and pricing are based on a
fixed price subscription.
For predictable costs, you can log in with Google.
@@ -80,8 +85,7 @@ Gemini CLI by upgrading to one of the following subscriptions:
- [Purchase a Gemini Code Assist Subscription through Google Cloud ](https://cloud.google.com/gemini/docs/codeassist/overview)
by signing up in the Google Cloud console. Learn more at
[Set up Gemini Code Assist](https://cloud.google.com/gemini/docs/discover/set-up-gemini).
[Set up Gemini Code Assist](https://cloud.google.com/gemini/docs/discover/set-up-gemini)
Quotas and pricing are based on a fixed price subscription with assigned
license seats. For predictable costs, you can sign in with Google.
@@ -97,7 +101,7 @@ Gemini CLI by upgrading to one of the following subscriptions:
[Learn more about Gemini Code Assist Standard and Enterprise license limits](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli).
## Pay as you go
## Pay As You Go
If you hit your daily request limits or exhaust your Gemini Pro quota even after
upgrading, the most flexible solution is to switch to a pay-as-you-go model,
@@ -127,7 +131,7 @@ Its important to highlight that when using an API key, you pay per token/call
This can be more expensive for many small calls with few tokens, but it's the
only way to ensure your workflow isn't interrupted by quota limits.
## Gemini for workspace plans
## Gemini for Workspace plans
These plans currently apply only to the use of Gemini web-based products
provided by Google-based experiences (for example, the Gemini web app or the
@@ -135,7 +139,7 @@ Flow video editor). These plans do not apply to the API usage which powers the
Gemini CLI. Supporting these plans is under active consideration for future
support.
## Tips to avoid high costs
## Tips to Avoid High Costs
When using a Pay as you Go API key, be mindful of your usage to avoid unexpected
costs.
+21 -21
View File
@@ -1,21 +1,21 @@
# Release confidence strategy
# Release Confidence Strategy
This document outlines the strategy for gaining confidence in every release of
the Gemini CLI. It serves as a checklist and quality gate for release manager to
ensure we are shipping a high-quality product.
## The goal
## The Goal
To answer the question, "Is this release _truly_ ready for our users?" with a
high degree of confidence, based on a holistic evaluation of automated signals,
manual verification, and data.
## Level 1: Automated gates (must pass)
## Level 1: Automated Gates (Must Pass)
These are the baseline requirements. If any of these fail, the release is a
no-go.
### 1. CI/CD health
### 1. CI/CD Health
All workflows in `.github/workflows/ci.yml` must pass on the `main` branch (for
nightly) or the release branch (for preview/stable).
@@ -31,15 +31,15 @@ nightly) or the release branch (for preview/stable).
pass.
- **Build:** The project must build and bundle successfully.
### 2. End-to-end (E2E) tests
### 2. End-to-End (E2E) Tests
All workflows in `.github/workflows/chained_e2e.yml` must pass.
All workflows in `.github/workflows/e2e.yml` must pass.
- **Platforms:** **Linux, macOS and Windows**.
- **Sandboxing:** Tests must pass with both `sandbox:none` and `sandbox:docker`
on Linux.
### 3. Post-deployment smoke tests
### 3. Post-Deployment Smoke Tests
After a release is published to npm, the `smoke-test.yml` workflow runs. This
must pass to confirm the package is installable and the binary is executable.
@@ -48,11 +48,11 @@ must pass to confirm the package is installable and the binary is executable.
correct version without error.
- **Platform:** Currently runs on `ubuntu-latest`.
## Level 2: Manual verification and dogfooding
## Level 2: Manual Verification & Dogfooding
Automated tests cannot catch everything, especially UX issues.
### 1. Dogfooding via `preview` tag
### 1. Dogfooding via `preview` Tag
The weekly release cadence promotes code from `main` -> `nightly` -> `preview`
-> `stable`.
@@ -66,7 +66,7 @@ The weekly release cadence promotes code from `main` -> `nightly` -> `preview`
- **Goal:** To catch regressions and UX issues in day-to-day usage before they
reach the broad user base.
### 2. Critical user journey (CUJ) checklist
### 2. Critical User Journey (CUJ) Checklist
Before promoting a `preview` release to `stable`, a release manager must
manually run through this checklist.
@@ -84,15 +84,15 @@ manually run through this checklist.
- [ ] API Key
- [ ] Vertex AI
- **Basic prompting:**
- **Basic Prompting:**
- [ ] Run `gemini "Tell me a joke"` and verify a sensible response.
- [ ] Run in interactive mode: `gemini`. Ask a follow-up question to test
context.
- **Piped input:**
- **Piped Input:**
- [ ] Run `echo "Summarize this" | gemini` and verify it processes stdin.
- **Context management:**
- **Context Management:**
- [ ] In interactive mode, use `@file` to add a local file to context. Ask a
question about it.
@@ -100,20 +100,20 @@ manually run through this checklist.
- [ ] In interactive mode run `/settings` and make modifications
- [ ] Validate that setting is changed
- **Function calling:**
- **Function Calling:**
- [ ] In interactive mode, ask gemini to "create a file named hello.md with
the content 'hello world'" and verify the file is created correctly.
If any of these CUJs fail, the release is a no-go until a patch is applied to
the `preview` channel.
### 3. Pre-Launch bug bash (tier 1 and 2 launches)
### 3. Pre-Launch Bug Bash (Tier 1 & 2 Launches)
For high-impact releases, an organized bug bash is required to ensure a higher
level of quality and to catch issues across a wider range of environments and
use cases.
**Definition of tiers:**
**Definition of Tiers:**
- **Tier 1:** Industry-Moving News 🚀
- **Tier 2:** Important News for Our Users 📣
@@ -125,7 +125,7 @@ use cases.
A bug bash must be scheduled at least **72 hours in advance** of any Tier 1 or
Tier 2 launch.
**Rule of thumb:**
**Rule of Thumb:**
A bug bash should be considered for any release that involves:
@@ -134,22 +134,22 @@ A bug bash should be considered for any release that involves:
- Media relations or press outreach
- A "Turbo" launch event
## Level 3: Telemetry and data review
## Level 3: Telemetry & Data Review
### Dashboard health
### Dashboard Health
- [ ] Go to `go/gemini-cli-dash`.
- [ ] Navigate to the "Tool Call" tab.
- [ ] Validate that there are no spikes in errors for the release you would like
to promote.
### Model evaluation
### Model Evaluation
- [ ] Navigate to `go/gemini-cli-offline-evals-dash`.
- [ ] Make sure that the release you want to promote's recurring run is within
average eval runs.
## The "go/no-go" decision
## The "Go/No-Go" Decision
Before triggering the `Release: Promote` workflow to move `preview` to `stable`:
+40 -40
View File
@@ -1,4 +1,4 @@
# Gemini CLI releases
# Gemini CLI Releases
## `dev` vs `prod` environment
@@ -22,7 +22,7 @@ More information can be found about these systems in the
| Core | @google/gemini-cli-core | @google-gemini/gemini-cli-core A2A Server |
| A2A Server | @google/gemini-cli-a2a-server | @google-gemini/gemini-cli-a2a-server |
## Release cadence and tags
## Release Cadence and Tags
We will follow https://semver.org/ as closely as possible but will call out when
or if we have to deviate from it. Our weekly releases will be minor version
@@ -66,24 +66,24 @@ npm install -g @google/gemini-cli@latest
npm install -g @google/gemini-cli@nightly
```
## Weekly release promotion
## Weekly Release Promotion
Each Tuesday, the on-call engineer will trigger the "Promote Release" workflow.
This single action automates the entire weekly release process:
1. **Promotes preview to stable:** The workflow identifies the latest `preview`
1. **Promotes Preview to Stable:** The workflow identifies the latest `preview`
release and promotes it to `stable`. This becomes the new `latest` version
on npm.
2. **Promotes nightly to preview:** The latest `nightly` release is then
2. **Promotes Nightly to Preview:** The latest `nightly` release is then
promoted to become the new `preview` version.
3. **Prepares for next nightly:** A pull request is automatically created and
3. **Prepares for next Nightly:** A pull request is automatically created and
merged to bump the version in `main` in preparation for the next nightly
release.
This process ensures a consistent and reliable release cadence with minimal
manual intervention.
### Source of truth for versioning
### Source of Truth for Versioning
To ensure the highest reliability, the release promotion process uses the **NPM
registry as the single source of truth** for determining the current version of
@@ -92,16 +92,16 @@ each release channel (`stable`, `preview`, and `nightly`).
1. **Fetch from NPM:** The workflow begins by querying NPM's `dist-tags`
(`latest`, `preview`, `nightly`) to get the exact version strings for the
packages currently available to users.
2. **Cross-check for integrity:** For each version retrieved from NPM, the
2. **Cross-Check for Integrity:** For each version retrieved from NPM, the
workflow performs a critical integrity check:
- It verifies that a corresponding **git tag** exists in the repository.
- It verifies that a corresponding **GitHub release** has been created.
3. **Halt on discrepancy:** If either the git tag or the GitHub Release is
- It verifies that a corresponding **GitHub Release** has been created.
3. **Halt on Discrepancy:** If either the git tag or the GitHub Release is
missing for a version listed on NPM, the workflow will immediately fail.
This strict check prevents promotions from a broken or incomplete previous
release and alerts the on-call engineer to a release state inconsistency
that must be manually resolved.
4. **Calculate next version:** Only after these checks pass does the workflow
4. **Calculate Next Version:** Only after these checks pass does the workflow
proceed to calculate the next semantic version based on the trusted version
numbers retrieved from NPM.
@@ -109,14 +109,14 @@ This NPM-first approach, backed by integrity checks, makes the release process
highly robust and prevents the kinds of versioning discrepancies that can arise
from relying solely on git history or API outputs.
## Manual releases
## Manual Releases
For situations requiring a release outside of the regular nightly and weekly
promotion schedule, and NOT already covered by patching process, you can use the
`Release: Manual` workflow. This workflow provides a direct way to publish a
specific version from any branch, tag, or commit SHA.
### How to create a manual release
### How to Create a Manual Release
1. Navigate to the **Actions** tab of the repository.
2. Select the **Release: Manual** workflow from the list.
@@ -144,7 +144,7 @@ The workflow will then proceed to test (if not skipped), build, and publish the
release. If the workflow fails during a non-dry run, it will automatically
create a GitHub issue with the failure details.
## Rollback/rollforward
## Rollback/Rollforward
In the event that a release has a critical regression, you can quickly roll back
to a previous stable version or roll forward to a new patch by changing the npm
@@ -154,7 +154,7 @@ way to do this.
This is the preferred method for both rollbacks and rollforwards, as it does not
require a full release cycle.
### How to change a release tag
### How to Change a Release Tag
1. Navigate to the **Actions** tab of the repository.
2. Select the **Release: Change Tags** workflow from the list.
@@ -181,13 +181,13 @@ channel to the specified version.
If a critical bug that is already fixed on `main` needs to be patched on a
`stable` or `preview` release, the process is now highly automated.
### How to patch
### How to Patch
#### 1. Create the patch pull request
#### 1. Create the Patch Pull Request
There are two ways to create a patch pull request:
**Option A: From a GitHub comment (recommended)**
**Option A: From a GitHub Comment (Recommended)**
After a pull request containing the fix has been merged, a maintainer can add a
comment on that same PR with the following format:
@@ -212,7 +212,7 @@ The `Release: Patch from Comment` workflow will automatically find the merge
commit SHA and trigger the `Release: Patch (1) Create PR` workflow. If the PR is
not yet merged, it will post a comment indicating the failure.
**Option B: Manually triggering the workflow**
**Option B: Manually Triggering the Workflow**
Navigate to the **Actions** tab and run the **Release: Patch (1) Create PR**
workflow.
@@ -229,17 +229,17 @@ This workflow will automatically:
4. Cherry-pick your specified commit into the hotfix branch.
5. Create a pull request from the hotfix branch back to the release branch.
#### 2. Review and merge
#### 2. Review and Merge
Review the automatically created pull request(s) to ensure the cherry-pick was
successful and the changes are correct. Once approved, merge the pull request.
**Security note:** The `release/*` branches are protected by branch protection
**Security Note:** The `release/*` branches are protected by branch protection
rules. A pull request to one of these branches requires at least one review from
a code owner before it can be merged. This ensures that no unauthorized code is
released.
#### 2.5. Adding multiple commits to a hotfix (advanced)
#### 2.5. Adding Multiple Commits to a Hotfix (Advanced)
If you need to include multiple fixes in a single patch release, you can add
additional commits to the hotfix branch after the initial patch PR has been
@@ -280,7 +280,7 @@ This approach allows you to group related fixes into a single patch release
while maintaining full control over what gets included and how conflicts are
resolved.
#### 3. Automatic release
#### 3. Automatic Release
Upon merging the pull request, the `Release: Patch (2) Trigger` workflow is
automatically triggered. It will then start the `Release: Patch (3) Release`
@@ -293,21 +293,21 @@ workflow, which will:
This fully automated process ensures that patches are created and released
consistently and reliably.
#### Troubleshooting: Older branch workflows
#### Troubleshooting: Older Branch Workflows
**Issue**: If the patch trigger workflow fails with errors like "Resource not
accessible by integration" or references to non-existent workflow files (e.g.,
`patch-release.yml`), this indicates the hotfix branch contains an outdated
version of the workflow files.
**Root cause**: When a PR is merged, GitHub Actions runs the workflow definition
**Root Cause**: When a PR is merged, GitHub Actions runs the workflow definition
from the **source branch** (the hotfix branch), not from the target branch (the
release branch). If the hotfix branch was created from an older release branch
that predates workflow improvements, it will use the old workflow logic.
**Solutions**:
**Option 1: Manual trigger (quick fix)** Manually trigger the updated workflow
**Option 1: Manual Trigger (Quick Fix)** Manually trigger the updated workflow
from the branch with the latest workflow code:
```bash
@@ -337,7 +337,7 @@ gh workflow run release-patch-2-trigger.yml --ref main \
the latest workflow improvements (usually `main`, but could be a feature branch
if testing updates).
**Option 2: Update the hotfix branch** Merge the latest main branch into your
**Option 2: Update the Hotfix Branch** Merge the latest main branch into your
hotfix branch to get the updated workflows:
```bash
@@ -348,7 +348,7 @@ git push
Then close and reopen the PR to retrigger the workflow with the updated version.
**Option 3: Direct release trigger** Skip the trigger workflow entirely and
**Option 3: Direct Release Trigger** Skip the trigger workflow entirely and
directly run the release workflow:
```bash
@@ -367,7 +367,7 @@ We also run a Google cloud build called
docker to match your release. This will also be moved to GH and combined with
the main release file once service account permissions are sorted out.
## Release validation
## Release Validation
After pushing a new release smoke testing should be performed to ensure that the
packages are working as expected. This can be done by installing the packages
@@ -384,7 +384,7 @@ correctly.
is recommended to ensure that the packages are working as expected. We'll
codify this more in the future.
## Local testing and validation: Changes to the packaging and publishing process
## Local Testing and Validation: Changes to the Packaging and Publishing Process
If you need to test the release process without actually publishing to NPM or
creating a public GitHub release, you can trigger the workflow manually from the
@@ -428,7 +428,7 @@ tarballs will be created in the root of each package's directory (e.g.,
By performing a dry run, you can be confident that your changes to the packaging
process are correct and that the packages will be published successfully.
## Release deep dive
## Release Deep Dive
The release process creates two distinct types of artifacts for different
distribution channels: standard packages for the NPM registry and a single,
@@ -436,14 +436,14 @@ self-contained executable for GitHub Releases.
Here are the key stages:
**Stage 1: Pre-release sanity checks and versioning**
**Stage 1: Pre-Release Sanity Checks and Versioning**
- **What happens:** Before any files are moved, the process ensures the project
is in a good state. This involves running tests, linting, and type-checking
(`npm run preflight`). The version number in the root `package.json` and
`packages/cli/package.json` is updated to the new release version.
**Stage 2: Building the source code for NPM**
**Stage 2: Building the Source Code for NPM**
- **What happens:** The TypeScript source code in `packages/core/src` and
`packages/cli/src` is compiled into standard JavaScript.
@@ -454,7 +454,7 @@ Here are the key stages:
into plain JavaScript that can be run by Node.js. The `core` package is built
first as the `cli` package depends on it.
**Stage 3: Publishing standard packages to NPM**
**Stage 3: Publishing Standard Packages to NPM**
- **What happens:** The `npm publish` command is run for the
`@google/gemini-cli-core` and `@google/gemini-cli` packages.
@@ -463,12 +463,12 @@ Here are the key stages:
`npm` will handle installing the `@google/gemini-cli-core` dependency
automatically. The code in these packages is not bundled into a single file.
**Stage 4: Assembling and creating the GitHub release asset**
**Stage 4: Assembling and Creating the GitHub Release Asset**
This stage happens _after_ the NPM publish and creates the single-file
executable that enables `npx` usage directly from the GitHub repository.
1. **The JavaScript bundle is created:**
1. **The JavaScript Bundle is Created:**
- **What happens:** The built JavaScript from both `packages/core/dist` and
`packages/cli/dist`, along with all third-party JavaScript dependencies,
are bundled by `esbuild` into a single, executable JavaScript file (e.g.,
@@ -479,7 +479,7 @@ executable that enables `npx` usage directly from the GitHub repository.
run the CLI without a full `npm install`, as all dependencies (including
the `core` package) are included directly.
2. **The `bundle` directory is assembled:**
2. **The `bundle` Directory is Assembled:**
- **What happens:** A temporary `bundle` folder is created at the project
root. The single `gemini.js` executable is placed inside it, along with
other essential files.
@@ -491,7 +491,7 @@ executable that enables `npx` usage directly from the GitHub repository.
- **Why:** This creates a clean, self-contained directory with everything
needed to run the CLI and understand its license and usage.
3. **The GitHub release is created:**
3. **The GitHub Release is Created:**
- **What happens:** The contents of the `bundle` directory, including the
`gemini.js` executable, are attached as assets to a new GitHub Release.
- **Why:** This makes the single-file version of the CLI available for
@@ -499,12 +499,12 @@ executable that enables `npx` usage directly from the GitHub repository.
`npx https://github.com/google-gemini/gemini-cli` command, which downloads
and runs this specific bundled asset.
**Summary of artifacts**
**Summary of Artifacts**
- **NPM:** Publishes standard, un-bundled Node.js packages. The primary artifact
is the code in `packages/cli/dist`, which depends on
`@google/gemini-cli-core`.
- **GitHub release:** Publishes a single, bundled `gemini.js` file that contains
- **GitHub Release:** Publishes a single, bundled `gemini.js` file that contains
all dependencies, for easy execution via `npx`.
This dual-artifact process ensures that both traditional `npm` users and those
+26 -72
View File
@@ -7,24 +7,24 @@
"slug": "docs"
},
{
"label": "Architecture overview",
"label": "Architecture Overview",
"slug": "docs/architecture"
},
{
"label": "Contribution guide",
"label": "Contribution Guide",
"slug": "docs/contributing"
}
]
},
{
"label": "Get started",
"label": "Get Started",
"items": [
{
"label": "Gemini CLI quickstart",
"label": "Gemini CLI Quickstart",
"slug": "docs/get-started"
},
{
"label": "Gemini 3 on Gemini CLI",
"label": "Gemini 3 Pro on Gemini CLI",
"slug": "docs/get-started/gemini-3"
},
{
@@ -61,7 +61,7 @@
"slug": "docs/cli/checkpointing"
},
{
"label": "Custom commands",
"label": "Custom Commands",
"slug": "docs/cli/custom-commands"
},
{
@@ -69,15 +69,15 @@
"slug": "docs/cli/enterprise"
},
{
"label": "Headless mode",
"label": "Headless Mode",
"slug": "docs/cli/headless"
},
{
"label": "Keyboard shortcuts",
"label": "Keyboard Shortcuts",
"slug": "docs/cli/keyboard-shortcuts"
},
{
"label": "Model selection",
"label": "Model Selection",
"slug": "docs/cli/model"
},
{
@@ -88,10 +88,6 @@
"label": "Session Management",
"slug": "docs/cli/session-management"
},
{
"label": "Agent Skills",
"slug": "docs/cli/skills"
},
{
"label": "Settings",
"slug": "docs/cli/settings"
@@ -105,7 +101,7 @@
"slug": "docs/cli/themes"
},
{
"label": "Token caching",
"label": "Token Caching",
"slug": "docs/cli/token-caching"
},
{
@@ -119,10 +115,6 @@
{
"label": "Uninstall",
"slug": "docs/cli/uninstall"
},
{
"label": "System prompt override",
"slug": "docs/cli/system-prompt"
}
]
},
@@ -155,7 +147,7 @@
"slug": "docs/tools"
},
{
"label": "File system",
"label": "File System",
"slug": "docs/tools/file-system"
},
{
@@ -163,11 +155,11 @@
"slug": "docs/tools/shell"
},
{
"label": "Web fetch",
"label": "Web Fetch",
"slug": "docs/tools/web-fetch"
},
{
"label": "Web search",
"label": "Web Search",
"slug": "docs/tools/web-search"
},
{
@@ -179,7 +171,7 @@
"slug": "docs/tools/todos"
},
{
"label": "MCP servers",
"label": "MCP Servers",
"slug": "docs/tools/mcp-server"
}
]
@@ -192,45 +184,24 @@
"slug": "docs/extensions"
},
{
"label": "Get started with extensions",
"label": "Get Started with Extensions",
"slug": "docs/extensions/getting-started-extensions"
},
{
"label": "Extension releasing",
"label": "Extension Releasing",
"slug": "docs/extensions/extension-releasing"
}
]
},
{
"label": "Hooks",
"items": [
{
"label": "Introduction",
"slug": "docs/hooks"
},
{
"label": "Writing hooks",
"slug": "docs/hooks/writing-hooks"
},
{
"label": "Hooks reference",
"slug": "docs/hooks/reference"
},
{
"label": "Best practices",
"slug": "docs/hooks/best-practices"
}
]
},
{
"label": "IDE integration",
"label": "IDE Integration",
"items": [
{
"label": "Introduction",
"slug": "docs/ide-integration"
},
{
"label": "IDE companion spec",
"label": "IDE Companion Spec",
"slug": "docs/ide-integration/ide-companion-spec"
}
]
@@ -247,36 +218,19 @@
"slug": "docs/releases"
},
{
"label": "Integration tests",
"label": "Changelog",
"slug": "docs/changelogs"
},
{
"label": "Integration Tests",
"slug": "docs/integration-tests"
},
{
"label": "Issue and PR automation",
"label": "Issue and PR Automation",
"slug": "docs/issue-and-pr-automation"
}
]
},
{
"label": "Releases",
"items": [
{
"label": "Release notes",
"slug": "docs/changelogs/"
},
{
"label": "Latest release",
"slug": "docs/changelogs/latest"
},
{
"label": "Preview release",
"slug": "docs/changelogs/preview"
},
{
"label": "Changelog",
"slug": "docs/changelogs/releases"
}
]
},
{
"label": "Support",
"items": [
@@ -289,11 +243,11 @@
"slug": "docs/troubleshooting"
},
{
"label": "Quota and pricing",
"label": "Quota and Pricing",
"slug": "docs/quota-and-pricing"
},
{
"label": "Terms of service",
"label": "Terms of Service",
"slug": "docs/tos-privacy"
}
]
+7 -8
View File
@@ -36,9 +36,8 @@ glob patterns.
## 2. `read_file` (ReadFile)
`read_file` reads and returns the content of a specified file. This tool handles
text, images (PNG, JPG, GIF, WEBP, SVG, BMP), audio files (MP3, WAV, AIFF, AAC,
OGG, FLAC), and PDF files. For text files, it can read specific line ranges.
Other binary file types are generally skipped.
text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it
can read specific line ranges. Other binary file types are generally skipped.
- **Tool name:** `read_file`
- **Display name:** ReadFile
@@ -54,16 +53,16 @@ Other binary file types are generally skipped.
- For text files: Returns the content. If `offset` and `limit` are used,
returns only that slice of lines. Indicates if content was truncated due to
line limits or line length limits.
- For image, audio, and PDF files: Returns the file content as a
base64-encoded data structure suitable for model consumption.
- For image and PDF files: Returns the file content as a base64-encoded data
structure suitable for model consumption.
- For other binary files: Attempts to identify and skip them, returning a
message indicating it's a generic binary file.
- **Output:** (`llmContent`):
- For text files: The file content, potentially prefixed with a truncation
message (e.g.,
`[File content truncated: showing lines 1-100 of 500 total lines...]\nActual file content...`).
- For image/audio/PDF files: An object containing `inlineData` with `mimeType`
and base64 `data` (e.g.,
- For image/PDF files: An object containing `inlineData` with `mimeType` and
base64 `data` (e.g.,
`{ inlineData: { mimeType: 'image/png', data: 'base64encodedstring' } }`).
- For other binary files: A message like
`Cannot display content of binary file: /path/to/data.bin`.
@@ -185,7 +184,7 @@ context around the `old_string` to ensure it modifies the correct location.
- If `old_string` is provided, it reads the `file_path` and attempts to find
exactly one occurrence of `old_string`.
- If one occurrence is found, it replaces it with `new_string`.
- **Enhanced reliability (multi-stage edit correction):** To significantly
- **Enhanced Reliability (Multi-Stage Edit Correction):** To significantly
improve the success rate of edits, especially when the model-provided
`old_string` might not be perfectly precise, the tool incorporates a
multi-stage edit correction mechanism.
+71 -104
View File
@@ -16,14 +16,14 @@ An MCP server enables the Gemini CLI to:
through standardized schema definitions.
- **Execute tools:** Call specific tools with defined arguments and receive
structured responses.
- **Access resources:** Read data from specific resources that the server
exposes (files, API payloads, reports, etc.).
- **Access resources:** Read data from specific resources (though the Gemini CLI
primarily focuses on tool execution).
With an MCP server, you can extend the Gemini CLI's capabilities to perform
actions beyond its built-in features, such as interacting with databases, APIs,
custom scripts, or specialized workflows.
## Core integration architecture
## Core Integration Architecture
The Gemini CLI integrates with MCP servers through a sophisticated discovery and
execution system built into the core package (`packages/core/src/tools/`):
@@ -40,9 +40,8 @@ The discovery process is orchestrated by `discoverMcpTools()`, which:
4. **Sanitizes and validates** tool schemas for compatibility with the Gemini
API
5. **Registers tools** in the global tool registry with conflict resolution
6. **Fetches and registers resources** if the server exposes any
### Execution layer (`mcp-tool.ts`)
### Execution Layer (`mcp-tool.ts`)
Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that:
@@ -52,7 +51,7 @@ Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that:
- **Processes responses** for both the LLM context and user display
- **Maintains connection state** and handles timeouts
### Transport mechanisms
### Transport Mechanisms
The Gemini CLI supports three MCP transport types:
@@ -60,32 +59,6 @@ The Gemini CLI supports three MCP transport types:
- **SSE Transport:** Connects to Server-Sent Events endpoints
- **Streamable HTTP Transport:** Uses HTTP streaming for communication
## Working with MCP resources
Some MCP servers expose contextual “resources” in addition to the tools and
prompts. Gemini CLI discovers these automatically and gives you the possibility
to reference them in the chat.
### Discovery and listing
- When discovery runs, the CLI fetches each servers `resources/list` results.
- The `/mcp` command displays a Resources section alongside Tools and Prompts
for every connected server.
This returns a concise, plain-text list of URIs plus metadata.
### Referencing resources in a conversation
You can use the same `@` syntax already known for referencing local files:
```
@server://resource/path
```
Resource URIs appear in the completion menu together with filesystem paths. When
you submit the message, the CLI calls `resources/read` and injects the content
in the conversation.
## How to set up your MCP server
The Gemini CLI uses the `mcpServers` configuration in your `settings.json` file
@@ -99,7 +72,7 @@ through the top-level `mcpServers` object for specific server definitions, and
through the `mcp` object for global settings that control server discovery and
execution.
#### Global MCP settings (`mcp`)
#### Global MCP Settings (`mcp`)
The `mcp` object in your `settings.json` allows you to define global rules for
all MCP servers.
@@ -122,12 +95,12 @@ all MCP servers.
}
```
#### Server-specific configuration (`mcpServers`)
#### Server-Specific Configuration (`mcpServers`)
The `mcpServers` object is where you define each individual MCP server you want
the CLI to connect to.
### Configuration structure
### Configuration Structure
Add an `mcpServers` object to your `settings.json` file:
@@ -148,7 +121,7 @@ Add an `mcpServers` object to your `settings.json` file:
}
```
### Configuration properties
### Configuration Properties
Each server configuration supports the following properties:
@@ -184,13 +157,13 @@ Each server configuration supports the following properties:
Service Account to impersonate. Used with
`authProviderType: 'service_account_impersonation'`.
### OAuth support for remote MCP servers
### OAuth Support for Remote MCP Servers
The Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using
SSE or HTTP transports. This enables secure access to MCP servers that require
authentication.
#### Automatic OAuth discovery
#### Automatic OAuth Discovery
For servers that support OAuth discovery, you can omit the OAuth configuration
and let the CLI discover it automatically:
@@ -212,7 +185,7 @@ The CLI will automatically:
- Perform dynamic client registration if supported
- Handle the OAuth flow and token management
#### Authentication flow
#### Authentication Flow
When connecting to an OAuth-enabled server:
@@ -223,7 +196,7 @@ When connecting to an OAuth-enabled server:
5. **Tokens are stored** securely for future use
6. **Connection retry** succeeds with valid tokens
#### Browser redirect requirements
#### Browser Redirect Requirements
**Important:** OAuth authentication requires that your local machine can:
@@ -236,7 +209,7 @@ This feature will not work in:
- Remote SSH sessions without X11 forwarding
- Containerized environments without browser support
#### Managing OAuth authentication
#### Managing OAuth Authentication
Use the `/mcp auth` command to manage OAuth authentication:
@@ -251,7 +224,7 @@ Use the `/mcp auth` command to manage OAuth authentication:
/mcp auth serverName
```
#### OAuth configuration properties
#### OAuth Configuration Properties
- **`enabled`** (boolean): Enable OAuth for this server
- **`clientId`** (string): OAuth client identifier (optional with dynamic
@@ -266,7 +239,7 @@ Use the `/mcp auth` command to manage OAuth authentication:
- **`tokenParamName`** (string): Query parameter name for tokens in SSE URLs
- **`audiences`** (string[]): Audiences the token is valid for
#### Token management
#### Token Management
OAuth tokens are automatically:
@@ -275,7 +248,7 @@ OAuth tokens are automatically:
- **Validated** before each connection attempt
- **Cleaned up** when invalid or expired
#### Authentication provider type
#### Authentication Provider Type
You can specify the authentication provider type using the `authProviderType`
property:
@@ -292,7 +265,7 @@ property:
accessing IAP-protected services (this was specifically designed for Cloud
Run services).
#### Google credentials
#### Google Credentials
```json
{
@@ -308,7 +281,7 @@ property:
}
```
#### Service account impersonation
#### Service Account Impersonation
To authenticate with a server using Service Account Impersonation, you must set
the `authProviderType` to `service_account_impersonation` and provide the
@@ -323,7 +296,7 @@ The CLI will use your local Application Default Credentials (ADC) to generate an
OIDC ID token for the specified service account and audience. This token will
then be used to authenticate with the MCP server.
#### Setup instructions
#### Setup Instructions
1. **[Create](https://cloud.google.com/iap/docs/oauth-client-creation) or use an
existing OAuth 2.0 client ID.** To use an existing OAuth 2.0 client ID,
@@ -345,9 +318,9 @@ then be used to authenticate with the MCP server.
6. **[Enable](https://console.cloud.google.com/apis/library/iamcredentials.googleapis.com)
the IAM Credentials API** for your project.
### Example configurations
### Example Configurations
#### Python MCP server (stdio)
#### Python MCP Server (Stdio)
```json
{
@@ -366,7 +339,7 @@ then be used to authenticate with the MCP server.
}
```
#### Node.js MCP server (stdio)
#### Node.js MCP Server (Stdio)
```json
{
@@ -381,7 +354,7 @@ then be used to authenticate with the MCP server.
}
```
#### Docker-based MCP server
#### Docker-based MCP Server
```json
{
@@ -406,7 +379,7 @@ then be used to authenticate with the MCP server.
}
```
#### HTTP-based MCP server
#### HTTP-based MCP Server
```json
{
@@ -419,7 +392,7 @@ then be used to authenticate with the MCP server.
}
```
#### HTTP-based MCP Server with custom headers
#### HTTP-based MCP Server with Custom Headers
```json
{
@@ -437,7 +410,7 @@ then be used to authenticate with the MCP server.
}
```
#### MCP server with tool filtering
#### MCP Server with Tool Filtering
```json
{
@@ -453,7 +426,7 @@ then be used to authenticate with the MCP server.
}
```
### SSE MCP server with SA impersonation
### SSE MCP Server with SA Impersonation
```json
{
@@ -468,12 +441,12 @@ then be used to authenticate with the MCP server.
}
```
## Discovery process deep dive
## Discovery Process Deep Dive
When the Gemini CLI starts, it performs MCP server discovery through the
following detailed process:
### 1. Server iteration and connection
### 1. Server Iteration and Connection
For each configured server in `mcpServers`:
@@ -487,7 +460,7 @@ For each configured server in `mcpServers`:
4. **Error handling:** Connection failures are logged and the server status is
set to `DISCONNECTED`
### 2. Tool discovery
### 2. Tool Discovery
Upon successful connection:
@@ -502,7 +475,7 @@ Upon successful connection:
- Names longer than 63 characters are truncated with middle replacement
(`___`)
### 3. Conflict resolution
### 3. Conflict Resolution
When multiple servers expose tools with the same name:
@@ -513,7 +486,7 @@ When multiple servers expose tools with the same name:
3. **Registry tracking:** The tool registry maintains mappings between server
names and their tools
### 4. Schema processing
### 4. Schema Processing
Tool parameter schemas undergo sanitization for Gemini API compatibility:
@@ -523,7 +496,7 @@ Tool parameter schemas undergo sanitization for Gemini API compatibility:
compatibility)
- **Recursive processing** applies to nested schemas
### 5. Connection management
### 5. Connection Management
After discovery:
@@ -534,23 +507,23 @@ After discovery:
- **Status updates:** Final server statuses are set to `CONNECTED` or
`DISCONNECTED`
## Tool execution flow
## Tool Execution Flow
When the Gemini model decides to use an MCP tool, the following execution flow
occurs:
### 1. Tool invocation
### 1. Tool Invocation
The model generates a `FunctionCall` with:
- **Tool name:** The registered name (potentially prefixed)
- **Arguments:** JSON object matching the tool's parameter schema
### 2. Confirmation process
### 2. Confirmation Process
Each `DiscoveredMCPTool` implements sophisticated confirmation logic:
#### Trust-based bypass
#### Trust-based Bypass
```typescript
if (this.trust) {
@@ -558,14 +531,14 @@ if (this.trust) {
}
```
#### Dynamic allow-listing
#### Dynamic Allow-listing
The system maintains internal allow-lists for:
- **Server-level:** `serverName` → All tools from this server are trusted
- **Tool-level:** `serverName.toolName` → This specific tool is trusted
#### User choice handling
#### User Choice Handling
When confirmation is required, users can choose:
@@ -593,7 +566,7 @@ Upon confirmation (or trust bypass):
3. **Response processing:** Results are formatted for both LLM context and user
display
### 4. Response handling
### 4. Response Handling
The execution result contains:
@@ -603,7 +576,7 @@ The execution result contains:
## How to interact with your MCP server
### Using the `/mcp` command
### Using the `/mcp` Command
The `/mcp` command provides comprehensive information about your MCP server
setup:
@@ -620,7 +593,7 @@ This displays:
- **Available tools:** List of tools from each server with descriptions
- **Discovery state:** Overall discovery process status
### Example `/mcp` output
### Example `/mcp` Output
```
MCP Servers Status:
@@ -642,7 +615,7 @@ MCP Servers Status:
Discovery State: COMPLETED
```
### Tool usage
### Tool Usage
Once discovered, MCP tools are available to the Gemini model like built-in
tools. The model will automatically:
@@ -652,27 +625,27 @@ tools. The model will automatically:
3. **Execute tools** with proper parameters
4. **Display results** in a user-friendly format
## Status monitoring and troubleshooting
## Status Monitoring and Troubleshooting
### Connection states
### Connection States
The MCP integration tracks several states:
#### Server status (`MCPServerStatus`)
#### Server Status (`MCPServerStatus`)
- **`DISCONNECTED`:** Server is not connected or has errors
- **`CONNECTING`:** Connection attempt in progress
- **`CONNECTED`:** Server is connected and ready
#### Discovery state (`MCPDiscoveryState`)
#### Discovery State (`MCPDiscoveryState`)
- **`NOT_STARTED`:** Discovery hasn't begun
- **`IN_PROGRESS`:** Currently discovering servers
- **`COMPLETED`:** Discovery finished (with or without errors)
### Common issues and solutions
### Common Issues and Solutions
#### Server won't connect
#### Server Won't Connect
**Symptoms:** Server shows `DISCONNECTED` status
@@ -684,7 +657,7 @@ The MCP integration tracks several states:
4. **Review logs:** Look for error messages in the CLI output
5. **Verify permissions:** Ensure the CLI can execute the server command
#### No tools discovered
#### No Tools Discovered
**Symptoms:** Server connects but no tools are available
@@ -696,7 +669,7 @@ The MCP integration tracks several states:
3. **Review server logs:** Check stderr output for server-side errors
4. **Test tool listing:** Manually test your server's tool discovery endpoint
#### Tools not executing
#### Tools Not Executing
**Symptoms:** Tools are discovered but fail during execution
@@ -707,7 +680,7 @@ The MCP integration tracks several states:
3. **Error handling:** Check if your tool is throwing unhandled exceptions
4. **Timeout issues:** Consider increasing the `timeout` setting
#### Sandbox compatibility
#### Sandbox Compatibility
**Symptoms:** MCP servers fail when sandboxing is enabled
@@ -720,7 +693,7 @@ The MCP integration tracks several states:
4. **Environment variables:** Verify required environment variables are passed
through
### Debugging tips
### Debugging Tips
1. **Enable debug mode:** Run the CLI with `--debug` for verbose output
2. **Check stderr:** MCP server stderr is captured and logged (INFO messages
@@ -730,9 +703,9 @@ The MCP integration tracks several states:
functionality
5. **Use `/mcp` frequently:** Monitor server status during development
## Important notes
## Important Notes
### Security sonsiderations
### Security Considerations
- **Trust settings:** The `trust` option bypasses all confirmation dialogs. Use
cautiously and only for servers you completely control
@@ -743,7 +716,7 @@ The MCP integration tracks several states:
- **Private data:** Using broadly scoped personal access tokens can lead to
information leakage between repositories
### Performance and resource management
### Performance and Resource Management
- **Connection persistence:** The CLI maintains persistent connections to
servers that successfully register tools
@@ -754,7 +727,7 @@ The MCP integration tracks several states:
- **Resource monitoring:** MCP servers run as separate processes and consume
system resources
### Schema compatibility
### Schema Compatibility
- **Property stripping:** The system automatically removes certain schema
properties (`$schema`, `additionalProperties`) for Gemini API compatibility
@@ -767,7 +740,7 @@ This comprehensive integration makes MCP servers a powerful way to extend the
Gemini CLI's capabilities while maintaining security, reliability, and ease of
use.
## Returning rich content from tools
## Returning Rich Content from Tools
MCP tools are not limited to returning simple text. You can return rich,
multi-part content, including text, images, audio, and other binary data in a
@@ -778,7 +751,7 @@ All data returned from the tool is processed and sent to the model as context
for its next generation, enabling it to reason about or summarize the provided
information.
### How it works
### How It Works
To return rich content, your tool's response must adhere to the MCP
specification for a
@@ -796,7 +769,7 @@ supported block types include:
- `resource` (embedded content)
- `resource_link`
### Example: Returning text and an image
### Example: Returning Text and an Image
Here is an example of a valid JSON response from an MCP tool that returns both a
text description and an image:
@@ -832,13 +805,13 @@ When the Gemini CLI receives this response, it will:
This enables you to build sophisticated tools that can provide rich, multi-modal
context to the Gemini model.
## MCP prompts as slash commands
## MCP Prompts as Slash Commands
In addition to tools, MCP servers can expose predefined prompts that can be
executed as slash commands within the Gemini CLI. This allows you to create
shortcuts for common or complex queries that can be easily invoked by name.
### Defining prompts on the server
### Defining Prompts on the Server
Here's a small example of a stdio MCP server that defines prompts:
@@ -889,7 +862,7 @@ This can be included in `settings.json` under `mcpServers` with:
}
```
### Invoking prompts
### Invoking Prompts
Once a prompt is discovered, you can invoke it using its name as a slash
command. The CLI will automatically handle parsing arguments.
@@ -910,7 +883,7 @@ substituting the arguments into the prompt template and returning the final
prompt text. The CLI then sends this prompt to the model for execution. This
provides a convenient way to automate and share common workflows.
## Managing MCP servers with `gemini mcp`
## Managing MCP Servers with `gemini mcp`
While you can always configure MCP servers by manually editing your
`settings.json` file, the Gemini CLI provides a convenient set of commands to
@@ -918,7 +891,7 @@ manage your server configurations programmatically. These commands streamline
the process of adding, listing, and removing MCP servers without needing to
directly edit JSON files.
### Adding a server (`gemini mcp add`)
### Adding a Server (`gemini mcp add`)
The `add` command configures a new MCP server in your `settings.json`. Based on
the scope (`-s, --scope`), it will be added to either the user config
@@ -935,7 +908,7 @@ gemini mcp add [options] <name> <commandOrUrl> [args...]
`http`/`sse`).
- `[args...]`: Optional arguments for a `stdio` command.
**Options (flags):**
**Options (Flags):**
- `-s, --scope`: Configuration scope (user or project). [default: "project"]
- `-t, --transport`: Transport type (stdio, sse, http). [default: "stdio"]
@@ -993,7 +966,7 @@ gemini mcp add --transport sse sse-server https://api.example.com/sse/
gemini mcp add --transport sse --header "Authorization: Bearer abc123" secure-sse https://api.example.com/sse/
```
### Listing servers (`gemini mcp list`)
### Listing Servers (`gemini mcp list`)
To view all MCP servers currently configured, use the `list` command. It
displays each server's name, configuration details, and connection status. This
@@ -1005,7 +978,7 @@ command has no flags.
gemini mcp list
```
**Example output:**
**Example Output:**
```sh
✓ stdio-server: command: python3 server.py (stdio) - Connected
@@ -1013,7 +986,7 @@ gemini mcp list
✗ sse-server: https://api.example.com/sse (sse) - Disconnected
```
### Removing a server (`gemini mcp remove`)
### Removing a Server (`gemini mcp remove`)
To delete a server from your configuration, use the `remove` command with the
server's name.
@@ -1024,7 +997,7 @@ server's name.
gemini mcp remove <name>
```
**Options (flags):**
**Options (Flags):**
- `-s, --scope`: Configuration scope (user or project). [default: "project"]
@@ -1036,9 +1009,3 @@ gemini mcp remove my-server
This will find and delete the "my-server" entry from the `mcpServers` object in
the appropriate `settings.json` file based on the scope (`-s, --scope`).
## Instructions
Gemini CLI supports
[MCP server instructions](https://modelcontextprotocol.io/specification/2025-06-18/schema#initializeresult),
which will be appended to the system instructions.
+1 -1
View File
@@ -1,4 +1,4 @@
# Memory tool (`save_memory`)
# Memory Tool (`save_memory`)
This document describes the `save_memory` tool for the Gemini CLI.
+12 -12
View File
@@ -1,4 +1,4 @@
# Shell tool (`run_shell_command`)
# Shell Tool (`run_shell_command`)
This document describes the `run_shell_command` tool for the Gemini CLI.
@@ -71,7 +71,7 @@ run_shell_command(command="npm run dev &", description="Start development server
You can configure the behavior of the `run_shell_command` tool by modifying your
`settings.json` file or by using the `/settings` command in the Gemini CLI.
### Enabling interactive commands
### Enabling Interactive Commands
To enable interactive commands, you need to set the
`tools.shell.enableInteractiveShell` setting to `true`. This will use `node-pty`
@@ -91,7 +91,7 @@ implementation, which does not support interactive commands.
}
```
### Showing color in output
### Showing Color in Output
To show color in the shell output, you need to set the `tools.shell.showColor`
setting to `true`. **Note: This setting only applies when
@@ -109,7 +109,7 @@ setting to `true`. **Note: This setting only applies when
}
```
### Setting the pager
### Setting the Pager
You can set a custom pager for the shell output by setting the
`tools.shell.pager` setting. The default pager is `cat`. **Note: This setting
@@ -127,7 +127,7 @@ only applies when `tools.shell.enableInteractiveShell` is enabled.**
}
```
## Interactive commands
## Interactive Commands
The `run_shell_command` tool now supports interactive commands by integrating a
pseudo-terminal (pty). This allows you to run commands that require real-time
@@ -149,13 +149,13 @@ including complex TUIs, will be rendered correctly.
background. The `Background PIDs` field will contain the process ID of the
background process.
## Environment variables
## Environment Variables
When `run_shell_command` executes a command, it sets the `GEMINI_CLI=1`
environment variable in the subprocess's environment. This allows scripts or
tools to detect if they are being run from within the Gemini CLI.
## Command restrictions
## Command Restrictions
You can restrict the commands that can be executed by the `run_shell_command`
tool by using the `tools.core` and `tools.exclude` settings in your
@@ -174,16 +174,16 @@ configuration file.
The validation logic is designed to be secure and flexible:
1. **Command chaining disabled**: The tool automatically splits commands
1. **Command Chaining Disabled**: The tool automatically splits commands
chained with `&&`, `||`, or `;` and validates each part separately. If any
part of the chain is disallowed, the entire command is blocked.
2. **Prefix matching**: The tool uses prefix matching. For example, if you
2. **Prefix Matching**: The tool uses prefix matching. For example, if you
allow `git`, you can run `git status` or `git log`.
3. **Blocklist precedence**: The `tools.exclude` list is always checked first.
3. **Blocklist Precedence**: The `tools.exclude` list is always checked first.
If a command matches a blocked prefix, it will be denied, even if it also
matches an allowed prefix in `tools.core`.
### Command restriction examples
### Command Restriction Examples
**Allow only specific command prefixes**
@@ -251,7 +251,7 @@ To block all shell commands, add the `run_shell_command` wildcard to
- `ls -l`: Blocked
- `any other command`: Blocked
## Security note for `excludeTools`
## Security Note for `excludeTools`
Command-specific restrictions in `excludeTools` for `run_shell_command` are
based on simple string matching and can be easily bypassed. This feature is
+5 -5
View File
@@ -1,4 +1,4 @@
# Todo tool (`write_todos`)
# Todo Tool (`write_todos`)
This document describes the `write_todos` tool for the Gemini CLI.
@@ -24,11 +24,11 @@ alignment where the agent is less likely to lose track of its current goal.
The agent uses this tool to break down complex multi-step requests into a clear
plan.
- **Progress tracking:** The agent updates this list as it works, marking tasks
- **Progress Tracking:** The agent updates this list as it works, marking tasks
as `completed` when done.
- **Single focus:** Only one task will be marked `in_progress` at a time,
- **Single Focus:** Only one task will be marked `in_progress` at a time,
indicating exactly what the agent is currently working on.
- **Dynamic updates:** The plan may evolve as the agent discovers new
- **Dynamic Updates:** The plan may evolve as the agent discovers new
information, leading to new tasks being added or unnecessary ones being
cancelled.
@@ -53,5 +53,5 @@ write_todos({
- **Enabling:** This tool is enabled by default. You can disable it in your
`settings.json` file by setting `"useWriteTodos": false`.
- **Intended use:** This tool is primarily used by the agent for complex,
- **Intended Use:** This tool is primarily used by the agent for complex,
multi-turn tasks. It is generally not used for simple, single-turn questions.
+1 -1
View File
@@ -1,4 +1,4 @@
# Web fetch tool (`web_fetch`)
# Web Fetch Tool (`web_fetch`)
This document describes the `web_fetch` tool for the Gemini CLI.
+1 -1
View File
@@ -1,4 +1,4 @@
# Web search tool (`google_web_search`)
# Web Search Tool (`google_web_search`)
This document describes the `google_web_search` tool.
+11 -31
View File
@@ -10,31 +10,13 @@ topics on:
## Authentication or login errors
- **Error:
`You must be a named user on your organization's Gemini Code Assist Standard edition subscription to use this service. Please contact your administrator to request an entitlement to Gemini Code Assist Standard edition.`**
- **Cause:** This error might occur if Gemini CLI detects the
`GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` environment variable is
defined. Setting these variables forces an organization subscription check.
This might be an issue if you are using an individual Google account not
linked to an organizational subscription.
- **Solution:**
- **Individual Users:** Unset the `GOOGLE_CLOUD_PROJECT` and
`GOOGLE_CLOUD_PROJECT_ID` environment variables. Check and remove these
variables from your shell configuration files (for example, `.bashrc`,
`.zshrc`) and any `.env` files. If this doesn't resolve the issue, try
using a different Google account.
- **Organizational Users:** Contact your Google Cloud administrator to be
added to your organization's Gemini Code Assist subscription.
- **Error: `Failed to login. Message: Request contains an invalid argument`**
- **Cause:** Users with Google Workspace accounts or Google Cloud accounts
associated with their Gmail accounts may not be able to activate the free
tier of the Google Code Assist plan.
- **Solution:** For Google Cloud accounts, you can work around this by setting
`GOOGLE_CLOUD_PROJECT` to your project ID. Alternatively, you can obtain the
Gemini API key from
- Users with Google Workspace accounts or Google Cloud accounts associated
with their Gmail accounts may not be able to activate the free tier of the
Google Code Assist plan.
- For Google Cloud accounts, you can work around this by setting
`GOOGLE_CLOUD_PROJECT` to your project ID.
- Alternatively, you can obtain the Gemini API key from
[Google AI Studio](http://aistudio.google.com/app/apikey), which also
includes a separate free tier.
@@ -108,7 +90,7 @@ topics on:
`advanced.excludedEnvVars` setting in your `settings.json` to exclude fewer
variables.
## Exit codes
## Exit Codes
The Gemini CLI uses specific exit codes to indicate the reason for termination.
This is especially useful for scripting and automation.
@@ -121,10 +103,11 @@ This is especially useful for scripting and automation.
| 52 | `FatalConfigError` | A configuration file (`settings.json`) is invalid or contains errors. |
| 53 | `FatalTurnLimitedError` | The maximum number of conversational turns for the session was reached. (non-interactive mode only) |
## Debugging tips
## Debugging Tips
- **CLI debugging:**
- Use the `--debug` flag for more detailed output.
- Use the `--verbose` flag (if available) with CLI commands for more detailed
output.
- Check the CLI logs, often found in a user-specific configuration or cache
directory.
@@ -146,13 +129,10 @@ This is especially useful for scripting and automation.
- Always run `npm run preflight` before committing code. This can catch many
common issues related to formatting, linting, and type errors.
## Existing GitHub issues similar to yours or creating new issues
## Existing GitHub Issues similar to yours or creating new Issues
If you encounter an issue that was not covered here in this _Troubleshooting
guide_, consider searching the Gemini CLI
[Issue tracker on GitHub](https://github.com/google-gemini/gemini-cli/issues).
If you can't find an issue similar to yours, consider creating a new GitHub
Issue with a detailed description. Pull requests are also welcome!
> **Note:** Issues tagged as "🔒Maintainers only" are reserved for project
> maintainers. We will not accept pull requests related to these issues.
+10 -28
View File
@@ -12,7 +12,7 @@ import prettierConfig from 'eslint-config-prettier';
import importPlugin from 'eslint-plugin-import';
import vitest from '@vitest/eslint-plugin';
import globals from 'globals';
import headers from 'eslint-plugin-headers';
import licenseHeader from 'eslint-plugin-license-header';
import path from 'node:path';
import url from 'node:url';
@@ -80,11 +80,6 @@ export default tseslint.config(
},
},
languageOptions: {
parser: tseslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: projectRoot,
},
globals: {
...globals.node,
...globals.es2021,
@@ -122,8 +117,6 @@ export default tseslint.config(
caughtErrorsIgnorePattern: '^_',
},
],
// Prevent async errors from bypassing catch handlers
'@typescript-eslint/return-await': ['error', 'in-try-catch'],
'import/no-internal-modules': [
'error',
{
@@ -164,11 +157,7 @@ export default tseslint.config(
'prefer-arrow-callback': 'error',
'prefer-const': ['error', { destructuring: 'all' }],
radix: 'error',
'no-console': 'error',
'default-case': 'error',
'@typescript-eslint/await-thenable': ['error'],
'@typescript-eslint/no-floating-promises': ['error'],
'@typescript-eslint/no-unnecessary-type-assertion': ['error'],
},
},
{
@@ -210,26 +199,19 @@ export default tseslint.config(
{
files: ['./**/*.{tsx,ts,js}'],
plugins: {
headers,
'license-header': licenseHeader,
import: importPlugin,
},
rules: {
'headers/header-format': [
'license-header/header': [
'error',
{
source: 'string',
content: [
'@license',
'Copyright (year) Google LLC',
'SPDX-License-Identifier: Apache-2.0',
].join('\n'),
patterns: {
year: {
pattern: '202[5-6]',
defaultValue: '2026',
},
},
},
[
'/**',
' * @license',
' * Copyright 2025 Google LLC',
' * SPDX-License-Identifier: Apache-2.0',
' */',
],
],
'import/enforce-node-protocol-usage': ['error', 'always'],
},

Some files were not shown because too many files have changed in this diff Show More