mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-08-02 21:21:09 -07:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eac33bf9e7 | |||
| 589f037b2d | |||
| 11f7a6a2d6 | |||
| aaca0bfbd6 | |||
| 97f8268998 | |||
| 17f9d949ff |
@@ -1,5 +1,5 @@
|
||||
name: 'Create Pull Request'
|
||||
description: 'Creates a pull request.'
|
||||
name: 'Create and Merge Pull Request'
|
||||
description: 'Creates a pull request and merges it automatically.'
|
||||
|
||||
inputs:
|
||||
branch-name:
|
||||
@@ -32,10 +32,8 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
- name: 'Creates a Pull Request'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
- name: 'Create and Approve Pull Request'
|
||||
if: "inputs.dry-run != 'true'"
|
||||
env:
|
||||
GH_TOKEN: '${{ inputs.github-token }}'
|
||||
@@ -53,4 +51,4 @@ runs:
|
||||
--base "${{ inputs.base-branch }}" \
|
||||
--head "${{ inputs.branch-name }}" \
|
||||
--fill)
|
||||
gh pr merge "$PR_URL" --auto
|
||||
gh pr merge "$PR_URL" --auto --squash
|
||||
|
||||
@@ -29,9 +29,7 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
- name: 'Prepare Coverage Comment'
|
||||
id: 'prep_coverage_comment'
|
||||
shell: 'bash'
|
||||
|
||||
@@ -48,18 +48,13 @@ inputs:
|
||||
gemini_api_key:
|
||||
description: 'The API key for running integration tests.'
|
||||
required: true
|
||||
registry:
|
||||
description: 'The registry to publish to.'
|
||||
required: false
|
||||
default: 'npm-wombat'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
|
||||
- name: '👤 Configure Git User'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
@@ -108,37 +103,14 @@ runs:
|
||||
npm run build:packages
|
||||
npm run prepare:package
|
||||
|
||||
- name: '🎁 Bundle'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
shell: 'bash'
|
||||
run: |
|
||||
npm run bundle
|
||||
|
||||
- name: '📦 Prepare for GitHub release'
|
||||
if: "inputs.registry == 'github'"
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
shell: 'bash'
|
||||
run: |
|
||||
node ${{ github.workspace }}/scripts/prepare-github-release.js
|
||||
|
||||
- name: 'Configure npm for publishing to npm'
|
||||
if: "inputs.registry != 'github'"
|
||||
- name: 'Configure npm for publishing'
|
||||
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020'
|
||||
with:
|
||||
node-version-file: '${{ inputs.working-directory }}/.nvmrc'
|
||||
registry-url: 'https://wombat-dressing-room.appspot.com'
|
||||
scope: '@google'
|
||||
|
||||
- name: 'Configure npm for publishing to GitHub'
|
||||
if: "inputs.registry == 'github'"
|
||||
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020'
|
||||
with:
|
||||
node-version-file: '${{ inputs.working-directory }}/.nvmrc'
|
||||
registry-url: 'https://npm.pkg.github.com'
|
||||
scope: '@google-gemini'
|
||||
|
||||
- name: '📦 Publish @google/gemini-cli-core to npm'
|
||||
if: "inputs.registry != 'github'"
|
||||
- name: '📦 Publish @google/gemini-cli-core'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: '${{ inputs.wombat-token-core }}'
|
||||
@@ -150,29 +122,16 @@ runs:
|
||||
npm publish --workspace="@google/gemini-cli-core" --no-tag
|
||||
fi
|
||||
|
||||
- name: '📦 Publish @google-gemini/gemini-cli-core to GitHub'
|
||||
if: "inputs.registry == 'github'"
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: '${{ inputs.github-token }}'
|
||||
shell: 'bash'
|
||||
run: |
|
||||
npm publish \
|
||||
--dry-run="${{ inputs.dry-run }}" \
|
||||
--workspace="@google-gemini/gemini-cli-core" \
|
||||
--no-tag
|
||||
|
||||
- name: '🔗 Install latest core package'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.registry != 'github' }}"
|
||||
if: "${{ inputs.dry-run != 'true' }}"
|
||||
shell: 'bash'
|
||||
run: |
|
||||
npm install "@google/gemini-cli-core@${{ inputs.release-version }}" \
|
||||
--workspace="@google/gemini-cli" \
|
||||
--save-exact
|
||||
|
||||
- name: '📦 Publish @google/gemini-cli to npm'
|
||||
if: "inputs.registry != 'github'"
|
||||
- name: '📦 Publish @google/gemini-cli'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: '${{ inputs.wombat-token-cli }}'
|
||||
@@ -184,21 +143,9 @@ runs:
|
||||
npm publish --workspace="@google/gemini-cli" --no-tag
|
||||
fi
|
||||
|
||||
- name: '📦 Publish @google-gemini/gemini-cli to GitHub'
|
||||
if: "inputs.registry == 'github'"
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: '${{ inputs.github-token }}'
|
||||
shell: 'bash'
|
||||
run: |
|
||||
npm publish \
|
||||
--dry-run="${{ inputs.dry-run }}" \
|
||||
--workspace="@google-gemini/gemini-cli" \
|
||||
--no-tag
|
||||
|
||||
- name: '🔬 Verify NPM release by version'
|
||||
uses: './.github/actions/verify-release'
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.force-skip-tests != 'true' && inputs.registry != 'github' }}"
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.force-skip-tests != 'true' }}"
|
||||
with:
|
||||
npm-package: '@google/gemini-cli@${{ inputs.release-version }}'
|
||||
expected-version: '${{ inputs.release-version }}'
|
||||
@@ -207,7 +154,7 @@ runs:
|
||||
|
||||
- name: '🏷️ Tag release'
|
||||
uses: './.github/actions/tag-npm-release'
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.registry != 'github' }}"
|
||||
if: "${{ inputs.dry-run != 'true' }}"
|
||||
with:
|
||||
channel: '${{ inputs.npm-tag }}'
|
||||
version: '${{ inputs.release-version }}'
|
||||
@@ -215,9 +162,15 @@ runs:
|
||||
wombat-token-core: '${{ inputs.wombat-token-core }}'
|
||||
wombat-token-cli: '${{ inputs.wombat-token-cli }}'
|
||||
|
||||
- name: '🎁 Bundle'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
shell: 'bash'
|
||||
run: |
|
||||
npm run bundle
|
||||
|
||||
- name: '🎉 Create GitHub Release'
|
||||
working-directory: '${{ inputs.working-directory }}'
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.skip-github-release != 'true' && inputs.npm-tag != 'dev' && inputs.registry != 'github' }}"
|
||||
if: "${{ inputs.dry-run != 'true' && inputs.skip-github-release != 'true' && inputs.npm-tag != 'dev' }}"
|
||||
env:
|
||||
GITHUB_TOKEN: '${{ inputs.github-token }}'
|
||||
shell: 'bash'
|
||||
|
||||
@@ -20,9 +20,7 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -30,9 +30,7 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@v4'
|
||||
with:
|
||||
|
||||
@@ -15,9 +15,7 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
- name: 'Run Tests'
|
||||
env:
|
||||
GEMINI_API_KEY: '${{ inputs.gemini_api_key }}'
|
||||
|
||||
@@ -16,16 +16,13 @@ inputs:
|
||||
required: true
|
||||
wombat-token-cli:
|
||||
description: 'The npm token for wombat @google/gemini-cli'
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020'
|
||||
|
||||
@@ -23,9 +23,7 @@ runs:
|
||||
steps:
|
||||
- name: '📝 Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955' # ratchet:actions/checkout@v4
|
||||
@@ -34,10 +32,6 @@ runs:
|
||||
ref: '${{ github.event.inputs.ref }}'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Clear npm cache'
|
||||
shell: 'bash'
|
||||
run: 'npm cache clean --force'
|
||||
|
||||
- name: 'Install from NPM'
|
||||
uses: 'nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08' # ratchet:nick-fields/retry@v3
|
||||
with:
|
||||
@@ -46,29 +40,25 @@ runs:
|
||||
max_attempts: 10
|
||||
command: 'cd ./verify && pkg="${{ inputs.npm-package }}" && npm install --prefer-online --no-cache -g "$pkg"'
|
||||
|
||||
- name: 'Smoke test - NPM Install'
|
||||
- name: 'Basic smoke test'
|
||||
shell: 'bash'
|
||||
working-directory: './verify'
|
||||
run: |-
|
||||
gemini_version=$(gemini --version)
|
||||
if [ "$gemini_version" != "${{ inputs.expected-version }}" ]; then
|
||||
echo "❌ NPM Version mismatch: Got $gemini_version from ${{ inputs.npm-package }}, expected ${{ inputs.expected-version }}"
|
||||
echo "❌ Version mismatch: Got $gemini_version from ${{ inputs.npm-package }}, expected ${{ inputs.expected-version }}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 'Clear npm cache'
|
||||
shell: 'bash'
|
||||
run: 'npm cache clean --force'
|
||||
|
||||
- name: 'Smoke test - NPX Run'
|
||||
- name: 'Install dependencies for integration tests'
|
||||
shell: 'bash'
|
||||
working-directory: './verify'
|
||||
run: |-
|
||||
gemini_version=$(npx --prefer-online "${{ inputs.npm-package}}" --version)
|
||||
if [ "$gemini_version" != "${{ inputs.expected-version }}" ]; then
|
||||
echo "❌ NPX Run Version mismatch: Got $gemini_version from ${{ inputs.npm-package }}, expected ${{ inputs.expected-version }}"
|
||||
exit 1
|
||||
fi
|
||||
run: 'npm install'
|
||||
|
||||
# TODO: Add back integration tests once we resolve
|
||||
# https://github.com/google-gemini/gemini-cli/issues/10517
|
||||
- name: '🔬 Run integration tests against NPM release'
|
||||
working-directory: './verify'
|
||||
env:
|
||||
GEMINI_API_KEY: '${{ inputs.gemini_api_key }}'
|
||||
INTEGRATION_TEST_USE_INSTALLED_GEMINI: 'true'
|
||||
shell: 'bash'
|
||||
run: 'npm run test:integration:sandbox:none'
|
||||
|
||||
@@ -34,7 +34,6 @@ defaults:
|
||||
|
||||
jobs:
|
||||
merge_queue_skipper:
|
||||
permissions: 'read-all'
|
||||
name: 'Merge Queue Skipper'
|
||||
runs-on: 'gemini-cli-ubuntu-16-core'
|
||||
outputs:
|
||||
@@ -55,7 +54,7 @@ jobs:
|
||||
uses: 'actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8' # ratchet:actions/checkout@v5
|
||||
with:
|
||||
ref: '${{ github.event.inputs.branch_ref || github.ref }}'
|
||||
fetch-depth: 0
|
||||
fetch-depth: 1
|
||||
|
||||
- name: 'Set up Node.js'
|
||||
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions/setup-node@v4.4.0
|
||||
@@ -87,9 +86,6 @@ jobs:
|
||||
- name: 'Run Prettier'
|
||||
run: 'node scripts/lint.js --prettier'
|
||||
|
||||
- name: 'Run sensitive keyword linter'
|
||||
run: 'node scripts/lint.js --sensitive-keywords'
|
||||
|
||||
test_linux:
|
||||
name: 'Test (Linux)'
|
||||
runs-on: 'gemini-cli-ubuntu-16-core'
|
||||
@@ -128,12 +124,6 @@ jobs:
|
||||
NO_COLOR: true
|
||||
run: 'npm run test:ci'
|
||||
|
||||
- name: 'Bundle'
|
||||
run: 'npm run bundle'
|
||||
|
||||
- name: 'Smoke test bundle'
|
||||
run: 'node ./bundle/gemini.js --version'
|
||||
|
||||
- name: 'Wait for file system sync'
|
||||
run: 'sleep 2'
|
||||
|
||||
@@ -196,12 +186,6 @@ jobs:
|
||||
NO_COLOR: true
|
||||
run: 'npm run test:ci -- --coverage.enabled=false'
|
||||
|
||||
- name: 'Bundle'
|
||||
run: 'npm run bundle'
|
||||
|
||||
- name: 'Smoke test bundle'
|
||||
run: 'node ./bundle/gemini.js --version'
|
||||
|
||||
- name: 'Wait for file system sync'
|
||||
run: 'sleep 2'
|
||||
|
||||
@@ -338,14 +322,6 @@ jobs:
|
||||
run: 'npm run test:ci -- --coverage.enabled=false'
|
||||
shell: 'pwsh'
|
||||
|
||||
- name: 'Bundle'
|
||||
run: 'npm run bundle'
|
||||
shell: 'pwsh'
|
||||
|
||||
- name: 'Smoke test bundle'
|
||||
run: 'node ./bundle/gemini.js --version'
|
||||
shell: 'pwsh'
|
||||
|
||||
ci:
|
||||
name: 'CI'
|
||||
if: 'always()'
|
||||
|
||||
@@ -11,23 +11,16 @@ on:
|
||||
description: 'The branch, tag, or SHA to release from.'
|
||||
required: true
|
||||
type: 'string'
|
||||
registry:
|
||||
description: 'The registry to publish to.'
|
||||
required: true
|
||||
type: 'choice'
|
||||
options:
|
||||
- 'npm-wombat'
|
||||
- 'github'
|
||||
default: 'npm-wombat'
|
||||
npm_channel:
|
||||
description: 'The npm channel to publish to (only used when registry is npm-wombat)'
|
||||
description: 'The npm channel to publish to.'
|
||||
required: true
|
||||
type: 'choice'
|
||||
options:
|
||||
- 'preview'
|
||||
- 'nightly'
|
||||
- 'latest'
|
||||
default: 'latest'
|
||||
- 'dev'
|
||||
default: 'dev'
|
||||
dry_run:
|
||||
description: 'Run a dry-run of the release process; no branches, npm packages or GitHub releases will be created.'
|
||||
required: true
|
||||
@@ -39,7 +32,7 @@ on:
|
||||
type: 'boolean'
|
||||
default: false
|
||||
skip_github_release:
|
||||
description: 'Select to skip creating a GitHub release (only used when registry is npm-wombat)'
|
||||
description: 'Select to skip creating a GitHub release and create a npm release only.'
|
||||
required: false
|
||||
type: 'boolean'
|
||||
default: false
|
||||
@@ -65,10 +58,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Debug Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: 'echo "${{ toJSON(inputs) }}"'
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020'
|
||||
@@ -110,7 +100,6 @@ jobs:
|
||||
skip-github-release: '${{ github.event.inputs.skip_github_release }}'
|
||||
working-directory: './release'
|
||||
gemini_api_key: '${{ secrets.GEMINI_API_KEY }}'
|
||||
registry: '${{ github.event.inputs.registry }}'
|
||||
|
||||
- name: 'Create Issue on Failure'
|
||||
if: '${{ failure() && github.event.inputs.dry_run == false }}'
|
||||
|
||||
@@ -53,13 +53,11 @@ jobs:
|
||||
run: 'npm ci'
|
||||
|
||||
- name: 'Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(github.event.inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: |
|
||||
echo "${{ toJSON(github.event.inputs) }}"
|
||||
|
||||
- name: 'Run Tests'
|
||||
if: "${{ github.event_name == 'schedule' || github.event.inputs.force_skip_tests == 'false' }}"
|
||||
if: "${{github.event.inputs.force_skip_tests == 'false'}}"
|
||||
uses: './.github/actions/run-tests'
|
||||
with:
|
||||
gemini_api_key: '${{ secrets.GEMINI_API_KEY }}'
|
||||
@@ -101,25 +99,24 @@ jobs:
|
||||
wombat-token-core: '${{ secrets.WOMBAT_TOKEN_CORE }}'
|
||||
wombat-token-cli: '${{ secrets.WOMBAT_TOKEN_CLI }}'
|
||||
github-token: '${{ secrets.GITHUB_TOKEN }}'
|
||||
dry-run: "${{ github.event_name != 'schedule' && github.event.inputs.dry_run == 'true' }}"
|
||||
dry-run: '${{ github.event.inputs.dry_run }}'
|
||||
previous-tag: '${{ steps.nightly_version.outputs.PREVIOUS_TAG }}'
|
||||
working-directory: './release'
|
||||
skip-branch-cleanup: true
|
||||
force-skip-tests: "${{ github.event_name != 'schedule' && github.event.inputs.force_skip_tests == 'true' }}"
|
||||
gemini_api_key: '${{ secrets.GEMINI_API_KEY }}'
|
||||
|
||||
- name: 'Create and Merge Pull Request'
|
||||
uses: './.github/actions/create-pull-request'
|
||||
with:
|
||||
branch-name: 'release/${{ steps.nightly_version.outputs.RELEASE_TAG }}'
|
||||
pr-title: 'chore/release: bump version to ${{ steps.nightly_version.outputs.RELEASE_VERSION }}'
|
||||
pr-title: 'chore(release): bump version to ${{ steps.nightly_version.outputs.RELEASE_VERSION }}'
|
||||
pr-body: 'Automated version bump for nightly release.'
|
||||
github-token: '${{ secrets.GEMINI_CLI_ROBOT_GITHUB_PAT }}'
|
||||
dry-run: "${{ github.event_name != 'schedule' && github.event.inputs.dry_run == 'true' }}"
|
||||
dry-run: '${{ github.event.inputs.dry_run }}'
|
||||
working-directory: './release'
|
||||
|
||||
- name: 'Create Issue on Failure'
|
||||
if: "${{ failure() && (github.event_name == 'schedule' || github.event.inputs.dry_run != 'true') }}"
|
||||
if: "${{ failure() && github.event.inputs.dry_run != 'true' }}"
|
||||
env:
|
||||
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
|
||||
RELEASE_TAG: '${{ steps.nightly_version.outputs.RELEASE_TAG }}'
|
||||
|
||||
@@ -35,7 +35,6 @@ jobs:
|
||||
permissions:
|
||||
contents: 'write'
|
||||
packages: 'write'
|
||||
pull-requests: 'write'
|
||||
issues: 'write'
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
@@ -58,14 +57,14 @@ jobs:
|
||||
cache: 'npm'
|
||||
|
||||
- name: 'Install Dependencies'
|
||||
working-directory: './release'
|
||||
run: |-
|
||||
npm ci
|
||||
|
||||
- name: 'Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: |-
|
||||
echo "${{ toJSON(inputs) }}"
|
||||
|
||||
- name: 'Get Patch Version'
|
||||
id: 'patch_version'
|
||||
|
||||
@@ -59,9 +59,8 @@ jobs:
|
||||
|
||||
- name: 'Print Inputs'
|
||||
shell: 'bash'
|
||||
env:
|
||||
JSON_INPUTS: '${{ toJSON(inputs) }}'
|
||||
run: 'echo "$JSON_INPUTS"'
|
||||
run: |-
|
||||
echo "${{ toJSON(inputs) }}"
|
||||
|
||||
- name: 'Calculate Versions and SHAs'
|
||||
id: 'versions'
|
||||
@@ -117,8 +116,8 @@ jobs:
|
||||
echo " - Commit: ${{ steps.versions.outputs.PREVIEW_SHA }} (${{ github.event.inputs.ref }})"
|
||||
echo " - Previous Tag: ${{ steps.versions.outputs.PREVIOUS_PREVIEW_TAG }}"
|
||||
echo ""
|
||||
echo "Preparing Next Nightly Release: ${{ steps.versions.outputs.NEXT_NIGHTLY_VERSION }}"
|
||||
echo " - Merging Version Update PR to Branch: ${{ github.event.inputs.ref }}"
|
||||
echo "Next Nightly Release: ${{ steps.versions.outputs.NEXT_NIGHTLY_VERSION }}"
|
||||
echo " - Commit: ${{ steps.versions.outputs.NEXT_SHA }} (${{ github.event.inputs.ref }})"
|
||||
echo " - Previous Tag: ${{ steps.versions.outputs.PREVIOUS_NIGHTLY_TAG }}"
|
||||
|
||||
test:
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
name: 'On Merge Smoke Test'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'release/**'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: 'The branch, tag, or SHA to test on.'
|
||||
required: false
|
||||
type: 'string'
|
||||
default: 'main'
|
||||
dry-run:
|
||||
description: 'Run a dry-run of the smoke test; No bug will be created'
|
||||
required: true
|
||||
type: 'boolean'
|
||||
default: true
|
||||
|
||||
jobs:
|
||||
smoke-test:
|
||||
runs-on: 'self-hosted'
|
||||
permissions:
|
||||
contents: 'read'
|
||||
issues: 'write'
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8'
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
- name: 'Install Dependencies'
|
||||
run: 'npm ci'
|
||||
- name: 'Build bundle'
|
||||
run: 'npm run bundle'
|
||||
- name: 'Smoke test bundle'
|
||||
run: 'node ./bundle/gemini.js --version'
|
||||
- name: 'Create Issue on Failure'
|
||||
if: '${{ failure() && github.event.inputs.dry-run == false }}'
|
||||
env:
|
||||
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
|
||||
DETAILS_URL: '${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}'
|
||||
REF: '${{ github.event.inputs.ref }}'
|
||||
run: |
|
||||
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 'kind/bug,priority/p0'
|
||||
@@ -11,12 +11,12 @@ Gemini CLI is an open-source AI agent that brings the power of Gemini directly i
|
||||
|
||||
## 🚀 Why Gemini CLI?
|
||||
|
||||
- **🎯 Free tier**: 60 requests/min and 1,000 requests/day with personal Google account.
|
||||
- **🧠 Powerful Gemini 2.5 Pro**: Access to 1M token context window.
|
||||
- **🔧 Built-in tools**: Google Search grounding, file operations, shell commands, web fetching.
|
||||
- **🔌 Extensible**: MCP (Model Context Protocol) support for custom integrations.
|
||||
- **💻 Terminal-first**: Designed for developers who live in the command line.
|
||||
- **🛡️ Open source**: Apache 2.0 licensed.
|
||||
- **🎯 Free tier**: 60 requests/min and 1,000 requests/day with personal Google account
|
||||
- **🧠 Powerful Gemini 2.5 Pro**: Access to 1M token context window
|
||||
- **🔧 Built-in tools**: Google Search grounding, file operations, shell commands, web fetching
|
||||
- **🔌 Extensible**: MCP (Model Context Protocol) support for custom integrations
|
||||
- **💻 Terminal-first**: Designed for developers who live in the command line
|
||||
- **🛡️ Open source**: Apache 2.0 licensed
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
@@ -109,14 +109,20 @@ Choose the authentication method that best fits your needs:
|
||||
|
||||
### Option 1: Login with Google (OAuth login using your Google Account)
|
||||
|
||||
**✨ Best for:** Individual developers as well as anyone who has a Gemini Code Assist License. (see [quota limits and terms of service](https://cloud.google.com/gemini/docs/quotas) for details)
|
||||
**✨ Best for:**
|
||||
|
||||
- Individual developers.
|
||||
- Google AI Pro and AI Ultra subscribers.
|
||||
- Anyone who has a Gemini Code Assist license.
|
||||
|
||||
_See [quota limits and terms of service](https://cloud.google.com/gemini/docs/quotas) for details._
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- **Free tier**: 60 requests/min and 1,000 requests/day
|
||||
- **Gemini 2.5 Pro** with 1M token context window
|
||||
- **Free tier** with 60 requests/min and 1,000 requests/day
|
||||
- **Gemini 2.5 Pro and Flash** with 1M token context window
|
||||
- **No API key management** - just sign in with your Google account
|
||||
- **Automatic updates** to latest models
|
||||
- **Automatic updates** to our latest models
|
||||
|
||||
#### Start Gemini CLI, then choose _Login with Google_ and follow the browser authentication flow when prompted
|
||||
|
||||
@@ -128,7 +134,7 @@ gemini
|
||||
|
||||
```bash
|
||||
# Set your Google Cloud Project
|
||||
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
|
||||
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_NAME"
|
||||
gemini
|
||||
```
|
||||
|
||||
@@ -165,7 +171,7 @@ export GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
gemini
|
||||
```
|
||||
|
||||
For Google Workspace accounts and other authentication methods, see the [authentication guide](./docs/get-started/authentication.md).
|
||||
For Google Workspace accounts and other authentication methods, see the [authentication guide](./docs/cli/authentication.md).
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
@@ -227,18 +233,17 @@ gemini
|
||||
|
||||
### Getting Started
|
||||
|
||||
- [**Quickstart Guide**](./docs/get-started/index.md) - Get up and running quickly.
|
||||
- [**Authentication Setup**](./docs/get-started/authentication.md) - Detailed auth configuration.
|
||||
- [**Configuration Guide**](./docs/get-started/configuration.md) - Settings and customization.
|
||||
- [**Keyboard Shortcuts**](./docs/cli/keyboard-shortcuts.md) - Productivity tips.
|
||||
- [**Quickstart Guide**](./docs/cli/index.md) - Get up and running quickly
|
||||
- [**Authentication Setup**](./docs/cli/authentication.md) - Detailed auth configuration
|
||||
- [**Configuration Guide**](./docs/cli/configuration.md) - Settings and customization
|
||||
- [**Keyboard Shortcuts**](./docs/keyboard-shortcuts.md) - Productivity tips
|
||||
|
||||
### Core Features
|
||||
|
||||
- [**Commands Reference**](./docs/cli/commands.md) - All slash commands (`/help`, `/chat`, etc).
|
||||
- [**Custom Commands**](./docs/cli/custom-commands.md) - Create your own reusable commands.
|
||||
- [**Context Files (GEMINI.md)**](./docs/cli/gemini-md.md) - Provide persistent context to Gemini CLI.
|
||||
- [**Checkpointing**](./docs/cli/checkpointing.md) - Save and resume conversations.
|
||||
- [**Token Caching**](./docs/cli/token-caching.md) - Optimize token usage.
|
||||
- [**Commands Reference**](./docs/cli/commands.md) - All slash commands (`/help`, `/chat`, `/mcp`, etc.)
|
||||
- [**Checkpointing**](./docs/checkpointing.md) - Save and resume conversations
|
||||
- [**Memory Management**](./docs/tools/memory.md) - Using GEMINI.md context files
|
||||
- [**Token Caching**](./docs/cli/token-caching.md) - Optimize token usage
|
||||
|
||||
### Tools & Extensions
|
||||
|
||||
@@ -246,25 +251,31 @@ gemini
|
||||
- [File System Operations](./docs/tools/file-system.md)
|
||||
- [Shell Commands](./docs/tools/shell.md)
|
||||
- [Web Fetch & Search](./docs/tools/web-fetch.md)
|
||||
- [**MCP Server Integration**](./docs/tools/mcp-server.md) - Extend with custom tools.
|
||||
- [**Custom Extensions**](./docs/extensions/index.md) - Build and share your own commands.
|
||||
- [Multi-file Operations](./docs/tools/multi-file.md)
|
||||
- [**MCP Server Integration**](./docs/tools/mcp-server.md) - Extend with custom tools
|
||||
- [**Custom Extensions**](./docs/extension.md) - Build your own commands
|
||||
|
||||
### Advanced Topics
|
||||
|
||||
- [**Headless Mode (Scripting)**](./docs/cli/headless.md) - Use Gemini CLI in automated workflows.
|
||||
- [**Architecture Overview**](./docs/architecture.md) - How Gemini CLI works.
|
||||
- [**IDE Integration**](./docs/ide-integration/index.md) - VS Code companion.
|
||||
- [**Sandboxing & Security**](./docs/cli/sandbox.md) - Safe execution environments.
|
||||
- [**Trusted Folders**](./docs/cli/trusted-folders.md) - Control execution policies by folder.
|
||||
- [**Enterprise Guide**](./docs/cli/enterprise.md) - Deploy and manage in a corporate environment.
|
||||
- [**Telemetry & Monitoring**](./docs/cli/telemetry.md) - Usage tracking.
|
||||
- [**Tools API Development**](./docs/core/tools-api.md) - Create custom tools.
|
||||
- [**Architecture Overview**](./docs/architecture.md) - How Gemini CLI works
|
||||
- [**IDE Integration**](./docs/ide-integration.md) - VS Code companion
|
||||
- [**Sandboxing & Security**](./docs/sandbox.md) - Safe execution environments
|
||||
- [**Enterprise Deployment**](./docs/deployment.md) - Docker, system-wide config
|
||||
- [**Telemetry & Monitoring**](./docs/telemetry.md) - Usage tracking
|
||||
- [**Tools API Development**](./docs/core/tools-api.md) - Create custom tools
|
||||
|
||||
### Configuration & Customization
|
||||
|
||||
- [**Settings Reference**](./docs/cli/configuration.md) - All configuration options
|
||||
- [**Theme Customization**](./docs/cli/themes.md) - Visual customization
|
||||
- [**.gemini Directory**](./docs/gemini-ignore.md) - Project-specific settings
|
||||
- [**Environment Variables**](./docs/cli/configuration.md#environment-variables)
|
||||
|
||||
### Troubleshooting & Support
|
||||
|
||||
- [**Troubleshooting Guide**](./docs/troubleshooting.md) - Common issues and solutions.
|
||||
- [**FAQ**](./docs/faq.md) - Frequently asked questions.
|
||||
- Use `/bug` command to report issues directly from the CLI.
|
||||
- [**Troubleshooting Guide**](./docs/troubleshooting.md) - Common issues and solutions
|
||||
- [**FAQ**](./docs/troubleshooting.md#frequently-asked-questions) - Quick answers
|
||||
- Use `/bug` command to report issues directly from the CLI
|
||||
|
||||
### Using MCP Servers
|
||||
|
||||
@@ -282,26 +293,25 @@ See the [MCP Server Integration guide](./docs/tools/mcp-server.md) for setup ins
|
||||
|
||||
We welcome contributions! Gemini CLI is fully open source (Apache 2.0), and we encourage the community to:
|
||||
|
||||
- Report bugs and suggest features.
|
||||
- Improve documentation.
|
||||
- Submit code improvements.
|
||||
- Share your MCP servers and extensions.
|
||||
- Report bugs and suggest features
|
||||
- Improve documentation
|
||||
- Submit code improvements
|
||||
- Share your MCP servers and extensions
|
||||
|
||||
See our [Contributing Guide](./CONTRIBUTING.md) for development setup, coding standards, and how to submit pull requests.
|
||||
|
||||
Check our [Official Roadmap](https://github.com/orgs/google-gemini/projects/11) for planned features and priorities.
|
||||
Check our [Official Roadmap](https://github.com/orgs/google-gemini/projects/11/) for planned features and priorities.
|
||||
|
||||
## 📖 Resources
|
||||
|
||||
- **[Official Roadmap](./ROADMAP.md)** - See what's coming next.
|
||||
- **[Changelog](./docs/changelogs/index.md)** - See recent notable updates.
|
||||
- **[NPM Package](https://www.npmjs.com/package/@google/gemini-cli)** - Package registry.
|
||||
- **[GitHub Issues](https://github.com/google-gemini/gemini-cli/issues)** - Report bugs or request features.
|
||||
- **[Security Advisories](https://github.com/google-gemini/gemini-cli/security/advisories)** - Security updates.
|
||||
- **[Official Roadmap](./ROADMAP.md)** - See what's coming next
|
||||
- **[NPM Package](https://www.npmjs.com/package/@google/gemini-cli)** - Package registry
|
||||
- **[GitHub Issues](https://github.com/google-gemini/gemini-cli/issues)** - Report bugs or request features
|
||||
- **[Security Advisories](https://github.com/google-gemini/gemini-cli/security/advisories)** - Security updates
|
||||
|
||||
### Uninstall
|
||||
|
||||
See the [Uninstall Guide](docs/cli/uninstall.md) for removal instructions.
|
||||
See the [Uninstall Guide](docs/Uninstall.md) for removal instructions.
|
||||
|
||||
## 📄 Legal
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ The Gemini CLI is primarily composed of two main packages, along with a suite of
|
||||
1. **CLI package (`packages/cli`):**
|
||||
- **Purpose:** This contains the user-facing portion of the Gemini CLI, such as handling the initial user input, presenting the final output, and managing the overall user experience.
|
||||
- **Key functions contained in the package:**
|
||||
- [Input processing](../cli/commands.md)
|
||||
- [Input processing](./cli/commands.md)
|
||||
- History management
|
||||
- Display rendering
|
||||
- [Theme and UI customization](../cli/themes.md)
|
||||
- [CLI configuration settings](../get-started/configuration.md)
|
||||
- [Theme and UI customization](./cli/themes.md)
|
||||
- [CLI configuration settings](./cli/configuration.md)
|
||||
|
||||
2. **Core package (`packages/core`):**
|
||||
- **Purpose:** This acts as the backend for the Gemini CLI. It receives requests sent from `packages/cli`, orchestrates interactions with the Gemini API, and manages the execution of available tools.
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
# Gemini CLI Changelog
|
||||
|
||||
Wondering what's new in Gemini CLI? This document provides key highlights and notable changes to Gemini CLI.
|
||||
|
||||
## 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 in-editor diffing in your IDE of choice. ([pr](https://github.com/google-gemini/gemini-cli/pull/8479) by [@skeshive](https://github.com/skeshive))
|
||||
- 🎉 **Gemini CLI extensions**
|
||||
- **Flutter:** An early version to help you create, build, test, and run Flutter apps with Gemini CLI ([extension](https://github.com/flutter/gemini-cli-extension))
|
||||
- **nanobanana:** Integrate nanobanana into Gemini CLI ([extension](https://github.com/gemini-cli-extensions/nanobanana))
|
||||
- **Telemetry config via environment:** Manage telemetry settings using environment variables for a more flexible setup. ([docs](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/telemetry.md#configuration), [pr](https://github.com/google-gemini/gemini-cli/pull/9113) by [@jerop](https://github.com/jerop))
|
||||
- **Experimental todos:** Track and display progress on complex tasks with a managed checklist. Off by default but can be enabled via `"useWriteTodos": true` ([pr](https://github.com/google-gemini/gemini-cli/pull/8761) by [@anj-s](https://github.com/anj-s))
|
||||
- **Share chat support for tools:** Using `/chat share` will now also render function calls and responses in the final markdown file. ([pr](https://github.com/google-gemini/gemini-cli/pull/8693) by [@rramkumar1](https://github.com/rramkumar1))
|
||||
- **Citations:** Now enabled for all users ([pr](https://github.com/google-gemini/gemini-cli/pull/8570) by [@scidomino](https://github.com/scidomino))
|
||||
- **Custom commands in Headless Mode:** Run custom slash commands directly from the command line in non-interactive mode: `gemini "/joke Chuck Norris"` ([pr](https://github.com/google-gemini/gemini-cli/pull/8305) by [@capachino](https://github.com/capachino))
|
||||
- **Small features, polish, reliability & bug fixes:** A large amount of changes, smaller features, UI updates, reliability and bug fixes + general polish made it in this week!
|
||||
|
||||
## v0.6.0 - Gemini CLI weekly update - 2025-09-15
|
||||
|
||||
- 🎉 **Higher limits for Google AI Pro and Ultra subscribers:** We’re psyched to finally announce that Google AI Pro and AI Ultra subscribers now get access to significantly higher 2.5 quota limits for Gemini CLI!
|
||||
- **Announcement:** [https://blog.google/technology/developers/gemini-cli-code-assist-higher-limits/](https://blog.google/technology/developers/gemini-cli-code-assist-higher-limits/)
|
||||
- 🎉**Gemini CLI Databases and BigQuery Extensions:** Connect Gemini CLI to all of your cloud data with Gemini CLI.
|
||||
- Announcement and how to get started with each of the below extensions: [https://cloud.google.com/blog/products/databases/gemini-cli-extensions-for-google-data-cloud?e=48754805](https://cloud.google.com/blog/products/databases/gemini-cli-extensions-for-google-data-cloud?e=48754805)
|
||||
- **AlloyDB:** Interact, manage and observe AlloyDB for PostgreSQL databases ([manage](https://github.com/gemini-cli-extensions/alloydb#configuration), [observe](https://github.com/gemini-cli-extensions/alloydb-observability#configuration))
|
||||
- **BigQuery:** Connect and query your BigQuery datasets or utilize a sub-agent for contextual insights ([query](https://github.com/gemini-cli-extensions/bigquery-data-analytics#configuration), [sub-agent](https://github.com/gemini-cli-extensions/bigquery-conversational-analytics))
|
||||
- **Cloud SQL:** Interact, manage and observe Cloud SQL for PostgreSQL ([manage](https://github.com/gemini-cli-extensions/cloud-sql-postgresql#configuration),[ observe](https://github.com/gemini-cli-extensions/cloud-sql-postgresql-observability#configuration)), Cloud SQL for MySQL ([manage](https://github.com/gemini-cli-extensions/cloud-sql-mysql#configuration),[ observe](https://github.com/gemini-cli-extensions/cloud-sql-mysql-observability#configuration)) and Cloud SQL for SQL Server ([manage](https://github.com/gemini-cli-extensions/cloud-sql-sqlserver#configuration),[ observe](https://github.com/gemini-cli-extensions/cloud-sql-sqlserver-observability#configuration)) databases.
|
||||
- **Dataplex:** Discover, manage, and govern data and AI artifacts ([extension](https://github.com/gemini-cli-extensions/dataplex#configuration))
|
||||
- **Firestore:** Interact with Firestore databases, collections and documents ([extension](https://github.com/gemini-cli-extensions/firestore-native#configuration))
|
||||
- **Looker:** Query data, run Looks and create dashboards ([extension](https://github.com/gemini-cli-extensions/looker#configuration))
|
||||
- **MySQL:** Interact with MySQL databases ([extension](https://github.com/gemini-cli-extensions/mysql#configuration))
|
||||
- **Postgres:** Interact with PostgreSQL databases ([extension](https://github.com/gemini-cli-extensions/postgres#configuration))
|
||||
- **Spanner:** Interact with Spanner databases ([extension](https://github.com/gemini-cli-extensions/spanner#configuration))
|
||||
- **SQL Server:** Interact with SQL Server databases ([extension](https://github.com/gemini-cli-extensions/sql-server#configuration))
|
||||
- **MCP Toolbox:** Configure and load custom tools for more than 30+ data sources ([extension](https://github.com/gemini-cli-extensions/mcp-toolbox#configuration))
|
||||
- **JSON output mode:** Have Gemini CLI output JSON with `--output-format json` when invoked headlessly for easy parsing and post-processing. Includes response, stats and errors. ([pr](https://github.com/google-gemini/gemini-cli/pull/8119) by [@jerop](https://github.com/jerop))
|
||||
- **Keybinding triggered approvals:** When you use shortcuts (`shift+y` or `shift+tab`) to activate YOLO/auto-edit modes any pending confirmation dialogs will now approve. ([pr](https://github.com/google-gemini/gemini-cli/pull/6665) by [@bulkypanda](https://github.com/bulkypanda))
|
||||
- **Chat sharing:** Convert the current conversation to a Markdown or JSON file with _/chat share <file.md|file.json>_ ([pr](https://github.com/google-gemini/gemini-cli/pull/8139) by [@rramkumar1](https://github.com/rramkumar1))
|
||||
- **Prompt search:** Search your prompt history using `ctrl+r`. ([pr](https://github.com/google-gemini/gemini-cli/pull/5539) by [@Aisha630](https://github.com/Aisha630))
|
||||
- **Input undo/redo:** Recover accidentally deleted text in the input prompt using `ctrl+z` (undo) and `ctrl+shift+z` (redo). ([pr](https://github.com/google-gemini/gemini-cli/pull/4625) by [@masiafrest](https://github.com/masiafrest))
|
||||
- **Loop detection confirmation:** When loops are detected you are now presented with a dialog to disable detection for the current session. ([pr](https://github.com/google-gemini/gemini-cli/pull/8231) by [@SandyTao520](https://github.com/SandyTao520))
|
||||
- **Direct to Google Cloud Telemetry:** Directly send telemetry to Google Cloud for a simpler and more streamlined setup. ([pr](https://github.com/google-gemini/gemini-cli/pull/8541) by [@jerop](https://github.com/jerop))
|
||||
- **Visual Mode Indicator Revamp:** ‘shell’, 'accept edits' and 'yolo' modes now have colors to match their impact / usage. Input box now also updates. ([shell](https://imgur.com/a/DovpVF1), [accept-edits](https://imgur.com/a/33KDz3J), [yolo](https://imgur.com/a/tbFwIWp), [pr](https://github.com/google-gemini/gemini-cli/pull/8200) by [@miguelsolorio](https://github.com/miguelsolorio))
|
||||
- **Small features, polish, reliability & bug fixes:** A large amount of changes, smaller features, UI updates, reliability and bug fixes + general polish made it in this week!
|
||||
|
||||
## 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), [pr](https://github.com/jlowin/fastmcp/pull/1709) by [@jackwotherspoon](https://github.com/jackwotherspoon)**)**
|
||||
- Getting started: [https://gofastmcp.com/integrations/gemini-cli](https://gofastmcp.com/integrations/gemini-cli)
|
||||
- **Positional Prompt for Non-Interactive:** Seamlessly invoke Gemini CLI headlessly via `gemini "Hello"`. Synonymous with passing `-p`. ([gif](https://imgur.com/a/hcBznpB), [pr](https://github.com/google-gemini/gemini-cli/pull/7668) by [@allenhutchison](https://github.com/allenhutchison))
|
||||
- **Experimental Tool output truncation:** Enable truncating shell tool outputs and saving full output to a file by setting `"enableToolOutputTruncation": true `([pr](https://github.com/google-gemini/gemini-cli/pull/8039) by [@SandyTao520](https://github.com/SandyTao520))
|
||||
- **Edit Tool improvements:** Gemini CLI’s ability to edit files should now be far more capable. ([pr](https://github.com/google-gemini/gemini-cli/pull/7679) by [@silviojr](https://github.com/silviojr))
|
||||
- **Custom witty messages:** The feature you’ve all been waiting for… Personalized witty loading messages via `"ui": { "customWittyPhrases": ["YOLO"]}` in `settings.json`. ([pr](https://github.com/google-gemini/gemini-cli/pull/7641) by [@JayadityaGit](https://github.com/JayadityaGit))
|
||||
- **Nested .gitignore File Handling:** Nested `.gitignore` files are now respected. ([pr](https://github.com/google-gemini/gemini-cli/pull/7645) by [@gsquared94](https://github.com/gsquared94))
|
||||
- **Enforced authentication:** System administrators can now mandate a specific authentication method via `"enforcedAuthType": "oauth-personal|gemini-api-key|…"`in `settings.json`. ([pr](https://github.com/google-gemini/gemini-cli/pull/6564) by [@chrstnb](https://github.com/chrstnb))
|
||||
- **A2A development-tool extension:** An RFC for an Agent2Agent ([A2A](https://a2a-protocol.org/latest/)) powered extension for developer tool use cases. ([feedback](https://github.com/google-gemini/gemini-cli/discussions/7822), [pr](https://github.com/google-gemini/gemini-cli/pull/7817) by [@skeshive](https://github.com/skeshive))
|
||||
- **Hands on Codelab: **[https://codelabs.developers.google.com/gemini-cli-hands-on](https://codelabs.developers.google.com/gemini-cli-hands-on)
|
||||
- **Small features, polish, reliability & bug fixes:** A large amount of changes, smaller features, UI updates, reliability and bug fixes + general polish made it in this week!
|
||||
|
||||
## 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 installed deploy your app to the cloud with `/deploy` and find and fix security vulnerabilities with `/security:analyze`.
|
||||
- Announcement and how to get started: [https://cloud.google.com/blog/products/ai-machine-learning/automate-app-deployment-and-security-analysis-with-new-gemini-cli-extensions](https://cloud.google.com/blog/products/ai-machine-learning/automate-app-deployment-and-security-analysis-with-new-gemini-cli-extensions)
|
||||
- **Experimental**
|
||||
- **Edit Tool:** Give our new edit tool a try by setting `"useSmartEdit": true` in `settings.json`! ([feedback](https://github.com/google-gemini/gemini-cli/discussions/7758), [pr](https://github.com/google-gemini/gemini-cli/pull/6823) by [@silviojr](https://github.com/silviojr))
|
||||
- **Model talking to itself fix:** We’ve removed a model workaround that would encourage Gemini CLI to continue conversations on your behalf. This may be disruptive and can be disabled via `"skipNextSpeakerCheck": false` in your `settings.json` ([feedback](https://github.com/google-gemini/gemini-cli/discussions/6666), [pr](https://github.com/google-gemini/gemini-cli/pull/7614) by [@SandyTao520](https://github.com/SandyTao520))
|
||||
- **Prompt completion:** Get real-time AI suggestions to complete your prompts as you type. Enable it with `"general": { "enablePromptCompletion": true }` and share your feedback! ([gif](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*hvegW7YXOg6N_beUWhTdxA.gif), [pr](https://github.com/google-gemini/gemini-cli/pull/4691) by [@3ks](https://github.com/3ks))
|
||||
- **Footer visibility configuration:** Customize the CLI's footer look and feel in `settings.json` ([pr](https://github.com/google-gemini/gemini-cli/pull/7419) by [@miguelsolorio](https://github.com/miguelsolorio))
|
||||
- `hideCWD`: hide current working directory.
|
||||
- `hideSandboxStatus`: hide sandbox status.
|
||||
- `hideModelInfo`: hide current model information.
|
||||
- `hideContextSummary`: hide request context summary.
|
||||
- **Citations:** For enterprise Code Assist licenses users will now see citations in their responses by default. Enable this yourself with `"showCitations": true` ([pr](https://github.com/google-gemini/gemini-cli/pull/7350) by [@scidomino](https://github.com/scidomino))
|
||||
- **Pro Quota Ddalog:** Handle daily Pro model usage limits with an interactive dialog that lets you immediately switch auth or fallback. ([pr](https://github.com/google-gemini/gemini-cli/pull/7094) by [@JayadityaGit](https://github.com/JayadityaGit))
|
||||
- **Custom commands @:** Embed local file or directory content directly into your custom command prompts using `@{path}` syntax ([gif](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*GosBAo2SjMfFffAnzT7ZMg.gif), [pr](https://github.com/google-gemini/gemini-cli/pull/6716) by [@abhipatel12](https://github.com/abhipatel12))
|
||||
- **2.5 Flash Lite support:** You can now use the `gemini-2.5-flash-lite` model for Gemini CLI via `gemini -m …`. ([gif](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*P4SKwnrsyBuULoHrFqsFKQ.gif), [pr](https://github.com/google-gemini/gemini-cli/pull/4652) by [@psinha40898](https://github.com/psinha40898))
|
||||
- **CLI streamlining:** We have deprecated a number of command line arguments in favor of `settings.json` alternatives. We will remove these arguments in a future release. See the PR for the full list of deprecations. ([pr](https://github.com/google-gemini/gemini-cli/pull/7360) by [@allenhutchison](https://github.com/allenhutchison))
|
||||
- **JSON session summary:** Track and save detailed CLI session statistics to a JSON file for performance analysis with `--session-summary <path>` ([pr](https://github.com/google-gemini/gemini-cli/pull/7347) by [@leehagoodjames](https://github.com/leehagoodjames))
|
||||
- **Robust keyboard handling:** More reliable and consistent behavior for arrow keys, special keys (Home, End, etc.), and modifier combinations across various terminals. ([pr](https://github.com/google-gemini/gemini-cli/pull/7118) by [@deepankarsharma](https://github.com/deepankarsharma))
|
||||
- **MCP loading indicator:** Provides visual feedback during CLI initialization when connecting to multiple servers. ([pr](https://github.com/google-gemini/gemini-cli/pull/6923) by [@swissspidy](https://github.com/swissspidy))
|
||||
- **Small features, polish, reliability & bug fixes:** A large amount of changes, smaller features, UI updates, reliability and bug fixes + general polish made it in this week!
|
||||
+179
-1
@@ -1,3 +1,181 @@
|
||||
# Authentication Setup
|
||||
|
||||
See: [Getting Started - Authentication Setup](../get-started/authentication.md).
|
||||
Gemini CLI requires you to authenticate with Google's AI services. On initial startup you'll need to configure **one** of the following authentication methods:
|
||||
|
||||
1. **Login with Google**
|
||||
1. **Google AI Pro and AI Ultra subscribers**
|
||||
- Use this option to log in with your Google account that you use with Google AI Pro and Ultra.
|
||||
- During initial startup, Gemini CLI will direct you to a webpage for authentication. Once authenticated, your credentials will be cached locally so the web login can be skipped on subsequent runs.
|
||||
- Note that the web login must be done in a browser that can communicate with the machine Gemini CLI is being run from. (Specifically, the browser will be redirected to a localhost URL that Gemini CLI will be listening on.)
|
||||
2. **Gemini Code Assist:**
|
||||
- Use this option to log in with your Google account.
|
||||
- During initial startup, Gemini CLI will direct you to a webpage for authentication. Once authenticated, your credentials will be cached locally so the web login can be skipped on subsequent runs.
|
||||
- Note that the web login must be done in a browser that can communicate with the machine Gemini CLI is being run from. (Specifically, the browser will be redirected to a localhost url that Gemini CLI will be listening on.)
|
||||
- <a id="workspace-gca">Users may have to specify a GOOGLE_CLOUD_PROJECT if:</a>
|
||||
1. You have a Google Workspace account. Google Workspace is a paid service for businesses and organizations that provides a suite of productivity tools, including a custom email domain (e.g. your-name@your-company.com), enhanced security features, and administrative controls. These accounts are often managed by an employer or school.
|
||||
1. You have received a Gemini Code Assist license through the [Google Developer Program](https://developers.google.com/program/plans-and-pricing) (including qualified Google Developer Experts).
|
||||
1. You have been assigned a license to a current Gemini Code Assist standard or enterprise subscription.
|
||||
1. You are using the product outside the [supported regions](https://developers.google.com/gemini-code-assist/resources/available-locations) for free individual usage.
|
||||
1. You are a Google account holder under the age of 18.
|
||||
- If you fall into one of these categories, you must first configure a Google Cloud Project ID to use, [enable the Gemini for Cloud API](https://cloud.google.com/gemini/docs/discover/set-up-gemini#enable-api) and [configure access permissions](https://cloud.google.com/gemini/docs/discover/set-up-gemini#grant-iam).
|
||||
|
||||
You can temporarily set the environment variable in your current shell session using the following command:
|
||||
|
||||
```bash
|
||||
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
|
||||
```
|
||||
- For repeated use, you can add the environment variable to your [.env file](#persisting-environment-variables-with-env-files) or your shell's configuration file (like `~/.bashrc`, `~/.zshrc`, or `~/.profile`). For example, the following command adds the environment variable to a `~/.bashrc` file:
|
||||
|
||||
```bash
|
||||
echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
2. **<a id="gemini-api-key"></a>Gemini API key:**
|
||||
- Obtain your API key from Google AI Studio: [https://aistudio.google.com/app/apikey](https://aistudio.google.com/app/apikey)
|
||||
- Set the `GEMINI_API_KEY` environment variable. In the following methods, replace `YOUR_GEMINI_API_KEY` with the API key you obtained from Google AI Studio:
|
||||
- You can temporarily set the environment variable in your current shell session using the following command:
|
||||
```bash
|
||||
export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
|
||||
```
|
||||
- For repeated use, you can add the environment variable to your [.env file](#persisting-environment-variables-with-env-files).
|
||||
|
||||
- Alternatively you can export the API key from your shell's configuration file (like `~/.bashrc`, `~/.zshrc`, or `~/.profile`). For example, the following command adds the environment variable to a `~/.bashrc` file:
|
||||
|
||||
```bash
|
||||
echo 'export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
|
||||
|
||||
3. **Vertex AI:**
|
||||
- **API Key:**
|
||||
- Obtain your Google Cloud API key: [Get an API Key](https://cloud.google.com/vertex-ai/generative-ai/docs/start/api-keys?usertype=newuser)
|
||||
- Set the `GOOGLE_API_KEY` environment variable. In the following methods, replace `YOUR_GOOGLE_API_KEY` with your Vertex AI API key:
|
||||
- You can temporarily set the environment variable in your current shell session using the following command:
|
||||
```bash
|
||||
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
|
||||
```
|
||||
- For repeated use, you can add the environment variable to your [.env file](#persisting-environment-variables-with-env-files) or your shell's configuration file (like `~/.bashrc`, `~/.zshrc`, or `~/.profile`). For example, the following command adds the environment variable to a `~/.bashrc` file:
|
||||
|
||||
```bash
|
||||
echo 'export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
|
||||
|
||||
> **Note:**
|
||||
> If you encounter an error like `"API keys are not supported by this API - Expected OAuth2 access token or other authentication credentials that assert a principal"`, it is likely that your organization has restricted the creation of service account API keys. In this case, please try the [service account JSON key](#service-account-json-key) method described below.
|
||||
|
||||
- **Application Default Credentials (ADC):**
|
||||
|
||||
> **Note:**
|
||||
> If you have previously set the `GOOGLE_API_KEY` or `GEMINI_API_KEY` environment variables, you must unset them to use Application Default Credentials.
|
||||
>
|
||||
> ```bash
|
||||
> unset GOOGLE_API_KEY GEMINI_API_KEY
|
||||
> ```
|
||||
- **Using `gcloud` (for local development):**
|
||||
- Ensure you have a Google Cloud project and have enabled the Vertex AI API.
|
||||
- Log in with your user credentials:
|
||||
```bash
|
||||
gcloud auth application-default login
|
||||
```
|
||||
For more information, see [Set up Application Default Credentials for Google Cloud](https://cloud.google.com/docs/authentication/provide-credentials-adc).
|
||||
- **<a id="service-account-json-key"></a>Using a Service Account (for applications or when service account API keys are restricted):**
|
||||
- If you are unable to create an API key due to [organization policies](https://cloud.google.com/vertex-ai/generative-ai/docs/start/api-keys?usertype=existinguser#expandable-2), or if you are running in a non-interactive environment, you can authenticate using a service account key.
|
||||
- [Create a service account and key](https://cloud.google.com/iam/docs/keys-create-delete), and download the JSON key file. The service account will need to be assigned the "Vertex AI User" role.
|
||||
- Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the absolute path of the JSON file.
|
||||
- You can temporarily set the environment variable in your current shell session:
|
||||
```bash
|
||||
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
|
||||
```
|
||||
- For repeated use, you can add the command to your shell's configuration file (e.g., `~/.bashrc`).
|
||||
```bash
|
||||
echo 'export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
:warning: Be advised that when you export service account credentials inside your shell configuration file, any other process executed from the shell can read it.
|
||||
|
||||
- **Required Environment Variables for ADC:**
|
||||
- When using ADC (either with `gcloud` or a service account), you must also set the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` environment variables. In the following methods, replace `YOUR_PROJECT_ID` and `YOUR_PROJECT_LOCATION` with the relevant values for your project:
|
||||
- You can temporarily set these environment variables in your current shell session using the following commands:
|
||||
```bash
|
||||
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
|
||||
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION" # e.g., us-central1
|
||||
```
|
||||
- For repeated use, you can add the environment variables to your [.env file](#persisting-environment-variables-with-env-files) or your shell's configuration file (like `~/.bashrc`, `~/.zshrc`, or `~/.profile`). For example, the following commands add the environment variables to a `~/.bashrc` file:
|
||||
```bash
|
||||
echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc
|
||||
echo 'export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
4. **Cloud Shell:**
|
||||
- This option is only available when running in a Google Cloud Shell environment.
|
||||
- It automatically uses the credentials of the logged-in user in the Cloud Shell environment.
|
||||
- This is the default authentication method when running in Cloud Shell and no other method is configured.
|
||||
|
||||
:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
|
||||
|
||||
### Persisting Environment Variables with `.env` Files
|
||||
|
||||
You can create a **`.gemini/.env`** file in your project directory or in your home directory. Creating a plain **`.env`** file also works, but `.gemini/.env` is recommended to keep Gemini variables isolated from other tools.
|
||||
|
||||
**Important:** Some environment variables (like `DEBUG` and `DEBUG_MODE`) are automatically excluded from project `.env` files to prevent interference with gemini-cli behavior. Use `.gemini/.env` files for gemini-cli specific variables.
|
||||
|
||||
Gemini CLI automatically loads environment variables from the **first** `.env` file it finds, using the following search order:
|
||||
|
||||
1. Starting in the **current directory** and moving upward toward `/`, for each directory it checks:
|
||||
1. `.gemini/.env`
|
||||
2. `.env`
|
||||
2. If no file is found, it falls back to your **home directory**:
|
||||
- `~/.gemini/.env`
|
||||
- `~/.env`
|
||||
|
||||
> **Important:** The search stops at the **first** file encountered—variables are **not merged** across multiple files.
|
||||
|
||||
#### Examples
|
||||
|
||||
**Project-specific overrides** (take precedence when you are inside the project):
|
||||
|
||||
```bash
|
||||
mkdir -p .gemini
|
||||
echo 'GOOGLE_CLOUD_PROJECT="your-project-id"' >> .gemini/.env
|
||||
```
|
||||
|
||||
**User-wide settings** (available in every directory):
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gemini
|
||||
cat >> ~/.gemini/.env <<'EOF'
|
||||
GOOGLE_CLOUD_PROJECT="your-project-id"
|
||||
GEMINI_API_KEY="your-gemini-api-key"
|
||||
EOF
|
||||
```
|
||||
|
||||
## Non-Interactive Mode / Headless Environments
|
||||
|
||||
When running the Gemini CLI in a non-interactive environment, you cannot use the interactive login flow.
|
||||
Instead, you must configure authentication using environment variables.
|
||||
|
||||
The CLI will automatically detect if it is running in a non-interactive terminal and will use one of the
|
||||
following authentication methods if available:
|
||||
|
||||
1. **Gemini API Key:**
|
||||
- Set the `GEMINI_API_KEY` environment variable.
|
||||
- The CLI will use this key to authenticate with the Gemini API.
|
||||
|
||||
2. **Vertex AI:**
|
||||
- Set the `GOOGLE_GENAI_USE_VERTEXAI=true` environment variable.
|
||||
- **Using an API Key:** Set the `GOOGLE_API_KEY` environment variable.
|
||||
- **Using Application Default Credentials (ADC):**
|
||||
- Run `gcloud auth application-default login` in your environment to configure ADC.
|
||||
- Ensure the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` environment variables are set.
|
||||
|
||||
If none of these environment variables are set in a non-interactive session, the CLI will exit with an error.
|
||||
|
||||
For comprehensive guidance on using Gemini CLI programmatically and in
|
||||
automation workflows, see the [Headless Mode Guide](../headless.md).
|
||||
|
||||
+244
-7
@@ -21,7 +21,7 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- Linux/macOS: `~/.gemini/tmp/<project_hash>/`
|
||||
- Windows: `C:\Users\<YourUsername>\.gemini\tmp\<project_hash>\`
|
||||
- When you run `/chat list`, the CLI only scans these specific directories to find available checkpoints.
|
||||
- **Note:** These checkpoints are for manually saving and resuming conversation states. For automatic checkpoints created before file modifications, see the [Checkpointing documentation](../cli/checkpointing.md).
|
||||
- **Note:** These checkpoints are for manually saving and resuming conversation states. For automatic checkpoints created before file modifications, see the [Checkpointing documentation](../checkpointing.md).
|
||||
- **`resume`**
|
||||
- **Description:** Resumes a conversation from a previous save.
|
||||
- **Usage:** `/chat resume <tag>`
|
||||
@@ -62,7 +62,7 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- **Description:** Open a dialog for selecting supported editors.
|
||||
|
||||
- **`/extensions`**
|
||||
- **Description:** Lists all active extensions in the current Gemini CLI session. See [Gemini CLI Extensions](../extensions/index.md).
|
||||
- **Description:** Lists all active extensions in the current Gemini CLI session. See [Gemini CLI Extensions](../extension.md).
|
||||
|
||||
- **`/help`** (or **`/?`**)
|
||||
- **Description:** Display help information about Gemini CLI, including available commands and their usage.
|
||||
@@ -87,14 +87,12 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- **Description:** Display the full, concatenated content of the current hierarchical memory that has been loaded from all `GEMINI.md` files. This lets you inspect the instructional context being provided to the Gemini model.
|
||||
- **`refresh`**:
|
||||
- **Description:** Reload the hierarchical instructional memory from all `GEMINI.md` files found in the configured locations (global, project/ancestors, and sub-directories). This command updates the model with the latest `GEMINI.md` content.
|
||||
- **`list`**:
|
||||
- **Description:** Lists the paths of the GEMINI.md files in use for hierarchical memory.
|
||||
- **Note:** For more details on how `GEMINI.md` files contribute to hierarchical memory, see the [CLI Configuration documentation](../get-started/configuration.md).
|
||||
- **Note:** For more details on how `GEMINI.md` files contribute to hierarchical memory, see the [CLI Configuration documentation](./configuration.md#4-geminimd-files-hierarchical-instructional-context).
|
||||
|
||||
- **`/restore`**
|
||||
- **Description:** Restores the project files to the state they were in just before a tool was executed. This is particularly useful for undoing file edits made by a tool. If run without a tool call ID, it will list available checkpoints to restore from.
|
||||
- **Usage:** `/restore [tool_call_id]`
|
||||
- **Note:** Only available if the CLI is invoked with the `--checkpointing` option or configured via [settings](../get-started/configuration.md). See [Checkpointing documentation](../cli/checkpointing.md) for more details.
|
||||
- **Note:** Only available if the CLI is invoked with the `--checkpointing` option or configured via [settings](./configuration.md). See [Checkpointing documentation](../checkpointing.md) for more details.
|
||||
|
||||
- **`/settings`**
|
||||
- **Description:** Open the settings editor to view and modify Gemini CLI settings.
|
||||
@@ -144,7 +142,246 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
|
||||
### 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).
|
||||
For a quick start, see the [example](#example-a-pure-function-refactoring-command) below.
|
||||
|
||||
Custom commands allow you to save and reuse your favorite or most frequently used prompts as personal shortcuts within Gemini CLI. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
|
||||
|
||||
#### File Locations & Precedence
|
||||
|
||||
Gemini CLI discovers commands from two locations, loaded in a specific order:
|
||||
|
||||
1. **User Commands (Global):** Located in `~/.gemini/commands/`. These commands are available in any project you are working on.
|
||||
2. **Project Commands (Local):** Located in `<your-project-root>/.gemini/commands/`. These commands are specific to the current project and can be checked into version control to be shared with your team.
|
||||
|
||||
If a command in the project directory has the same name as a command in the user directory, the **project command will always be used.** This allows projects to override global commands with project-specific versions.
|
||||
|
||||
#### Naming and Namespacing
|
||||
|
||||
The name of a command is determined by its file path relative to its `commands` directory. Subdirectories are used to create namespaced commands, with the path separator (`/` or `\`) being converted to a colon (`:`).
|
||||
|
||||
- A file at `~/.gemini/commands/test.toml` becomes the command `/test`.
|
||||
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced command `/git:commit`.
|
||||
|
||||
#### TOML File Format (v1)
|
||||
|
||||
Your command definition files must be written in the TOML format and use the `.toml` file extension.
|
||||
|
||||
##### Required Fields
|
||||
|
||||
- `prompt` (String): The prompt that will be sent to the Gemini model when the command is executed. This can be a single-line or multi-line string.
|
||||
|
||||
##### Optional Fields
|
||||
|
||||
- `description` (String): A brief, one-line description of what the command does. This text will be displayed next to your command in the `/help` menu. **If you omit this field, a generic description will be generated from the filename.**
|
||||
|
||||
#### Handling Arguments
|
||||
|
||||
Custom commands support two powerful methods for handling arguments. The CLI automatically chooses the correct method based on the content of your command's `prompt`.
|
||||
|
||||
##### 1. Context-Aware Injection with `{{args}}`
|
||||
|
||||
If your `prompt` contains the special placeholder `{{args}}`, the CLI will replace that placeholder with the text the user typed after the command name.
|
||||
|
||||
The behavior of this injection depends on where it is used:
|
||||
|
||||
**A. Raw Injection (Outside Shell Commands)**
|
||||
|
||||
When used in the main body of the prompt, the arguments are injected exactly as the user typed them.
|
||||
|
||||
**Example (`git/fix.toml`):**
|
||||
|
||||
```toml
|
||||
# Invoked via: /git:fix "Button is misaligned"
|
||||
|
||||
description = "Generates a fix for a given issue."
|
||||
prompt = "Please provide a code fix for the issue described here: {{args}}."
|
||||
```
|
||||
|
||||
The model receives: `Please provide a code fix for the issue described here: "Button is misaligned".`
|
||||
|
||||
**B. Using Arguments in Shell Commands (Inside `!{...}` Blocks)**
|
||||
|
||||
When you use `{{args}}` inside a shell injection block (`!{...}`), the arguments are automatically **shell-escaped** before replacement. This allows you to safely pass arguments to shell commands, ensuring the resulting command is syntactically correct and secure while preventing command injection vulnerabilities.
|
||||
|
||||
**Example (`/grep-code.toml`):**
|
||||
|
||||
```toml
|
||||
prompt = """
|
||||
Please summarize the findings for the pattern `{{args}}`.
|
||||
|
||||
Search Results:
|
||||
!{grep -r {{args}} .}
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/grep-code It's complicated`:
|
||||
|
||||
1. The CLI sees `{{args}}` used both outside and inside `!{...}`.
|
||||
2. Outside: The first `{{args}}` is replaced raw with `It's complicated`.
|
||||
3. Inside: The second `{{args}}` is replaced with the escaped version (e.g., on Linux: `"It's complicated"`).
|
||||
4. The command executed is `grep -r "It's complicated" .`.
|
||||
5. The CLI prompts you to confirm this exact, secure command before execution.
|
||||
6. The final prompt is sent.
|
||||
|
||||
##### 2. Default Argument Handling
|
||||
|
||||
If your `prompt` does **not** contain the special placeholder `{{args}}`, the CLI uses a default behavior for handling arguments.
|
||||
|
||||
If you provide arguments to the command (e.g., `/mycommand arg1`), the CLI will append the full command you typed to the end of the prompt, separated by two newlines. This allows the model to see both the original instructions and the specific arguments you just provided.
|
||||
|
||||
If you do **not** provide any arguments (e.g., `/mycommand`), the prompt is sent to the model exactly as it is, with nothing appended.
|
||||
|
||||
**Example (`changelog.toml`):**
|
||||
|
||||
This example shows how to create a robust command by defining a role for the model, explaining where to find the user's input, and specifying the expected format and behavior.
|
||||
|
||||
```toml
|
||||
# In: <project>/.gemini/commands/changelog.toml
|
||||
# Invoked via: /changelog 1.2.0 added "Support for default argument parsing."
|
||||
|
||||
description = "Adds a new entry to the project's CHANGELOG.md file."
|
||||
prompt = """
|
||||
# Task: Update Changelog
|
||||
|
||||
You are an expert maintainer of this software project. A user has invoked a command to add a new entry to the changelog.
|
||||
|
||||
**The user's raw command is appended below your instructions.**
|
||||
|
||||
Your task is to parse the `<version>`, `<change_type>`, and `<message>` from their input and use the `write_file` tool to correctly update the `CHANGELOG.md` file.
|
||||
|
||||
## Expected Format
|
||||
The command follows this format: `/changelog <version> <type> <message>`
|
||||
- `<type>` must be one of: "added", "changed", "fixed", "removed".
|
||||
|
||||
## Behavior
|
||||
1. Read the `CHANGELOG.md` file.
|
||||
2. Find the section for the specified `<version>`.
|
||||
3. Add the `<message>` under the correct `<type>` heading.
|
||||
4. If the version or type section doesn't exist, create it.
|
||||
5. Adhere strictly to the "Keep a Changelog" format.
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/changelog 1.2.0 added "New feature"`, the final text sent to the model will be the original prompt followed by two newlines and the command you typed.
|
||||
|
||||
##### 3. Executing Shell Commands with `!{...}`
|
||||
|
||||
You can make your commands dynamic by executing shell commands directly within your `prompt` and injecting their output. This is ideal for gathering context from your local environment, like reading file content or checking the status of Git.
|
||||
|
||||
When a custom command attempts to execute a shell command, Gemini CLI will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
|
||||
|
||||
**How It Works:**
|
||||
|
||||
1. **Inject Commands:** Use the `!{...}` syntax.
|
||||
2. **Argument Substitution:** If `{{args}}` is present inside the block, it is automatically shell-escaped (see [Context-Aware Injection](#1-context-aware-injection-with-args) above).
|
||||
3. **Robust Parsing:** The parser correctly handles complex shell commands that include nested braces, such as JSON payloads. **Note:** The content inside `!{...}` must have balanced braces (`{` and `}`). If you need to execute a command containing unbalanced braces, consider wrapping it in an external script file and calling the script within the `!{...}` block.
|
||||
4. **Security Check and Confirmation:** The CLI performs a security check on the final, resolved command (after arguments are escaped and substituted). A dialog will appear showing the exact command(s) to be executed.
|
||||
5. **Execution and Error Reporting:** The command is executed. If the command fails, the output injected into the prompt will include the error messages (stderr) followed by a status line, e.g., `[Shell command exited with code 1]`. This helps the model understand the context of the failure.
|
||||
|
||||
**Example (`git/commit.toml`):**
|
||||
|
||||
This command gets the staged git diff and uses it to ask the model to write a commit message.
|
||||
|
||||
````toml
|
||||
# In: <project>/.gemini/commands/git/commit.toml
|
||||
# Invoked via: /git:commit
|
||||
|
||||
description = "Generates a Git commit message based on staged changes."
|
||||
|
||||
# The prompt uses !{...} to execute the command and inject its output.
|
||||
prompt = """
|
||||
Please generate a Conventional Commit message based on the following git diff:
|
||||
|
||||
```diff
|
||||
!{git diff --staged}
|
||||
```
|
||||
|
||||
"""
|
||||
|
||||
````
|
||||
|
||||
When you run `/git:commit`, the CLI first executes `git diff --staged`, then replaces `!{git diff --staged}` with the output of that command before sending the final, complete prompt to the model.
|
||||
|
||||
##### 4. Injecting File Content with `@{...}`
|
||||
|
||||
You can directly embed the content of a file or a directory listing into your prompt using the `@{...}` syntax. This is useful for creating commands that operate on specific files.
|
||||
|
||||
**How It Works:**
|
||||
|
||||
- **File Injection**: `@{path/to/file.txt}` is replaced by the content of `file.txt`.
|
||||
- **Multimodal Support**: If the path points to a supported image (e.g., PNG, JPEG), PDF, audio, or video file, it will be correctly encoded and injected as multimodal input. Other binary files are handled gracefully and skipped.
|
||||
- **Directory Listing**: `@{path/to/dir}` is traversed and each file present within the directory and all subdirectories are inserted into the prompt. This respects `.gitignore` and `.geminiignore` if enabled.
|
||||
- **Workspace-Aware**: The command searches for the path in the current directory and any other workspace directories. Absolute paths are allowed if they are within the workspace.
|
||||
- **Processing Order**: File content injection with `@{...}` is processed _before_ shell commands (`!{...}`) and argument substitution (`{{args}}`).
|
||||
- **Parsing**: The parser requires the content inside `@{...}` (the path) to have balanced braces (`{` and `}`).
|
||||
|
||||
**Example (`review.toml`):**
|
||||
|
||||
This command injects the content of a _fixed_ best practices file (`docs/best-practices.md`) and uses the user's arguments to provide context for the review.
|
||||
|
||||
```toml
|
||||
# In: <project>/.gemini/commands/review.toml
|
||||
# Invoked via: /review FileCommandLoader.ts
|
||||
|
||||
description = "Reviews the provided context using a best practice guide."
|
||||
prompt = """
|
||||
You are an expert code reviewer.
|
||||
|
||||
Your task is to review {{args}}.
|
||||
|
||||
Use the following best practices when providing your review:
|
||||
|
||||
@{docs/best-practices.md}
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/review FileCommandLoader.ts`, the `@{docs/best-practices.md}` placeholder is replaced by the content of that file, and `{{args}}` is replaced by the text you provided, before the final prompt is sent to the model.
|
||||
|
||||
---
|
||||
|
||||
#### Example: A "Pure Function" Refactoring Command
|
||||
|
||||
Let's create a global command that asks the model to refactor a piece of code.
|
||||
|
||||
**1. Create the file and directories:**
|
||||
|
||||
First, ensure the user commands directory exists, then create a `refactor` subdirectory for organization and the final TOML file.
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gemini/commands/refactor
|
||||
touch ~/.gemini/commands/refactor/pure.toml
|
||||
```
|
||||
|
||||
**2. Add the content to the file:**
|
||||
|
||||
Open `~/.gemini/commands/refactor/pure.toml` in your editor and add the following content. We are including the optional `description` for best practice.
|
||||
|
||||
```toml
|
||||
# In: ~/.gemini/commands/refactor/pure.toml
|
||||
# This command will be invoked via: /refactor:pure
|
||||
|
||||
description = "Asks the model to refactor the current context into a pure function."
|
||||
|
||||
prompt = """
|
||||
Please analyze the code I've provided in the current context.
|
||||
Refactor it into a pure function.
|
||||
|
||||
Your response should include:
|
||||
1. The refactored, pure function code block.
|
||||
2. A brief explanation of the key changes you made and why they contribute to purity.
|
||||
"""
|
||||
```
|
||||
|
||||
**3. Run the Command:**
|
||||
|
||||
That's it! You can now run your command in the CLI. First, you might add a file to the context, and then invoke your command:
|
||||
|
||||
```
|
||||
> @my-messy-function.js
|
||||
> /refactor:pure
|
||||
```
|
||||
|
||||
Gemini CLI will then execute the multi-line prompt defined in your TOML file.
|
||||
|
||||
## Input Prompt Shortcuts
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ Gemini CLI uses JSON settings files for persistent configuration. There are four
|
||||
|
||||
**Note on environment variables in settings:** String values within your `settings.json` files can reference environment variables using either `$VAR_NAME` or `${VAR_NAME}` syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like this: `"apiKey": "$MY_API_TOKEN"`.
|
||||
|
||||
> **Note for Enterprise Users:** For guidance on deploying and managing Gemini CLI in a corporate environment, please see the [Enterprise Configuration](../cli/enterprise.md) documentation.
|
||||
> **Note for Enterprise Users:** For guidance on deploying and managing Gemini CLI in a corporate environment, please see the [Enterprise Configuration](./enterprise.md) documentation.
|
||||
|
||||
### The `.gemini` directory in your project
|
||||
|
||||
@@ -131,7 +131,7 @@ If you are experiencing performance issues with file searching (e.g., with `@` c
|
||||
- **Example:** `"autoAccept": true`
|
||||
|
||||
- **`theme`** (string):
|
||||
- **Description:** Sets the visual [theme](../cli/themes.md) for Gemini CLI.
|
||||
- **Description:** Sets the visual [theme](./themes.md) for Gemini CLI.
|
||||
- **Default:** `"Default"`
|
||||
- **Example:** `"theme": "GitHub"`
|
||||
|
||||
@@ -216,7 +216,7 @@ If you are experiencing performance issues with file searching (e.g., with `@` c
|
||||
```
|
||||
|
||||
- **`checkpointing`** (object):
|
||||
- **Description:** Configures the checkpointing feature, which allows you to save and restore conversation and file states. See the [Checkpointing documentation](../cli/checkpointing.md) for more details.
|
||||
- **Description:** Configures the checkpointing feature, which allows you to save and restore conversation and file states. See the [Checkpointing documentation](../checkpointing.md) for more details.
|
||||
- **Default:** `{"enabled": false}`
|
||||
- **Properties:**
|
||||
- **`enabled`** (boolean): When `true`, the `/restore` command is available.
|
||||
@@ -227,7 +227,7 @@ If you are experiencing performance issues with file searching (e.g., with `@` c
|
||||
- **Example:** `"preferredEditor": "vscode"`
|
||||
|
||||
- **`telemetry`** (object)
|
||||
- **Description:** Configures logging and metrics collection for Gemini CLI. For more information, see [Telemetry](../cli/telemetry.md).
|
||||
- **Description:** Configures logging and metrics collection for Gemini CLI. For more information, see [Telemetry](../telemetry.md).
|
||||
- **Default:** `{"enabled": false, "target": "local", "otlpEndpoint": "http://localhost:4317", "logPrompts": true}`
|
||||
- **Properties:**
|
||||
- **`enabled`** (boolean): Whether or not telemetry is enabled.
|
||||
@@ -497,17 +497,17 @@ Arguments passed directly when running the CLI can override other configurations
|
||||
- A comma-separated list of tool names that will bypass the confirmation dialog.
|
||||
- Example: `gemini --allowed-tools "ShellTool(git status)"`
|
||||
- **`--telemetry`**:
|
||||
- Enables [telemetry](../cli/telemetry.md).
|
||||
- Enables [telemetry](../telemetry.md).
|
||||
- **`--telemetry-target`**:
|
||||
- Sets the telemetry target. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the telemetry target. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-otlp-endpoint`**:
|
||||
- Sets the OTLP endpoint for telemetry. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the OTLP endpoint for telemetry. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-otlp-protocol`**:
|
||||
- Sets the OTLP protocol for telemetry (`grpc` or `http`). Defaults to `grpc`. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the OTLP protocol for telemetry (`grpc` or `http`). Defaults to `grpc`. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-log-prompts`**:
|
||||
- Enables logging of prompts for telemetry. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Enables logging of prompts for telemetry. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--checkpointing`**:
|
||||
- Enables [checkpointing](../cli/checkpointing.md).
|
||||
- Enables [checkpointing](../checkpointing.md).
|
||||
- **`--extensions <extension_name ...>`** (**`-e <extension_name ...>`**):
|
||||
- Specifies a list of extensions to use for the session. If not provided, all available extensions are used.
|
||||
- Use the special term `gemini -e none` to disable all extensions.
|
||||
@@ -583,7 +583,7 @@ This example demonstrates how you can provide general project context, specific
|
||||
- **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 loaded, allowing you to verify the hierarchy and content being used by the AI.
|
||||
- See the [Commands documentation](../cli/commands.md#memory) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
|
||||
- See the [Commands documentation](./commands.md#memory) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
|
||||
|
||||
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor the Gemini CLI's responses to your specific needs and projects.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
# Gemini CLI Configuration
|
||||
|
||||
> **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 **[09/10/25]**.
|
||||
> - Automatic migration from the old format to the new format will begin on **[09/17/25]**.
|
||||
>
|
||||
> For details on the previous format, please see the [v1 Configuration documentation](./configuration-v1.md).
|
||||
**Note on New Configuration Format**
|
||||
|
||||
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 **[09/10/25]**.
|
||||
- Automatic migration from the old format to the new format will begin on **[09/17/25]**.
|
||||
|
||||
For details on the previous format, please see the [v1 Configuration documentation](./configuration-v1.md).
|
||||
|
||||
Gemini CLI offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
|
||||
|
||||
@@ -40,7 +42,7 @@ Gemini CLI uses JSON settings files for persistent configuration. There are four
|
||||
|
||||
**Note on environment variables in settings:** String values within your `settings.json` files can reference environment variables using either `$VAR_NAME` or `${VAR_NAME}` syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like this: `"apiKey": "$MY_API_TOKEN"`.
|
||||
|
||||
> **Note for Enterprise Users:** For guidance on deploying and managing Gemini CLI in a corporate environment, please see the [Enterprise Configuration](../cli/enterprise.md) documentation.
|
||||
> **Note for Enterprise Users:** For guidance on deploying and managing Gemini CLI in a corporate environment, please see the [Enterprise Configuration](./enterprise.md) documentation.
|
||||
|
||||
### The `.gemini` directory in your project
|
||||
|
||||
@@ -84,7 +86,7 @@ Settings are organized into categories. All settings should be placed within the
|
||||
#### `ui`
|
||||
|
||||
- **`ui.theme`** (string):
|
||||
- **Description:** The color theme for the UI. See [Themes](../cli/themes.md) for available options.
|
||||
- **Description:** The color theme for the UI. See [Themes](./themes.md) for available options.
|
||||
- **Default:** `undefined`
|
||||
|
||||
- **`ui.customThemes`** (object):
|
||||
@@ -123,11 +125,6 @@ Settings are organized into categories. All settings should be placed within the
|
||||
- **Description:** Disable loading phrases for accessibility.
|
||||
- **Default:** `false`
|
||||
|
||||
- **`ui.accessibility.screenReader`** (boolean):
|
||||
- **Description:** Show plaintext interactive view that is more screen reader
|
||||
friendly.
|
||||
- **Default:** `false`
|
||||
|
||||
- **`ui.customWittyPhrases`** (array of strings):
|
||||
- **Description:** A list of custom phrases to display during loading states. When provided, the CLI will cycle through these phrases instead of the default ones.
|
||||
- **Default:** `[]`
|
||||
@@ -211,11 +208,11 @@ Settings are organized into categories. All settings should be placed within the
|
||||
- **Default:** `undefined`
|
||||
|
||||
- **`tools.shell.enableInteractiveShell`** (boolean):
|
||||
- **Description:** Enables interactive terminal for running shell commands. If an interactive session cannot be started, it will fall back to a standard shell.
|
||||
- **Default:** `true`
|
||||
|
||||
Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. Defaults to `false`.
|
||||
|
||||
- **`tools.core`** (array of strings):
|
||||
- **Description:** This can be used to restrict the set of built-in tools [with an allowlist](../cli/enterprise.md#restricting-tool-access). See [Built-in Tools](../core/tools-api.md#built-in-tools) for a list of core tools. The match semantics are the same as `tools.allowed`.
|
||||
- **Description:** This can be used to restrict the set of built-in tools [with an allowlist](./enterprise.md#restricting-tool-access). See [Built-in Tools](../core/tools-api.md#built-in-tools) for a list of core tools. The match semantics are the same as `tools.allowed`.
|
||||
- **Default:** `undefined`
|
||||
|
||||
- **`tools.exclude`** (array of strings):
|
||||
@@ -232,7 +229,7 @@ Settings are organized into categories. All settings should be placed within the
|
||||
|
||||
- **`tools.callCommand`** (string):
|
||||
- **Description:** Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria:
|
||||
- It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as the first command line argument.
|
||||
- It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument.
|
||||
- It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall).
|
||||
- It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse).
|
||||
- **Default:** `undefined`
|
||||
@@ -307,7 +304,7 @@ Configures connections to one or more Model-Context Protocol (MCP) servers for d
|
||||
|
||||
#### `telemetry`
|
||||
|
||||
Configures logging and metrics collection for Gemini CLI. For more information, see [Telemetry](../cli/telemetry.md).
|
||||
Configures logging and metrics collection for Gemini CLI. For more information, see [Telemetry](../telemetry.md).
|
||||
|
||||
- **Properties:**
|
||||
- **`enabled`** (boolean): Whether or not telemetry is enabled.
|
||||
@@ -452,7 +449,7 @@ The CLI automatically loads environment variables from an `.env` file. The loadi
|
||||
- Overrides the `telemetry.useCollector` setting.
|
||||
- **`GOOGLE_CLOUD_LOCATION`**:
|
||||
- Your Google Cloud Project Location (e.g., us-central1).
|
||||
- Required for using Vertex AI in non-express mode.
|
||||
- Required for using Vertex AI in non express mode.
|
||||
- Example: `export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"`.
|
||||
- **`GEMINI_SANDBOX`**:
|
||||
- Alternative to the `sandbox` setting in `settings.json`.
|
||||
@@ -519,17 +516,17 @@ Arguments passed directly when running the CLI can override other configurations
|
||||
- A comma-separated list of tool names that will bypass the confirmation dialog.
|
||||
- Example: `gemini --allowed-tools "ShellTool(git status)"`
|
||||
- **`--telemetry`**:
|
||||
- Enables [telemetry](../cli/telemetry.md).
|
||||
- Enables [telemetry](../telemetry.md).
|
||||
- **`--telemetry-target`**:
|
||||
- Sets the telemetry target. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the telemetry target. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-otlp-endpoint`**:
|
||||
- Sets the OTLP endpoint for telemetry. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the OTLP endpoint for telemetry. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-otlp-protocol`**:
|
||||
- Sets the OTLP protocol for telemetry (`grpc` or `http`). Defaults to `grpc`. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Sets the OTLP protocol for telemetry (`grpc` or `http`). Defaults to `grpc`. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--telemetry-log-prompts`**:
|
||||
- Enables logging of prompts for telemetry. See [telemetry](../cli/telemetry.md) for more information.
|
||||
- Enables logging of prompts for telemetry. See [telemetry](../telemetry.md) for more information.
|
||||
- **`--checkpointing`**:
|
||||
- Enables [checkpointing](../cli/checkpointing.md).
|
||||
- Enables [checkpointing](../checkpointing.md).
|
||||
- **`--extensions <extension_name ...>`** (**`-e <extension_name ...>`**):
|
||||
- Specifies a list of extensions to use for the session. If not provided, all available extensions are used.
|
||||
- Use the special term `gemini -e none` to disable all extensions.
|
||||
@@ -605,7 +602,7 @@ This example demonstrates how you can provide general project context, specific
|
||||
- **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 loaded, allowing you to verify the hierarchy and content being used by the AI.
|
||||
- See the [Commands documentation](../cli/commands.md#memory) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
|
||||
- See the [Commands documentation](./commands.md#memory) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
|
||||
|
||||
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor the Gemini CLI's responses to your specific needs and projects.
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
# Custom Commands
|
||||
|
||||
Custom commands let you save and reuse your favorite or most frequently used prompts as personal shortcuts within Gemini CLI. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
|
||||
|
||||
## File locations and precedence
|
||||
|
||||
Gemini CLI discovers commands from two locations, loaded in a specific order:
|
||||
|
||||
1. **User Commands (Global):** Located in `~/.gemini/commands/`. These commands are available in any project you are working on.
|
||||
2. **Project Commands (Local):** Located in `<your-project-root>/.gemini/commands/`. These commands are specific to the current project and can be checked into version control to be shared with your team.
|
||||
|
||||
If a command in the project directory has the same name as a command in the user directory, the **project command will always be used.** This allows projects to override global commands with project-specific versions.
|
||||
|
||||
## Naming and namespacing
|
||||
|
||||
The name of a command is determined by its file path relative to its `commands` directory. Subdirectories are used to create namespaced commands, with the path separator (`/` or `\`) being converted to a colon (`:`).
|
||||
|
||||
- A file at `~/.gemini/commands/test.toml` becomes the command `/test`.
|
||||
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced command `/git:commit`.
|
||||
|
||||
## TOML File Format (v1)
|
||||
|
||||
Your command definition files must be written in the TOML format and use the `.toml` file extension.
|
||||
|
||||
### Required fields
|
||||
|
||||
- `prompt` (String): The prompt that will be sent to the Gemini model when the command is executed. This can be a single-line or multi-line string.
|
||||
|
||||
### Optional fields
|
||||
|
||||
- `description` (String): A brief, one-line description of what the command does. This text will be displayed next to your command in the `/help` menu. **If you omit this field, a generic description will be generated from the filename.**
|
||||
|
||||
## Handling arguments
|
||||
|
||||
Custom commands support two powerful methods for handling arguments. The CLI automatically chooses the correct method based on the content of your command\'s `prompt`.
|
||||
|
||||
### 1. Context-aware injection with `{{args}}`
|
||||
|
||||
If your `prompt` contains the special placeholder `{{args}}`, the CLI will replace that placeholder with the text the user typed after the command name.
|
||||
|
||||
The behavior of this injection depends on where it is used:
|
||||
|
||||
**A. Raw injection (outside Shell commands)**
|
||||
|
||||
When used in the main body of the prompt, the arguments are injected exactly as the user typed them.
|
||||
|
||||
**Example (`git/fix.toml`):**
|
||||
|
||||
```toml
|
||||
# Invoked via: /git:fix "Button is misaligned"
|
||||
|
||||
description = "Generates a fix for a given issue."
|
||||
prompt = "Please provide a code fix for the issue described here: {{args}}."
|
||||
```
|
||||
|
||||
The model receives: `Please provide a code fix for the issue described here: "Button is misaligned".`
|
||||
|
||||
**B. Using arguments in Shell commands (inside `!{...}` blocks)**
|
||||
|
||||
When you use `{{args}}` inside a shell injection block (`!{...}`), the arguments are automatically **shell-escaped** before replacement. This allows you to safely pass arguments to shell commands, ensuring the resulting command is syntactically correct and secure while preventing command injection vulnerabilities.
|
||||
|
||||
**Example (`/grep-code.toml`):**
|
||||
|
||||
```toml
|
||||
prompt = """
|
||||
Please summarize the findings for the pattern `{{args}}`.
|
||||
|
||||
Search Results:
|
||||
!{grep -r {{args}} .}
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/grep-code It\'s complicated`:
|
||||
|
||||
1. The CLI sees `{{args}}` used both outside and inside `!{...}`.
|
||||
2. Outside: The first `{{args}}` is replaced raw with `It\'s complicated`.
|
||||
3. Inside: The second `{{args}}` is replaced with the escaped version (e.g., on Linux: `"It\'s complicated"`).
|
||||
4. The command executed is `grep -r "It\'s complicated" .`.
|
||||
5. The CLI prompts you to confirm this exact, secure command before execution.
|
||||
6. The final prompt is sent.
|
||||
|
||||
### 2. Default argument handling
|
||||
|
||||
If your `prompt` does **not** contain the special placeholder `{{args}}`, the CLI uses a default behavior for handling arguments.
|
||||
|
||||
If you provide arguments to the command (e.g., `/mycommand arg1`), the CLI will append the full command you typed to the end of the prompt, separated by two newlines. This allows the model to see both the original instructions and the specific arguments you just provided.
|
||||
|
||||
If you do **not** provide any arguments (e.g., `/mycommand`), the prompt is sent to the model exactly as it is, with nothing appended.
|
||||
|
||||
**Example (`changelog.toml`):**
|
||||
|
||||
This example shows how to create a robust command by defining a role for the model, explaining where to find the user's input, and specifying the expected format and behavior.
|
||||
|
||||
```toml
|
||||
# In: <project>/.gemini/commands/changelog.toml
|
||||
# Invoked via: /changelog 1.2.0 added "Support for default argument parsing."
|
||||
|
||||
description = "Adds a new entry to the project\'s CHANGELOG.md file."
|
||||
prompt = """
|
||||
# Task: Update Changelog
|
||||
|
||||
You are an expert maintainer of this software project. A user has invoked a command to add a new entry to the changelog.
|
||||
|
||||
**The user\'s raw command is appended below your instructions.**
|
||||
|
||||
Your task is to parse the `<version>`, `<change_type>`, and `<message>` from their input and use the `write_file` tool to correctly update the `CHANGELOG.md` file.
|
||||
|
||||
## Expected Format
|
||||
The command follows this format: `/changelog <version> <type> <message>`
|
||||
- `<type>` must be one of: "added", "changed", "fixed", "removed".
|
||||
|
||||
## Behavior
|
||||
1. Read the `CHANGELOG.md` file.
|
||||
2. Find the section for the specified `<version>`.
|
||||
3. Add the `<message>` under the correct `<type>` heading.
|
||||
4. If the version or type section doesn\'t exist, create it.
|
||||
5. Adhere strictly to the "Keep a Changelog" format.
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/changelog 1.2.0 added "New feature"`, the final text sent to the model will be the original prompt followed by two newlines and the command you typed.
|
||||
|
||||
### 3. Executing Shell commands with `!{...}`
|
||||
|
||||
You can make your commands dynamic by executing shell commands directly within your `prompt` and injecting their output. This is ideal for gathering context from your local environment, like reading file content or checking the status of Git.
|
||||
|
||||
When a custom command attempts to execute a shell command, Gemini CLI will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Inject commands:** Use the `!{...}` syntax.
|
||||
2. **Argument substitution:** If `{{args}}` is present inside the block, it is automatically shell-escaped (see [Context-Aware Injection](#1-context-aware-injection-with-args) above).
|
||||
3. **Robust parsing:** The parser correctly handles complex shell commands that include nested braces, such as JSON payloads. **Note:** The content inside `!{...}` must have balanced braces (`{` and `}`). If you need to execute a command containing unbalanced braces, consider wrapping it in an external script file and calling the script within the `!{...}` block.
|
||||
4. **Security check and confirmation:** The CLI performs a security check on the final, resolved command (after arguments are escaped and substituted). A dialog will appear showing the exact command(s) to be executed.
|
||||
5. **Execution and error reporting:** The command is executed. If the command fails, the output injected into the prompt will include the error messages (stderr) followed by a status line, e.g., `[Shell command exited with code 1]`. This helps the model understand the context of the failure.
|
||||
|
||||
**Example (`git/commit.toml`):**
|
||||
|
||||
This command gets the staged git diff and uses it to ask the model to write a commit message.
|
||||
|
||||
````toml
|
||||
# In: <project>/.gemini/commands/git/commit.toml
|
||||
# Invoked via: /git:commit
|
||||
|
||||
description = "Generates a Git commit message based on staged changes."
|
||||
|
||||
# The prompt uses !{...} to execute the command and inject its output.
|
||||
prompt = """
|
||||
Please generate a Conventional Commit message based on the following git diff:
|
||||
|
||||
```diff
|
||||
!{git diff --staged}
|
||||
```
|
||||
|
||||
"""
|
||||
|
||||
````
|
||||
|
||||
When you run `/git:commit`, the CLI first executes `git diff --staged`, then replaces `!{git diff --staged}` with the output of that command before sending the final, complete prompt to the model.
|
||||
|
||||
### 4. Injecting file content with `@{...}`
|
||||
|
||||
You can directly embed the content of a file or a directory listing into your prompt using the `@{...}` syntax. This is useful for creating commands that operate on specific files.
|
||||
|
||||
**How it works:**
|
||||
|
||||
- **File injection**: `@{path/to/file.txt}` is replaced by the content of `file.txt`.
|
||||
- **Multimodal support**: If the path points to a supported image (e.g., PNG, JPEG), PDF, audio, or video file, it will be correctly encoded and injected as multimodal input. Other binary files are handled gracefully and skipped.
|
||||
- **Directory listing**: `@{path/to/dir}` is traversed and each file present within the directory and all subdirectories is inserted into the prompt. This respects `.gitignore` and `.geminiignore` if enabled.
|
||||
- **Workspace-aware**: The command searches for the path in the current directory and any other workspace directories. Absolute paths are allowed if they are within the workspace.
|
||||
- **Processing order**: File content injection with `@{...}` is processed _before_ shell commands (`!{...}`) and argument substitution (`{{args}}`).
|
||||
- **Parsing**: The parser requires the content inside `@{...}` (the path) to have balanced braces (`{` and `}`).
|
||||
|
||||
**Example (`review.toml`):**
|
||||
|
||||
This command injects the content of a _fixed_ best practices file (`docs/best-practices.md`) and uses the user\'s arguments to provide context for the review.
|
||||
|
||||
```toml
|
||||
# In: <project>/.gemini/commands/review.toml
|
||||
# Invoked via: /review FileCommandLoader.ts
|
||||
|
||||
description = "Reviews the provided context using a best practice guide."
|
||||
prompt = """
|
||||
You are an expert code reviewer.
|
||||
|
||||
Your task is to review {{args}}.
|
||||
|
||||
Use the following best practices when providing your review:
|
||||
|
||||
@{docs/best-practices.md}
|
||||
"""
|
||||
```
|
||||
|
||||
When you run `/review FileCommandLoader.ts`, the `@{docs/best-practices.md}` placeholder is replaced by the content of that file, and `{{args}}` is replaced by the text you provided, before the final prompt is sent to the model.
|
||||
|
||||
---
|
||||
|
||||
## Example: A "Pure Function" refactoring command
|
||||
|
||||
Let's create a global command that asks the model to refactor a piece of code.
|
||||
|
||||
**1. Create the file and directories:**
|
||||
|
||||
First, ensure the user commands directory exists, then create a `refactor` subdirectory for organization and the final TOML file.
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gemini/commands/refactor
|
||||
touch ~/.gemini/commands/refactor/pure.toml
|
||||
```
|
||||
|
||||
**2. Add the content to the file:**
|
||||
|
||||
Open `~/.gemini/commands/refactor/pure.toml` in your editor and add the following content. We are including the optional `description` for best practice.
|
||||
|
||||
```toml
|
||||
# In: ~/.gemini/commands/refactor/pure.toml
|
||||
# This command will be invoked via: /refactor:pure
|
||||
|
||||
description = "Asks the model to refactor the current context into a pure function."
|
||||
|
||||
prompt = """
|
||||
Please analyze the code I\'ve provided in the current context.
|
||||
Refactor it into a pure function.
|
||||
|
||||
Your response should include:
|
||||
1. The refactored, pure function code block.
|
||||
2. A brief explanation of the key changes you made and why they contribute to purity.
|
||||
"""
|
||||
```
|
||||
|
||||
**3. Run the Command:**
|
||||
|
||||
That's it! You can now run your command in the CLI. First, you might add a file to the context, and then invoke your command:
|
||||
|
||||
```
|
||||
> @my-messy-function.js
|
||||
> /refactor:pure
|
||||
```
|
||||
|
||||
Gemini CLI will then execute the multi-line prompt defined in your TOML file.
|
||||
@@ -6,7 +6,7 @@ This document outlines configuration patterns and best practices for deploying a
|
||||
|
||||
## Centralized Configuration: The System Settings File
|
||||
|
||||
The most powerful tools for enterprise administration are the system-wide settings files. These files allow you to define a baseline configuration (`system-defaults.json`) and a set of overrides (`settings.json`) that apply to all users on a machine. For a complete overview of configuration options, see the [Configuration documentation](../get-started/configuration.md).
|
||||
The most powerful tools for enterprise administration are the system-wide settings files. These files allow you to define a baseline configuration (`system-defaults.json`) and a set of overrides (`settings.json`) that apply to all users on a machine. For a complete overview of configuration options, see the [Configuration documentation](./configuration.md).
|
||||
|
||||
Settings are merged from four files. The precedence order for single-value settings (like `theme`) is:
|
||||
|
||||
@@ -276,7 +276,7 @@ To mitigate the risk of potentially harmful operations, you can enforce the use
|
||||
}
|
||||
```
|
||||
|
||||
You can also specify a custom, hardened Docker image for the sandbox using the `--sandbox-image` command-line argument or by building a custom `sandbox.Dockerfile` as described in the [Sandboxing documentation](./sandbox.md).
|
||||
You can also specify a custom, hardened Docker image for the sandbox using the `--sandbox-image` command-line argument or by building a custom `sandbox.Dockerfile` as described in the [Sandboxing documentation](./configuration.md#sandboxing).
|
||||
|
||||
## Controlling Network Access via Proxy
|
||||
|
||||
@@ -301,7 +301,7 @@ In corporate environments with strict network policies, you can configure Gemini
|
||||
|
||||
## Telemetry and Auditing
|
||||
|
||||
For auditing and monitoring purposes, you can configure Gemini CLI to send telemetry data to a central location. This allows you to track tool usage and other events. For more information, see the [telemetry documentation](./telemetry.md).
|
||||
For auditing and monitoring purposes, you can configure Gemini CLI to send telemetry data to a central location. This allows you to track tool usage and other events. For more information, see the [telemetry documentation](../telemetry.md).
|
||||
|
||||
**Example:** Enable telemetry and send it to a local OTLP collector. If `otlpEndpoint` is not specified, it defaults to `http://localhost:4317`.
|
||||
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
# Provide Context with GEMINI.md Files
|
||||
|
||||
Context files, which use the default name `GEMINI.md`, are a powerful feature for providing instructional context to the Gemini model. You can use these files to give project-specific instructions, define a persona, or provide coding style guides to make the AI's responses more accurate and tailored to your needs.
|
||||
|
||||
Instead of repeating instructions in every prompt, you can define them once in a context file.
|
||||
|
||||
## Understand the context hierarchy
|
||||
|
||||
The CLI uses a hierarchical system to source context. It loads various context files from several locations, concatenates the contents of all found files, and sends them to the model with every prompt. The CLI loads files in the following order:
|
||||
|
||||
1. **Global context file:**
|
||||
- **Location:** `~/.gemini/GEMINI.md` (in your user home directory).
|
||||
- **Scope:** Provides default instructions for all your projects.
|
||||
|
||||
2. **Project root and ancestor context files:**
|
||||
- **Location:** The CLI searches for a `GEMINI.md` file in your current working directory and then in each parent directory up to the project root (identified by a `.git` folder).
|
||||
- **Scope:** Provides context relevant to the entire project.
|
||||
|
||||
3. **Sub-directory context files:**
|
||||
- **Location:** The CLI also scans for `GEMINI.md` files in subdirectories below your current working directory. It respects rules in `.gitignore` and `.geminiignore`.
|
||||
- **Scope:** Lets you write highly specific instructions for a particular component or module.
|
||||
|
||||
The CLI footer displays the number of loaded context files, which gives you a quick visual cue of the active instructional context.
|
||||
|
||||
### Example `GEMINI.md` file
|
||||
|
||||
Here is an example of what you can include in a `GEMINI.md` file at the root of a TypeScript project:
|
||||
|
||||
```markdown
|
||||
# Project: My TypeScript Library
|
||||
|
||||
## General Instructions
|
||||
|
||||
- When you generate new TypeScript code, follow the existing coding style.
|
||||
- Ensure all new functions and classes have JSDoc comments.
|
||||
- Prefer functional programming paradigms where appropriate.
|
||||
|
||||
## Coding Style
|
||||
|
||||
- Use 2 spaces for indentation.
|
||||
- Prefix interface names with `I` (for example, `IUserService`).
|
||||
- Always use strict equality (`===` and `!==`).
|
||||
```
|
||||
|
||||
## Manage context with the `/memory` command
|
||||
|
||||
You can interact with the loaded context files by using the `/memory` command.
|
||||
|
||||
- **`/memory show`**: Displays the full, concatenated content of the current hierarchical memory. This lets you inspect the exact instructional context being provided to the model.
|
||||
- **`/memory refresh`**: Forces a re-scan and reload of all `GEMINI.md` files from all configured locations.
|
||||
- **`/memory add <text>`**: Appends your text to your global `~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly.
|
||||
|
||||
## Modularize context with imports
|
||||
|
||||
You can break down large `GEMINI.md` files into smaller, more manageable components by importing content from other files using the `@file.md` syntax. This feature supports both relative and absolute paths.
|
||||
|
||||
**Example `GEMINI.md` with imports:**
|
||||
|
||||
```markdown
|
||||
# Main GEMINI.md file
|
||||
|
||||
This is the main content.
|
||||
|
||||
@./components/instructions.md
|
||||
|
||||
More content here.
|
||||
|
||||
@../shared/style-guide.md
|
||||
```
|
||||
|
||||
For more details, see the [Memory Import Processor](../core/memport.md) documentation.
|
||||
|
||||
## Customize the context file name
|
||||
|
||||
While `GEMINI.md` is the default filename, you can configure this in your `settings.json` file. To specify a different name or a list of names, use the `context.fileName` property.
|
||||
|
||||
**Example `settings.json`:**
|
||||
|
||||
```json
|
||||
{
|
||||
"context": {
|
||||
"fileName": ["AGENTS.md", "CONTEXT.md", "GEMINI.md"]
|
||||
}
|
||||
}
|
||||
```
|
||||
+10
-19
@@ -2,25 +2,16 @@
|
||||
|
||||
Within Gemini CLI, `packages/cli` is the frontend for users to send and receive prompts with the Gemini AI model and its associated tools. For a general overview of Gemini CLI, see the [main documentation page](../index.md).
|
||||
|
||||
## Basic features
|
||||
## Navigating this section
|
||||
|
||||
- **[Commands](./commands.md):** A reference for all built-in slash commands (e.g., `/help`, `/chat`, `/tools`).
|
||||
- **[Custom Commands](./custom-commands.md):** Create your own commands and shortcuts for frequently used prompts.
|
||||
- **[Headless Mode](./headless.md):** Use Gemini CLI programmatically for scripting and automation.
|
||||
- **[Themes](./themes.md):** Customizing the CLI's appearance with different themes.
|
||||
- **[Keyboard Shortcuts](./keyboard-shortcuts.md):** A reference for all keyboard shortcuts to improve your workflow.
|
||||
- **[Tutorials](./tutorials.md):** Step-by-step guides for common tasks.
|
||||
|
||||
## Advanced features
|
||||
|
||||
- **[Checkpointing](./checkpointing.md):** Automatically save and restore snapshots of your session and files.
|
||||
- **[Enterprise Configuration](./enterprise.md):** Deploying and manage Gemini CLI in an enterprise environment.
|
||||
- **[Sandboxing](./sandbox.md):** Isolate tool execution in a secure, containerized environment.
|
||||
- **[Telemetry](./telemetry.md):** Configure observability to monitor usage and performance.
|
||||
- **[Token Caching](./token-caching.md):** Optimize API costs by caching tokens.
|
||||
- **[Trusted Folders](./trusted-folders.md):** A security feature to control which projects can use the full capabilities of the CLI.
|
||||
- **[Ignoring Files (.geminiignore)](./gemini-ignore.md):** Exclude specific files and directories from being accessed by tools.
|
||||
- **[Context Files (GEMINI.md)](./gemini-md.md):** Provide persistent, hierarchical context to the model.
|
||||
- **[Authentication](./authentication.md):** A guide to setting up authentication with Google's AI services.
|
||||
- **[Commands](./commands.md):** A reference for Gemini CLI commands (e.g., `/help`, `/tools`, `/theme`).
|
||||
- **[Configuration](./configuration.md):** A guide to tailoring Gemini CLI behavior using configuration files.
|
||||
- **[Enterprise](./enterprise.md):** A guide to enterprise configuration.
|
||||
- **[Headless Mode](../headless.md):** A comprehensive guide to using Gemini CLI programmatically for scripting and automation.
|
||||
- **[Token Caching](./token-caching.md):** Optimize API costs through token caching.
|
||||
- **[Themes](./themes.md)**: A guide to customizing the CLI's appearance with different themes.
|
||||
- **[Tutorials](tutorials.md)**: A tutorial showing how to use Gemini CLI to automate a development task.
|
||||
|
||||
## Non-interactive mode
|
||||
|
||||
@@ -38,4 +29,4 @@ You can also use the `--prompt` or `-p` flag:
|
||||
gemini -p "What is fine tuning?"
|
||||
```
|
||||
|
||||
For comprehensive documentation on headless usage, scripting, automation, and advanced examples, see the **[Headless Mode](./headless.md)** guide.
|
||||
For comprehensive documentation on headless usage, scripting, automation, and advanced examples, see the **[Headless Mode](../headless.md)** guide.
|
||||
|
||||
+2
-2
@@ -32,7 +32,7 @@ Gemini CLI comes with a selection of pre-defined themes, which you can list usin
|
||||
|
||||
### Theme Persistence
|
||||
|
||||
Selected themes are saved in Gemini CLI's [configuration](../get-started/configuration.md) so your preference is remembered across sessions.
|
||||
Selected themes are saved in Gemini CLI's [configuration](./configuration.md) so your preference is remembered across sessions.
|
||||
|
||||
---
|
||||
|
||||
@@ -146,7 +146,7 @@ The theme file must be a valid JSON file that follows the same structure as a cu
|
||||
|
||||
- Select your custom theme using the `/theme` command in Gemini CLI. Your custom theme will appear in the theme selection dialog.
|
||||
- Or, set it as the default by adding `"theme": "MyCustomTheme"` to the `ui` object in your `settings.json`.
|
||||
- Custom themes can be set at the user, project, or system level, and follow the same [configuration precedence](../get-started/configuration.md) as other settings.
|
||||
- Custom themes can be set at the user, project, or system level, and follow the same [configuration precedence](./configuration.md) as other settings.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Before you begin, ensure you have the following installed and configured:
|
||||
|
||||
#### Configure the MCP server in `settings.json`
|
||||
|
||||
In your project's root directory, create or open the [`.gemini/settings.json` file](../get-started/configuration.md). Within the file, add the `mcpServers` configuration block, which provides instructions for how to launch the GitHub MCP server.
|
||||
In your project's root directory, create or open the [`.gemini/settings.json` file](./configuration.md). Within the file, add the `mcpServers` configuration block, which provides instructions for how to launch the GitHub MCP server.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -43,7 +43,7 @@ More content here.
|
||||
|
||||
Welcome to my project!
|
||||
|
||||
@./get-started.md
|
||||
@./getting-started.md
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
# Gemini CLI Execution and Deployment
|
||||
|
||||
This document describes how to run Gemini CLI and its deployment architecture.
|
||||
This document describes how to run Gemini CLI and explains the deployment architecture that Gemini CLI uses.
|
||||
|
||||
## Running Gemini CLI
|
||||
|
||||
There are several ways to run Gemini CLI. The option you choose depends on how you intend to use Gemini CLI.
|
||||
|
||||
- As a standard installation. This is the most straightforward method of using Gemini CLI.
|
||||
- In a sandbox. This method offers increased security and isolation.
|
||||
- From the source. This is recommended for contributors to the project.
|
||||
---
|
||||
|
||||
### 1. Standard installation (recommended for standard users)
|
||||
### 1. Standard installation (Recommended for typical users)
|
||||
|
||||
This is the recommended way for end-users to install Gemini CLI. It involves downloading the Gemini CLI package from the NPM registry.
|
||||
|
||||
@@ -33,7 +31,9 @@ This is the recommended way for end-users to install Gemini CLI. It involves dow
|
||||
npx @google/gemini-cli
|
||||
```
|
||||
|
||||
### 2. Run in a sandbox (Docker/Podman)
|
||||
---
|
||||
|
||||
### 2. Running in a sandbox (Docker/Podman)
|
||||
|
||||
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.
|
||||
|
||||
@@ -49,7 +49,9 @@ For security and isolation, Gemini CLI can be run inside a container. This is th
|
||||
gemini --sandbox -y -p "your prompt here"
|
||||
```
|
||||
|
||||
### 3. Run from source (recommended for Gemini CLI contributors)
|
||||
---
|
||||
|
||||
### 3. Running from source (Recommended for Gemini CLI contributors)
|
||||
|
||||
Contributors to the project will want to run the CLI directly from the source code.
|
||||
|
||||
@@ -9,7 +9,7 @@ Git repository releases tend to be the simplest and most flexible approach, whil
|
||||
|
||||
## Releasing through a git repository
|
||||
|
||||
This is the most flexible and simple option. All you need to do is create a publicly accessible git repo (such as a public github repository) and then users can install your extension using `gemini extensions install <your-repo-uri>`, or for a GitHub repository they can use the simplified `gemini extensions install <org>/<repo>` format. They can optionally depend on a specific ref (branch/tag/commit) using the `--ref=<some-ref>` argument, this defaults to the default branch.
|
||||
This is the most flexible and simple option. All you need to do us create a publicly accessible git repo (such as a public github repository) and then users can install your extension using `gemini extensions install <your-repo-uri>`, or for a GitHub repository they can use the simplified `gemini extensions install <org>/<repo>` format. They can optionally depend on a specific ref (branch/tag/commit) using the `--ref=<some-ref>` argument, this defaults to the default branch.
|
||||
|
||||
Whenever commits are pushed to the ref that a user depends on, they will be prompted to update the extension. Note that this also allows for easy rollbacks, the HEAD commit is always treated as the latest version regardless of the actual version in the `gemini-extension.json` file.
|
||||
|
||||
@@ -74,7 +74,7 @@ To ensure Gemini CLI can automatically find the correct release asset for each p
|
||||
|
||||
Archives must be fully contained extensions and have all the standard requirements - specifically the `gemini-extension.json` file must be at the root of the archive.
|
||||
|
||||
The rest of the layout should look exactly the same as a typical extension, see [extensions.md](./index.md).
|
||||
The rest of the layout should look exactly the same as a typical extension, see [extensions.md](extension.md).
|
||||
|
||||
#### Example GitHub Actions workflow
|
||||
|
||||
@@ -4,10 +4,6 @@ _This documentation is up-to-date with the v0.4.0 release._
|
||||
|
||||
Gemini CLI extensions package prompts, MCP servers, and custom commands into a familiar and user-friendly format. With extensions, you can expand the capabilities of Gemini CLI and share those capabilities with others. They are designed to be easily installable and shareable.
|
||||
|
||||
See [getting started docs](getting-started-extensions.md) for a guide on creating your first extension.
|
||||
|
||||
See [releasing docs](extension-releasing.md) for an advanced guide on setting up GitHub releases.
|
||||
|
||||
## Extension management
|
||||
|
||||
We offer a suite of extension management tools using `gemini extensions` commands.
|
||||
@@ -22,8 +18,6 @@ You can install an extension using `gemini extensions install` with either a Git
|
||||
|
||||
Note that we create a copy of the installed extension, so you will need to run `gemini extensions update` to pull in changes from both locally-defined extensions and those on GitHub.
|
||||
|
||||
NOTE: If you are installing an extension from GitHub, you'll need to have `git` installed on your machine. See [git installation instructions](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) for help.
|
||||
|
||||
```
|
||||
gemini extensions install https://github.com/gemini-cli-extensions/security
|
||||
```
|
||||
@@ -112,7 +106,7 @@ The `gemini-extension.json` file contains the configuration for the extension. T
|
||||
|
||||
- `name`: The name of the extension. This is used to uniquely identify the extension and for conflict resolution when extension commands have the same name as user or project commands. The name should be lowercase or numbers and use dashes instead of underscores or spaces. This is how users will refer to 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 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 configured in a [`settings.json` file](../get-started/configuration.md). If both an extension and a `settings.json` file configure an MCP server with the same name, the server defined in the `settings.json` file takes precedence.
|
||||
- `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 configured in a [`settings.json` file](./cli/configuration.md). If both an extension 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`.
|
||||
- `contextFileName`: The name of the file that contains the context for the extension. This will be used to load the context from the extension directory. If this property is not used but a `GEMINI.md` file is present in your extension directory, then that file will be loaded.
|
||||
- `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. Note that this differs from the MCP server `excludeTools` functionality, which can be listed in the MCP server config.
|
||||
@@ -121,7 +115,7 @@ When Gemini CLI starts, it loads all the extensions and merges their configurati
|
||||
|
||||
### Custom commands
|
||||
|
||||
Extensions can provide [custom commands](../cli/custom-commands.md) by placing TOML files in a `commands/` subdirectory within the extension directory. These commands follow the same format as user and project custom commands and use standard naming conventions.
|
||||
Extensions can provide [custom commands](./cli/commands.md#custom-commands) by placing TOML files in a `commands/` subdirectory within the extension directory. These commands follow the same format as user and project custom commands and use standard naming conventions.
|
||||
|
||||
**Example**
|
||||
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
# Frequently Asked Questions (FAQ)
|
||||
|
||||
This page provides answers to common questions and solutions to frequent problems encountered while using Gemini CLI.
|
||||
|
||||
## General issues
|
||||
|
||||
### Why am I getting an `API error: 429 - Resource exhausted`?
|
||||
|
||||
This error indicates that you have exceeded your API request limit. The Gemini API has rate limits to prevent abuse and ensure fair usage.
|
||||
|
||||
To resolve this, you can:
|
||||
|
||||
- **Check your usage:** Review your API usage in the Google AI Studio or your Google Cloud project dashboard.
|
||||
- **Optimize your prompts:** If you are making many requests in a short period, try to batch your prompts or introduce delays between requests.
|
||||
- **Request a quota increase:** If you consistently need a higher limit, you can request a quota increase from Google.
|
||||
|
||||
### Why am I getting an `ERR_REQUIRE_ESM` error when running `npm run start`?
|
||||
|
||||
This error typically occurs in Node.js projects when there is a mismatch between CommonJS and ES Modules.
|
||||
|
||||
This is often due to a misconfiguration in your `package.json` or `tsconfig.json`. Ensure that:
|
||||
|
||||
1. Your `package.json` has `"type": "module"`.
|
||||
2. Your `tsconfig.json` has `"module": "NodeNext"` or a compatible setting in the `compilerOptions`.
|
||||
|
||||
If the problem persists, try deleting your `node_modules` directory and `package-lock.json` file, and then run `npm install` again.
|
||||
|
||||
### Why don't I see cached token counts in my stats output?
|
||||
|
||||
Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Gemini API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Gemini Code Assist API does not support cached content creation. You can still view your total token usage using the `/stats` command in Gemini CLI.
|
||||
|
||||
## Installation and updates
|
||||
|
||||
### How do I update Gemini CLI to the latest version?
|
||||
|
||||
If you installed it globally via `npm`, update it using the command `npm install -g @google/gemini-cli@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
|
||||
## Platform-specific issues
|
||||
|
||||
### Why does the CLI crash on Windows when I run a command like `chmod +x`?
|
||||
|
||||
Commands like `chmod` are specific to Unix-like operating systems (Linux, macOS). They are not available on Windows by default.
|
||||
|
||||
To resolve this, you can:
|
||||
|
||||
- **Use Windows-equivalent commands:** Instead of `chmod`, you can use `icacls` to modify file permissions on Windows.
|
||||
- **Use a compatibility layer:** Tools like Git Bash or Windows Subsystem for Linux (WSL) provide a Unix-like environment on Windows where these commands will work.
|
||||
|
||||
## Configuration
|
||||
|
||||
### How do I configure my `GOOGLE_CLOUD_PROJECT`?
|
||||
|
||||
You can configure your Google Cloud Project ID using an environment variable.
|
||||
|
||||
Set the `GOOGLE_CLOUD_PROJECT` environment variable in your shell:
|
||||
|
||||
```bash
|
||||
export GOOGLE_CLOUD_PROJECT="your-project-id"
|
||||
```
|
||||
|
||||
To make this setting permanent, add this line to your shell's startup file (e.g., `~/.bashrc`, `~/.zshrc`).
|
||||
|
||||
### What is the best way to store my API keys securely?
|
||||
|
||||
Exposing API keys in scripts or checking them into source control is a security risk.
|
||||
|
||||
To store your API keys securely, you can:
|
||||
|
||||
- **Use a `.env` file:** Create a `.env` file in your project's `.gemini` directory (`.gemini/.env`) and store your keys there. Gemini CLI will automatically load these variables.
|
||||
- **Use your system's keyring:** For the most secure storage, use your operating system's secret management tool (like macOS Keychain, Windows Credential Manager, or a secret manager on Linux). You can then have your scripts or environment load the key from the secure storage at runtime.
|
||||
|
||||
### Where are the Gemini CLI configuration and settings files stored?
|
||||
|
||||
The Gemini CLI configuration is stored in two `settings.json` files:
|
||||
|
||||
1. In your home directory: `~/.gemini/settings.json`.
|
||||
2. In your project's root directory: `./.gemini/settings.json`.
|
||||
|
||||
Refer to [Gemini CLI Configuration](./get-started/configuration.md) for more details.
|
||||
|
||||
## Google AI Pro/Ultra and subscription FAQs
|
||||
|
||||
### Where can I learn more about my Google AI Pro or Google AI Ultra subscription?
|
||||
|
||||
To learn more about your Google AI Pro or Google AI Ultra subscription, visit **Manage subscription** in your [subscription settings](https://one.google.com).
|
||||
|
||||
### How do I know if I have higher limits for Google AI Pro or Ultra?
|
||||
|
||||
If you're subscribed to Google AI Pro or Ultra, you automatically have higher limits to Gemini Code Assist and Gemini CLI. These are shared across Gemini CLI and agent mode in the IDE. You can confirm you have higher limits by checking if you are still subscribed to Google AI Pro or Ultra in your [subscription settings](https://one.google.com).
|
||||
|
||||
### What is the privacy policy for using Gemini Code Assist or Gemini CLI if I've subscribed to Google AI Pro or Ultra?
|
||||
|
||||
To learn more about your privacy policy and terms of service governed by your subscription, visit [Gemini Code Assist: Terms of Service and Privacy Policies](https://developers.google.com/gemini-code-assist/resources/privacy-notices).
|
||||
|
||||
### I've upgraded to Google AI Pro or Ultra but it still says I am hitting quota limits. Is this a bug?
|
||||
|
||||
The higher limits in your Google AI Pro or Ultra subscription are for Gemini 2.5 across both Gemini 2.5 Pro and Flash. They are shared quota across Gemini CLI and agent mode in Gemini Code Assist IDE extensions. You can learn more about quota limits for Gemini CLI, Gemini Code Assist and agent mode in Gemini Code Assist at [Quotas and limits](https://developers.google.com/gemini-code-assist/resources/quotas).
|
||||
|
||||
### If I upgrade to higher limits for Gemini CLI and Gemini Code Assist by purchasing a Google AI Pro or Ultra subscription, will Gemini start using my data to improve its machine learning models?
|
||||
|
||||
Google does not use your data to improve Google's machine learning models if you purchase a paid plan. Note: If you decide to remain on the free version of Gemini Code Assist, Gemini Code Assist for individuals, you can also opt out of using your data to improve Google's machine learning models. See the [Gemini Code Assist for individuals privacy notice](https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals) for more information.
|
||||
|
||||
## Not seeing your question?
|
||||
|
||||
Search 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!
|
||||
@@ -6,7 +6,7 @@ The Gemini CLI includes the ability to automatically ignore files, similar to `.
|
||||
|
||||
## How it works
|
||||
|
||||
When you add a path to your `.geminiignore` file, tools that respect this file will exclude matching files and directories from their operations. For example, when you use the [`read_many_files`](../tools/multi-file.md) command, any paths in your `.geminiignore` file will be automatically excluded.
|
||||
When you add a path to your `.geminiignore` file, tools that respect this file will exclude matching files and directories from their operations. For example, when you use the [`read_many_files`](./tools/multi-file.md) command, any paths in your `.geminiignore` file will be automatically excluded.
|
||||
|
||||
For the most part, `.geminiignore` follows the conventions of `.gitignore` files:
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
# Gemini CLI Authentication Setup
|
||||
|
||||
Gemini CLI requires authentication using Google's services. Before using Gemini CLI, configure **one** of the following authentication methods:
|
||||
|
||||
- Interactive mode:
|
||||
- Recommended: Login with Google
|
||||
- Use Gemini API key
|
||||
- Use Vertex AI
|
||||
- Headless (non-interactive) mode
|
||||
- Google Cloud Shell
|
||||
|
||||
## Quick Check: Running in Google Cloud Shell?
|
||||
|
||||
If you are running the Gemini CLI within a Google Cloud Shell environment, authentication is typically automatic using your Cloud Shell credentials.
|
||||
|
||||
## Authenticate in Interactive mode
|
||||
|
||||
When you run Gemini CLI through the command-line, Gemini CLI will provide the following options:
|
||||
|
||||
```bash
|
||||
> 1. Login with Google
|
||||
> 2. Use Gemini API key
|
||||
> 3. Vertex AI
|
||||
```
|
||||
|
||||
The following sections provide instructions for each of these authentication options.
|
||||
|
||||
### Recommended: Login with Google
|
||||
|
||||
If you are running Gemini CLI on your local machine, the simplest method is logging in with your Google account.
|
||||
|
||||
> **Important:** Use this method if you are a **Google AI Pro** or **Google AI Ultra** subscriber.
|
||||
|
||||
1. Select **Login with Google**. Gemini CLI will open a login prompt using your web browser.
|
||||
|
||||
If you are a **Google AI Pro** or **Google AI Ultra** subscriber, login with the Google account associated with your subscription.
|
||||
|
||||
2. Follow the on-screen instructions. Your credentials will be cached locally for future sessions.
|
||||
|
||||
> **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.
|
||||
|
||||
#### (Optional) Set your GOOGLE_CLOUD_PROJECT
|
||||
|
||||
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, export the `GOOGLE_CLOUD_PROJECT` environment 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-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.
|
||||
|
||||
1. Obtain your API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
|
||||
2. Set the `GEMINI_API_KEY` environment variable:
|
||||
|
||||
```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-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
|
||||
|
||||
If you intend to use Google Cloud's Vertex AI platform, you have several authentication options:
|
||||
|
||||
- Application Default Credentials (ADC) and `gcloud`.
|
||||
- A Service Account JSON key.
|
||||
- A Google Cloud API key.
|
||||
|
||||
#### First: Set required environment variables
|
||||
|
||||
Regardless of your method of authentication, you'll typically need to set the following variables: `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.
|
||||
|
||||
To set these variables:
|
||||
|
||||
```bash
|
||||
# Replace with your project ID and desired location (e.g., us-central1)
|
||||
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
|
||||
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"
|
||||
```
|
||||
|
||||
#### A. Vertex AI - Application Default Credentials (ADC) using `gcloud`
|
||||
|
||||
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. 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
|
||||
```
|
||||
|
||||
See [Set up Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) for details.
|
||||
|
||||
3. Ensure `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` are set.
|
||||
|
||||
#### B. Vertex AI - Service Account JSON key
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
# Replace /path/to/your/keyfile.json with the actual path
|
||||
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
|
||||
```
|
||||
|
||||
3. Ensure `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` are set.
|
||||
|
||||
> **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
|
||||
# Replace YOUR_GOOGLE_API_KEY with your Vertex AI API key
|
||||
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
|
||||
```
|
||||
|
||||
> **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 [Service Account JSON Key](#b-vertex-ai-service-account-json-key) or [ADC](#a-vertex-ai-application-default-credentials-adc-using-gcloud) methods instead.
|
||||
|
||||
To make any of these Vertex AI environment variable settings persistent, see [Persisting Environment Variables](#persisting-environment-variables).
|
||||
|
||||
## Persisting Environment Variables
|
||||
|
||||
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`, `~/.zshrc`, or `~/.profile`) and reload your shell (e.g., `source ~/.bashrc`).
|
||||
|
||||
```bash
|
||||
# Example for .bashrc
|
||||
echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
> **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 the first `.env` file it finds, searching up from the current directory, then in `~/.gemini/.env` or `~/.env`. `.gemini/.env` is recommended.
|
||||
|
||||
Example for user-wide settings:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gemini
|
||||
cat >> ~/.gemini/.env <<'EOF'
|
||||
GOOGLE_CLOUD_PROJECT="your-project-id"
|
||||
# Add other variables like GEMINI_API_KEY as needed
|
||||
EOF
|
||||
```
|
||||
|
||||
Variables are loaded from the first file found, not merged.
|
||||
|
||||
## Non-interactive mode / headless environments
|
||||
|
||||
Non-interative mode / headless environments will use your existing authentication method, if an existing authentication credential is cached.
|
||||
|
||||
If you have not already logged in with an authentication credential (such as a Google account), you **must** configure authentication using environment variables:
|
||||
|
||||
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` and `GOOGLE_CLOUD_LOCATION`.
|
||||
|
||||
The CLI will exit with an error in non-interactive mode if no suitable environment variables are found.
|
||||
|
||||
## What's next?
|
||||
|
||||
Your authentication method affects your quotas, pricing, Terms of Service, and privacy notices. Review the following pages to learn more:
|
||||
|
||||
- [Gemini CLI: Quotas and Pricing](../quota-and-pricing.md).
|
||||
- [Gemini CLI: Terms of Service and Privacy Notice](../tos-privacy.md).
|
||||
@@ -1,200 +0,0 @@
|
||||
# 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.
|
||||
|
||||
**Note:** Results are examples intended to showcase potential use cases. Your results may vary.
|
||||
|
||||
## Rename your photographs based on content
|
||||
|
||||
Scenario: You have a folder containing the following files:
|
||||
|
||||
```bash
|
||||
photos/photo1.png
|
||||
photos/photo2.png
|
||||
photos/photo3.png
|
||||
```
|
||||
|
||||
Give Gemini the following prompt:
|
||||
|
||||
```cli
|
||||
Rename the photos in my "photos" directory based on their contents.
|
||||
```
|
||||
|
||||
Result: Gemini will ask for permission to rename your files.
|
||||
|
||||
Select **Yes, allow once.** and your files will be renamed:
|
||||
|
||||
```bash
|
||||
photos/yellow_flowers.png
|
||||
photos/antique_dresser.png
|
||||
photos/green_android_robot.png
|
||||
```
|
||||
|
||||
## Explain a repository by reading its code
|
||||
|
||||
Scenario: You want to understand how a popular open-source utility works by inspecting its code, not just its README.
|
||||
|
||||
Give Gemini CLI the following prompt:
|
||||
|
||||
```cli
|
||||
Clone the 'chalk' repository from https://github.com/chalk/chalk, read its key source files, and explain how it works.
|
||||
```
|
||||
|
||||
Result: Gemini will perform a sequence of actions to answer your request.
|
||||
|
||||
1. First, it will ask for permission to run `git clone` to download the repository.
|
||||
2. Next, it will find the important source files and ask for permission to read them.
|
||||
3. Finally, after analyzing the code, it will provide a summary.
|
||||
|
||||
Gemini CLI will return an explanation based on the actual source code:
|
||||
|
||||
```markdown
|
||||
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 modifier (like `bold` or `italic`) is a getter that appends the corresponding ANSI escape code to an internal stack.
|
||||
|
||||
- **Chainable API:** When you call `chalk.red.bold('Hello')`, you are accessing 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 `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 terminal can render.
|
||||
```
|
||||
|
||||
## Combine two spreadsheets into one spreadsheet
|
||||
|
||||
Scenario: You have two .csv files: `Revenue - 2023.csv` and `Revenue - 2024.csv`. Each file contains monthly revenue figures, like so:
|
||||
|
||||
```csv
|
||||
January,0
|
||||
February,0
|
||||
March,0
|
||||
April,900
|
||||
May,1000
|
||||
June,1000
|
||||
July,1200
|
||||
August,1800
|
||||
September,2000
|
||||
October,2400
|
||||
November,3400
|
||||
December,2100
|
||||
```
|
||||
|
||||
You want to combine these two .csv files into a single .csv file.
|
||||
|
||||
Give Gemini CLI the following prompt:
|
||||
|
||||
```cli
|
||||
Combine the two .csv files into a single .csv file, with each year a different column.
|
||||
```
|
||||
|
||||
Result: Gemini CLI will read each file and then ask for permission to write a new file. Provide your permission and Gemini CLI will provide the following .csv:
|
||||
|
||||
```csv
|
||||
Month,2023,2024
|
||||
January,0,1000
|
||||
February,0,1200
|
||||
March,0,2400
|
||||
April,900,500
|
||||
May,1000,800
|
||||
June,1000,900
|
||||
July,1200,1000
|
||||
August,1800,400
|
||||
September,2000,2000
|
||||
October,2400,3400
|
||||
November,3400,1800
|
||||
December,2100,9000
|
||||
```
|
||||
|
||||
## Run unit tests
|
||||
|
||||
Scenario: You've written a simple login page. You wish to write unit tests to ensure that your login page has code coverage.
|
||||
|
||||
Give Gemini CLI the following prompt:
|
||||
|
||||
```cli
|
||||
Write unit tests for Login.js.
|
||||
```
|
||||
|
||||
Result: Gemini CLI will ask for permission to write a new file and create a test for your login page
|
||||
|
||||
```javascript
|
||||
import React from 'react';
|
||||
import { render, fireEvent, waitFor } from '@testing-library/react';
|
||||
import Login from './Login';
|
||||
|
||||
// Mock the API call for login
|
||||
jest.mock('./api', () => ({
|
||||
login: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('Login component', () => {
|
||||
it('renders the login form correctly', () => {
|
||||
const { getByLabelText, getByText } = render(<Login />);
|
||||
|
||||
expect(getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(getByText('Login')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error message with invalid credentials', async () => {
|
||||
const { getByLabelText, getByText, findByText } = render(<Login />);
|
||||
const usernameInput = getByLabelText('Username');
|
||||
const passwordInput = getByLabelText('Password');
|
||||
const loginButton = getByText('Login');
|
||||
|
||||
// Mock the API to return an error
|
||||
require('./api').login.mockRejectedValue(new Error('Invalid credentials'));
|
||||
|
||||
fireEvent.change(usernameInput, { target: { value: 'testuser' } });
|
||||
fireEvent.change(passwordInput, { target: { value: 'wrongpassword' } });
|
||||
fireEvent.click(loginButton);
|
||||
|
||||
const errorMessage = await findByText('Invalid credentials');
|
||||
expect(errorMessage).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('logs in successfully with valid credentials', async () => {
|
||||
const onLoginSuccess = jest.fn();
|
||||
const { getByLabelText, getByText } = render(
|
||||
<Login onLoginSuccess={onLoginSuccess} />,
|
||||
);
|
||||
const usernameInput = getByLabelText('Username');
|
||||
const passwordInput = getByLabelText('Password');
|
||||
const loginButton = getByText('Login');
|
||||
|
||||
// Mock the API to return a success message
|
||||
require('./api').login.mockResolvedValue({ success: true });
|
||||
|
||||
fireEvent.change(usernameInput, { target: { value: 'testuser' } });
|
||||
fireEvent.change(passwordInput, { target: { value: 'correctpassword' } });
|
||||
fireEvent.click(loginButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onLoginSuccess).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('disables the submit button while submitting', async () => {
|
||||
const { getByLabelText, getByText } = render(<Login />);
|
||||
const usernameInput = getByLabelText('Username');
|
||||
const passwordInput = getByLabelText('Password');
|
||||
const loginButton = getByText('Login');
|
||||
|
||||
// Mock the API to have a delay
|
||||
require('./api').login.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) =>
|
||||
setTimeout(() => resolve({ success: true }), 1000),
|
||||
),
|
||||
);
|
||||
|
||||
fireEvent.change(usernameInput, { target: { value: 'testuser' } });
|
||||
fireEvent.change(passwordInput, { target: { value: 'correctpassword' } });
|
||||
fireEvent.click(loginButton);
|
||||
|
||||
expect(loginButton).toBeDisabled();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(loginButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
# 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.
|
||||
|
||||
## Quickstart: Install, authenticate, configure, and use Gemini CLI
|
||||
|
||||
Gemini CLI brings the power of advanced language models directly to your command line interface. As an AI-powered assistant, Gemini CLI can help you with a variety of tasks, from understanding and generating code to reviewing and editing documents.
|
||||
|
||||
## Install
|
||||
|
||||
The standard method to install and run Gemini CLI uses `npm`:
|
||||
|
||||
```bash
|
||||
npm install -g @google/gemini-cli
|
||||
```
|
||||
|
||||
Once Gemini CLI is installed, run Gemini CLI from your command line:
|
||||
|
||||
```bash
|
||||
gemini
|
||||
```
|
||||
|
||||
For more deployment options, see [Gemini CLI Execution and Deployment](./deployment.md).
|
||||
|
||||
## Authenticate
|
||||
|
||||
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**.
|
||||
|
||||
For other authentication options and information, see [GeminI CLI Authentication Setup](./authentication.md).
|
||||
|
||||
## Configure
|
||||
|
||||
Gemini CLI offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files.
|
||||
|
||||
To explore your configuration options, see [Gemini CLI Configuration](./configuration.md).
|
||||
|
||||
## Use
|
||||
|
||||
Once installed and authenticated, you can start using Gemini CLI by issuing commands and prompts in your terminal. Ask it to generate code, explain files, and more.
|
||||
|
||||
To explore the power of Gemini CLI, see [Gemini CLI examples](./examples.md).
|
||||
|
||||
## What's next?
|
||||
|
||||
- Find out more about [Gemini CLI's tools](../tools/index.md).
|
||||
- Review [Gemini CLI's commands](../cli/commands.md).
|
||||
@@ -198,7 +198,7 @@ Restart the CLI again. The model will now have the context from your `GEMINI.md`
|
||||
|
||||
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 Releases. Using a public Git repository is the simplest method.
|
||||
|
||||
For detailed instructions on both methods, please refer to the [Extension Releasing Guide](./extension-releasing.md).
|
||||
For detailed instructions on both methods, please refer to the [Extension Releasing Guide](extension-releasing.md).
|
||||
|
||||
## Conclusion
|
||||
|
||||
@@ -244,7 +244,7 @@ Key command-line options for headless usage:
|
||||
| `--yolo`, `-y` | Auto-approve all actions | `gemini -p "query" --yolo` |
|
||||
| `--approval-mode` | Set approval mode | `gemini -p "query" --approval-mode auto_edit` |
|
||||
|
||||
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](../get-started/configuration.md).
|
||||
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](./cli/configuration.md).
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -317,7 +317,7 @@ tail -5 usage.log
|
||||
|
||||
## Resources
|
||||
|
||||
- [CLI Configuration](../get-started/configuration.md) - Complete configuration guide
|
||||
- [Authentication](../get-started/authentication.md) - Setup authentication
|
||||
- [Commands](./commands.md) - Interactive commands reference
|
||||
- [Tutorials](./tutorials.md) - Step-by-step automation guides
|
||||
- [CLI Configuration](./cli/configuration.md) - Complete configuration guide
|
||||
- [Authentication](./cli/authentication.md) - Setup authentication
|
||||
- [Commands](./cli/commands.md) - Interactive commands reference
|
||||
- [Tutorials](./cli/tutorials.md) - Step-by-step automation guides
|
||||
+25
-53
@@ -10,61 +10,33 @@ Gemini CLI brings the capabilities of Gemini models to your terminal in an inter
|
||||
|
||||
This documentation is organized into the following sections:
|
||||
|
||||
### Get started
|
||||
|
||||
- **[Gemini CLI Quickstart](./get-started/index.md):** Let's get started with Gemini CLI.
|
||||
- **[Deployment](./get-started/deployment.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.
|
||||
|
||||
### CLI
|
||||
|
||||
- **[CLI overview](./cli/index.md):** Overview of the command-line interface.
|
||||
- **[Commands](./cli/commands.md):** Description of available CLI commands.
|
||||
- **[Enterprise](./cli/enterprise.md):** Gemini CLI for enterprise.
|
||||
- **[Themes](./cli/themes.md):** Themes for Gemini CLI.
|
||||
- **[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.
|
||||
|
||||
### 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.
|
||||
|
||||
### Tools
|
||||
|
||||
- **[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.
|
||||
- **[MCP servers](./tools/mcp-server.md):** Using MCP servers with Gemini CLI.
|
||||
- **[Multi-File Read Tool](./tools/multi-file.md):** Documentation for the `read_many_files` tool.
|
||||
- **[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.
|
||||
|
||||
### Extensions
|
||||
|
||||
- **[Extensions](./extensions/index.md):** How to extend the CLI with new functionality.
|
||||
- **[Extension Releasing](./extensions/extension-releasing.md):** How to release Gemini CLI extensions.
|
||||
|
||||
### IDE integration
|
||||
|
||||
- **[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.
|
||||
|
||||
### About the Gemini CLI project
|
||||
|
||||
- **[Execution and Deployment](./deployment.md):** Information for running Gemini CLI.
|
||||
- **[Architecture Overview](./architecture.md):** Understand the high-level design of Gemini CLI, including its components and how they interact.
|
||||
- **CLI Usage:** Documentation for `packages/cli`.
|
||||
- **[CLI Introduction](./cli/index.md):** Overview of the command-line interface.
|
||||
- **[Commands](./cli/commands.md):** Description of available CLI commands.
|
||||
- **[Configuration](./cli/configuration.md):** Information on configuring the CLI.
|
||||
- **[Checkpointing](./checkpointing.md):** Documentation for the checkpointing feature.
|
||||
- **[Extensions](./extension.md):** How to extend the CLI with new functionality.
|
||||
- **[IDE Integration](./ide-integration.md):** Connect the CLI to your editor.
|
||||
- **[IDE Companion Extension Spec](./ide-companion-spec.md):** Spec for building IDE companion extensions.
|
||||
- **[Telemetry](./telemetry.md):** Overview of telemetry in the CLI.
|
||||
- **[Trusted Folders](./trusted-folders.md):** An overview of the Trusted Folders security feature.
|
||||
- **Core Details:** Documentation for `packages/core`.
|
||||
- **[Core Introduction](./core/index.md):** Overview of the core component.
|
||||
- **[Tools API](./core/tools-api.md):** Information on how the core manages and exposes tools.
|
||||
- **Tools:**
|
||||
- **[Tools Overview](./tools/index.md):** Overview of the available tools.
|
||||
- **[File System Tools](./tools/file-system.md):** Documentation for the `read_file` and `write_file` tools.
|
||||
- **[Multi-File Read Tool](./tools/multi-file.md):** Documentation for the `read_many_files` tool.
|
||||
- **[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.
|
||||
- **[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.
|
||||
- **[NPM](./npm.md):** Details on how the project's packages are structured
|
||||
- **[Troubleshooting Guide](./troubleshooting.md):** Find solutions to common problems and FAQs.
|
||||
- **[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.
|
||||
|
||||
We hope this documentation helps you make the most of Gemini CLI!
|
||||
We hope this documentation helps you make the most of the Gemini CLI!
|
||||
|
||||
+3
-3
@@ -6,9 +6,9 @@ We will follow https://semver.org/ as closely as possible but will call out when
|
||||
|
||||
Each Tuesday ~2000 UTC new Stable and Preview releases will be cut. The promotion flow is:
|
||||
|
||||
- Code is committed to main and pushed each night to nightly
|
||||
- Code is commited to main and pushed each night to nightly
|
||||
- After no more than 1 week on main, code is promoted to the `preview` channel
|
||||
- After 1 week the most recent `preview` channel is promoted to `stable` channel
|
||||
- After 1 week the most recent `preview` channel is promoted to `stable` cannel
|
||||
- Patch fixes will be produced against both `preview` and `stable` as needed, with the final 'patch' version number incrementing each time.
|
||||
|
||||
### Preview
|
||||
@@ -138,7 +138,7 @@ Navigate to the **Actions** tab and run the **Release: Patch (1) Create PR** wor
|
||||
This workflow will automatically:
|
||||
|
||||
1. Find the latest release tag for the channel.
|
||||
2. Create a release branch from that tag if one doesn't exist (e.g., `release/v0.5.1-pr-12345`).
|
||||
2. Create a release branch from that tag if one doesn't exist (e.g., `release/v0.5.1`).
|
||||
3. Create a new hotfix branch from the release branch.
|
||||
4. Cherry-pick your specified commit into the hotfix branch.
|
||||
5. Create a pull request from the hotfix branch back to the release branch.
|
||||
|
||||
@@ -152,6 +152,6 @@ gemini -s -p "run shell command: mount | grep workspace"
|
||||
|
||||
## Related documentation
|
||||
|
||||
- [Configuration](../get-started/configuration.md): Full configuration options.
|
||||
- [Commands](./commands.md): Available commands.
|
||||
- [Troubleshooting](../troubleshooting.md): General troubleshooting.
|
||||
- [Configuration](./cli/configuration.md): Full configuration options.
|
||||
- [Commands](./cli/commands.md): Available commands.
|
||||
- [Troubleshooting](./troubleshooting.md): General troubleshooting.
|
||||
+35
-189
@@ -2,222 +2,68 @@
|
||||
{
|
||||
"label": "Overview",
|
||||
"items": [
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs"
|
||||
},
|
||||
{
|
||||
"label": "Architecture Overview",
|
||||
"slug": "docs/architecture"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Get Started",
|
||||
"items": [
|
||||
{
|
||||
"label": "Gemini CLI Quickstart",
|
||||
"slug": "docs/get-started"
|
||||
},
|
||||
{
|
||||
"label": "Authentication",
|
||||
"slug": "docs/get-started/authentication"
|
||||
},
|
||||
{
|
||||
"label": "Configuration",
|
||||
"slug": "docs/get-started/configuration"
|
||||
},
|
||||
{
|
||||
"label": "Deployment",
|
||||
"slug": "docs/get-started/deployment"
|
||||
},
|
||||
{
|
||||
"label": "Examples",
|
||||
"slug": "docs/get-started/examples"
|
||||
}
|
||||
{ "label": "Welcome", "slug": "docs" },
|
||||
{ "label": "Execution and Deployment", "slug": "docs/deployment" },
|
||||
{ "label": "Architecture Overview", "slug": "docs/architecture" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "CLI",
|
||||
"items": [
|
||||
{ "label": "Introduction", "slug": "docs/cli" },
|
||||
{ "label": "Authentication", "slug": "docs/cli/authentication" },
|
||||
{ "label": "Commands", "slug": "docs/cli/commands" },
|
||||
{ "label": "Configuration", "slug": "docs/cli/configuration" },
|
||||
{ "label": "Checkpointing", "slug": "docs/checkpointing" },
|
||||
{ "label": "Enterprise", "slug": "docs/cli/enterprise" },
|
||||
{ "label": "Extensions", "slug": "docs/extension" },
|
||||
{ "label": "Headless Mode", "slug": "docs/headless" },
|
||||
{ "label": "IDE Integration", "slug": "docs/ide-integration" },
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs/cli"
|
||||
"label": "IDE Companion Spec",
|
||||
"slug": "docs/ide-companion-spec"
|
||||
},
|
||||
{
|
||||
"label": "Commands",
|
||||
"slug": "docs/cli/commands"
|
||||
},
|
||||
{
|
||||
"label": "Checkpointing",
|
||||
"slug": "docs/cli/checkpointing"
|
||||
},
|
||||
{
|
||||
"label": "Custom Commands",
|
||||
"slug": "docs/cli/custom-commands"
|
||||
},
|
||||
{
|
||||
"label": "Enterprise",
|
||||
"slug": "docs/cli/enterprise"
|
||||
},
|
||||
{
|
||||
"label": "Headless Mode",
|
||||
"slug": "docs/cli/headless"
|
||||
},
|
||||
{
|
||||
"label": "Keyboard Shortcuts",
|
||||
"slug": "docs/cli/keyboard-shortcuts"
|
||||
},
|
||||
{
|
||||
"label": "Sandbox",
|
||||
"slug": "docs/cli/sandbox"
|
||||
},
|
||||
{
|
||||
"label": "Telemetry",
|
||||
"slug": "docs/cli/telemetry"
|
||||
},
|
||||
{
|
||||
"label": "Themes",
|
||||
"slug": "docs/cli/themes"
|
||||
},
|
||||
{
|
||||
"label": "Token Caching",
|
||||
"slug": "docs/cli/token-caching"
|
||||
},
|
||||
{
|
||||
"label": "Trusted Folders",
|
||||
"slug": "docs/cli/trusted-folders"
|
||||
},
|
||||
{
|
||||
"label": "Tutorials",
|
||||
"slug": "docs/cli/tutorials"
|
||||
},
|
||||
{
|
||||
"label": "Uninstall",
|
||||
"slug": "docs/cli/uninstall"
|
||||
}
|
||||
{ "label": "Telemetry", "slug": "docs/telemetry" },
|
||||
{ "label": "Themes", "slug": "docs/cli/themes" },
|
||||
{ "label": "Token Caching", "slug": "docs/cli/token-caching" },
|
||||
{ "label": "Trusted Folders", "slug": "docs/trusted-folders" },
|
||||
{ "label": "Tutorials", "slug": "docs/cli/tutorials" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Core",
|
||||
"items": [
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs/core"
|
||||
},
|
||||
{
|
||||
"label": "Tools API",
|
||||
"slug": "docs/core/tools-api"
|
||||
},
|
||||
{
|
||||
"label": "Memory Import Processor",
|
||||
"slug": "docs/core/memport"
|
||||
}
|
||||
{ "label": "Introduction", "slug": "docs/core" },
|
||||
{ "label": "Tools API", "slug": "docs/core/tools-api" },
|
||||
{ "label": "Memory Import Processor", "slug": "docs/core/memport" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Tools",
|
||||
"items": [
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs/tools"
|
||||
},
|
||||
{
|
||||
"label": "File System",
|
||||
"slug": "docs/tools/file-system"
|
||||
},
|
||||
{
|
||||
"label": "Multi-File Read",
|
||||
"slug": "docs/tools/multi-file"
|
||||
},
|
||||
{
|
||||
"label": "Shell",
|
||||
"slug": "docs/tools/shell"
|
||||
},
|
||||
{
|
||||
"label": "Web Fetch",
|
||||
"slug": "docs/tools/web-fetch"
|
||||
},
|
||||
{
|
||||
"label": "Web Search",
|
||||
"slug": "docs/tools/web-search"
|
||||
},
|
||||
{
|
||||
"label": "Memory",
|
||||
"slug": "docs/tools/memory"
|
||||
},
|
||||
{
|
||||
"label": "MCP Servers",
|
||||
"slug": "docs/tools/mcp-server"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Extensions",
|
||||
"items": [
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs/extensions"
|
||||
},
|
||||
{
|
||||
"label": "Extension Releasing",
|
||||
"slug": "docs/extensions/extension-releasing"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "IDE Integration",
|
||||
"items": [
|
||||
{
|
||||
"label": "Introduction",
|
||||
"slug": "docs/ide-integration"
|
||||
},
|
||||
{
|
||||
"label": "IDE Companion Spec",
|
||||
"slug": "docs/ide-integration/ide-companion-spec"
|
||||
}
|
||||
{ "label": "Overview", "slug": "docs/tools" },
|
||||
{ "label": "File System", "slug": "docs/tools/file-system" },
|
||||
{ "label": "Multi-File Read", "slug": "docs/tools/multi-file" },
|
||||
{ "label": "Shell", "slug": "docs/tools/shell" },
|
||||
{ "label": "Web Fetch", "slug": "docs/tools/web-fetch" },
|
||||
{ "label": "Web Search", "slug": "docs/tools/web-search" },
|
||||
{ "label": "Memory", "slug": "docs/tools/memory" },
|
||||
{ "label": "MCP Servers", "slug": "docs/tools/mcp-server" },
|
||||
{ "label": "Sandboxing", "slug": "docs/sandbox" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Development",
|
||||
"items": [
|
||||
{
|
||||
"label": "NPM",
|
||||
"slug": "docs/npm"
|
||||
},
|
||||
{
|
||||
"label": "Releases",
|
||||
"slug": "docs/releases"
|
||||
},
|
||||
{
|
||||
"label": "Integration Tests",
|
||||
"slug": "docs/integration-tests"
|
||||
},
|
||||
{
|
||||
"label": "Issue and PR Automation",
|
||||
"slug": "docs/issue-and-pr-automation"
|
||||
}
|
||||
{ "label": "NPM", "slug": "docs/npm" },
|
||||
{ "label": "Releases", "slug": "docs/releases" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Support",
|
||||
"items": [
|
||||
{
|
||||
"label": "FAQ",
|
||||
"slug": "docs/faq"
|
||||
},
|
||||
{
|
||||
"label": "Troubleshooting",
|
||||
"slug": "docs/troubleshooting"
|
||||
},
|
||||
{
|
||||
"label": "Quota and Pricing",
|
||||
"slug": "docs/quota-and-pricing"
|
||||
},
|
||||
{
|
||||
"label": "Terms of Service",
|
||||
"slug": "docs/tos-privacy"
|
||||
}
|
||||
{ "label": "Troubleshooting", "slug": "docs/troubleshooting" },
|
||||
{ "label": "Terms of Service", "slug": "docs/tos-privacy" }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -16,8 +16,6 @@ Learn how to enable and setup OpenTelemetry for Gemini CLI.
|
||||
- [Logs and Metrics](#logs-and-metrics)
|
||||
- [Logs](#logs)
|
||||
- [Metrics](#metrics)
|
||||
- [Custom](#custom)
|
||||
- [GenAI Semantic Convention](#genai-semantic-convention)
|
||||
|
||||
## Key Benefits
|
||||
|
||||
@@ -68,7 +66,7 @@ These settings can be overridden by environment variables or CLI flags.
|
||||
`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](./cli/configuration.md).
|
||||
|
||||
## Google Cloud Telemetry
|
||||
|
||||
@@ -324,9 +322,7 @@ for Gemini CLI:
|
||||
|
||||
### Metrics
|
||||
|
||||
Metrics are numerical measurements of behavior over time.
|
||||
|
||||
#### Custom
|
||||
Metrics are numerical measurements of behavior over time. The following metrics are collected for Gemini CLI:
|
||||
|
||||
- `gemini_cli.session.count` (Counter, Int): Incremented once per CLI startup.
|
||||
|
||||
@@ -351,16 +347,11 @@ Metrics are numerical measurements of behavior over time.
|
||||
- `gemini_cli.api.request.latency` (Histogram, ms): Measures API request latency.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- **Note**: This metric overlaps with `gen_ai.client.operation.duration` below
|
||||
that's compliant with GenAI Semantic Conventions.
|
||||
|
||||
- `gemini_cli.token.usage` (Counter, Int): Counts the number of tokens used.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `type` (string: "input", "output", "thought", "cache", or "tool")
|
||||
- **Note**: This metric overlaps with `gen_ai.client.token.usage` below for
|
||||
`input`/`output` token types that's compliant with GenAI Semantic
|
||||
Conventions.
|
||||
|
||||
- `gemini_cli.file.operation.count` (Counter, Int): Counts file operations.
|
||||
- **Attributes**:
|
||||
@@ -378,30 +369,3 @@ Metrics are numerical measurements of behavior over time.
|
||||
- **Attributes**:
|
||||
- `tokens_before`: (Int): Number of tokens in context prior to compression
|
||||
- `tokens_after`: (Int): Number of tokens in context after compression
|
||||
|
||||
#### GenAI Semantic Convention
|
||||
|
||||
The following metrics comply with [OpenTelemetry GenAI semantic conventions]
|
||||
for standardized observability across GenAI applications:
|
||||
|
||||
- `gen_ai.client.token.usage` (Histogram, token): Number of input and output tokens used per operation.
|
||||
- **Attributes**:
|
||||
- `gen_ai.operation.name` (string): The operation type (e.g., "generate_content", "chat")
|
||||
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or "gcp.vertex_ai")
|
||||
- `gen_ai.token.type` (string): The token type ("input" or "output")
|
||||
- `gen_ai.request.model` (string, optional): The model name used for the request
|
||||
- `gen_ai.response.model` (string, optional): The model name that generated the response
|
||||
- `server.address` (string, optional): GenAI server address
|
||||
- `server.port` (int, optional): GenAI server port
|
||||
|
||||
- `gen_ai.client.operation.duration` (Histogram, s): GenAI operation duration in seconds.
|
||||
- **Attributes**:
|
||||
- `gen_ai.operation.name` (string): The operation type (e.g., "generate_content", "chat")
|
||||
- `gen_ai.provider.name` (string): The GenAI provider ("gcp.gen_ai" or "gcp.vertex_ai")
|
||||
- `gen_ai.request.model` (string, optional): The model name used for the request
|
||||
- `gen_ai.response.model` (string, optional): The model name that generated the response
|
||||
- `server.address` (string, optional): GenAI server address
|
||||
- `server.port` (int, optional): GenAI server port
|
||||
- `error.type` (string, optional): Error type if the operation failed
|
||||
|
||||
[OpenTelemetry GenAI semantic conventions]: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-metrics.md
|
||||
+4
-4
@@ -35,7 +35,7 @@ You will typically see messages in the CLI indicating when a tool is being calle
|
||||
Many tools, especially those that can modify your file system or execute commands (`write_file`, `edit`, `run_shell_command`), are designed with safety in mind. The Gemini CLI will typically:
|
||||
|
||||
- **Require confirmation:** Prompt you before executing potentially sensitive operations, showing you what action is about to be taken.
|
||||
- **Utilize sandboxing:** All tools are subject to restrictions enforced by sandboxing (see [Sandboxing in the Gemini CLI](../cli/sandbox.md)). This means that when operating in a sandbox, any tools (including MCP servers) you wish to use must be available _inside_ the sandbox environment. For example, to run an MCP server through `npx`, the `npx` executable must be installed within the sandbox's Docker image or be available in the `sandbox-exec` environment.
|
||||
- **Utilize sandboxing:** All tools are subject to restrictions enforced by sandboxing (see [Sandboxing in the Gemini CLI](../sandbox.md)). This means that when operating in a sandbox, any tools (including MCP servers) you wish to use must be available _inside_ the sandbox environment. For example, to run an MCP server through `npx`, the `npx` executable must be installed within the sandbox's Docker image or be available in the `sandbox-exec` environment.
|
||||
|
||||
It's important to always review confirmation prompts carefully before allowing a tool to proceed.
|
||||
|
||||
@@ -46,11 +46,11 @@ Gemini CLI's built-in tools can be broadly categorized as follows:
|
||||
- **[File System Tools](./file-system.md):** For interacting with files and directories (reading, writing, listing, searching, etc.).
|
||||
- **[Shell Tool](./shell.md) (`run_shell_command`):** For executing shell commands.
|
||||
- **[Web Fetch Tool](./web-fetch.md) (`web_fetch`):** For retrieving content from URLs.
|
||||
- **[Web Search Tool](./web-search.md) (`google_web_search`):** For searching the web.
|
||||
- **[Multi-File Read Tool](./multi-file.md) (`read_many_files`):** A specialized tool for reading content from multiple files or directories.
|
||||
- **[Web Search Tool](./web-search.md) (`web_search`):** For searching the web.
|
||||
- **[Multi-File Read Tool](./multi-file.md) (`read_many_files`):** A specialized tool for reading content from multiple files or directories, often used by the `@` command.
|
||||
- **[Memory Tool](./memory.md) (`save_memory`):** For saving and recalling information across sessions.
|
||||
|
||||
Additionally, these tools incorporate:
|
||||
|
||||
- **[MCP servers](./mcp-server.md)**: MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
|
||||
- **[Sandboxing](../cli/sandbox.md)**: Sandboxing isolates the model and its changes from your environment to reduce potential risk.
|
||||
- **[Sandboxing](../sandbox.md)**: Sandboxing isolates the model and its changes from your environment to reduce potential risk.
|
||||
|
||||
+2
-2
@@ -55,7 +55,7 @@ If you are using a Gemini API key for authentication with a [Vertex AI GenAI API
|
||||
|
||||
### Usage Statistics Opt-Out
|
||||
|
||||
You may opt-out from sending Usage Statistics to Google by following the instructions available here: [Usage Statistics Configuration](./get-started/configuration.md#usage-statistics).
|
||||
You may opt-out from sending Usage Statistics to Google by following the instructions available here: [Usage Statistics Configuration](./cli/configuration.md#usage-statistics).
|
||||
|
||||
## Frequently Asked Questions (FAQ) for the Gemini CLI
|
||||
|
||||
@@ -90,4 +90,4 @@ The data it collects depends on your account and authentication type:
|
||||
|
||||
Please refer to the Privacy Notice that applies to your authentication method for more information about what data is collected and how this data is used.
|
||||
|
||||
You can disable Usage Statistics for any account type by following the instructions in the [Usage Statistics Configuration](./get-started/configuration-v1.md#usage-statistics) documentation.
|
||||
You can disable Usage Statistics for any account type by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
|
||||
+16
-1
@@ -24,6 +24,21 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
- **Solution:** Set the `NODE_EXTRA_CA_CERTS` environment variable to the absolute path of your corporate root CA certificate file.
|
||||
- Example: `export NODE_EXTRA_CA_CERTS=/path/to/your/corporate-ca.crt`
|
||||
|
||||
## Frequently asked questions (FAQs)
|
||||
|
||||
- **Q: How do I update Gemini CLI to the latest version?**
|
||||
- A: If you installed it globally via `npm`, update it using the command `npm install -g @google/gemini-cli@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
|
||||
- **Q: Where are the Gemini CLI configuration or settings files stored?**
|
||||
- A: The Gemini CLI configuration is stored in two `settings.json` files:
|
||||
1. In your home directory: `~/.gemini/settings.json`.
|
||||
2. In your project's root directory: `./.gemini/settings.json`.
|
||||
|
||||
Refer to [Gemini CLI Configuration](./cli/configuration.md) for more details.
|
||||
|
||||
- **Q: Why don't I see cached token counts in my stats output?**
|
||||
- A: Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Gemini API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Gemini Code Assist API does not support cached content creation. You can still view your total token usage using the `/stats` command in Gemini CLI.
|
||||
|
||||
## Common error messages and solutions
|
||||
|
||||
- **Error: `EADDRINUSE` (Address already in use) when starting an MCP server.**
|
||||
@@ -47,7 +62,7 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
|
||||
- **Error: "Operation not permitted", "Permission denied", or similar.**
|
||||
- **Cause:** When sandboxing is enabled, Gemini CLI may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
|
||||
- **Solution:** Refer to the [Configuration: Sandboxing](./cli/sandbox.md) documentation for more information, including how to customize your sandbox configuration.
|
||||
- **Solution:** Refer to the [Configuration: Sandboxing](./cli/configuration.md#sandboxing) documentation for more information, including how to customize your sandbox configuration.
|
||||
|
||||
- **Gemini CLI is not running in interactive mode in "CI" environments**
|
||||
- **Issue:** The Gemini CLI does not enter interactive mode (no prompt appears) if an environment variable starting with `CI_` (e.g., `CI_TOKEN`) is set. This is because the `is-in-ci` package, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment.
|
||||
|
||||
@@ -56,6 +56,6 @@ If you need to change a decision or see all your settings, you have a couple of
|
||||
|
||||
For advanced users, it's helpful to know the exact order of operations for how trust is determined:
|
||||
|
||||
1. **IDE Trust Signal**: If you are using the [IDE Integration](../ide-integration/index.md), the CLI first asks the IDE if the workspace is trusted. The IDE's response takes highest priority.
|
||||
1. **IDE Trust Signal**: If you are using the [IDE Integration](./ide-integration.md), the CLI first asks the IDE if the workspace is trusted. The IDE's response takes highest priority.
|
||||
|
||||
2. **Local Trust File**: If the IDE is not connected, the CLI checks the central `~/.gemini/trustedFolders.json` file.
|
||||
@@ -18,87 +18,99 @@ describe('Interactive Mode', () => {
|
||||
await rig.cleanup();
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10770
|
||||
it.skip('should trigger chat compression with /compress command', async () => {
|
||||
await rig.setup('interactive-compress-test');
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'should trigger chat compression with /compress command',
|
||||
async () => {
|
||||
await rig.setup('interactive-compress-test');
|
||||
|
||||
const { ptyProcess } = rig.runInteractive();
|
||||
const { ptyProcess } = rig.runInteractive();
|
||||
|
||||
let fullOutput = '';
|
||||
ptyProcess.onData((data) => (fullOutput += data));
|
||||
let fullOutput = '';
|
||||
ptyProcess.onData((data) => (fullOutput += data));
|
||||
|
||||
const authDialogAppeared = await rig.waitForText(
|
||||
'How would you like to authenticate',
|
||||
5000,
|
||||
);
|
||||
const authDialogAppeared = await rig.waitForText(
|
||||
'How would you like to authenticate',
|
||||
5000,
|
||||
);
|
||||
|
||||
// select the second option if auth dialog come's up
|
||||
if (authDialogAppeared) {
|
||||
ptyProcess.write('2');
|
||||
}
|
||||
// select the second option if auth dialog come's up
|
||||
if (authDialogAppeared) {
|
||||
ptyProcess.write('2');
|
||||
}
|
||||
|
||||
// Wait for the app to be ready
|
||||
const isReady = await rig.waitForText('Type your message', 15000);
|
||||
expect(isReady, 'CLI did not start up in interactive mode correctly').toBe(
|
||||
true,
|
||||
);
|
||||
// Wait for the app to be ready
|
||||
const isReady = await rig.waitForText('Type your message', 15000);
|
||||
expect(
|
||||
isReady,
|
||||
'CLI did not start up in interactive mode correctly',
|
||||
).toBe(true);
|
||||
|
||||
const longPrompt =
|
||||
'Dont do anything except returning a 1000 token long paragragh with the <name of the scientist who discovered theory of relativity> at the end to indicate end of response. This is a moderately long sentence.';
|
||||
const longPrompt =
|
||||
'Dont do anything except returning a 1000 token long paragragh with the <name of the scientist who discovered theory of relativity> at the end to indicate end of response. This is a moderately long sentence.';
|
||||
|
||||
await type(ptyProcess, longPrompt);
|
||||
await type(ptyProcess, '\r');
|
||||
await type(ptyProcess, longPrompt);
|
||||
await type(ptyProcess, '\r');
|
||||
|
||||
await rig.waitForText('einstein', 25000);
|
||||
await rig.waitForText('einstein', 25000);
|
||||
|
||||
await type(ptyProcess, '/compress');
|
||||
// A small delay to allow React to re-render the command list.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await type(ptyProcess, '\r');
|
||||
await type(ptyProcess, '/compress');
|
||||
// A small delay to allow React to re-render the command list.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await type(ptyProcess, '\r');
|
||||
|
||||
const foundEvent = await rig.waitForTelemetryEvent(
|
||||
'chat_compression',
|
||||
90000,
|
||||
);
|
||||
expect(foundEvent, 'chat_compression telemetry event was not found').toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
const foundEvent = await rig.waitForTelemetryEvent(
|
||||
'chat_compression',
|
||||
90000,
|
||||
);
|
||||
expect(foundEvent, 'chat_compression telemetry event was not found').toBe(
|
||||
true,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10769
|
||||
it.skip('should handle compression failure on token inflation', async () => {
|
||||
await rig.setup('interactive-compress-test');
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'should handle compression failure on token inflation',
|
||||
async () => {
|
||||
await rig.setup('interactive-compress-test');
|
||||
|
||||
const { ptyProcess } = rig.runInteractive();
|
||||
const { ptyProcess } = rig.runInteractive();
|
||||
|
||||
let fullOutput = '';
|
||||
ptyProcess.onData((data) => (fullOutput += data));
|
||||
let fullOutput = '';
|
||||
ptyProcess.onData((data) => (fullOutput += data));
|
||||
|
||||
const authDialogAppeared = await rig.waitForText(
|
||||
'How would you like to authenticate',
|
||||
5000,
|
||||
);
|
||||
const authDialogAppeared = await rig.waitForText(
|
||||
'How would you like to authenticate',
|
||||
5000,
|
||||
);
|
||||
|
||||
// select the second option if auth dialog come's up
|
||||
if (authDialogAppeared) {
|
||||
ptyProcess.write('2');
|
||||
}
|
||||
// select the second option if auth dialog come's up
|
||||
if (authDialogAppeared) {
|
||||
ptyProcess.write('2');
|
||||
}
|
||||
|
||||
// Wait for the app to be ready
|
||||
const isReady = await rig.waitForText('Type your message', 25000);
|
||||
expect(isReady, 'CLI did not start up in interactive mode correctly').toBe(
|
||||
true,
|
||||
);
|
||||
// Wait for the app to be ready
|
||||
const isReady = await rig.waitForText('Type your message', 25000);
|
||||
expect(
|
||||
isReady,
|
||||
'CLI did not start up in interactive mode correctly',
|
||||
).toBe(true);
|
||||
|
||||
await type(ptyProcess, '/compress');
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await type(ptyProcess, '\r');
|
||||
await type(ptyProcess, '/compress');
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await type(ptyProcess, '\r');
|
||||
|
||||
const compressionFailed = await rig.waitForText(
|
||||
'compression was not beneficial',
|
||||
25000,
|
||||
);
|
||||
const foundEvent = await rig.waitForTelemetryEvent(
|
||||
'chat_compression',
|
||||
90000,
|
||||
);
|
||||
expect(foundEvent).toBe(true);
|
||||
|
||||
expect(compressionFailed).toBe(true);
|
||||
});
|
||||
const compressionFailed = await rig.waitForText(
|
||||
'compression was not beneficial',
|
||||
25000,
|
||||
);
|
||||
|
||||
expect(compressionFailed).toBe(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,89 +5,125 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import * as os from 'node:os';
|
||||
import { TestRig } from './test-helper.js';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
|
||||
describe('Ctrl+C exit', () => {
|
||||
it('should exit gracefully on second Ctrl+C', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should exit gracefully on second Ctrl+C');
|
||||
// (#9782) Temporarily disabling on windows because it is failing on main and every
|
||||
// PR, which is potentially hiding other failures
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'should exit gracefully on second Ctrl+C',
|
||||
async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should exit gracefully on second Ctrl+C');
|
||||
|
||||
const { ptyProcess, promise } = rig.runInteractive();
|
||||
const { ptyProcess, promise } = rig.runInteractive();
|
||||
|
||||
let output = '';
|
||||
ptyProcess.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
let output = '';
|
||||
ptyProcess.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
|
||||
// Wait for the app to be ready by looking for the initial prompt indicator
|
||||
await rig.poll(() => output.includes('▶'), 5000, 100);
|
||||
// Wait for the app to be ready by looking for the initial prompt indicator
|
||||
await rig.poll(() => output.includes('▶'), 5000, 100);
|
||||
|
||||
// Send first Ctrl+C
|
||||
ptyProcess.write('\x03');
|
||||
// Send first Ctrl+C
|
||||
ptyProcess.write(String.fromCharCode(3));
|
||||
|
||||
// Wait for the exit prompt
|
||||
await rig.poll(
|
||||
() => output.includes('Press Ctrl+C again to exit'),
|
||||
1500,
|
||||
50,
|
||||
);
|
||||
// Wait for the exit prompt
|
||||
await rig.poll(
|
||||
() => output.includes('Press Ctrl+C again to exit'),
|
||||
1500,
|
||||
50,
|
||||
);
|
||||
|
||||
// Send second Ctrl+C
|
||||
if (os.platform() === 'win32') {
|
||||
// This is a workaround for node-pty/winpty on Windows.
|
||||
// Reliably sending a second Ctrl+C signal to a process that is already
|
||||
// handling the first one is not possible in the emulated pty environment.
|
||||
// The first signal is caught correctly (verified by the poll above),
|
||||
// which is the most critical part of the test on this platform.
|
||||
// To allow the test to pass, we forcefully kill the process,
|
||||
// simulating a successful exit. We accept that we cannot test the
|
||||
// graceful shutdown message on Windows in this automated context.
|
||||
ptyProcess.kill();
|
||||
} else {
|
||||
// On Unix-like systems, send the second Ctrl+C to trigger the graceful exit.
|
||||
ptyProcess.write('\x03');
|
||||
}
|
||||
// Send second Ctrl+C
|
||||
ptyProcess.write(String.fromCharCode(3));
|
||||
|
||||
const timeout = new Promise((_, reject) =>
|
||||
setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error(
|
||||
`Test timed out: process did not exit within a minute. Output: ${output}`,
|
||||
),
|
||||
),
|
||||
60000,
|
||||
),
|
||||
);
|
||||
const result = await promise;
|
||||
|
||||
const result = await Promise.race([promise, timeout]);
|
||||
|
||||
// On Windows, killing the process may result in a non-zero exit code. On
|
||||
// other platforms, a graceful exit is code 0.
|
||||
if (os.platform() === 'win32') {
|
||||
// On Windows, the exit code after ptyProcess.kill() can be unpredictable
|
||||
// (often 1), so we accept any non-null exit code as a pass condition,
|
||||
// focusing on the fact that the process did terminate.
|
||||
expect(
|
||||
result.exitCode,
|
||||
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
|
||||
).not.toBeNull();
|
||||
} else {
|
||||
// Expect a graceful exit (code 0) on non-Windows platforms
|
||||
// Expect a graceful exit (code 0)
|
||||
expect(
|
||||
result.exitCode,
|
||||
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
|
||||
).toBe(0);
|
||||
|
||||
// Only check for the quitting message on non-Windows platforms due to the
|
||||
// forceful kill workaround.
|
||||
// Check that the quitting message is displayed
|
||||
const quittingMessage = 'Agent powering down. Goodbye!';
|
||||
// The regex below is intentionally matching the ESC control character (\x1b)
|
||||
// to strip ANSI color codes from the terminal output.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
expect(cleanOutput).toContain(quittingMessage);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'should exit gracefully on second Ctrl+C when calling a tool',
|
||||
async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup(
|
||||
'should exit gracefully on second Ctrl+C when calling a tool',
|
||||
);
|
||||
|
||||
const childProcessFile = 'child_process_file.txt';
|
||||
rig.createFile(
|
||||
'wait.js',
|
||||
`setTimeout(() => require('fs').writeFileSync('${childProcessFile}', 'done'), 5000)`,
|
||||
);
|
||||
|
||||
const { ptyProcess, promise } = rig.runInteractive();
|
||||
|
||||
let output = '';
|
||||
ptyProcess.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
|
||||
// Wait for the app to be ready by looking for the initial prompt indicator
|
||||
await rig.poll(() => output.includes('▶'), 5000, 100);
|
||||
|
||||
ptyProcess.write('use the tool to run "node -e wait.js"\n');
|
||||
|
||||
await rig.poll(() => output.includes('Shell'), 5000, 100);
|
||||
|
||||
// Send first Ctrl+C
|
||||
ptyProcess.write(String.fromCharCode(3));
|
||||
|
||||
// Wait for the exit prompt
|
||||
await rig.poll(
|
||||
() => output.includes('Press Ctrl+C again to exit'),
|
||||
1500,
|
||||
50,
|
||||
);
|
||||
|
||||
// Send second Ctrl+C
|
||||
ptyProcess.write(String.fromCharCode(3));
|
||||
|
||||
const result = await promise;
|
||||
|
||||
// Expect a graceful exit (code 0)
|
||||
expect(
|
||||
result.exitCode,
|
||||
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
|
||||
).toBe(0);
|
||||
|
||||
// Check that the quitting message is displayed
|
||||
const quittingMessage = 'Agent powering down. Goodbye!';
|
||||
// The regex below is intentionally matching the ESC control character (\x1b)
|
||||
// to strip ANSI color codes from the terminal output.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
expect(cleanOutput).toContain(quittingMessage);
|
||||
|
||||
// Check that the child process was terminated and did not create the file.
|
||||
const childProcessFileExists = fs.existsSync(
|
||||
path.join(rig.testDir!, childProcessFile),
|
||||
);
|
||||
expect(
|
||||
childProcessFileExists,
|
||||
'Child process file should not exist',
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -192,8 +192,7 @@ describe('mcp server with cyclic tool schema is detected', () => {
|
||||
}
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10735
|
||||
it.skip('mcp tool list should include tool with cyclic tool schema', async () => {
|
||||
it('mcp tool list should include tool with cyclic tool schema', async () => {
|
||||
const tool_list_output = await rig.run('/mcp list');
|
||||
expect(tool_list_output).toContain('tool_with_cyclic_schema');
|
||||
});
|
||||
|
||||
@@ -140,14 +140,13 @@ describe('replace', () => {
|
||||
it('should insert a multi-line block of text', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should insert a multi-line block of text');
|
||||
const fileName = 'insert_block.txt';
|
||||
const originalContent = 'Line A\n<INSERT_TEXT_HERE>\nLine C';
|
||||
const newBlock = 'First line\nSecond line\nThird line';
|
||||
const expectedContent =
|
||||
'Line A\nFirst line\nSecond line\nThird line\nLine C';
|
||||
const fileName = 'insert_block.js';
|
||||
const originalContent = 'function hello() {\n // INSERT_CODE_HERE\n}';
|
||||
const newBlock = "console.log('hello');\n console.log('world');";
|
||||
const expectedContent = `function hello() {\n ${newBlock}\n}`;
|
||||
rig.createFile(fileName, originalContent);
|
||||
|
||||
const prompt = `In ${fileName}, replace "<INSERT_TEXT_HERE>" with:\n${newBlock}`;
|
||||
const prompt = `In ${fileName}, replace "// INSERT_CODE_HERE" with:\n${newBlock}`;
|
||||
const result = await rig.run(prompt);
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('replace');
|
||||
|
||||
@@ -6,24 +6,6 @@
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { TestRig, printDebugInfo, validateModelOutput } from './test-helper.js';
|
||||
import { getShellConfiguration } from '../packages/core/src/utils/shell-utils.js';
|
||||
|
||||
const { shell } = getShellConfiguration();
|
||||
|
||||
function getLineCountCommand(): { command: string; tool: string } {
|
||||
switch (shell) {
|
||||
case 'powershell':
|
||||
return {
|
||||
command: `(Get-Content test.txt).Length`,
|
||||
tool: 'Get-Content',
|
||||
};
|
||||
case 'cmd':
|
||||
return { command: `find /c /v "" test.txt`, tool: 'find' };
|
||||
case 'bash':
|
||||
default:
|
||||
return { command: `wc -l test.txt`, tool: 'wc' };
|
||||
}
|
||||
}
|
||||
|
||||
describe('run_shell_command', () => {
|
||||
it('should be able to run a shell command', async () => {
|
||||
@@ -86,177 +68,6 @@ describe('run_shell_command', () => {
|
||||
validateModelOutput(result, 'test-stdin', 'Shell command stdin test');
|
||||
});
|
||||
|
||||
it('should run allowed sub-command in non-interactive mode', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should run allowed sub-command in non-interactive mode');
|
||||
|
||||
const testFile = rig.createFile('test.txt', 'Lorem\nIpsum\nDolor\n');
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use ${tool} to tell me how many lines there are in ${testFile}`;
|
||||
|
||||
// Provide the prompt via stdin to simulate non-interactive mode
|
||||
const result = await rig.run({
|
||||
stdin: prompt,
|
||||
args: [`--allowed-tools=run_shell_command(${tool})`],
|
||||
});
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should succeed with no parens in non-interactive mode', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should succeed with no parens in non-interactive mode');
|
||||
|
||||
const testFile = rig.createFile('test.txt', 'Lorem\nIpsum\nDolor\n');
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use ${tool} to tell me how many lines there are in ${testFile}`;
|
||||
|
||||
const result = await rig.run({
|
||||
stdin: prompt,
|
||||
args: ['--allowed-tools=run_shell_command'],
|
||||
});
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should succeed with --yolo mode', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should succeed with --yolo mode');
|
||||
|
||||
const testFile = rig.createFile('test.txt', 'Lorem\nIpsum\nDolor\n');
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use ${tool} to tell me how many lines there are in ${testFile}`;
|
||||
|
||||
const result = await rig.run(
|
||||
{
|
||||
prompt: prompt,
|
||||
},
|
||||
'--yolo',
|
||||
);
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should work with ShellTool alias', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should work with ShellTool alias');
|
||||
|
||||
const testFile = rig.createFile('test.txt', 'Lorem\nIpsum\nDolor\n');
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use ${tool} to tell me how many lines there are in ${testFile}`;
|
||||
|
||||
const result = await rig.run({
|
||||
stdin: prompt,
|
||||
args: [`--allowed-tools=ShellTool(${tool})`],
|
||||
});
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10737
|
||||
it.skip('should combine multiple --allowed-tools flags', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should combine multiple --allowed-tools flags');
|
||||
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use ${tool} and ls`;
|
||||
|
||||
const result = await rig.run({
|
||||
stdin: prompt,
|
||||
args: [
|
||||
`--allowed-tools=run_shell_command(${tool})`,
|
||||
'--allowed-tools=run_shell_command(ls)',
|
||||
],
|
||||
});
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10768
|
||||
it.skip('should allow all with "ShellTool" and other specifics', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should allow all with "ShellTool" and other specifics');
|
||||
|
||||
const { tool } = getLineCountCommand();
|
||||
const prompt = `use date`;
|
||||
|
||||
const result = await rig.run({
|
||||
stdin: prompt,
|
||||
args: [
|
||||
`--allowed-tools=run_shell_command(${tool})`,
|
||||
'--allowed-tools=run_shell_command',
|
||||
],
|
||||
});
|
||||
|
||||
const foundToolCall = await rig.waitForToolCall('run_shell_command', 15000);
|
||||
|
||||
if (!foundToolCall) {
|
||||
printDebugInfo(rig, result, {
|
||||
'Found tool call': foundToolCall,
|
||||
});
|
||||
}
|
||||
|
||||
expect(
|
||||
foundToolCall,
|
||||
'Expected to find a run_shell_command tool call',
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should propagate environment variables to the child process', async () => {
|
||||
const rig = new TestRig();
|
||||
await rig.setup('should propagate environment variables');
|
||||
|
||||
@@ -210,8 +210,7 @@ describe('simple-mcp-server', () => {
|
||||
}
|
||||
});
|
||||
|
||||
//TODO -https://github.com/google-gemini/gemini-cli/issues/10738
|
||||
it.skip('should add two numbers', async () => {
|
||||
it('should add two numbers', async () => {
|
||||
// Test directory is already set up in before hook
|
||||
// Just run the command - MCP server config is in settings.json
|
||||
const output = await rig.run('add 5 and 10');
|
||||
|
||||
@@ -13,7 +13,6 @@ import { DEFAULT_GEMINI_MODEL } from '../packages/core/src/config/models.js';
|
||||
import fs from 'node:fs';
|
||||
import * as pty from '@lydell/node-pty';
|
||||
import stripAnsi from 'strip-ansi';
|
||||
import * as os from 'node:os';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -814,27 +813,16 @@ export class TestRig {
|
||||
} {
|
||||
const { command, initialArgs } = this._getCommandAndArgs(['--yolo']);
|
||||
const commandArgs = [...initialArgs, ...args];
|
||||
const isWindows = os.platform() === 'win32';
|
||||
|
||||
this._interactiveOutput = ''; // Reset output for the new run
|
||||
|
||||
const options: pty.IPtyForkOptions = {
|
||||
const ptyProcess = pty.spawn(command, commandArgs, {
|
||||
name: 'xterm-color',
|
||||
cols: 80,
|
||||
rows: 30,
|
||||
cwd: this.testDir!,
|
||||
env: Object.fromEntries(
|
||||
Object.entries(process.env).filter(([, v]) => v !== undefined),
|
||||
) as { [key: string]: string },
|
||||
};
|
||||
|
||||
if (isWindows) {
|
||||
// node-pty on Windows requires a shell to be specified when using winpty.
|
||||
options.shell = process.env.COMSPEC || 'cmd.exe';
|
||||
}
|
||||
|
||||
const executable = command === 'node' ? process.execPath : command;
|
||||
const ptyProcess = pty.spawn(executable, commandArgs, options);
|
||||
env: process.env as { [key: string]: string },
|
||||
});
|
||||
|
||||
ptyProcess.onData((data) => {
|
||||
this._interactiveOutput += data;
|
||||
|
||||
Generated
+34
-239
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -18,7 +18,6 @@
|
||||
"gemini": "bundle/gemini.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@octokit/rest": "^22.0.0",
|
||||
"@types/marked": "^5.0.2",
|
||||
"@types/mime-types": "^3.0.1",
|
||||
"@types/minimatch": "^5.1.2",
|
||||
@@ -2406,172 +2405,6 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/auth-token": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-6.0.0.tgz",
|
||||
"integrity": "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/core": {
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.5.tgz",
|
||||
"integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/auth-token": "^6.0.0",
|
||||
"@octokit/graphql": "^9.0.2",
|
||||
"@octokit/request": "^10.0.4",
|
||||
"@octokit/request-error": "^7.0.1",
|
||||
"@octokit/types": "^15.0.0",
|
||||
"before-after-hook": "^4.0.0",
|
||||
"universal-user-agent": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/endpoint": {
|
||||
"version": "11.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.1.tgz",
|
||||
"integrity": "sha512-7P1dRAZxuWAOPI7kXfio88trNi/MegQ0IJD3vfgC3b+LZo1Qe6gRJc2v0mz2USWWJOKrB2h5spXCzGbw+fAdqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^15.0.0",
|
||||
"universal-user-agent": "^7.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/graphql": {
|
||||
"version": "9.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.2.tgz",
|
||||
"integrity": "sha512-iz6KzZ7u95Fzy9Nt2L8cG88lGRMr/qy1Q36ih/XVzMIlPDMYwaNLE/ENhqmIzgPrlNWiYJkwmveEetvxAgFBJw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/request": "^10.0.4",
|
||||
"@octokit/types": "^15.0.0",
|
||||
"universal-user-agent": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/openapi-types": {
|
||||
"version": "26.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-26.0.0.tgz",
|
||||
"integrity": "sha512-7AtcfKtpo77j7Ts73b4OWhOZHTKo/gGY8bB3bNBQz4H+GRSWqx2yvj8TXRsbdTE0eRmYmXOEY66jM7mJ7LzfsA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@octokit/plugin-paginate-rest": {
|
||||
"version": "13.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-13.2.0.tgz",
|
||||
"integrity": "sha512-YuAlyjR8o5QoRSOvMHxSJzPtogkNMgeMv2mpccrvdUGeC3MKyfi/hS+KiFwyH/iRKIKyx+eIMsDjbt3p9r2GYA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^15.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@octokit/core": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/plugin-request-log": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz",
|
||||
"integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@octokit/core": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/plugin-rest-endpoint-methods": {
|
||||
"version": "16.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-16.1.0.tgz",
|
||||
"integrity": "sha512-nCsyiKoGRnhH5LkH8hJEZb9swpqOcsW+VXv1QoyUNQXJeVODG4+xM6UICEqyqe9XFr6LkL8BIiFCPev8zMDXPw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^15.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@octokit/core": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/request": {
|
||||
"version": "10.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.5.tgz",
|
||||
"integrity": "sha512-TXnouHIYLtgDhKo+N6mXATnDBkV05VwbR0TtMWpgTHIoQdRQfCSzmy/LGqR1AbRMbijq/EckC/E3/ZNcU92NaQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/endpoint": "^11.0.1",
|
||||
"@octokit/request-error": "^7.0.1",
|
||||
"@octokit/types": "^15.0.0",
|
||||
"fast-content-type-parse": "^3.0.0",
|
||||
"universal-user-agent": "^7.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/request-error": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.0.1.tgz",
|
||||
"integrity": "sha512-CZpFwV4+1uBrxu7Cw8E5NCXDWFNf18MSY23TdxCBgjw1tXXHvTrZVsXlW8hgFTOLw8RQR1BBrMvYRtuyaijHMA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^15.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/rest": {
|
||||
"version": "22.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-22.0.0.tgz",
|
||||
"integrity": "sha512-z6tmTu9BTnw51jYGulxrlernpsQYXpui1RK21vmXn8yF5bp6iX16yfTtJYGK5Mh1qDkvDOmp2n8sRMcQmR8jiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/core": "^7.0.2",
|
||||
"@octokit/plugin-paginate-rest": "^13.0.1",
|
||||
"@octokit/plugin-request-log": "^6.0.0",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^16.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/@octokit/types": {
|
||||
"version": "15.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-15.0.0.tgz",
|
||||
"integrity": "sha512-8o6yDfmoGJUIeR9OfYU0/TUJTnMPG2r68+1yEdUeG2Fdqpj8Qetg0ziKIgcBm0RW/j29H41WP37CYCEhp6GoHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/openapi-types": "^26.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@open-draft/deferred-promise": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz",
|
||||
@@ -6049,13 +5882,6 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/before-after-hook": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz",
|
||||
"integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/bignumber.js": {
|
||||
"version": "9.3.0",
|
||||
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.0.tgz",
|
||||
@@ -8730,23 +8556,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-content-type-parse": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-3.0.0.tgz",
|
||||
"integrity": "sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
@@ -15734,9 +15543,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
|
||||
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
|
||||
"integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
@@ -15963,14 +15772,14 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@@ -15980,14 +15789,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@@ -15998,9 +15804,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/picomatch": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -16468,13 +16274,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/universal-user-agent": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz",
|
||||
"integrity": "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
|
||||
@@ -16709,18 +16508,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.1.9",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.9.tgz",
|
||||
"integrity": "sha512-4nVGliEpxmhCL8DslSAUdxlB6+SMrhB0a1v5ijlh1xB1nEPuy1mxaHxysVucLHuWryAxLWg6a5ei+U4TLn/rFg==",
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.0.0.tgz",
|
||||
"integrity": "sha512-ixXJB1YRgDIw2OszKQS9WxGHKwLdCsbQNkpJN171udl6szi/rIySHL6/Os3s2+oE4P/FLD4dxg4mD7Wust+u5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"fdir": "^6.4.6",
|
||||
"picomatch": "^4.0.2",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.15"
|
||||
"rollup": "^4.40.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
@@ -16807,14 +16606,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@@ -16825,9 +16621,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/picomatch": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -17601,7 +17397,7 @@
|
||||
},
|
||||
"packages/a2a-server": {
|
||||
"name": "@google/gemini-cli-a2a-server",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"dependencies": {
|
||||
"@a2a-js/sdk": "^0.3.2",
|
||||
"@google-cloud/storage": "^7.16.0",
|
||||
@@ -17872,7 +17668,7 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"dependencies": {
|
||||
"@google/gemini-cli-core": "file:../core",
|
||||
"@google/genai": "1.16.0",
|
||||
@@ -17892,7 +17688,6 @@
|
||||
"ink-gradient": "^3.0.0",
|
||||
"ink-spinner": "^5.0.0",
|
||||
"lowlight": "^3.3.0",
|
||||
"mnemonist": "^0.40.3",
|
||||
"open": "^10.1.2",
|
||||
"react": "^19.1.0",
|
||||
"read-package-up": "^11.0.0",
|
||||
@@ -17985,7 +17780,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@google/gemini-cli-core",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"dependencies": {
|
||||
"@google-cloud/logging": "^11.2.1",
|
||||
"@google-cloud/opentelemetry-cloud-monitoring-exporter": "^0.21.0",
|
||||
@@ -18124,7 +17919,7 @@
|
||||
},
|
||||
"packages/test-utils": {
|
||||
"name": "@google/gemini-cli-test-utils",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.3"
|
||||
@@ -18135,7 +17930,7 @@
|
||||
},
|
||||
"packages/vscode-ide-companion": {
|
||||
"name": "gemini-cli-vscode-ide-companion",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"license": "LICENSE",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||
|
||||
+3
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
@@ -14,10 +14,10 @@
|
||||
"url": "git+https://github.com/google-gemini/gemini-cli.git"
|
||||
},
|
||||
"config": {
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.9.0"
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.8.0-preview.2"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "cross-env NODE_ENV=development node scripts/start.js",
|
||||
"start": "cross-env node scripts/start.js",
|
||||
"start:a2a-server": "CODER_AGENT_PORT=41242 npm run start --workspace @google/gemini-cli-a2a-server",
|
||||
"debug": "cross-env DEBUG=1 node --inspect-brk scripts/start.js",
|
||||
"auth:npm": "npx google-artifactregistry-auth",
|
||||
@@ -70,7 +70,6 @@
|
||||
"LICENSE"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@octokit/rest": "^22.0.0",
|
||||
"@types/marked": "^5.0.2",
|
||||
"@types/mime-types": "^3.0.1",
|
||||
"@types/minimatch": "^5.1.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-a2a-server",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"private": true,
|
||||
"description": "Gemini CLI A2A Server",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.8.0-preview.2",
|
||||
"description": "Gemini CLI",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -25,7 +25,7 @@
|
||||
"dist"
|
||||
],
|
||||
"config": {
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.9.0"
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.8.0-preview.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@google/gemini-cli-core": "file:../core",
|
||||
@@ -45,7 +45,6 @@
|
||||
"ink-gradient": "^3.0.0",
|
||||
"ink-spinner": "^5.0.0",
|
||||
"lowlight": "^3.3.0",
|
||||
"mnemonist": "^0.40.3",
|
||||
"open": "^10.1.2",
|
||||
"react": "^19.1.0",
|
||||
"read-package-up": "^11.0.0",
|
||||
|
||||
@@ -53,13 +53,16 @@ export async function handleUpdate(args: UpdateArgs) {
|
||||
console.log(`Extension "${args.name}" not found.`);
|
||||
return;
|
||||
}
|
||||
let updateState: ExtensionUpdateState | undefined;
|
||||
if (!extension.installMetadata) {
|
||||
console.log(
|
||||
`Unable to install extension "${args.name}" due to missing install metadata`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const updateState = await checkForExtensionUpdate(extension);
|
||||
await checkForExtensionUpdate(extension, (newState) => {
|
||||
updateState = newState;
|
||||
});
|
||||
if (updateState !== ExtensionUpdateState.UPDATE_AVAILABLE) {
|
||||
console.log(`Extension "${args.name}" is already up to date.`);
|
||||
return;
|
||||
@@ -88,23 +91,11 @@ export async function handleUpdate(args: UpdateArgs) {
|
||||
}
|
||||
if (args.all) {
|
||||
try {
|
||||
const extensionState = new Map();
|
||||
await checkForAllExtensionUpdates(
|
||||
extensions,
|
||||
(action) => {
|
||||
if (action.type === 'SET_STATE') {
|
||||
extensionState.set(action.payload.name, {
|
||||
status: action.payload.state,
|
||||
});
|
||||
}
|
||||
},
|
||||
workingDir,
|
||||
);
|
||||
let updateInfos = await updateAllUpdatableExtensions(
|
||||
workingDir,
|
||||
requestConsentNonInteractive,
|
||||
extensions,
|
||||
extensionState,
|
||||
await checkForAllExtensionUpdates(extensions, new Map(), (_) => {}),
|
||||
() => {},
|
||||
);
|
||||
updateInfos = updateInfos.filter(
|
||||
|
||||
@@ -28,10 +28,6 @@ vi.mock('./trustedFolders.js', () => ({
|
||||
.mockReturnValue({ isTrusted: true, source: 'file' }), // Default to trusted
|
||||
}));
|
||||
|
||||
vi.mock('./sandboxConfig.js', () => ({
|
||||
loadSandboxConfig: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actualFs = await importOriginal<typeof import('fs')>();
|
||||
const pathMod = await import('node:path');
|
||||
@@ -2538,59 +2534,6 @@ describe('loadCliConfig useRipgrep', () => {
|
||||
expect(config.getUseModelRouter()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig enableSubagents', () => {
|
||||
it('should be false by default when enableSubagents is not set in settings', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const settings: Settings = {};
|
||||
const config = await loadCliConfig(
|
||||
settings,
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getEnableSubagents()).toBe(false);
|
||||
});
|
||||
|
||||
it('should be true when enableSubagents is set to true in settings', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const settings: Settings = { experimental: { enableSubagents: true } };
|
||||
const config = await loadCliConfig(
|
||||
settings,
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getEnableSubagents()).toBe(true);
|
||||
});
|
||||
|
||||
it('should be false when enableSubagents is explicitly set to false in settings', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const settings: Settings = { experimental: { enableSubagents: false } };
|
||||
const config = await loadCliConfig(
|
||||
settings,
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getEnableSubagents()).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('screenReader configuration', () => {
|
||||
@@ -2777,78 +2720,6 @@ describe('loadCliConfig tool exclusions', () => {
|
||||
expect(config.getExcludeTools()).not.toContain('replace');
|
||||
expect(config.getExcludeTools()).not.toContain('write_file');
|
||||
});
|
||||
|
||||
it('should not exclude shell tool in non-interactive mode when --allowed-tools="ShellTool" is set', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = [
|
||||
'node',
|
||||
'script.js',
|
||||
'-p',
|
||||
'test',
|
||||
'--allowed-tools',
|
||||
'ShellTool',
|
||||
];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const config = await loadCliConfig(
|
||||
{},
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getExcludeTools()).not.toContain(ShellTool.Name);
|
||||
});
|
||||
|
||||
it('should not exclude shell tool in non-interactive mode when --allowed-tools="run_shell_command" is set', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = [
|
||||
'node',
|
||||
'script.js',
|
||||
'-p',
|
||||
'test',
|
||||
'--allowed-tools',
|
||||
'run_shell_command',
|
||||
];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const config = await loadCliConfig(
|
||||
{},
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getExcludeTools()).not.toContain(ShellTool.Name);
|
||||
});
|
||||
|
||||
it('should not exclude shell tool in non-interactive mode when --allowed-tools="ShellTool(wc)" is set', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = [
|
||||
'node',
|
||||
'script.js',
|
||||
'-p',
|
||||
'test',
|
||||
'--allowed-tools',
|
||||
'ShellTool(wc)',
|
||||
];
|
||||
const argv = await parseArguments({} as Settings);
|
||||
const config = await loadCliConfig(
|
||||
{},
|
||||
[],
|
||||
new ExtensionEnablementManager(
|
||||
ExtensionStorage.getUserExtensionsDir(),
|
||||
argv.extensions,
|
||||
),
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getExcludeTools()).not.toContain(ShellTool.Name);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig interactive', () => {
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
ShellTool,
|
||||
EditTool,
|
||||
WriteFileTool,
|
||||
SHELL_TOOL_NAMES,
|
||||
resolveTelemetrySettings,
|
||||
FatalConfigError,
|
||||
} from '@google/gemini-cli-core';
|
||||
@@ -401,7 +400,7 @@ export async function loadHierarchicalGeminiMemory(
|
||||
folderTrust: boolean,
|
||||
memoryImportFormat: 'flat' | 'tree' = 'tree',
|
||||
fileFilteringOptions?: FileFilteringOptions,
|
||||
): Promise<{ memoryContent: string; fileCount: number; filePaths: string[] }> {
|
||||
): Promise<{ memoryContent: string; fileCount: number }> {
|
||||
// FIX: Use real, canonical paths for a reliable comparison to handle symlinks.
|
||||
const realCwd = fs.realpathSync(path.resolve(currentWorkingDirectory));
|
||||
const realHome = fs.realpathSync(path.resolve(homedir()));
|
||||
@@ -431,36 +430,6 @@ export async function loadHierarchicalGeminiMemory(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a filter function to determine if a tool should be excluded.
|
||||
*
|
||||
* In non-interactive mode, we want to disable tools that require user
|
||||
* interaction to prevent the CLI from hanging. This function creates a predicate
|
||||
* that returns `true` if a tool should be excluded.
|
||||
*
|
||||
* A tool is excluded if it's not in the `allowedToolsSet`. The shell tool
|
||||
* has a special case: it's not excluded if any of its subcommands
|
||||
* are in the `allowedTools` list.
|
||||
*
|
||||
* @param allowedTools A list of explicitly allowed tool names.
|
||||
* @param allowedToolsSet A set of explicitly allowed tool names for quick lookups.
|
||||
* @returns A function that takes a tool name and returns `true` if it should be excluded.
|
||||
*/
|
||||
function createToolExclusionFilter(
|
||||
allowedTools: string[],
|
||||
allowedToolsSet: Set<string>,
|
||||
) {
|
||||
return (tool: string): boolean => {
|
||||
if (tool === ShellTool.Name) {
|
||||
// If any of the allowed tools is ShellTool (even with subcommands), don't exclude it.
|
||||
return !allowedTools.some((allowed) =>
|
||||
SHELL_TOOL_NAMES.some((shellName) => allowed.startsWith(shellName)),
|
||||
);
|
||||
}
|
||||
return !allowedToolsSet.has(tool);
|
||||
};
|
||||
}
|
||||
|
||||
export function isDebugMode(argv: CliArgs): boolean {
|
||||
return (
|
||||
argv.debug ||
|
||||
@@ -524,20 +493,19 @@ export async function loadCliConfig(
|
||||
.concat((argv.includeDirectories || []).map(resolvePath));
|
||||
|
||||
// Call the (now wrapper) loadHierarchicalGeminiMemory which calls the server's version
|
||||
const { memoryContent, fileCount, filePaths } =
|
||||
await loadHierarchicalGeminiMemory(
|
||||
cwd,
|
||||
settings.context?.loadMemoryFromIncludeDirectories
|
||||
? includeDirectories
|
||||
: [],
|
||||
debugMode,
|
||||
fileService,
|
||||
settings,
|
||||
extensionContextFilePaths,
|
||||
trustedFolder,
|
||||
memoryImportFormat,
|
||||
fileFiltering,
|
||||
);
|
||||
const { memoryContent, fileCount } = await loadHierarchicalGeminiMemory(
|
||||
cwd,
|
||||
settings.context?.loadMemoryFromIncludeDirectories
|
||||
? includeDirectories
|
||||
: [],
|
||||
debugMode,
|
||||
fileService,
|
||||
settings,
|
||||
extensionContextFilePaths,
|
||||
trustedFolder,
|
||||
memoryImportFormat,
|
||||
fileFiltering,
|
||||
);
|
||||
|
||||
let mcpServers = mergeMcpServers(settings, activeExtensions);
|
||||
const question = argv.promptInteractive || argv.prompt || '';
|
||||
@@ -593,9 +561,6 @@ export async function loadCliConfig(
|
||||
|
||||
const policyEngineConfig = createPolicyEngineConfig(settings, approvalMode);
|
||||
|
||||
const allowedTools = argv.allowedTools || settings.tools?.allowed || [];
|
||||
const allowedToolsSet = new Set(allowedTools);
|
||||
|
||||
// Interactive mode: explicit -i flag or (TTY + no args + no -p flag)
|
||||
const hasQuery = !!argv.query;
|
||||
const interactive =
|
||||
@@ -604,22 +569,14 @@ export async function loadCliConfig(
|
||||
// In non-interactive mode, exclude tools that require a prompt.
|
||||
const extraExcludes: string[] = [];
|
||||
if (!interactive && !argv.experimentalAcp) {
|
||||
const defaultExcludes = [ShellTool.Name, EditTool.Name, WriteFileTool.Name];
|
||||
const autoEditExcludes = [ShellTool.Name];
|
||||
|
||||
const toolExclusionFilter = createToolExclusionFilter(
|
||||
allowedTools,
|
||||
allowedToolsSet,
|
||||
);
|
||||
|
||||
switch (approvalMode) {
|
||||
case ApprovalMode.DEFAULT:
|
||||
// In default non-interactive mode, all tools that require approval are excluded.
|
||||
extraExcludes.push(...defaultExcludes.filter(toolExclusionFilter));
|
||||
extraExcludes.push(ShellTool.Name, EditTool.Name, WriteFileTool.Name);
|
||||
break;
|
||||
case ApprovalMode.AUTO_EDIT:
|
||||
// In auto-edit non-interactive mode, only tools that still require a prompt are excluded.
|
||||
extraExcludes.push(...autoEditExcludes.filter(toolExclusionFilter));
|
||||
extraExcludes.push(ShellTool.Name);
|
||||
break;
|
||||
case ApprovalMode.YOLO:
|
||||
// No extra excludes for YOLO mode.
|
||||
@@ -691,7 +648,7 @@ export async function loadCliConfig(
|
||||
question,
|
||||
fullContext: argv.allFiles || false,
|
||||
coreTools: settings.tools?.core || undefined,
|
||||
allowedTools: allowedTools.length > 0 ? allowedTools : undefined,
|
||||
allowedTools: argv.allowedTools || settings.tools?.allowed || undefined,
|
||||
policyEngineConfig,
|
||||
excludeTools,
|
||||
toolDiscoveryCommand: settings.tools?.discoveryCommand,
|
||||
@@ -700,7 +657,6 @@ export async function loadCliConfig(
|
||||
mcpServers,
|
||||
userMemory: memoryContent,
|
||||
geminiMdFileCount: fileCount,
|
||||
geminiMdFilePaths: filePaths,
|
||||
approvalMode,
|
||||
showMemoryUsage:
|
||||
argv.showMemoryUsage || settings.ui?.showMemoryUsage || false,
|
||||
@@ -737,8 +693,7 @@ export async function loadCliConfig(
|
||||
interactive,
|
||||
trustedFolder,
|
||||
useRipgrep: settings.tools?.useRipgrep,
|
||||
enableInteractiveShell:
|
||||
settings.tools?.shell?.enableInteractiveShell ?? true,
|
||||
shouldUseNodePtyShell: settings.tools?.shell?.enableInteractiveShell,
|
||||
skipNextSpeakerCheck: settings.model?.skipNextSpeakerCheck,
|
||||
enablePromptCompletion: settings.general?.enablePromptCompletion ?? false,
|
||||
truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
|
||||
@@ -753,7 +708,6 @@ export async function loadCliConfig(
|
||||
useModelRouter,
|
||||
enableMessageBusIntegration:
|
||||
settings.tools?.enableMessageBusIntegration ?? false,
|
||||
enableSubagents: settings.experimental?.enableSubagents ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -869,8 +869,7 @@ describe('extension tests', () => {
|
||||
expect(mockLogExtensionInstallEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10739
|
||||
it.skip('should show users information on their mcp server when installing', async () => {
|
||||
it('should show users information on their mcp server when installing', async () => {
|
||||
const consoleInfoSpy = vi.spyOn(console, 'info');
|
||||
const sourceExtDir = createExtension({
|
||||
extensionsDir: tempHomeDir,
|
||||
|
||||
@@ -138,7 +138,11 @@ describe('git extension helpers', () => {
|
||||
source: '',
|
||||
},
|
||||
};
|
||||
const result = await checkForExtensionUpdate(extension);
|
||||
let result: ExtensionUpdateState | undefined = undefined;
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(newState) => (result = newState),
|
||||
);
|
||||
expect(result).toBe(ExtensionUpdateState.NOT_UPDATABLE);
|
||||
});
|
||||
|
||||
@@ -154,7 +158,11 @@ describe('git extension helpers', () => {
|
||||
},
|
||||
};
|
||||
mockGit.getRemotes.mockResolvedValue([]);
|
||||
const result = await checkForExtensionUpdate(extension);
|
||||
let result: ExtensionUpdateState | undefined = undefined;
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(newState) => (result = newState),
|
||||
);
|
||||
expect(result).toBe(ExtensionUpdateState.ERROR);
|
||||
});
|
||||
|
||||
@@ -175,7 +183,11 @@ describe('git extension helpers', () => {
|
||||
mockGit.listRemote.mockResolvedValue('remote-hash\tHEAD');
|
||||
mockGit.revparse.mockResolvedValue('local-hash');
|
||||
|
||||
const result = await checkForExtensionUpdate(extension);
|
||||
let result: ExtensionUpdateState | undefined = undefined;
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(newState) => (result = newState),
|
||||
);
|
||||
expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
});
|
||||
|
||||
@@ -196,7 +208,11 @@ describe('git extension helpers', () => {
|
||||
mockGit.listRemote.mockResolvedValue('same-hash\tHEAD');
|
||||
mockGit.revparse.mockResolvedValue('same-hash');
|
||||
|
||||
const result = await checkForExtensionUpdate(extension);
|
||||
let result: ExtensionUpdateState | undefined = undefined;
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(newState) => (result = newState),
|
||||
);
|
||||
expect(result).toBe(ExtensionUpdateState.UP_TO_DATE);
|
||||
});
|
||||
|
||||
@@ -213,7 +229,11 @@ describe('git extension helpers', () => {
|
||||
};
|
||||
mockGit.getRemotes.mockRejectedValue(new Error('git error'));
|
||||
|
||||
const result = await checkForExtensionUpdate(extension);
|
||||
let result: ExtensionUpdateState | undefined = undefined;
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(newState) => (result = newState),
|
||||
);
|
||||
expect(result).toBe(ExtensionUpdateState.ERROR);
|
||||
});
|
||||
});
|
||||
@@ -278,20 +298,13 @@ describe('git extension helpers', () => {
|
||||
expect(repo).toBe('repo');
|
||||
});
|
||||
|
||||
it('should parse owner and repo from a full GitHub URL without .git', () => {
|
||||
it('should parse owner and repo from a full GitHub UR without .git', () => {
|
||||
const source = 'https://github.com/owner/repo';
|
||||
const { owner, repo } = parseGitHubRepoForReleases(source);
|
||||
expect(owner).toBe('owner');
|
||||
expect(repo).toBe('repo');
|
||||
});
|
||||
|
||||
it('should parse owner and repo from a full GitHub URL with a trailing slash', () => {
|
||||
const source = 'https://github.com/owner/repo/';
|
||||
const { owner, repo } = parseGitHubRepoForReleases(source);
|
||||
expect(owner).toBe('owner');
|
||||
expect(repo).toBe('repo');
|
||||
});
|
||||
|
||||
it('should fail on a GitHub SSH URL', () => {
|
||||
const source = 'git@github.com:owner/repo.git';
|
||||
expect(() => parseGitHubRepoForReleases(source)).toThrow(
|
||||
|
||||
@@ -86,11 +86,7 @@ export function parseGitHubRepoForReleases(source: string): {
|
||||
// Default to a github repo path, so `source` can be just an org/repo
|
||||
const parsedUrl = URL.parse(source, 'https://github.com');
|
||||
// The pathname should be "/owner/repo".
|
||||
const parts = parsedUrl?.pathname
|
||||
.substring(1)
|
||||
.split('/')
|
||||
// Remove the empty segments, fixes trailing slashes
|
||||
.filter((part) => part !== '');
|
||||
const parts = parsedUrl?.pathname.substring(1).split('/');
|
||||
if (parts?.length !== 2 || parsedUrl?.host !== 'github.com') {
|
||||
throw new Error(
|
||||
`Invalid GitHub repository source: ${source}. Expected "owner/repo" or a github repo uri.`,
|
||||
@@ -120,8 +116,10 @@ async function fetchReleaseFromGithub(
|
||||
|
||||
export async function checkForExtensionUpdate(
|
||||
extension: GeminiCLIExtension,
|
||||
setExtensionUpdateState: (updateState: ExtensionUpdateState) => void,
|
||||
cwd: string = process.cwd(),
|
||||
): Promise<ExtensionUpdateState> {
|
||||
): Promise<void> {
|
||||
setExtensionUpdateState(ExtensionUpdateState.CHECKING_FOR_UPDATES);
|
||||
const installMetadata = extension.installMetadata;
|
||||
if (installMetadata?.type === 'local') {
|
||||
const newExtension = loadExtension({
|
||||
@@ -132,19 +130,23 @@ export async function checkForExtensionUpdate(
|
||||
console.error(
|
||||
`Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}`,
|
||||
);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
if (newExtension.config.version !== extension.version) {
|
||||
return ExtensionUpdateState.UPDATE_AVAILABLE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
return;
|
||||
}
|
||||
return ExtensionUpdateState.UP_TO_DATE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!installMetadata ||
|
||||
(installMetadata.type !== 'git' &&
|
||||
installMetadata.type !== 'github-release')
|
||||
) {
|
||||
return ExtensionUpdateState.NOT_UPDATABLE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.NOT_UPDATABLE);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (installMetadata.type === 'git') {
|
||||
@@ -152,12 +154,14 @@ export async function checkForExtensionUpdate(
|
||||
const remotes = await git.getRemotes(true);
|
||||
if (remotes.length === 0) {
|
||||
console.error('No git remotes found.');
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
const remoteUrl = remotes[0].refs.fetch;
|
||||
if (!remoteUrl) {
|
||||
console.error(`No fetch URL found for git remote ${remotes[0].name}.`);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine the ref to check on the remote.
|
||||
@@ -167,7 +171,8 @@ export async function checkForExtensionUpdate(
|
||||
|
||||
if (typeof lsRemoteOutput !== 'string' || lsRemoteOutput.trim() === '') {
|
||||
console.error(`Git ref ${refToCheck} not found.`);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
|
||||
const remoteHash = lsRemoteOutput.split('\t')[0];
|
||||
@@ -177,17 +182,21 @@ export async function checkForExtensionUpdate(
|
||||
console.error(
|
||||
`Unable to parse hash from git ls-remote output "${lsRemoteOutput}"`,
|
||||
);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
if (remoteHash === localHash) {
|
||||
return ExtensionUpdateState.UP_TO_DATE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE);
|
||||
return;
|
||||
}
|
||||
return ExtensionUpdateState.UPDATE_AVAILABLE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
return;
|
||||
} else {
|
||||
const { source, releaseTag } = installMetadata;
|
||||
if (!source) {
|
||||
console.error(`No "source" provided for extension.`);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
const { owner, repo } = parseGitHubRepoForReleases(source);
|
||||
|
||||
@@ -197,15 +206,18 @@ export async function checkForExtensionUpdate(
|
||||
installMetadata.ref,
|
||||
);
|
||||
if (releaseData.tag_name !== releaseTag) {
|
||||
return ExtensionUpdateState.UPDATE_AVAILABLE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
return;
|
||||
}
|
||||
return ExtensionUpdateState.UP_TO_DATE;
|
||||
setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Failed to check for updates for extension "${installMetadata.source}": ${getErrorMessage(error)}`,
|
||||
);
|
||||
return ExtensionUpdateState.ERROR;
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
export interface GitHubDownloadResult {
|
||||
|
||||
@@ -185,7 +185,8 @@ describe('update tests', () => {
|
||||
});
|
||||
mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]);
|
||||
|
||||
const dispatch = vi.fn();
|
||||
const setExtensionUpdateState = vi.fn();
|
||||
|
||||
const extension = annotateActiveExtensions(
|
||||
[
|
||||
loadExtension({
|
||||
@@ -201,23 +202,15 @@ describe('update tests', () => {
|
||||
tempHomeDir,
|
||||
async (_) => true,
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
dispatch,
|
||||
setExtensionUpdateState,
|
||||
);
|
||||
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extensionName,
|
||||
state: ExtensionUpdateState.UPDATING,
|
||||
},
|
||||
});
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extensionName,
|
||||
state: ExtensionUpdateState.UPDATED_NEEDS_RESTART,
|
||||
},
|
||||
});
|
||||
expect(setExtensionUpdateState).toHaveBeenCalledWith(
|
||||
ExtensionUpdateState.UPDATING,
|
||||
);
|
||||
expect(setExtensionUpdateState).toHaveBeenCalledWith(
|
||||
ExtensionUpdateState.UPDATED_NEEDS_RESTART,
|
||||
);
|
||||
});
|
||||
|
||||
it('should call setExtensionUpdateState with ERROR on failure', async () => {
|
||||
@@ -235,7 +228,7 @@ describe('update tests', () => {
|
||||
mockGit.clone.mockRejectedValue(new Error('Git clone failed'));
|
||||
mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]);
|
||||
|
||||
const dispatch = vi.fn();
|
||||
const setExtensionUpdateState = vi.fn();
|
||||
const extension = annotateActiveExtensions(
|
||||
[
|
||||
loadExtension({
|
||||
@@ -252,24 +245,16 @@ describe('update tests', () => {
|
||||
tempHomeDir,
|
||||
async (_) => true,
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
dispatch,
|
||||
setExtensionUpdateState,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extensionName,
|
||||
state: ExtensionUpdateState.UPDATING,
|
||||
},
|
||||
});
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extensionName,
|
||||
state: ExtensionUpdateState.ERROR,
|
||||
},
|
||||
});
|
||||
expect(setExtensionUpdateState).toHaveBeenCalledWith(
|
||||
ExtensionUpdateState.UPDATING,
|
||||
);
|
||||
expect(setExtensionUpdateState).toHaveBeenCalledWith(
|
||||
ExtensionUpdateState.ERROR,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -301,19 +286,20 @@ describe('update tests', () => {
|
||||
mockGit.listRemote.mockResolvedValue('remoteHash HEAD');
|
||||
mockGit.revparse.mockResolvedValue('localHash');
|
||||
|
||||
const dispatch = vi.fn();
|
||||
await checkForAllExtensionUpdates(
|
||||
let extensionState = new Map();
|
||||
const results = await checkForAllExtensionUpdates(
|
||||
[extension],
|
||||
dispatch,
|
||||
tempWorkspaceDir,
|
||||
);
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: 'test-extension',
|
||||
state: ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
extensionState,
|
||||
(newState) => {
|
||||
if (typeof newState === 'function') {
|
||||
newState(extensionState);
|
||||
} else {
|
||||
extensionState = newState;
|
||||
}
|
||||
},
|
||||
});
|
||||
);
|
||||
const result = results.get('test-extension');
|
||||
expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
});
|
||||
|
||||
it('should return UpToDate for a git extension with no updates', async () => {
|
||||
@@ -343,19 +329,20 @@ describe('update tests', () => {
|
||||
mockGit.listRemote.mockResolvedValue('sameHash HEAD');
|
||||
mockGit.revparse.mockResolvedValue('sameHash');
|
||||
|
||||
const dispatch = vi.fn();
|
||||
await checkForAllExtensionUpdates(
|
||||
let extensionState = new Map();
|
||||
const results = await checkForAllExtensionUpdates(
|
||||
[extension],
|
||||
dispatch,
|
||||
tempWorkspaceDir,
|
||||
);
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: 'test-extension',
|
||||
state: ExtensionUpdateState.UP_TO_DATE,
|
||||
extensionState,
|
||||
(newState) => {
|
||||
if (typeof newState === 'function') {
|
||||
newState(extensionState);
|
||||
} else {
|
||||
extensionState = newState;
|
||||
}
|
||||
},
|
||||
});
|
||||
);
|
||||
const result = results.get('test-extension');
|
||||
expect(result).toBe(ExtensionUpdateState.UP_TO_DATE);
|
||||
});
|
||||
|
||||
it('should return UpToDate for a local extension with no updates', async () => {
|
||||
@@ -382,19 +369,21 @@ describe('update tests', () => {
|
||||
process.cwd(),
|
||||
new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()),
|
||||
)[0];
|
||||
const dispatch = vi.fn();
|
||||
await checkForAllExtensionUpdates(
|
||||
let extensionState = new Map();
|
||||
const results = await checkForAllExtensionUpdates(
|
||||
[extension],
|
||||
dispatch,
|
||||
extensionState,
|
||||
(newState) => {
|
||||
if (typeof newState === 'function') {
|
||||
newState(extensionState);
|
||||
} else {
|
||||
extensionState = newState;
|
||||
}
|
||||
},
|
||||
tempWorkspaceDir,
|
||||
);
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: 'local-extension',
|
||||
state: ExtensionUpdateState.UP_TO_DATE,
|
||||
},
|
||||
});
|
||||
const result = results.get('local-extension');
|
||||
expect(result).toBe(ExtensionUpdateState.UP_TO_DATE);
|
||||
});
|
||||
|
||||
it('should return UpdateAvailable for a local extension with updates', async () => {
|
||||
@@ -421,19 +410,21 @@ describe('update tests', () => {
|
||||
process.cwd(),
|
||||
new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()),
|
||||
)[0];
|
||||
const dispatch = vi.fn();
|
||||
await checkForAllExtensionUpdates(
|
||||
let extensionState = new Map();
|
||||
const results = await checkForAllExtensionUpdates(
|
||||
[extension],
|
||||
dispatch,
|
||||
extensionState,
|
||||
(newState) => {
|
||||
if (typeof newState === 'function') {
|
||||
newState(extensionState);
|
||||
} else {
|
||||
extensionState = newState;
|
||||
}
|
||||
},
|
||||
tempWorkspaceDir,
|
||||
);
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: 'local-extension',
|
||||
state: ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
},
|
||||
});
|
||||
const result = results.get('local-extension');
|
||||
expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE);
|
||||
});
|
||||
|
||||
it('should return Error when git check fails', async () => {
|
||||
@@ -459,19 +450,20 @@ describe('update tests', () => {
|
||||
|
||||
mockGit.getRemotes.mockRejectedValue(new Error('Git error'));
|
||||
|
||||
const dispatch = vi.fn();
|
||||
await checkForAllExtensionUpdates(
|
||||
let extensionState = new Map();
|
||||
const results = await checkForAllExtensionUpdates(
|
||||
[extension],
|
||||
dispatch,
|
||||
tempWorkspaceDir,
|
||||
);
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: 'error-extension',
|
||||
state: ExtensionUpdateState.ERROR,
|
||||
extensionState,
|
||||
(newState) => {
|
||||
if (typeof newState === 'function') {
|
||||
newState(extensionState);
|
||||
} else {
|
||||
extensionState = newState;
|
||||
}
|
||||
},
|
||||
});
|
||||
);
|
||||
const result = results.get('error-extension');
|
||||
expect(result).toBe(ExtensionUpdateState.ERROR);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import {
|
||||
type ExtensionUpdateAction,
|
||||
ExtensionUpdateState,
|
||||
type ExtensionUpdateStatus,
|
||||
} from '../../ui/state/extensions.js';
|
||||
import type { GeminiCLIExtension } from '@google/gemini-cli-core';
|
||||
import * as fs from 'node:fs';
|
||||
import { getErrorMessage } from '../../utils/errors.js';
|
||||
import { ExtensionUpdateState } from '../../ui/state/extensions.js';
|
||||
import { type Dispatch, type SetStateAction } from 'react';
|
||||
import {
|
||||
copyExtension,
|
||||
installExtension,
|
||||
@@ -19,9 +19,6 @@ import {
|
||||
loadExtensionConfig,
|
||||
} from '../extension.js';
|
||||
import { checkForExtensionUpdate } from './github.js';
|
||||
import type { GeminiCLIExtension } from '@google/gemini-cli-core';
|
||||
import * as fs from 'node:fs';
|
||||
import { getErrorMessage } from '../../utils/errors.js';
|
||||
|
||||
export interface ExtensionUpdateInfo {
|
||||
name: string;
|
||||
@@ -34,31 +31,22 @@ export async function updateExtension(
|
||||
cwd: string = process.cwd(),
|
||||
requestConsent: (consent: string) => Promise<boolean>,
|
||||
currentState: ExtensionUpdateState,
|
||||
dispatchExtensionStateUpdate: (action: ExtensionUpdateAction) => void,
|
||||
setExtensionUpdateState: (updateState: ExtensionUpdateState) => void,
|
||||
): Promise<ExtensionUpdateInfo | undefined> {
|
||||
if (currentState === ExtensionUpdateState.UPDATING) {
|
||||
return undefined;
|
||||
}
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state: ExtensionUpdateState.UPDATING },
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.UPDATING);
|
||||
const installMetadata = loadInstallMetadata(extension.path);
|
||||
|
||||
if (!installMetadata?.type) {
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state: ExtensionUpdateState.ERROR },
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
throw new Error(
|
||||
`Extension ${extension.name} cannot be updated, type is unknown.`,
|
||||
);
|
||||
}
|
||||
if (installMetadata?.type === 'link') {
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state: ExtensionUpdateState.UP_TO_DATE },
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE);
|
||||
throw new Error(`Extension is linked so does not need to be updated`);
|
||||
}
|
||||
const originalVersion = extension.version;
|
||||
@@ -84,20 +72,11 @@ export async function updateExtension(
|
||||
workspaceDir: cwd,
|
||||
});
|
||||
if (!updatedExtension) {
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state: ExtensionUpdateState.ERROR },
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
throw new Error('Updated extension not found after installation.');
|
||||
}
|
||||
const updatedVersion = updatedExtension.config.version;
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extension.name,
|
||||
state: ExtensionUpdateState.UPDATED_NEEDS_RESTART,
|
||||
},
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.UPDATED_NEEDS_RESTART);
|
||||
return {
|
||||
name: extension.name,
|
||||
originalVersion,
|
||||
@@ -107,10 +86,7 @@ export async function updateExtension(
|
||||
console.error(
|
||||
`Error updating extension, rolling back. ${getErrorMessage(e)}`,
|
||||
);
|
||||
dispatchExtensionStateUpdate({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state: ExtensionUpdateState.ERROR },
|
||||
});
|
||||
setExtensionUpdateState(ExtensionUpdateState.ERROR);
|
||||
await copyExtension(tempDir, extension.path);
|
||||
throw e;
|
||||
} finally {
|
||||
@@ -122,15 +98,17 @@ export async function updateAllUpdatableExtensions(
|
||||
cwd: string = process.cwd(),
|
||||
requestConsent: (consent: string) => Promise<boolean>,
|
||||
extensions: GeminiCLIExtension[],
|
||||
extensionsState: Map<string, ExtensionUpdateStatus>,
|
||||
dispatch: (action: ExtensionUpdateAction) => void,
|
||||
extensionsState: Map<string, ExtensionUpdateState>,
|
||||
setExtensionsUpdateState: Dispatch<
|
||||
SetStateAction<Map<string, ExtensionUpdateState>>
|
||||
>,
|
||||
): Promise<ExtensionUpdateInfo[]> {
|
||||
return (
|
||||
await Promise.all(
|
||||
extensions
|
||||
.filter(
|
||||
(extension) =>
|
||||
extensionsState.get(extension.name)?.status ===
|
||||
extensionsState.get(extension.name) ===
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
)
|
||||
.map((extension) =>
|
||||
@@ -138,8 +116,14 @@ export async function updateAllUpdatableExtensions(
|
||||
extension,
|
||||
cwd,
|
||||
requestConsent,
|
||||
extensionsState.get(extension.name)!.status,
|
||||
dispatch,
|
||||
extensionsState.get(extension.name)!,
|
||||
(updateState) => {
|
||||
setExtensionsUpdateState((prev) => {
|
||||
const finalState = new Map(prev);
|
||||
finalState.set(extension.name, updateState);
|
||||
return finalState;
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -153,38 +137,38 @@ export interface ExtensionUpdateCheckResult {
|
||||
|
||||
export async function checkForAllExtensionUpdates(
|
||||
extensions: GeminiCLIExtension[],
|
||||
dispatch: (action: ExtensionUpdateAction) => void,
|
||||
extensionsUpdateState: Map<string, ExtensionUpdateState>,
|
||||
setExtensionsUpdateState: Dispatch<
|
||||
SetStateAction<Map<string, ExtensionUpdateState>>
|
||||
>,
|
||||
cwd: string = process.cwd(),
|
||||
): Promise<void> {
|
||||
dispatch({ type: 'BATCH_CHECK_START' });
|
||||
const promises: Array<Promise<void>> = [];
|
||||
): Promise<Map<string, ExtensionUpdateState>> {
|
||||
let newStates: Map<string, ExtensionUpdateState> = new Map(
|
||||
extensionsUpdateState,
|
||||
);
|
||||
for (const extension of extensions) {
|
||||
if (!extension.installMetadata) {
|
||||
dispatch({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extension.name,
|
||||
state: ExtensionUpdateState.NOT_UPDATABLE,
|
||||
const initialState = extensionsUpdateState.get(extension.name);
|
||||
if (initialState === undefined) {
|
||||
if (!extension.installMetadata) {
|
||||
setExtensionsUpdateState((prev) => {
|
||||
newStates = new Map(prev);
|
||||
newStates.set(extension.name, ExtensionUpdateState.NOT_UPDATABLE);
|
||||
return newStates;
|
||||
});
|
||||
continue;
|
||||
}
|
||||
await checkForExtensionUpdate(
|
||||
extension,
|
||||
(updatedState) => {
|
||||
setExtensionsUpdateState((prev) => {
|
||||
newStates = new Map(prev);
|
||||
newStates.set(extension.name, updatedState);
|
||||
return newStates;
|
||||
});
|
||||
},
|
||||
});
|
||||
continue;
|
||||
cwd,
|
||||
);
|
||||
}
|
||||
dispatch({
|
||||
type: 'SET_STATE',
|
||||
payload: {
|
||||
name: extension.name,
|
||||
state: ExtensionUpdateState.CHECKING_FOR_UPDATES,
|
||||
},
|
||||
});
|
||||
promises.push(
|
||||
checkForExtensionUpdate(extension, cwd).then((state) =>
|
||||
dispatch({
|
||||
type: 'SET_STATE',
|
||||
payload: { name: extension.name, state },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
await Promise.all(promises);
|
||||
dispatch({ type: 'BATCH_CHECK_END' });
|
||||
return newStates;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ export const defaultKeyBindings: KeyBindingConfig = {
|
||||
[Command.CLEAR_SCREEN]: [{ key: 'l', ctrl: true }],
|
||||
|
||||
// History navigation
|
||||
[Command.HISTORY_UP]: [{ key: 'p', ctrl: true, shift: false }],
|
||||
[Command.HISTORY_UP]: [{ key: 'p', ctrl: true }],
|
||||
[Command.HISTORY_DOWN]: [{ key: 'n', ctrl: true }],
|
||||
[Command.NAVIGATION_UP]: [{ key: 'up' }],
|
||||
[Command.NAVIGATION_DOWN]: [{ key: 'down' }],
|
||||
|
||||
@@ -110,7 +110,7 @@ const MIGRATION_MAP: Record<string, string> = {
|
||||
preferredEditor: 'general.preferredEditor',
|
||||
sandbox: 'tools.sandbox',
|
||||
selectedAuthType: 'security.auth.selectedType',
|
||||
enableInteractiveShell: 'tools.shell.enableInteractiveShell',
|
||||
shouldUseNodePtyShell: 'tools.shell.enableInteractiveShell',
|
||||
shellPager: 'tools.shell.pager',
|
||||
shellShowColor: 'tools.shell.showColor',
|
||||
skipNextSpeakerCheck: 'model.skipNextSpeakerCheck',
|
||||
@@ -170,20 +170,6 @@ export interface AccessibilitySettings {
|
||||
screenReader?: boolean;
|
||||
}
|
||||
|
||||
export interface SessionRetentionSettings {
|
||||
/** Enable automatic session cleanup */
|
||||
enabled?: boolean;
|
||||
|
||||
/** Maximum age of sessions to keep (e.g., "30d", "7d", "24h", "1w") */
|
||||
maxAge?: string;
|
||||
|
||||
/** Alternative: Maximum number of sessions to keep (most recent) */
|
||||
maxCount?: number;
|
||||
|
||||
/** Minimum retention period (safety limit, defaults to "1d") */
|
||||
minRetention?: string;
|
||||
}
|
||||
|
||||
export interface SettingsError {
|
||||
message: string;
|
||||
path: string;
|
||||
|
||||
@@ -330,24 +330,5 @@ describe('SettingsSchema', () => {
|
||||
getSettingsSchema().experimental.properties.useModelRouter.default,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should have enableSubagents setting in schema', () => {
|
||||
expect(
|
||||
getSettingsSchema().experimental.properties.enableSubagents,
|
||||
).toBeDefined();
|
||||
expect(
|
||||
getSettingsSchema().experimental.properties.enableSubagents.type,
|
||||
).toBe('boolean');
|
||||
expect(
|
||||
getSettingsSchema().experimental.properties.enableSubagents.category,
|
||||
).toBe('Experimental');
|
||||
expect(
|
||||
getSettingsSchema().experimental.properties.enableSubagents.default,
|
||||
).toBe(false);
|
||||
expect(
|
||||
getSettingsSchema().experimental.properties.enableSubagents
|
||||
.requiresRestart,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,8 +16,6 @@ import {
|
||||
DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
|
||||
} from '@google/gemini-cli-core';
|
||||
import type { CustomTheme } from '../ui/themes/theme.js';
|
||||
import type { SessionRetentionSettings } from './settings.js';
|
||||
import { DEFAULT_MIN_RETENTION } from '../utils/sessionCleanup.js';
|
||||
|
||||
export type SettingsType =
|
||||
| 'boolean'
|
||||
@@ -187,54 +185,6 @@ const SETTINGS_SCHEMA = {
|
||||
description: 'Enable debug logging of keystrokes to the console.',
|
||||
showInDialog: true,
|
||||
},
|
||||
sessionRetention: {
|
||||
type: 'object',
|
||||
label: 'Session Retention',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as SessionRetentionSettings | undefined,
|
||||
properties: {
|
||||
enabled: {
|
||||
type: 'boolean',
|
||||
label: 'Enable Session Cleanup',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Enable automatic session cleanup',
|
||||
showInDialog: true,
|
||||
},
|
||||
maxAge: {
|
||||
type: 'string',
|
||||
label: 'Max Session Age',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | undefined,
|
||||
description:
|
||||
'Maximum age of sessions to keep (e.g., "30d", "7d", "24h", "1w")',
|
||||
showInDialog: false,
|
||||
},
|
||||
maxCount: {
|
||||
type: 'number',
|
||||
label: 'Max Session Count',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as number | undefined,
|
||||
description:
|
||||
'Alternative: Maximum number of sessions to keep (most recent)',
|
||||
showInDialog: false,
|
||||
},
|
||||
minRetention: {
|
||||
type: 'string',
|
||||
label: 'Min Retention Period',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: DEFAULT_MIN_RETENTION,
|
||||
description: `Minimum retention period (safety limit, defaults to "${DEFAULT_MIN_RETENTION}")`,
|
||||
showInDialog: false,
|
||||
},
|
||||
},
|
||||
description: 'Settings for automatic session cleanup.',
|
||||
},
|
||||
},
|
||||
},
|
||||
output: {
|
||||
@@ -443,7 +393,7 @@ const SETTINGS_SCHEMA = {
|
||||
label: 'Screen Reader Mode',
|
||||
category: 'UI',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
default: undefined as boolean | undefined,
|
||||
description:
|
||||
'Render output in plain-text to be more screen reader accessible',
|
||||
showInDialog: true,
|
||||
@@ -713,7 +663,7 @@ const SETTINGS_SCHEMA = {
|
||||
label: 'Enable Interactive Shell',
|
||||
category: 'Tools',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
default: false,
|
||||
description:
|
||||
'Use node-pty for an interactive shell experience. Fallback to child_process still applies.',
|
||||
showInDialog: true,
|
||||
@@ -1051,15 +1001,6 @@ const SETTINGS_SCHEMA = {
|
||||
'Enable model routing to route requests to the best model based on complexity.',
|
||||
showInDialog: true,
|
||||
},
|
||||
enableSubagents: {
|
||||
type: 'boolean',
|
||||
label: 'Enable Subagents',
|
||||
category: 'Experimental',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Enable experimental subagents.',
|
||||
showInDialog: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -46,8 +46,6 @@ import {
|
||||
} from './core/initializer.js';
|
||||
import { validateAuthMethod } from './config/auth.js';
|
||||
import { setMaxSizedBoxDebugging } from './ui/components/shared/MaxSizedBox.js';
|
||||
import { runZedIntegration } from './zed-integration/zedIntegration.js';
|
||||
import { cleanupExpiredSessions } from './utils/sessionCleanup.js';
|
||||
import { validateNonInteractiveAuth } from './validateNonInterActiveAuth.js';
|
||||
import { detectAndEnableKittyProtocol } from './ui/utils/kittyProtocolDetector.js';
|
||||
import { checkForUpdates } from './ui/utils/updateCheck.js';
|
||||
@@ -64,8 +62,6 @@ import {
|
||||
relaunchAppInChildProcess,
|
||||
relaunchOnExitCode,
|
||||
} from './utils/relaunch.js';
|
||||
import { loadSandboxConfig } from './config/sandboxConfig.js';
|
||||
import { ExtensionEnablementManager } from './config/extensions/extensionEnablement.js';
|
||||
|
||||
export function validateDnsResolutionOrder(
|
||||
order: string | undefined,
|
||||
@@ -115,6 +111,10 @@ function getNodeMemoryArgs(isDebugMode: boolean): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
import { runZedIntegration } from './zed-integration/zedIntegration.js';
|
||||
import { loadSandboxConfig } from './config/sandboxConfig.js';
|
||||
import { ExtensionEnablementManager } from './config/extensions/extensionEnablement.js';
|
||||
|
||||
export function setupUnhandledRejectionHandler() {
|
||||
let unhandledRejectionOccurred = false;
|
||||
process.on('unhandledRejection', (reason, _promise) => {
|
||||
@@ -351,9 +351,6 @@ export async function main() {
|
||||
argv,
|
||||
);
|
||||
|
||||
// Cleanup sessions after config initialization
|
||||
await cleanupExpiredSessions(config, settings.merged);
|
||||
|
||||
if (config.getListExtensions()) {
|
||||
console.log('Installed extensions:');
|
||||
for (const extension of extensions) {
|
||||
|
||||
@@ -873,57 +873,4 @@ describe('runNonInteractive', () => {
|
||||
|
||||
expect(processStdoutSpy).toHaveBeenCalledWith('Acknowledged');
|
||||
});
|
||||
|
||||
it('should allow a normally-excluded tool when --allowed-tools is set', async () => {
|
||||
// By default, ShellTool is excluded in non-interactive mode.
|
||||
// This test ensures that --allowed-tools overrides this exclusion.
|
||||
vi.mocked(mockConfig.getToolRegistry).mockReturnValue({
|
||||
getTool: vi.fn().mockReturnValue({
|
||||
name: 'ShellTool',
|
||||
description: 'A shell tool',
|
||||
run: vi.fn(),
|
||||
}),
|
||||
getFunctionDeclarations: vi.fn().mockReturnValue([{ name: 'ShellTool' }]),
|
||||
} as unknown as ToolRegistry);
|
||||
|
||||
const toolCallEvent: ServerGeminiStreamEvent = {
|
||||
type: GeminiEventType.ToolCallRequest,
|
||||
value: {
|
||||
callId: 'tool-shell-1',
|
||||
name: 'ShellTool',
|
||||
args: { command: 'ls' },
|
||||
isClientInitiated: false,
|
||||
prompt_id: 'prompt-id-allowed',
|
||||
},
|
||||
};
|
||||
const toolResponse: Part[] = [{ text: 'file.txt' }];
|
||||
mockCoreExecuteToolCall.mockResolvedValue({ responseParts: toolResponse });
|
||||
|
||||
const firstCallEvents: ServerGeminiStreamEvent[] = [toolCallEvent];
|
||||
const secondCallEvents: ServerGeminiStreamEvent[] = [
|
||||
{ type: GeminiEventType.Content, value: 'file.txt' },
|
||||
{
|
||||
type: GeminiEventType.Finished,
|
||||
value: { reason: undefined, usageMetadata: { totalTokenCount: 10 } },
|
||||
},
|
||||
];
|
||||
|
||||
mockGeminiClient.sendMessageStream
|
||||
.mockReturnValueOnce(createStreamFromEvents(firstCallEvents))
|
||||
.mockReturnValueOnce(createStreamFromEvents(secondCallEvents));
|
||||
|
||||
await runNonInteractive(
|
||||
mockConfig,
|
||||
mockSettings,
|
||||
'List the files',
|
||||
'prompt-id-allowed',
|
||||
);
|
||||
|
||||
expect(mockCoreExecuteToolCall).toHaveBeenCalledWith(
|
||||
mockConfig,
|
||||
expect.objectContaining({ name: 'ShellTool' }),
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(processStdoutSpy).toHaveBeenCalledWith('file.txt');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,17 +4,6 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
vi.mock('../ui/commands/profileCommand.js', async () => {
|
||||
const { CommandKind } = await import('../ui/commands/types.js');
|
||||
return {
|
||||
profileCommand: {
|
||||
name: 'profile',
|
||||
description: 'Profile command',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../ui/commands/aboutCommand.js', async () => {
|
||||
const { CommandKind } = await import('../ui/commands/types.js');
|
||||
return {
|
||||
@@ -188,34 +177,3 @@ describe('BuiltinCommandLoader', () => {
|
||||
expect(modelCmd).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('BuiltinCommandLoader profile', () => {
|
||||
let mockConfig: Config;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
mockConfig = {
|
||||
getFolderTrust: vi.fn().mockReturnValue(false),
|
||||
getUseModelRouter: () => false,
|
||||
getCheckpointingEnabled: () => false,
|
||||
} as unknown as Config;
|
||||
});
|
||||
|
||||
it('should not include profile command when isDevelopment is false', async () => {
|
||||
process.env['NODE_ENV'] = 'production';
|
||||
const { BuiltinCommandLoader } = await import('./BuiltinCommandLoader.js');
|
||||
const loader = new BuiltinCommandLoader(mockConfig);
|
||||
const commands = await loader.loadCommands(new AbortController().signal);
|
||||
const profileCmd = commands.find((c) => c.name === 'profile');
|
||||
expect(profileCmd).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include profile command when isDevelopment is true', async () => {
|
||||
process.env['NODE_ENV'] = 'development';
|
||||
const { BuiltinCommandLoader } = await import('./BuiltinCommandLoader.js');
|
||||
const loader = new BuiltinCommandLoader(mockConfig);
|
||||
const commands = await loader.loadCommands(new AbortController().signal);
|
||||
const profileCmd = commands.find((c) => c.name === 'profile');
|
||||
expect(profileCmd).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { isDevelopment } from '../utils/installationInfo.js';
|
||||
import type { ICommandLoader } from './types.js';
|
||||
import type { SlashCommand } from '../ui/commands/types.js';
|
||||
import type { Config } from '@google/gemini-cli-core';
|
||||
@@ -28,7 +27,6 @@ import { memoryCommand } from '../ui/commands/memoryCommand.js';
|
||||
import { modelCommand } from '../ui/commands/modelCommand.js';
|
||||
import { permissionsCommand } from '../ui/commands/permissionsCommand.js';
|
||||
import { privacyCommand } from '../ui/commands/privacyCommand.js';
|
||||
import { profileCommand } from '../ui/commands/profileCommand.js';
|
||||
import { quitCommand } from '../ui/commands/quitCommand.js';
|
||||
import { restoreCommand } from '../ui/commands/restoreCommand.js';
|
||||
import { statsCommand } from '../ui/commands/statsCommand.js';
|
||||
@@ -75,7 +73,6 @@ export class BuiltinCommandLoader implements ICommandLoader {
|
||||
...(this.config?.getUseModelRouter() ? [modelCommand] : []),
|
||||
...(this.config?.getFolderTrust() ? [permissionsCommand] : []),
|
||||
privacyCommand,
|
||||
...(isDevelopment ? [profileCommand] : []),
|
||||
quitCommand,
|
||||
restoreCommand(this.config),
|
||||
statsCommand,
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('ShellProcessor', () => {
|
||||
mockConfig = {
|
||||
getTargetDir: vi.fn().mockReturnValue('/test/dir'),
|
||||
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
|
||||
getEnableInteractiveShell: vi.fn().mockReturnValue(false),
|
||||
getShouldUseNodePtyShell: vi.fn().mockReturnValue(false),
|
||||
getShellExecutionConfig: vi.fn().mockReturnValue({}),
|
||||
};
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ export class ShellProcessor implements IPromptProcessor {
|
||||
config.getTargetDir(),
|
||||
() => {},
|
||||
new AbortController().signal,
|
||||
config.getEnableInteractiveShell(),
|
||||
config.getShouldUseNodePtyShell(),
|
||||
shellExecutionConfig,
|
||||
);
|
||||
|
||||
|
||||
@@ -5,15 +5,34 @@
|
||||
*/
|
||||
|
||||
import { useIsScreenReaderEnabled } from 'ink';
|
||||
import { useTerminalSize } from './hooks/useTerminalSize.js';
|
||||
import { lerp } from '../utils/math.js';
|
||||
import { useUIState } from './contexts/UIStateContext.js';
|
||||
import { StreamingContext } from './contexts/StreamingContext.js';
|
||||
import { QuittingDisplay } from './components/QuittingDisplay.js';
|
||||
import { ScreenReaderAppLayout } from './layouts/ScreenReaderAppLayout.js';
|
||||
import { DefaultAppLayout } from './layouts/DefaultAppLayout.js';
|
||||
|
||||
const getContainerWidth = (terminalWidth: number): string => {
|
||||
if (terminalWidth <= 80) {
|
||||
return '98%';
|
||||
}
|
||||
if (terminalWidth >= 132) {
|
||||
return '90%';
|
||||
}
|
||||
|
||||
// Linearly interpolate between 80 columns (98%) and 132 columns (90%).
|
||||
const t = (terminalWidth - 80) / (132 - 80);
|
||||
const percentage = lerp(98, 90, t);
|
||||
|
||||
return `${Math.round(percentage)}%`;
|
||||
};
|
||||
|
||||
export const App = () => {
|
||||
const uiState = useUIState();
|
||||
const isScreenReaderEnabled = useIsScreenReaderEnabled();
|
||||
const { columns } = useTerminalSize();
|
||||
const containerWidth = getContainerWidth(columns);
|
||||
|
||||
if (uiState.quittingMessages) {
|
||||
return <QuittingDisplay />;
|
||||
@@ -21,7 +40,11 @@ export const App = () => {
|
||||
|
||||
return (
|
||||
<StreamingContext.Provider value={uiState.streamingState}>
|
||||
{isScreenReaderEnabled ? <ScreenReaderAppLayout /> : <DefaultAppLayout />}
|
||||
{isScreenReaderEnabled ? (
|
||||
<ScreenReaderAppLayout />
|
||||
) : (
|
||||
<DefaultAppLayout width={containerWidth} />
|
||||
)}
|
||||
</StreamingContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -139,7 +139,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
);
|
||||
const [isProcessing, setIsProcessing] = useState<boolean>(false);
|
||||
const [embeddedShellFocused, setEmbeddedShellFocused] = useState(false);
|
||||
const [showDebugProfiler, setShowDebugProfiler] = useState(false);
|
||||
|
||||
const [geminiMdFileCount, setGeminiMdFileCount] = useState<number>(
|
||||
initializationResult.geminiMdFileCount,
|
||||
@@ -156,8 +155,7 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
const extensions = config.getExtensions();
|
||||
const {
|
||||
extensionsUpdateState,
|
||||
extensionsUpdateStateInternal,
|
||||
dispatchExtensionStateUpdate,
|
||||
setExtensionsUpdateState,
|
||||
confirmUpdateExtensionRequests,
|
||||
addConfirmUpdateExtensionRequest,
|
||||
} = useExtensionUpdates(
|
||||
@@ -176,11 +174,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
[],
|
||||
);
|
||||
|
||||
const toggleDebugProfiler = useCallback(
|
||||
() => setShowDebugProfiler((prev) => !prev),
|
||||
[],
|
||||
);
|
||||
|
||||
// Helper to determine the effective model, considering the fallback state.
|
||||
const getEffectiveModel = useCallback(() => {
|
||||
if (config.isInFallbackMode()) {
|
||||
@@ -466,8 +459,7 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
},
|
||||
setDebugMessage,
|
||||
toggleCorgiMode: () => setCorgiMode((prev) => !prev),
|
||||
toggleDebugProfiler,
|
||||
dispatchExtensionStateUpdate,
|
||||
setExtensionsUpdateState,
|
||||
addConfirmUpdateExtensionRequest,
|
||||
}),
|
||||
[
|
||||
@@ -480,10 +472,9 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
setDebugMessage,
|
||||
setShowPrivacyNotice,
|
||||
setCorgiMode,
|
||||
dispatchExtensionStateUpdate,
|
||||
setExtensionsUpdateState,
|
||||
openPermissionsDialog,
|
||||
addConfirmUpdateExtensionRequest,
|
||||
toggleDebugProfiler,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -505,7 +496,7 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
setIsProcessing,
|
||||
setGeminiMdFileCount,
|
||||
slashCommandActions,
|
||||
extensionsUpdateStateInternal,
|
||||
extensionsUpdateState,
|
||||
isConfigInitialized,
|
||||
);
|
||||
|
||||
@@ -518,25 +509,22 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
Date.now(),
|
||||
);
|
||||
try {
|
||||
const { memoryContent, fileCount, filePaths } =
|
||||
await loadHierarchicalGeminiMemory(
|
||||
process.cwd(),
|
||||
settings.merged.context?.loadMemoryFromIncludeDirectories
|
||||
? config.getWorkspaceContext().getDirectories()
|
||||
: [],
|
||||
config.getDebugMode(),
|
||||
config.getFileService(),
|
||||
settings.merged,
|
||||
config.getExtensionContextFilePaths(),
|
||||
config.isTrustedFolder(),
|
||||
settings.merged.context?.importFormat || 'tree', // Use setting or default to 'tree'
|
||||
config.getFileFilteringOptions(),
|
||||
);
|
||||
const { memoryContent, fileCount } = await loadHierarchicalGeminiMemory(
|
||||
process.cwd(),
|
||||
settings.merged.context?.loadMemoryFromIncludeDirectories
|
||||
? config.getWorkspaceContext().getDirectories()
|
||||
: [],
|
||||
config.getDebugMode(),
|
||||
config.getFileService(),
|
||||
settings.merged,
|
||||
config.getExtensionContextFilePaths(),
|
||||
config.isTrustedFolder(),
|
||||
settings.merged.context?.importFormat || 'tree', // Use setting or default to 'tree'
|
||||
config.getFileFilteringOptions(),
|
||||
);
|
||||
|
||||
config.setUserMemory(memoryContent);
|
||||
config.setGeminiMdFileCount(fileCount);
|
||||
config.setGeminiMdFilePaths(filePaths);
|
||||
|
||||
setGeminiMdFileCount(fileCount);
|
||||
|
||||
historyManager.addItem(
|
||||
@@ -1154,7 +1142,6 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
extensionsUpdateState,
|
||||
activePtyId,
|
||||
embeddedShellFocused,
|
||||
showDebugProfiler,
|
||||
}),
|
||||
[
|
||||
isThemeDialogOpen,
|
||||
@@ -1235,7 +1222,6 @@ Logging in with Google... Please restart Gemini CLI to continue.
|
||||
activePtyId,
|
||||
historyManager,
|
||||
embeddedShellFocused,
|
||||
showDebugProfiler,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import type React from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text } from 'ink';
|
||||
import { CliSpinner } from '../components/CliSpinner.js';
|
||||
import Spinner from 'ink-spinner';
|
||||
import { theme } from '../semantic-colors.js';
|
||||
import { useKeypress } from '../hooks/useKeypress.js';
|
||||
|
||||
@@ -53,8 +53,8 @@ export function AuthInProgress({
|
||||
) : (
|
||||
<Box>
|
||||
<Text>
|
||||
<CliSpinner type="dots" /> Waiting for auth... (Press ESC or CTRL+C
|
||||
to cancel)
|
||||
<Spinner type="dots" /> Waiting for auth... (Press ESC or CTRL+C to
|
||||
cancel)
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,11 @@
|
||||
import type { Mocked } from 'vitest';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
import type { SlashCommand, CommandContext } from './types.js';
|
||||
import type {
|
||||
MessageActionReturn,
|
||||
SlashCommand,
|
||||
type CommandContext,
|
||||
} from './types.js';
|
||||
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
|
||||
import type { Content } from '@google/genai';
|
||||
import type { GeminiClient } from '@google/gemini-cli-core';
|
||||
@@ -94,37 +98,69 @@ describe('chatCommand', () => {
|
||||
listCommand = getSubCommand('list');
|
||||
});
|
||||
|
||||
it('should add a chat_list item to the UI', async () => {
|
||||
it('should inform when no checkpoints are found', async () => {
|
||||
mockFs.readdir.mockImplementation(
|
||||
(async (_: string): Promise<string[]> =>
|
||||
[] as string[]) as unknown as typeof fsPromises.readdir,
|
||||
);
|
||||
const result = await listCommand?.action?.(mockContext, '');
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: 'No saved conversation checkpoints found.',
|
||||
});
|
||||
});
|
||||
|
||||
it('should list found checkpoints', async () => {
|
||||
const fakeFiles = ['checkpoint-test1.json', 'checkpoint-test2.json'];
|
||||
const date1 = new Date();
|
||||
const date2 = new Date(date1.getTime() + 1000);
|
||||
const date = new Date();
|
||||
|
||||
mockFs.readdir.mockImplementation(
|
||||
(async (_: string): Promise<string[]> =>
|
||||
fakeFiles as string[]) as unknown as typeof fsPromises.readdir,
|
||||
);
|
||||
mockFs.stat.mockImplementation((async (path: string): Promise<Stats> => {
|
||||
if (path.endsWith('test1.json')) {
|
||||
return { mtime: date } as Stats;
|
||||
}
|
||||
return { mtime: new Date(date.getTime() + 1000) } as Stats;
|
||||
}) as unknown as typeof fsPromises.stat);
|
||||
|
||||
const result = (await listCommand?.action?.(
|
||||
mockContext,
|
||||
'',
|
||||
)) as MessageActionReturn;
|
||||
|
||||
const content = result?.content ?? '';
|
||||
expect(result?.type).toBe('message');
|
||||
expect(content).toContain('List of saved conversations:');
|
||||
const isoDate = date
|
||||
.toISOString()
|
||||
.match(/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
|
||||
const formattedDate = isoDate ? `${isoDate[1]} ${isoDate[2]}` : '';
|
||||
expect(content).toContain(formattedDate);
|
||||
const index1 = content.indexOf('- \u001b[36mtest1\u001b[0m');
|
||||
const index2 = content.indexOf('- \u001b[36mtest2\u001b[0m');
|
||||
expect(index1).toBeGreaterThanOrEqual(0);
|
||||
expect(index2).toBeGreaterThan(index1);
|
||||
});
|
||||
|
||||
it('should handle invalid date formats gracefully', async () => {
|
||||
const fakeFiles = ['checkpoint-baddate.json'];
|
||||
const badDate = {
|
||||
toISOString: () => 'an-invalid-date-string',
|
||||
} as Date;
|
||||
|
||||
mockFs.readdir.mockResolvedValue(fakeFiles);
|
||||
mockFs.stat.mockImplementation(async (path: string): Promise<Stats> => {
|
||||
if (path.endsWith('test1.json')) {
|
||||
return { mtime: date1 } as Stats;
|
||||
}
|
||||
return { mtime: date2 } as Stats;
|
||||
});
|
||||
mockFs.stat.mockResolvedValue({ mtime: badDate } as Stats);
|
||||
|
||||
await listCommand?.action?.(mockContext, '');
|
||||
const result = (await listCommand?.action?.(
|
||||
mockContext,
|
||||
'',
|
||||
)) as MessageActionReturn;
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
type: 'chat_list',
|
||||
chats: [
|
||||
{
|
||||
name: 'test1',
|
||||
mtime: date1.toISOString(),
|
||||
},
|
||||
{
|
||||
name: 'test2',
|
||||
mtime: date2.toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
expect.any(Number),
|
||||
);
|
||||
const content = result?.content ?? '';
|
||||
expect(content).toContain('(saved on Invalid Date)');
|
||||
});
|
||||
});
|
||||
describe('save subcommand', () => {
|
||||
|
||||
@@ -17,14 +17,15 @@ import type {
|
||||
import { CommandKind } from './types.js';
|
||||
import { decodeTagName } from '@google/gemini-cli-core';
|
||||
import path from 'node:path';
|
||||
import type {
|
||||
HistoryItemWithoutId,
|
||||
HistoryItemChatList,
|
||||
ChatDetail,
|
||||
} from '../types.js';
|
||||
import type { HistoryItemWithoutId } from '../types.js';
|
||||
import { MessageType } from '../types.js';
|
||||
import type { Content } from '@google/genai';
|
||||
|
||||
interface ChatDetail {
|
||||
name: string;
|
||||
mtime: Date;
|
||||
}
|
||||
|
||||
const getSavedChatTags = async (
|
||||
context: CommandContext,
|
||||
mtSortDesc: boolean,
|
||||
@@ -38,7 +39,7 @@ const getSavedChatTags = async (
|
||||
const file_head = 'checkpoint-';
|
||||
const file_tail = '.json';
|
||||
const files = await fsPromises.readdir(geminiDir);
|
||||
const chatDetails: ChatDetail[] = [];
|
||||
const chatDetails: Array<{ name: string; mtime: Date }> = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (file.startsWith(file_head) && file.endsWith(file_tail)) {
|
||||
@@ -47,15 +48,15 @@ const getSavedChatTags = async (
|
||||
const tagName = file.slice(file_head.length, -file_tail.length);
|
||||
chatDetails.push({
|
||||
name: decodeTagName(tagName),
|
||||
mtime: stats.mtime.toISOString(),
|
||||
mtime: stats.mtime,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
chatDetails.sort((a, b) =>
|
||||
mtSortDesc
|
||||
? b.mtime.localeCompare(a.mtime)
|
||||
: a.mtime.localeCompare(b.mtime),
|
||||
? b.mtime.getTime() - a.mtime.getTime()
|
||||
: a.mtime.getTime() - b.mtime.getTime(),
|
||||
);
|
||||
|
||||
return chatDetails;
|
||||
@@ -68,15 +69,34 @@ const listCommand: SlashCommand = {
|
||||
name: 'list',
|
||||
description: 'List saved conversation checkpoints',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: async (context): Promise<void> => {
|
||||
action: async (context): Promise<MessageActionReturn> => {
|
||||
const chatDetails = await getSavedChatTags(context, false);
|
||||
if (chatDetails.length === 0) {
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: 'No saved conversation checkpoints found.',
|
||||
};
|
||||
}
|
||||
|
||||
const item: HistoryItemChatList = {
|
||||
type: MessageType.CHAT_LIST,
|
||||
chats: chatDetails,
|
||||
const maxNameLength = Math.max(
|
||||
...chatDetails.map((chat) => chat.name.length),
|
||||
);
|
||||
|
||||
let message = 'List of saved conversations:\n\n';
|
||||
for (const chat of chatDetails) {
|
||||
const paddedName = chat.name.padEnd(maxNameLength, ' ');
|
||||
const isoString = chat.mtime.toISOString();
|
||||
const match = isoString.match(/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
|
||||
const formattedDate = match ? `${match[1]} ${match[2]}` : 'Invalid Date';
|
||||
message += ` - \u001b[36m${paddedName}\u001b[0m \u001b[90m(saved on ${formattedDate})\u001b[0m\n`;
|
||||
}
|
||||
message += `\n\u001b[90mNote: Newest last, oldest first\u001b[0m`;
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: message,
|
||||
};
|
||||
|
||||
context.ui.addItem(item, Date.now());
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -5,23 +5,42 @@
|
||||
*/
|
||||
|
||||
import type { GeminiCLIExtension } from '@google/gemini-cli-core';
|
||||
import {
|
||||
updateAllUpdatableExtensions,
|
||||
updateExtension,
|
||||
} from '../../config/extensions/update.js';
|
||||
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
|
||||
import { MessageType } from '../types.js';
|
||||
import { extensionsCommand } from './extensionsCommand.js';
|
||||
import { type CommandContext } from './types.js';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { type ExtensionUpdateAction } from '../state/extensions.js';
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
vi,
|
||||
beforeEach,
|
||||
type MockedFunction,
|
||||
} from 'vitest';
|
||||
import { ExtensionUpdateState } from '../state/extensions.js';
|
||||
|
||||
vi.mock('../../config/extensions/update.js', () => ({
|
||||
updateExtension: vi.fn(),
|
||||
checkForAllExtensionUpdates: vi.fn(),
|
||||
updateAllUpdatableExtensions: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockUpdateExtension = updateExtension as MockedFunction<
|
||||
typeof updateExtension
|
||||
>;
|
||||
|
||||
const mockUpdateAllUpdatableExtensions =
|
||||
updateAllUpdatableExtensions as MockedFunction<
|
||||
typeof updateAllUpdatableExtensions
|
||||
>;
|
||||
|
||||
const mockGetExtensions = vi.fn();
|
||||
|
||||
describe('extensionsCommand', () => {
|
||||
let mockContext: CommandContext;
|
||||
const mockDispatchExtensionState = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
@@ -32,9 +51,6 @@ describe('extensionsCommand', () => {
|
||||
getWorkingDir: () => '/test/dir',
|
||||
},
|
||||
},
|
||||
ui: {
|
||||
dispatchExtensionStateUpdate: mockDispatchExtensionState,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,14 +89,7 @@ describe('extensionsCommand', () => {
|
||||
});
|
||||
|
||||
it('should inform user if there are no extensions to update with --all', async () => {
|
||||
mockDispatchExtensionState.mockImplementationOnce(
|
||||
(action: ExtensionUpdateAction) => {
|
||||
if (action.type === 'SCHEDULE_UPDATE') {
|
||||
action.payload.onComplete([]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
mockUpdateAllUpdatableExtensions.mockResolvedValue([]);
|
||||
await updateAction(mockContext, '--all');
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -92,24 +101,18 @@ describe('extensionsCommand', () => {
|
||||
});
|
||||
|
||||
it('should call setPendingItem and addItem in a finally block on success', async () => {
|
||||
mockDispatchExtensionState.mockImplementationOnce(
|
||||
(action: ExtensionUpdateAction) => {
|
||||
if (action.type === 'SCHEDULE_UPDATE') {
|
||||
action.payload.onComplete([
|
||||
{
|
||||
name: 'ext-one',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
},
|
||||
{
|
||||
name: 'ext-two',
|
||||
originalVersion: '2.0.0',
|
||||
updatedVersion: '2.0.1',
|
||||
},
|
||||
]);
|
||||
}
|
||||
mockUpdateAllUpdatableExtensions.mockResolvedValue([
|
||||
{
|
||||
name: 'ext-one',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
},
|
||||
);
|
||||
{
|
||||
name: 'ext-two',
|
||||
originalVersion: '2.0.0',
|
||||
updatedVersion: '2.0.1',
|
||||
},
|
||||
]);
|
||||
await updateAction(mockContext, '--all');
|
||||
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
@@ -124,9 +127,9 @@ describe('extensionsCommand', () => {
|
||||
});
|
||||
|
||||
it('should call setPendingItem and addItem in a finally block on failure', async () => {
|
||||
mockDispatchExtensionState.mockImplementationOnce((_) => {
|
||||
throw new Error('Something went wrong');
|
||||
});
|
||||
mockUpdateAllUpdatableExtensions.mockRejectedValue(
|
||||
new Error('Something went wrong'),
|
||||
);
|
||||
await updateAction(mockContext, '--all');
|
||||
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
@@ -148,58 +151,95 @@ describe('extensionsCommand', () => {
|
||||
});
|
||||
|
||||
it('should update a single extension by name', async () => {
|
||||
mockDispatchExtensionState.mockImplementationOnce(
|
||||
(action: ExtensionUpdateAction) => {
|
||||
if (action.type === 'SCHEDULE_UPDATE') {
|
||||
action.payload.onComplete([
|
||||
{
|
||||
name: 'ext-one',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
},
|
||||
]);
|
||||
}
|
||||
const extension: GeminiCLIExtension = {
|
||||
name: 'ext-one',
|
||||
version: '1.0.0',
|
||||
isActive: true,
|
||||
path: '/test/dir/ext-one',
|
||||
installMetadata: {
|
||||
type: 'git',
|
||||
autoUpdate: false,
|
||||
source: 'https://github.com/some/extension.git',
|
||||
},
|
||||
};
|
||||
mockUpdateExtension.mockResolvedValue({
|
||||
name: extension.name,
|
||||
originalVersion: extension.version,
|
||||
updatedVersion: '1.0.1',
|
||||
});
|
||||
mockGetExtensions.mockReturnValue([extension]);
|
||||
mockContext.ui.extensionsUpdateState.set(
|
||||
extension.name,
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
);
|
||||
await updateAction(mockContext, 'ext-one');
|
||||
expect(mockDispatchExtensionState).toHaveBeenCalledWith({
|
||||
type: 'SCHEDULE_UPDATE',
|
||||
payload: {
|
||||
all: false,
|
||||
names: ['ext-one'],
|
||||
onComplete: expect.any(Function),
|
||||
expect(mockUpdateExtension).toHaveBeenCalledWith(
|
||||
extension,
|
||||
'/test/dir',
|
||||
expect.any(Function),
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle errors when updating a single extension', async () => {
|
||||
mockUpdateExtension.mockRejectedValue(new Error('Extension not found'));
|
||||
mockGetExtensions.mockReturnValue([]);
|
||||
await updateAction(mockContext, 'ext-one');
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
type: MessageType.ERROR,
|
||||
text: 'Extension ext-one not found.',
|
||||
},
|
||||
});
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it('should update multiple extensions by name', async () => {
|
||||
mockDispatchExtensionState.mockImplementationOnce(
|
||||
(action: ExtensionUpdateAction) => {
|
||||
if (action.type === 'SCHEDULE_UPDATE') {
|
||||
action.payload.onComplete([
|
||||
{
|
||||
name: 'ext-one',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
},
|
||||
{
|
||||
name: 'ext-two',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
},
|
||||
]);
|
||||
}
|
||||
const extensionOne: GeminiCLIExtension = {
|
||||
name: 'ext-one',
|
||||
version: '1.0.0',
|
||||
isActive: true,
|
||||
path: '/test/dir/ext-one',
|
||||
installMetadata: {
|
||||
type: 'git',
|
||||
autoUpdate: false,
|
||||
source: 'https://github.com/some/extension.git',
|
||||
},
|
||||
};
|
||||
const extensionTwo: GeminiCLIExtension = {
|
||||
name: 'ext-two',
|
||||
version: '1.0.0',
|
||||
isActive: true,
|
||||
path: '/test/dir/ext-two',
|
||||
installMetadata: {
|
||||
type: 'git',
|
||||
autoUpdate: false,
|
||||
source: 'https://github.com/some/extension.git',
|
||||
},
|
||||
};
|
||||
mockGetExtensions.mockReturnValue([extensionOne, extensionTwo]);
|
||||
mockContext.ui.extensionsUpdateState.set(
|
||||
extensionOne.name,
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
);
|
||||
mockContext.ui.extensionsUpdateState.set(
|
||||
extensionTwo.name,
|
||||
ExtensionUpdateState.UPDATE_AVAILABLE,
|
||||
);
|
||||
mockUpdateExtension
|
||||
.mockResolvedValueOnce({
|
||||
name: 'ext-one',
|
||||
originalVersion: '1.0.0',
|
||||
updatedVersion: '1.0.1',
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
name: 'ext-two',
|
||||
originalVersion: '2.0.0',
|
||||
updatedVersion: '2.0.1',
|
||||
});
|
||||
await updateAction(mockContext, 'ext-one ext-two');
|
||||
expect(mockDispatchExtensionState).toHaveBeenCalledWith({
|
||||
type: 'SCHEDULE_UPDATE',
|
||||
payload: {
|
||||
all: false,
|
||||
names: ['ext-one', 'ext-two'],
|
||||
onComplete: expect.any(Function),
|
||||
},
|
||||
});
|
||||
expect(mockUpdateExtension).toHaveBeenCalledTimes(2);
|
||||
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
});
|
||||
|
||||
@@ -4,8 +4,14 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import type { ExtensionUpdateInfo } from '../../config/extension.js';
|
||||
import { requestConsentInteractive } from '../../config/extension.js';
|
||||
import {
|
||||
updateAllUpdatableExtensions,
|
||||
type ExtensionUpdateInfo,
|
||||
updateExtension,
|
||||
} from '../../config/extensions/update.js';
|
||||
import { getErrorMessage } from '../../utils/errors.js';
|
||||
import { ExtensionUpdateState } from '../state/extensions.js';
|
||||
import { MessageType } from '../types.js';
|
||||
import {
|
||||
type CommandContext,
|
||||
@@ -22,10 +28,11 @@ async function listAction(context: CommandContext) {
|
||||
);
|
||||
}
|
||||
|
||||
function updateAction(context: CommandContext, args: string): Promise<void> {
|
||||
async function updateAction(context: CommandContext, args: string) {
|
||||
const updateArgs = args.split(' ').filter((value) => value.length > 0);
|
||||
const all = updateArgs.length === 1 && updateArgs[0] === '--all';
|
||||
const names = all ? null : updateArgs;
|
||||
const names = all ? undefined : updateArgs;
|
||||
let updateInfos: ExtensionUpdateInfo[] = [];
|
||||
|
||||
if (!all && names?.length === 0) {
|
||||
context.ui.addItem(
|
||||
@@ -35,48 +42,28 @@ function updateAction(context: CommandContext, args: string): Promise<void> {
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
return Promise.resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
let resolveUpdateComplete: (updateInfo: ExtensionUpdateInfo[]) => void;
|
||||
const updateComplete = new Promise<ExtensionUpdateInfo[]>(
|
||||
(resolve) => (resolveUpdateComplete = resolve),
|
||||
);
|
||||
updateComplete.then((updateInfos) => {
|
||||
if (updateInfos.length === 0) {
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: 'No extensions to update.',
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
}
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
context.ui.setPendingItem(null);
|
||||
});
|
||||
|
||||
try {
|
||||
context.ui.setPendingItem({
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
});
|
||||
|
||||
context.ui.dispatchExtensionStateUpdate({
|
||||
type: 'SCHEDULE_UPDATE',
|
||||
payload: {
|
||||
all,
|
||||
names,
|
||||
onComplete: (updateInfos) => {
|
||||
resolveUpdateComplete(updateInfos);
|
||||
},
|
||||
},
|
||||
});
|
||||
if (names?.length) {
|
||||
if (all) {
|
||||
updateInfos = await updateAllUpdatableExtensions(
|
||||
context.services.config!.getWorkingDir(),
|
||||
// We don't have the ability to prompt for consent yet in this flow.
|
||||
(description) =>
|
||||
requestConsentInteractive(
|
||||
description,
|
||||
context.ui.addConfirmUpdateExtensionRequest,
|
||||
),
|
||||
context.services.config!.getExtensions(),
|
||||
context.ui.extensionsUpdateState,
|
||||
context.ui.setExtensionsUpdateState,
|
||||
);
|
||||
} else if (names?.length) {
|
||||
const workingDir = context.services.config!.getWorkingDir();
|
||||
const extensions = context.services.config!.getExtensions();
|
||||
for (const name of names) {
|
||||
const extension = extensions.find(
|
||||
@@ -92,10 +79,39 @@ function updateAction(context: CommandContext, args: string): Promise<void> {
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const updateInfo = await updateExtension(
|
||||
extension,
|
||||
workingDir,
|
||||
(description) =>
|
||||
requestConsentInteractive(
|
||||
description,
|
||||
context.ui.addConfirmUpdateExtensionRequest,
|
||||
),
|
||||
context.ui.extensionsUpdateState.get(extension.name) ??
|
||||
ExtensionUpdateState.UNKNOWN,
|
||||
(updateState) => {
|
||||
context.ui.setExtensionsUpdateState((prev) => {
|
||||
const newState = new Map(prev);
|
||||
newState.set(name, updateState);
|
||||
return newState;
|
||||
});
|
||||
},
|
||||
);
|
||||
if (updateInfo) updateInfos.push(updateInfo);
|
||||
}
|
||||
}
|
||||
|
||||
if (updateInfos.length === 0) {
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: 'No extensions to update.',
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
resolveUpdateComplete!([]);
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.ERROR,
|
||||
@@ -103,8 +119,15 @@ function updateAction(context: CommandContext, args: string): Promise<void> {
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
} finally {
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.EXTENSIONS_LIST,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
context.ui.setPendingItem(null);
|
||||
}
|
||||
return updateComplete.then((_) => {});
|
||||
}
|
||||
|
||||
const listExtensionsCommand: SlashCommand = {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import type { Mock } from 'vitest';
|
||||
import { vi, describe, it, expect, beforeEach } from 'vitest';
|
||||
import { memoryCommand } from './memoryCommand.js';
|
||||
import type { SlashCommand, CommandContext } from './types.js';
|
||||
import type { SlashCommand, type CommandContext } from './types.js';
|
||||
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
|
||||
import { MessageType } from '../types.js';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
@@ -36,9 +36,7 @@ const mockLoadServerHierarchicalMemory = loadServerHierarchicalMemory as Mock;
|
||||
describe('memoryCommand', () => {
|
||||
let mockContext: CommandContext;
|
||||
|
||||
const getSubCommand = (
|
||||
name: 'show' | 'add' | 'refresh' | 'list',
|
||||
): SlashCommand => {
|
||||
const getSubCommand = (name: 'show' | 'add' | 'refresh'): SlashCommand => {
|
||||
const subCommand = memoryCommand.subCommands?.find(
|
||||
(cmd) => cmd.name === name,
|
||||
);
|
||||
@@ -153,18 +151,14 @@ describe('memoryCommand', () => {
|
||||
let refreshCommand: SlashCommand;
|
||||
let mockSetUserMemory: Mock;
|
||||
let mockSetGeminiMdFileCount: Mock;
|
||||
let mockSetGeminiMdFilePaths: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
refreshCommand = getSubCommand('refresh');
|
||||
mockSetUserMemory = vi.fn();
|
||||
mockSetGeminiMdFileCount = vi.fn();
|
||||
mockSetGeminiMdFilePaths = vi.fn();
|
||||
|
||||
const mockConfig = {
|
||||
setUserMemory: mockSetUserMemory,
|
||||
setGeminiMdFileCount: mockSetGeminiMdFileCount,
|
||||
setGeminiMdFilePaths: mockSetGeminiMdFilePaths,
|
||||
getWorkingDir: () => '/test/dir',
|
||||
getDebugMode: () => false,
|
||||
getFileService: () => ({}) as FileDiscoveryService,
|
||||
@@ -182,7 +176,7 @@ describe('memoryCommand', () => {
|
||||
|
||||
mockContext = createMockCommandContext({
|
||||
services: {
|
||||
config: mockConfig,
|
||||
config: Promise.resolve(mockConfig),
|
||||
settings: {
|
||||
merged: {
|
||||
memoryDiscoveryMaxDirs: 1000,
|
||||
@@ -199,7 +193,6 @@ describe('memoryCommand', () => {
|
||||
const refreshResult: LoadServerHierarchicalMemoryResponse = {
|
||||
memoryContent: 'new memory content',
|
||||
fileCount: 2,
|
||||
filePaths: ['/path/one/GEMINI.md', '/path/two/GEMINI.md'],
|
||||
};
|
||||
mockLoadServerHierarchicalMemory.mockResolvedValue(refreshResult);
|
||||
|
||||
@@ -220,9 +213,6 @@ describe('memoryCommand', () => {
|
||||
expect(mockSetGeminiMdFileCount).toHaveBeenCalledWith(
|
||||
refreshResult.fileCount,
|
||||
);
|
||||
expect(mockSetGeminiMdFilePaths).toHaveBeenCalledWith(
|
||||
refreshResult.filePaths,
|
||||
);
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -236,7 +226,7 @@ describe('memoryCommand', () => {
|
||||
it('should display success message when memory is refreshed with no content', async () => {
|
||||
if (!refreshCommand.action) throw new Error('Command has no action');
|
||||
|
||||
const refreshResult = { memoryContent: '', fileCount: 0, filePaths: [] };
|
||||
const refreshResult = { memoryContent: '', fileCount: 0 };
|
||||
mockLoadServerHierarchicalMemory.mockResolvedValue(refreshResult);
|
||||
|
||||
await refreshCommand.action(mockContext, '');
|
||||
@@ -244,7 +234,6 @@ describe('memoryCommand', () => {
|
||||
expect(loadServerHierarchicalMemory).toHaveBeenCalledOnce();
|
||||
expect(mockSetUserMemory).toHaveBeenCalledWith('');
|
||||
expect(mockSetGeminiMdFileCount).toHaveBeenCalledWith(0);
|
||||
expect(mockSetGeminiMdFilePaths).toHaveBeenCalledWith([]);
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -266,7 +255,6 @@ describe('memoryCommand', () => {
|
||||
expect(loadServerHierarchicalMemory).toHaveBeenCalledOnce();
|
||||
expect(mockSetUserMemory).not.toHaveBeenCalled();
|
||||
expect(mockSetGeminiMdFileCount).not.toHaveBeenCalled();
|
||||
expect(mockSetGeminiMdFilePaths).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -301,54 +289,4 @@ describe('memoryCommand', () => {
|
||||
expect(loadServerHierarchicalMemory).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('/memory list', () => {
|
||||
let listCommand: SlashCommand;
|
||||
let mockGetGeminiMdfilePaths: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
listCommand = getSubCommand('list');
|
||||
mockGetGeminiMdfilePaths = vi.fn();
|
||||
mockContext = createMockCommandContext({
|
||||
services: {
|
||||
config: {
|
||||
getGeminiMdFilePaths: mockGetGeminiMdfilePaths,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should display a message if no GEMINI.md files are found', async () => {
|
||||
if (!listCommand.action) throw new Error('Command has no action');
|
||||
|
||||
mockGetGeminiMdfilePaths.mockReturnValue([]);
|
||||
|
||||
await listCommand.action(mockContext, '');
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: 'No GEMINI.md files in use.',
|
||||
},
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it('should display the file count and paths if they exist', async () => {
|
||||
if (!listCommand.action) throw new Error('Command has no action');
|
||||
|
||||
const filePaths = ['/path/one/GEMINI.md', '/path/two/GEMINI.md'];
|
||||
mockGetGeminiMdfilePaths.mockReturnValue(filePaths);
|
||||
|
||||
await listCommand.action(mockContext, '');
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: `There are 2 GEMINI.md file(s) in use:\n\n${filePaths.join('\n')}`,
|
||||
},
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -83,7 +83,7 @@ export const memoryCommand: SlashCommand = {
|
||||
try {
|
||||
const config = await context.services.config;
|
||||
if (config) {
|
||||
const { memoryContent, fileCount, filePaths } =
|
||||
const { memoryContent, fileCount } =
|
||||
await loadServerHierarchicalMemory(
|
||||
config.getWorkingDir(),
|
||||
config.shouldLoadMemoryFromIncludeDirectories()
|
||||
@@ -100,7 +100,6 @@ export const memoryCommand: SlashCommand = {
|
||||
);
|
||||
config.setUserMemory(memoryContent);
|
||||
config.setGeminiMdFileCount(fileCount);
|
||||
config.setGeminiMdFilePaths(filePaths);
|
||||
|
||||
const successMessage =
|
||||
memoryContent.length > 0
|
||||
@@ -127,27 +126,5 @@ export const memoryCommand: SlashCommand = {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'Lists the paths of the GEMINI.md files in use.',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: async (context) => {
|
||||
const filePaths = context.services.config?.getGeminiMdFilePaths() || [];
|
||||
const fileCount = filePaths.length;
|
||||
|
||||
const messageContent =
|
||||
fileCount > 0
|
||||
? `There are ${fileCount} GEMINI.md file(s) in use:\n\n${filePaths.join('\n')}`
|
||||
: 'No GEMINI.md files in use.';
|
||||
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: messageContent,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { isDevelopment } from '../../utils/installationInfo.js';
|
||||
import { CommandKind, type SlashCommand } from './types.js';
|
||||
|
||||
export const profileCommand: SlashCommand | null = isDevelopment
|
||||
? {
|
||||
name: 'profile',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
description: 'Toggle the debug profile display',
|
||||
action: async (context) => {
|
||||
context.ui.toggleDebugProfiler();
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: 'Toggled profile display.',
|
||||
};
|
||||
},
|
||||
}
|
||||
: null;
|
||||
@@ -49,8 +49,7 @@ describe('setupGithubCommand', async () => {
|
||||
if (scratchDir) await fs.rm(scratchDir, { recursive: true });
|
||||
});
|
||||
|
||||
//TODO - https://github.com/google-gemini/gemini-cli/issues/10740
|
||||
it.skip('returns a tool action to download github workflows and handles paths', async () => {
|
||||
it('returns a tool action to download github workflows and handles paths', async () => {
|
||||
const fakeRepoOwner = 'fake';
|
||||
const fakeRepoName = 'repo';
|
||||
const fakeRepoRoot = scratchDir;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import type { Content, PartListUnion } from '@google/genai';
|
||||
import type {
|
||||
HistoryItemWithoutId,
|
||||
@@ -15,10 +15,7 @@ import type { Config, GitService, Logger } from '@google/gemini-cli-core';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
import type { UseHistoryManagerReturn } from '../hooks/useHistoryManager.js';
|
||||
import type { SessionStatsState } from '../contexts/SessionContext.js';
|
||||
import type {
|
||||
ExtensionUpdateAction,
|
||||
ExtensionUpdateStatus,
|
||||
} from '../state/extensions.js';
|
||||
import type { ExtensionUpdateState } from '../state/extensions.js';
|
||||
|
||||
// Grouped dependencies for clarity and easier mocking
|
||||
export interface CommandContext {
|
||||
@@ -66,12 +63,13 @@ export interface CommandContext {
|
||||
loadHistory: UseHistoryManagerReturn['loadHistory'];
|
||||
/** Toggles a special display mode. */
|
||||
toggleCorgiMode: () => void;
|
||||
toggleDebugProfiler: () => void;
|
||||
toggleVimEnabled: () => Promise<boolean>;
|
||||
setGeminiMdFileCount: (count: number) => void;
|
||||
reloadCommands: () => void;
|
||||
extensionsUpdateState: Map<string, ExtensionUpdateStatus>;
|
||||
dispatchExtensionStateUpdate: (action: ExtensionUpdateAction) => void;
|
||||
extensionsUpdateState: Map<string, ExtensionUpdateState>;
|
||||
setExtensionsUpdateState: Dispatch<
|
||||
SetStateAction<Map<string, ExtensionUpdateState>>
|
||||
>;
|
||||
addConfirmUpdateExtensionRequest: (value: ConfirmationRequest) => void;
|
||||
};
|
||||
// Session-specific data
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import Spinner from 'ink-spinner';
|
||||
import { type ComponentProps, useEffect } from 'react';
|
||||
|
||||
// A top-level field to track the total number of active spinners.
|
||||
export let debugNumSpinners = 0;
|
||||
|
||||
export type SpinnerProps = ComponentProps<typeof Spinner>;
|
||||
|
||||
export const CliSpinner = (props: SpinnerProps) => {
|
||||
useEffect(() => {
|
||||
debugNumSpinners++;
|
||||
return () => {
|
||||
debugNumSpinners--;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <Spinner {...props} />;
|
||||
};
|
||||
@@ -11,15 +11,21 @@ import { tokenLimit } from '@google/gemini-cli-core';
|
||||
export const ContextUsageDisplay = ({
|
||||
promptTokenCount,
|
||||
model,
|
||||
terminalWidth,
|
||||
}: {
|
||||
promptTokenCount: number;
|
||||
model: string;
|
||||
terminalWidth: number;
|
||||
}) => {
|
||||
const percentage = promptTokenCount / tokenLimit(model);
|
||||
const percentageLeft = ((1 - percentage) * 100).toFixed(0);
|
||||
|
||||
const label = terminalWidth < 100 ? '%' : '% context left';
|
||||
|
||||
return (
|
||||
<Text color={theme.text.secondary}>
|
||||
({((1 - percentage) * 100).toFixed(0)}% context left)
|
||||
({percentageLeft}
|
||||
{label})
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import {
|
||||
profiler,
|
||||
ACTION_TIMESTAMP_CAPACITY,
|
||||
FRAME_TIMESTAMP_CAPACITY,
|
||||
} from './DebugProfiler.js';
|
||||
import { FixedDeque } from 'mnemonist';
|
||||
|
||||
describe('DebugProfiler', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
profiler.numFrames = 0;
|
||||
profiler.totalIdleFrames = 0;
|
||||
profiler.lastFrameStartTime = 0;
|
||||
profiler.openedDebugConsole = false;
|
||||
profiler.lastActionTimestamp = 0;
|
||||
profiler.possiblyIdleFrameTimestamps = new FixedDeque<number>(
|
||||
Array,
|
||||
FRAME_TIMESTAMP_CAPACITY,
|
||||
);
|
||||
profiler.actionTimestamps = new FixedDeque<number>(
|
||||
Array,
|
||||
ACTION_TIMESTAMP_CAPACITY,
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
profiler.actionTimestamps.clear();
|
||||
profiler.possiblyIdleFrameTimestamps.clear();
|
||||
});
|
||||
|
||||
it('should not exceed action timestamp capacity', () => {
|
||||
for (let i = 0; i < ACTION_TIMESTAMP_CAPACITY + 10; i++) {
|
||||
profiler.reportAction();
|
||||
// To ensure we don't trigger the debounce
|
||||
profiler.lastActionTimestamp = 0;
|
||||
}
|
||||
expect(profiler.actionTimestamps.size).toBe(ACTION_TIMESTAMP_CAPACITY);
|
||||
});
|
||||
|
||||
it('should not exceed frame timestamp capacity', () => {
|
||||
for (let i = 0; i < FRAME_TIMESTAMP_CAPACITY + 10; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
// To ensure we don't trigger the debounce
|
||||
profiler.lastFrameStartTime = 0;
|
||||
}
|
||||
expect(profiler.possiblyIdleFrameTimestamps.size).toBe(
|
||||
FRAME_TIMESTAMP_CAPACITY,
|
||||
);
|
||||
});
|
||||
|
||||
it('should drop oldest action timestamps when capacity is reached', () => {
|
||||
for (let i = 0; i < ACTION_TIMESTAMP_CAPACITY; i++) {
|
||||
profiler.actionTimestamps.push(i);
|
||||
}
|
||||
profiler.lastActionTimestamp = 0;
|
||||
profiler.reportAction();
|
||||
|
||||
expect(profiler.actionTimestamps.size).toBe(ACTION_TIMESTAMP_CAPACITY);
|
||||
expect(profiler.actionTimestamps.peekFirst()).toBe(1);
|
||||
});
|
||||
|
||||
it('should drop oldest frame timestamps when capacity is reached', () => {
|
||||
for (let i = 0; i < FRAME_TIMESTAMP_CAPACITY; i++) {
|
||||
profiler.possiblyIdleFrameTimestamps.push(i);
|
||||
}
|
||||
profiler.lastFrameStartTime = 0;
|
||||
profiler.reportFrameRendered();
|
||||
|
||||
expect(profiler.possiblyIdleFrameTimestamps.size).toBe(
|
||||
FRAME_TIMESTAMP_CAPACITY,
|
||||
);
|
||||
expect(profiler.possiblyIdleFrameTimestamps.peekFirst()).toBe(1);
|
||||
});
|
||||
|
||||
it('should not report frames as idle if an action happens shortly after', async () => {
|
||||
const startTime = Date.now();
|
||||
vi.setSystemTime(startTime);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
|
||||
vi.setSystemTime(startTime + 400);
|
||||
profiler.reportAction();
|
||||
|
||||
vi.advanceTimersByTime(600);
|
||||
profiler.checkForIdleFrames();
|
||||
|
||||
expect(profiler.totalIdleFrames).toBe(0);
|
||||
});
|
||||
|
||||
it('should report frames as idle if no action happens nearby', async () => {
|
||||
const startTime = Date.now();
|
||||
vi.setSystemTime(startTime);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
profiler.checkForIdleFrames();
|
||||
|
||||
expect(profiler.totalIdleFrames).toBe(5);
|
||||
});
|
||||
|
||||
it('should not report frames as idle if an action happens shortly before', async () => {
|
||||
const startTime = Date.now();
|
||||
vi.setSystemTime(startTime);
|
||||
|
||||
profiler.reportAction();
|
||||
|
||||
vi.advanceTimersByTime(400);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(600);
|
||||
profiler.checkForIdleFrames();
|
||||
|
||||
expect(profiler.totalIdleFrames).toBe(0);
|
||||
});
|
||||
|
||||
it('should correctly identify mixed idle and non-idle frames', async () => {
|
||||
const startTime = Date.now();
|
||||
vi.setSystemTime(startTime);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
profiler.reportAction();
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(600);
|
||||
profiler.checkForIdleFrames();
|
||||
|
||||
expect(profiler.totalIdleFrames).toBe(3);
|
||||
});
|
||||
|
||||
it('should not report idle frames when actions are interleaved', async () => {
|
||||
const startTime = Date.now();
|
||||
vi.setSystemTime(startTime);
|
||||
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(200);
|
||||
|
||||
profiler.reportAction();
|
||||
vi.advanceTimersByTime(200);
|
||||
|
||||
profiler.reportFrameRendered();
|
||||
vi.advanceTimersByTime(20);
|
||||
|
||||
profiler.reportFrameRendered();
|
||||
|
||||
vi.advanceTimersByTime(600);
|
||||
profiler.checkForIdleFrames();
|
||||
|
||||
expect(profiler.totalIdleFrames).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -5,193 +5,32 @@
|
||||
*/
|
||||
|
||||
import { Text } from 'ink';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { FixedDeque } from 'mnemonist';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { theme } from '../semantic-colors.js';
|
||||
import { useUIState } from '../contexts/UIStateContext.js';
|
||||
import { debugNumSpinners } from './CliSpinner.js';
|
||||
import { appEvents, AppEvent } from '../../utils/events.js';
|
||||
|
||||
// Frames that render at least this far before or after an action are considered
|
||||
// idle frames.
|
||||
const MIN_TIME_FROM_ACTION_TO_BE_IDLE = 500;
|
||||
|
||||
export const ACTION_TIMESTAMP_CAPACITY = 2048;
|
||||
export const FRAME_TIMESTAMP_CAPACITY = 2048;
|
||||
|
||||
// Exported for testing purposes.
|
||||
export const profiler = {
|
||||
numFrames: 0,
|
||||
totalIdleFrames: 0,
|
||||
lastFrameStartTime: 0,
|
||||
openedDebugConsole: false,
|
||||
lastActionTimestamp: 0,
|
||||
|
||||
possiblyIdleFrameTimestamps: new FixedDeque<number>(
|
||||
Array,
|
||||
FRAME_TIMESTAMP_CAPACITY,
|
||||
),
|
||||
actionTimestamps: new FixedDeque<number>(Array, ACTION_TIMESTAMP_CAPACITY),
|
||||
|
||||
reportAction() {
|
||||
const now = Date.now();
|
||||
if (now - this.lastActionTimestamp > 16) {
|
||||
if (this.actionTimestamps.size >= ACTION_TIMESTAMP_CAPACITY) {
|
||||
this.actionTimestamps.shift();
|
||||
}
|
||||
this.actionTimestamps.push(now);
|
||||
this.lastActionTimestamp = now;
|
||||
}
|
||||
},
|
||||
|
||||
reportFrameRendered() {
|
||||
const now = Date.now();
|
||||
// Simple frame detection logic (a write after at least 16ms is a new frame)
|
||||
if (now - this.lastFrameStartTime > 16) {
|
||||
this.lastFrameStartTime = now;
|
||||
this.numFrames++;
|
||||
if (debugNumSpinners === 0) {
|
||||
if (this.possiblyIdleFrameTimestamps.size >= FRAME_TIMESTAMP_CAPACITY) {
|
||||
this.possiblyIdleFrameTimestamps.shift();
|
||||
}
|
||||
this.possiblyIdleFrameTimestamps.push(now);
|
||||
} else {
|
||||
// If a spinner is present, consider this an action that both prevents
|
||||
// this frame from being idle and also should prevent a follow on frame
|
||||
// from being considered idle.
|
||||
if (this.actionTimestamps.size >= ACTION_TIMESTAMP_CAPACITY) {
|
||||
this.actionTimestamps.shift();
|
||||
}
|
||||
this.actionTimestamps.push(now);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
checkForIdleFrames() {
|
||||
const now = Date.now();
|
||||
const judgementCutoff = now - MIN_TIME_FROM_ACTION_TO_BE_IDLE;
|
||||
const oneSecondIntervalFromJudgementCutoff = judgementCutoff - 1000;
|
||||
|
||||
let idleInPastSecond = 0;
|
||||
|
||||
while (
|
||||
this.possiblyIdleFrameTimestamps.size > 0 &&
|
||||
this.possiblyIdleFrameTimestamps.peekFirst()! <= judgementCutoff
|
||||
) {
|
||||
const frameTime = this.possiblyIdleFrameTimestamps.shift()!;
|
||||
const start = frameTime - MIN_TIME_FROM_ACTION_TO_BE_IDLE;
|
||||
const end = frameTime + MIN_TIME_FROM_ACTION_TO_BE_IDLE;
|
||||
|
||||
while (
|
||||
this.actionTimestamps.size > 0 &&
|
||||
this.actionTimestamps.peekFirst()! < start
|
||||
) {
|
||||
this.actionTimestamps.shift();
|
||||
}
|
||||
|
||||
const hasAction =
|
||||
this.actionTimestamps.size > 0 &&
|
||||
this.actionTimestamps.peekFirst()! <= end;
|
||||
|
||||
if (!hasAction) {
|
||||
if (frameTime >= oneSecondIntervalFromJudgementCutoff) {
|
||||
idleInPastSecond++;
|
||||
}
|
||||
this.totalIdleFrames++;
|
||||
}
|
||||
}
|
||||
|
||||
if (idleInPastSecond >= 5) {
|
||||
if (this.openedDebugConsole === false) {
|
||||
this.openedDebugConsole = true;
|
||||
appEvents.emit(AppEvent.OpenDebugConsole);
|
||||
}
|
||||
appEvents.emit(
|
||||
AppEvent.LogError,
|
||||
`${idleInPastSecond} frames rendered while the app was ` +
|
||||
`idle in the past second. This likely indicates severe infinite loop ` +
|
||||
`React state management bugs.`,
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
import { useKeypress } from '../hooks/useKeypress.js';
|
||||
|
||||
export const DebugProfiler = () => {
|
||||
const { showDebugProfiler } = useUIState();
|
||||
const [forceRefresh, setForceRefresh] = useState(0);
|
||||
const numRenders = useRef(0);
|
||||
const [showNumRenders, setShowNumRenders] = useState(false);
|
||||
|
||||
// Effect for listening to stdin for keypresses and stdout for resize events.
|
||||
useEffect(() => {
|
||||
const stdin = process.stdin;
|
||||
const stdout = process.stdout;
|
||||
numRenders.current++;
|
||||
});
|
||||
|
||||
const handler = () => {
|
||||
profiler.reportAction();
|
||||
};
|
||||
|
||||
stdin.on('data', handler);
|
||||
stdout.on('resize', handler);
|
||||
|
||||
return () => {
|
||||
stdin.off('data', handler);
|
||||
stdout.off('resize', handler);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Effect for patching stdout to count frames and detect idle ones
|
||||
useEffect(() => {
|
||||
const originalWrite = process.stdout.write;
|
||||
const boundOriginalWrite = originalWrite.bind(process.stdout);
|
||||
|
||||
process.stdout.write = (
|
||||
chunk: Uint8Array | string,
|
||||
encodingOrCb?:
|
||||
| BufferEncoding
|
||||
| ((err?: NodeJS.ErrnoException | null) => void),
|
||||
cb?: (err?: NodeJS.ErrnoException | null) => void,
|
||||
) => {
|
||||
profiler.reportFrameRendered();
|
||||
|
||||
if (typeof encodingOrCb === 'function') {
|
||||
return boundOriginalWrite(chunk, encodingOrCb);
|
||||
useKeypress(
|
||||
(key) => {
|
||||
if (key.ctrl && key.name === 'b') {
|
||||
setShowNumRenders((prev) => !prev);
|
||||
}
|
||||
return boundOriginalWrite(chunk, encodingOrCb, cb);
|
||||
};
|
||||
},
|
||||
{ isActive: true },
|
||||
);
|
||||
|
||||
return () => {
|
||||
process.stdout.write = originalWrite;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const updateInterval = setInterval(() => {
|
||||
profiler.checkForIdleFrames();
|
||||
}, 1000);
|
||||
return () => clearInterval(updateInterval);
|
||||
}, []);
|
||||
|
||||
// Effect for updating stats
|
||||
useEffect(() => {
|
||||
if (!showDebugProfiler) {
|
||||
return;
|
||||
}
|
||||
// Only update the UX infrequently as updating the UX itself will cause
|
||||
// frames to run so can disturb what we are measuing.
|
||||
const forceRefreshInterval = setInterval(() => {
|
||||
setForceRefresh((f) => f + 1);
|
||||
profiler.reportAction();
|
||||
}, 4000);
|
||||
return () => clearInterval(forceRefreshInterval);
|
||||
}, [showDebugProfiler]);
|
||||
|
||||
if (!showDebugProfiler) {
|
||||
if (!showNumRenders) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Text color={theme.status.warning} key={forceRefresh}>
|
||||
Renders: {profiler.numFrames} (total),{' '}
|
||||
<Text color={theme.status.error}>{profiler.totalIdleFrames} (idle) </Text>
|
||||
</Text>
|
||||
<Text color={theme.status.warning}>Renders: {numRenders.current} </Text>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -9,7 +9,6 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { Footer } from './Footer.js';
|
||||
import * as useTerminalSize from '../hooks/useTerminalSize.js';
|
||||
import { tildeifyPath } from '@google/gemini-cli-core';
|
||||
import path from 'node:path';
|
||||
import { type UIState, UIStateContext } from '../contexts/UIStateContext.js';
|
||||
import { ConfigContext } from '../contexts/ConfigContext.js';
|
||||
import { SettingsContext } from '../contexts/SettingsContext.js';
|
||||
@@ -103,34 +102,22 @@ describe('<Footer />', () => {
|
||||
});
|
||||
|
||||
describe('path display', () => {
|
||||
it('should display shortened path on a wide terminal', () => {
|
||||
const { lastFrame } = renderWithWidth(120, createMockUIState());
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const expectedPath = '...' + tildePath.slice(tildePath.length - 48 + 3);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should display only the base directory name on a narrow terminal', () => {
|
||||
it('should display a shortened path on a narrow terminal', () => {
|
||||
const { lastFrame } = renderWithWidth(79, createMockUIState());
|
||||
const expectedPath = path.basename(defaultProps.targetDir);
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const pathLength = Math.max(20, Math.floor(79 * 0.25));
|
||||
const expectedPath =
|
||||
'...' + tildePath.slice(tildePath.length - pathLength + 3);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should use wide layout at 80 columns', () => {
|
||||
const { lastFrame } = renderWithWidth(80, createMockUIState());
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const expectedPath = '...' + tildePath.slice(tildePath.length - 32 + 3);
|
||||
const expectedPath =
|
||||
'...' + tildePath.slice(tildePath.length - 80 * 0.25 + 3);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should use narrow layout at 79 columns', () => {
|
||||
const { lastFrame } = renderWithWidth(79, createMockUIState());
|
||||
const expectedPath = path.basename(defaultProps.targetDir);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const unexpectedPath = '...' + tildePath.slice(tildePath.length - 31 + 3);
|
||||
expect(lastFrame()).not.toContain(unexpectedPath);
|
||||
});
|
||||
});
|
||||
|
||||
it('displays the branch name when provided', () => {
|
||||
@@ -151,7 +138,13 @@ describe('<Footer />', () => {
|
||||
it('displays the model name and context percentage', () => {
|
||||
const { lastFrame } = renderWithWidth(120, createMockUIState());
|
||||
expect(lastFrame()).toContain(defaultProps.model);
|
||||
expect(lastFrame()).toMatch(/\(\d+% context[\s\S]*left\)/);
|
||||
expect(lastFrame()).toMatch(/\(\d+% context left\)/);
|
||||
});
|
||||
|
||||
it('displays the model name and abbreviated context percentage', () => {
|
||||
const { lastFrame } = renderWithWidth(99, createMockUIState());
|
||||
expect(lastFrame()).toContain(defaultProps.model);
|
||||
expect(lastFrame()).toMatch(/\(\d+%\)/);
|
||||
});
|
||||
|
||||
describe('sandbox and trust info', () => {
|
||||
|
||||
@@ -10,15 +10,11 @@ import { theme } from '../semantic-colors.js';
|
||||
import { shortenPath, tildeifyPath } from '@google/gemini-cli-core';
|
||||
import { ConsoleSummaryDisplay } from './ConsoleSummaryDisplay.js';
|
||||
import process from 'node:process';
|
||||
import path from 'node:path';
|
||||
import Gradient from 'ink-gradient';
|
||||
import { MemoryUsageDisplay } from './MemoryUsageDisplay.js';
|
||||
import { ContextUsageDisplay } from './ContextUsageDisplay.js';
|
||||
import { DebugProfiler } from './DebugProfiler.js';
|
||||
|
||||
import { useTerminalSize } from '../hooks/useTerminalSize.js';
|
||||
import { isNarrowWidth } from '../utils/isNarrowWidth.js';
|
||||
import { isDevelopment } from '../../utils/installationInfo.js';
|
||||
|
||||
import { useUIState } from '../contexts/UIStateContext.js';
|
||||
import { useConfig } from '../contexts/ConfigContext.js';
|
||||
@@ -66,29 +62,22 @@ export const Footer: React.FC = () => {
|
||||
|
||||
const { columns: terminalWidth } = useTerminalSize();
|
||||
|
||||
const isNarrow = isNarrowWidth(terminalWidth);
|
||||
|
||||
// Adjust path length based on terminal width
|
||||
const pathLength = Math.max(20, Math.floor(terminalWidth * 0.4));
|
||||
const displayPath = isNarrow
|
||||
? path.basename(tildeifyPath(targetDir))
|
||||
: shortenPath(tildeifyPath(targetDir), pathLength);
|
||||
const pathLength = Math.max(20, Math.floor(terminalWidth * 0.25));
|
||||
const displayPath = shortenPath(tildeifyPath(targetDir), pathLength);
|
||||
|
||||
const justifyContent = hideCWD && hideModelInfo ? 'center' : 'space-between';
|
||||
const displayVimMode = vimEnabled ? vimMode : undefined;
|
||||
|
||||
const showDebugProfiler = debugMode || isDevelopment;
|
||||
|
||||
return (
|
||||
<Box
|
||||
justifyContent={justifyContent}
|
||||
width="100%"
|
||||
flexDirection={isNarrow ? 'column' : 'row'}
|
||||
alignItems={isNarrow ? 'flex-start' : 'center'}
|
||||
flexDirection="row"
|
||||
alignItems="center"
|
||||
>
|
||||
{(showDebugProfiler || displayVimMode || !hideCWD) && (
|
||||
{(debugMode || displayVimMode || !hideCWD) && (
|
||||
<Box>
|
||||
{showDebugProfiler && <DebugProfiler />}
|
||||
{debugMode && <DebugProfiler />}
|
||||
{displayVimMode && (
|
||||
<Text color={theme.text.secondary}>[{displayVimMode}] </Text>
|
||||
)}
|
||||
@@ -119,12 +108,10 @@ export const Footer: React.FC = () => {
|
||||
{/* Middle Section: Centered Trust/Sandbox Info */}
|
||||
{!hideSandboxStatus && (
|
||||
<Box
|
||||
flexGrow={isNarrow || hideCWD || hideModelInfo ? 0 : 1}
|
||||
flexGrow={1}
|
||||
alignItems="center"
|
||||
justifyContent={isNarrow || hideCWD ? 'flex-start' : 'center'}
|
||||
justifyContent="center"
|
||||
display="flex"
|
||||
paddingX={isNarrow ? 0 : 1}
|
||||
paddingTop={isNarrow ? 1 : 0}
|
||||
>
|
||||
{isTrustedFolder === false ? (
|
||||
<Text color={theme.status.warning}>untrusted</Text>
|
||||
@@ -142,35 +129,33 @@ export const Footer: React.FC = () => {
|
||||
</Text>
|
||||
) : (
|
||||
<Text color={theme.status.error}>
|
||||
no sandbox <Text color={theme.text.secondary}>(see /docs)</Text>
|
||||
no sandbox
|
||||
{terminalWidth >= 100 && (
|
||||
<Text color={theme.text.secondary}> (see /docs)</Text>
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Right Section: Gemini Label and Console Summary */}
|
||||
{(!hideModelInfo ||
|
||||
showMemoryUsage ||
|
||||
corgiMode ||
|
||||
(!showErrorDetails && errorCount > 0)) && (
|
||||
<Box alignItems="center" paddingTop={isNarrow ? 1 : 0}>
|
||||
{!hideModelInfo && (
|
||||
<Box alignItems="center">
|
||||
<Text color={theme.text.accent}>
|
||||
{isNarrow ? '' : ' '}
|
||||
{model}{' '}
|
||||
<ContextUsageDisplay
|
||||
promptTokenCount={promptTokenCount}
|
||||
model={model}
|
||||
/>
|
||||
</Text>
|
||||
{showMemoryUsage && <MemoryUsageDisplay />}
|
||||
</Box>
|
||||
)}
|
||||
{!hideModelInfo && (
|
||||
<Box alignItems="center" justifyContent="flex-end">
|
||||
<Box alignItems="center">
|
||||
<Text color={theme.text.accent}>
|
||||
{model}{' '}
|
||||
<ContextUsageDisplay
|
||||
promptTokenCount={promptTokenCount}
|
||||
model={model}
|
||||
terminalWidth={terminalWidth}
|
||||
/>
|
||||
</Text>
|
||||
{showMemoryUsage && <MemoryUsageDisplay />}
|
||||
</Box>
|
||||
<Box alignItems="center" paddingLeft={2}>
|
||||
{corgiMode && (
|
||||
<Text>
|
||||
{!hideModelInfo && <Text color={theme.ui.comment}>| </Text>}
|
||||
<Text color={theme.ui.symbol}>| </Text>
|
||||
<Text color={theme.status.error}>▼</Text>
|
||||
<Text color={theme.text.primary}>(´</Text>
|
||||
<Text color={theme.status.error}>ᴥ</Text>
|
||||
@@ -180,7 +165,7 @@ export const Footer: React.FC = () => {
|
||||
)}
|
||||
{!showErrorDetails && errorCount > 0 && (
|
||||
<Box>
|
||||
{!hideModelInfo && <Text color={theme.ui.comment}>| </Text>}
|
||||
<Text color={theme.ui.symbol}>| </Text>
|
||||
<ConsoleSummaryDisplay errorCount={errorCount} />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
import type React from 'react';
|
||||
import { Text, useIsScreenReaderEnabled } from 'ink';
|
||||
import { CliSpinner } from './CliSpinner.js';
|
||||
import Spinner from 'ink-spinner';
|
||||
import type { SpinnerName } from 'cli-spinners';
|
||||
import { useStreamingContext } from '../contexts/StreamingContext.js';
|
||||
import { StreamingState } from '../types.js';
|
||||
@@ -61,7 +61,7 @@ export const GeminiSpinner: React.FC<GeminiSpinnerProps> = ({
|
||||
<Text>{altText}</Text>
|
||||
) : (
|
||||
<Text color={theme.text.primary}>
|
||||
<CliSpinner type={spinnerType} />
|
||||
<Spinner type={spinnerType} />
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user