Skip to content

Gemini CLI -- Sandbox Analysis Report

Analysis Date: 2026-02-12 Repository: https://github.com/google-gemini/gemini-cliGit Commit: 099aa9621c530885fd69687953f5b1fe4bf006dfLatest Version: 0.30.0-nightly.20260210.a2174751d (monorepo), latest tag v0.1.12 License: Open source Source Availability: Open source


1. Overview

Gemini CLI is a terminal-based agentic coding assistant from Google that uses the Gemini family of AI models. It is a TypeScript/Node.js monorepo (Node.js >= 20.0.0) consisting of multiple packages: the CLI itself (@google/gemini-cli), a core library (@google/gemini-cli-core), an A2A server (@google/gemini-cli-a2a-server), a VS Code IDE companion (gemini-cli-vscode-ide-companion), and test utilities.

The CLI provides an interactive terminal UI for agentic coding tasks, supporting file editing, shell command execution, web fetching, code search, and browser automation. It includes built-in sandbox mechanisms (macOS Seatbelt, Docker, Podman) for isolating AI-driven tool execution.

2. UI & Execution Modes

Primary Framework: Ink (React for the terminal)

Gemini CLI uses Ink (@jrichman/ink@6.4.10, a fork of React-Ink) to render its terminal user interface. The entire interactive UI is built with React components (.tsx files) rendered to the terminal via Ink.

Evidence from packages/cli/src/gemini.tsx:

typescript
import React from 'react';
import { render } from 'ink';
import { AppContainer } from './ui/AppContainer.js';

The CLI contains approximately 270 .tsx component files in packages/cli/src/ui/, including:

  • Layout components (DefaultAppLayout.tsx, ScreenReaderAppLayout.tsx)
  • Message renderers (GeminiMessage.tsx, ToolMessage.tsx, UserMessage.tsx)
  • Dialog components (SettingsDialog.tsx, ModelDialog.tsx, AuthDialog.tsx)
  • Code display (CodeColorizer.tsx, DiffRenderer.tsx, MarkdownDisplay.tsx)
  • Input components (Composer.tsx, TextInput.tsx, InputPrompt.tsx)

Additional UI elements:

  • ink-gradient and tinygradient for colored gradient effects
  • ink-spinner for loading indicators
  • highlight.js / lowlight for syntax highlighting

Execution Modes

  • Interactive TUI -- Primary mode using Ink-based React terminal UI.
  • Non-interactive/print -- For scripted/CI usage.
  • DevTools service -- Optionally connects to gemini-cli-devtools via WebSocket on port 25417.
  • VSCode IDE Companion -- Separate package using Express to serve a local HTTP server for IDE integration.
  • A2A Server -- Separate package using Express for its HTTP server (default port 41242).

The CLI does not serve a web UI in its core package.

3. Authentication & Credentials

3.1 Credential Storage

Keychain Storage (macOS Keychain via keytar):

Uses the keytar npm package (optional dependency) for macOS Keychain / Linux Secret Service / Windows Credential Manager integration:

typescript
// packages/core/src/mcp/token-storage/keychain-token-storage.ts
export class KeychainTokenStorage extends BaseTokenStorage implements SecretStorage {
  private keychainAvailable: boolean | null = null;
  private keytarModule: Keytar | null = null;

  async getKeytar(): Promise<Keytar | null> {
    const moduleName = 'keytar';
    const module = await import(moduleName);
    this.keytarModule = module.default || module;
  }
}

Keytar service names used:

  • gemini-cli-oauth -- for main OAuth credential storage
  • MCP server-specific service names -- for MCP OAuth tokens

Hybrid Token Storage (Keychain with file fallback):

The HybridTokenStorage class first attempts to use the Keychain. If that fails (keytar not available, or keychain not working), it falls back to encrypted file storage:

typescript
// packages/core/src/mcp/token-storage/hybrid-token-storage.ts
private async initializeStorage(): Promise<TokenStorage> {
  const forceFileStorage = process.env[FORCE_FILE_STORAGE_ENV_VAR] === 'true';
  if (!forceFileStorage) {
    const keychainStorage = new KeychainTokenStorage(this.serviceName);
    if (await keychainStorage.isAvailable()) {
      return keychainStorage;
    }
  }
  return new FileTokenStorage(this.serviceName);
}

Encrypted File Token Storage:

When keychain is unavailable, tokens are stored in an encrypted JSON file:

typescript
// packages/core/src/mcp/token-storage/file-token-storage.ts
this.tokenFilePath = path.join(configDir, 'mcp-oauth-tokens-v2.json');
const salt = `${os.hostname()}-${os.userInfo().username}-gemini-cli`;
this.encryptionKey = crypto.scryptSync('gemini-cli-oauth', salt, 32);
// Uses AES-256-GCM encryption

3.2 API Key Sources and Priority Order

Gemini CLI supports four authentication methods, configured via the authType setting:

  1. OAuth2 with Google (Login with Google) -- Primary method
  2. Gemini API Key -- Via GEMINI_API_KEY environment variable
  3. Vertex AI -- Via GOOGLE_CLOUD_PROJECT + GOOGLE_CLOUD_LOCATION or GOOGLE_API_KEY
  4. Compute ADC (Application Default Credentials) -- Via Google metadata server for Cloud Shell / GCE

3.3 OAuth Flows

Browser-based OAuth flow (default):

  • Uses hardcoded OAuth2 client credentials (public client for "installed applications"):
    typescript
    // packages/core/src/code_assist/oauth2.ts
    const OAUTH_CLIENT_ID = '<REDACTED_GOOGLE_OAUTH_CLIENT_ID>';
    const OAUTH_CLIENT_SECRET = '<REDACTED_GOOGLE_OAUTH_CLIENT_SECRET>';
    
    const OAUTH_SCOPE = [
      'https://www.googleapis.com/auth/cloud-platform',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/userinfo.profile',
    ];
  • Starts a local HTTP server on a random port (http://127.0.0.1:<port>/oauth2callback)
  • Opens the browser with the open npm package
  • Receives the auth code via the callback server
  • 5-minute timeout, with SIGINT cancellation support

User code flow (when NO_BROWSER=true or browser suppressed):

  • Prints an auth URL to the terminal
  • User manually visits URL and pastes back the authorization code via readline

After auth, fetches user info from https://www.googleapis.com/oauth2/v2/userinfo. Token refresh is automatic via the OAuth2Client.

3.4 Credential File Locations and Formats

PathPurpose
~/.gemini/oauth_creds.jsonOAuth credentials (legacy, migrated)
~/.gemini/mcp-oauth-tokens.jsonMCP OAuth tokens (legacy)
~/.gemini/mcp-oauth-tokens-v2.jsonMCP OAuth tokens (encrypted, current)
~/.gemini/google_accounts.jsonGoogle account info cache
macOS Keychain (gemini-cli-oauth)OAuth tokens (primary)
~/.config/gcloud/Google Cloud SDK config (read-only)
Path from GOOGLE_APPLICATION_CREDENTIALSADC key file

4. Configuration & Filesystem

4.1 User-Level Config Paths (~/.gemini/)

The constant GEMINI_DIR = '.gemini' is defined in packages/core/src/utils/paths.ts. The home directory can be overridden with GEMINI_CLI_HOME.

typescript
// packages/core/src/config/storage.ts
static getGlobalGeminiDir(): string {
  const homeDir = homedir();
  if (!homeDir) {
    return path.join(os.tmpdir(), GEMINI_DIR);
  }
  return path.join(homeDir, GEMINI_DIR);
}
PathPurposeR/W
~/.gemini/settings.jsonUser settingsR/W
~/.gemini/memory.mdGlobal memory fileR/W
~/.gemini/commands/User-defined commandsR
~/.gemini/skills/User-defined skillsR
~/.gemini/agents/User agent definitionsR
~/.gemini/policies/User policies (TOML)R
~/.gemini/acknowledgments/agents.jsonAcknowledged agentsR/W
~/.gemini/projects.jsonProject registry (maps project paths to short IDs)R/W
~/.gemini/installation_idInstallation identifierR/W
~/.agents/Global agents directoryR
~/.agents/skills/Agent skillsR

4.2 Project-Level Config Paths

PathPurposeR/W
.gemini/settings.jsonWorkspace settingsR
.gemini/memory.mdWorkspace memoryR
.gemini/system.mdCustom system promptR
.gemini/commands/Project commandsR
.gemini/skills/Project skillsR
.gemini/agents/Project agent definitionsR
.gemini/extensions/Extensions directoryR/W
.gemini/extensions/gemini-extension.jsonExtensions configR/W
.gemini/sandbox.DockerfileCustom sandbox DockerfileR
.gemini/sandbox.venv/Sandbox Python venvR/W
.gemini/.envEnvironment variables (preferred)R
.geminiignoreFile ignore patternsR
.envEnvironment variables (fallback)R
.agents/skills/Project agent skillsR

4.3 System/Enterprise Config Paths

PathPlatformPurpose
/Library/Application Support/GeminiCli/settings.jsonmacOSSystem settings
/Library/Application Support/GeminiCli/policies/macOSSystem policies
C:\ProgramData\gemini-cli\settings.jsonWindowsSystem settings
/etc/gemini-cli/settings.jsonLinuxSystem settings
/etc/gemini-cli/policies/LinuxSystem policies

Overridable via:

  • GEMINI_CLI_SYSTEM_SETTINGS_PATH
  • GEMINI_CLI_SYSTEM_DEFAULTS_PATH

4.4 Data & State Directories

PathPurposeR/W
~/.gemini/tmp/Global temp directoryR/W
~/.gemini/tmp/bin/Downloaded binaries (e.g., ripgrep)R/W
~/.gemini/tmp/<project-id>/Per-project temp directoryR/W
~/.gemini/tmp/<project-id>/checkpoints/Git checkpointsR/W
~/.gemini/tmp/<project-id>/logs/Project logsR/W
~/.gemini/tmp/<project-id>/plans/PlansR/W
~/.gemini/tmp/<project-id>/images/Clipboard images temp storageR/W
~/.gemini/tmp/<project-id>/shell_historyShell historyR/W
~/.gemini/history/Session history directoryR/W
~/.gemini/history/<project-id>/Per-project session historyR/W

4.5 Workspace Files Read

PathPurpose
.gemini/settings.jsonWorkspace settings
.gemini/memory.mdWorkspace memory
.gemini/system.mdCustom system prompt
.geminiignoreFile ignore patterns
.gitignoreGit ignore patterns (also used for file exclusion)
.git/logs/HEADWatched for branch name changes

4.6 Temp Directory Usage

Primary temp directory strategy:

typescript
// packages/core/src/utils/paths.ts
export function tmpdir(): string {
  return os.tmpdir();
}

The system temp directory (os.tmpdir()) is used for:

  • Test-related temp directories (via fs.mkdtemp(path.join(os.tmpdir(), ...)))
  • The macOS Seatbelt sandbox passes TMP_DIR as os.tmpdir() resolved path

Most persistent temp files go into ~/.gemini/tmp/ (NOT os.tmpdir()):

  • Per-project temp directories: ~/.gemini/tmp/<project-short-id>/
  • Downloaded binaries: ~/.gemini/tmp/bin/
  • Clipboard images, logs, plans, checkpoints

IDE server port file:

typescript
const portDir = path.join(tmpdir(), 'gemini', 'ide');
// File: gemini-ide-server-<ppid>-<port>.json

Podman auth file:

typescript
const emptyAuthFilePath = path.join(os.tmpdir(), 'empty_auth.json');
fs.writeFileSync(emptyAuthFilePath, '{}', 'utf-8');

.env File Search Order:

The .env file search walks up from cwd:

  1. <dir>/.gemini/.env (preferred)
  2. <dir>/.env
  3. Walks up to parent directories
  4. Falls back to ~/.gemini/.env
  5. Falls back to ~/.env

5. Tools Available to the LLM

The following tools/capabilities are available to the AI during agentic sessions:

ToolDescription
Shell command executionExecutes shell commands via PTY or child_process spawn
File read/write/editReads, writes, and edits files in the workspace via Node.js fs module
Ripgrep searchFile content searching via downloaded rg binary (cached in ~/.gemini/tmp/bin/rg)
Git operationsRepository detection, branch info, diff, status, checkpoint creation via simple-git and git spawn
Web fetchFetches arbitrary HTTP/HTTPS URLs (with private IP blocking) via web-fetch.ts
MCP toolsAny tools provided by configured MCP servers (stdio, SSE, HTTP transports)
Editor launchingCan spawn external editors (code, vim, emacs, etc.) for diff viewing

6. Host System Interactions

6.1 Subprocess Execution

Shell command execution (primary tool interaction):

The ShellExecutionService is the main mechanism for executing AI-requested shell commands. It supports two execution methods:

  1. PTY-based execution (preferred): Uses @lydell/node-pty or node-pty (optional dependencies) to spawn commands in a pseudo-terminal
  2. child_process fallback: Uses spawn() with ['bash', '-c', command] or equivalent
typescript
// packages/core/src/services/shellExecutionService.ts
const child = cpSpawn(executable, spawnArgs, {
  cwd,
  stdio: ['ignore', 'pipe', 'pipe'],
  shell: false,
  detached: !isWindows,
  env: {
    ...sanitizeEnvironment(process.env, sanitizationConfig),
    GEMINI_CLI: '1',
    TERM: 'xterm-256color',
    PAGER: 'cat',
    GIT_PAGER: 'cat',
  },
});

All shell executions set GEMINI_CLI=1 in the environment.

Ripgrep: Downloads and caches ripgrep binary to ~/.gemini/tmp/bin/rg. Falls back to system rg if available.

Git operations: Uses simple-git library and direct spawnAsync('git', ...) calls for repository detection, branch info, diff, status, and checkpoint creation (shadow git repos).

Editor launching: Can spawn external editors for diff viewing: GUI editors (code, vscodium, windsurf, cursor, zed, antigravity) and terminal editors (vim, neovim, emacs, hx).

Sandbox execution: Spawns one of: sandbox-exec (macOS Seatbelt) with .sb profile files, docker run ... (Docker container), or podman run ... (Podman container).

MCP Server launching: Uses StdioClientTransport from the MCP SDK to spawn MCP servers as child processes via their configured command and args.

Clipboard operations: On macOS, spawns osascript -e 'clipboard info' to check clipboard type and osascript -e '...' to save clipboard images. On Linux, spawns wl-paste or xclip depending on display server.

Browser launching: Uses the open npm package to launch URLs in the default browser for OAuth, documentation, bug reporting, extensions page, and DevTools UI. Also has a secure browser launcher that uses execFile (not exec) to avoid shell interpretation.

Process relaunch: Uses spawn(process.execPath, nodeArgs, ...) to relaunch itself.

Safety checker: Spawns safety checker processes via spawn(checkerPath, [], {...}).

6.2 Network Requests

Gemini API / Google AI endpoints:

The primary API interaction is through the @google/genai SDK (version 1.30.0):

  • Gemini API: generativelanguage.googleapis.com
  • Vertex AI: aiplatform.googleapis.com
  • Configurable via GOOGLE_GEMINI_BASE_URL and GOOGLE_VERTEX_BASE_URL

Code Assist endpoint:

typescript
// packages/core/src/code_assist/server.ts
export const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com';

Overridable via CODE_ASSIST_ENDPOINT environment variable.

Telemetry endpoints:

  1. Clearcut logging: https://play.googleapis.com/log?format=json&hasfast=true
  2. OpenTelemetry OTLP: Configurable via GEMINI_TELEMETRY_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_ENDPOINT
  3. Google Cloud Monitoring/Trace exporters (when using GCP telemetry target)

OAuth / User info:

  • Google OAuth2 authorization endpoint
  • https://www.googleapis.com/oauth2/v2/userinfo for user profile
  • https://codeassist.google.com/authcode for user-code auth redirect
  • https://developers.google.com/gemini-code-assist/auth_success_gemini (success redirect)
  • https://developers.google.com/gemini-code-assist/auth_failure_gemini (failure redirect)

Web fetch tool: The AI can fetch arbitrary HTTP/HTTPS URLs (with private IP blocking).

Update checks: Uses latest-version npm package to check for updates.

MCP server connections: Supports SSE, Streamable HTTP, and stdio transports for connecting to MCP servers.

Proxy support: HTTP proxy support via https-proxy-agent and environment variables: HTTPS_PROXY / https_proxy, HTTP_PROXY / http_proxy, NO_PROXY / no_proxy.

6.3 Port Binding

PortPurposeBound to
Random ephemeralOAuth callback server127.0.0.1 (or OAUTH_CALLBACK_HOST)
25417 (default)DevTools WebSocket server127.0.0.1
Random ephemeralVSCode IDE Companion HTTP server127.0.0.1
8877Sandbox proxy (when GEMINI_SANDBOX_PROXY_COMMAND set)localhost
41242A2A server (default from config)localhost

6.4 Browser Launching

Uses the open npm package to launch URLs in the default browser for:

  • OAuth authentication
  • Documentation (/docs command)
  • Bug reporting (/bug command)
  • Extensions page (/extensions command)
  • DevTools UI

Also has a secure browser launcher at packages/core/src/utils/secure-browser-launcher.ts that uses execFile (not exec) to avoid shell interpretation.

6.5 Clipboard Access

Full clipboard integration:

  • Text read/write: via clipboardy npm package (or OSC 52 sequence for remote sessions)
  • Image read: platform-specific (osascript on macOS, PowerShell on Windows, wl-paste/xclip on Linux)
  • Image save: Saves clipboard images to ~/.gemini/tmp/<project-id>/images/

6.6 File System Watchers

typescript
// packages/cli/src/ui/hooks/useGitBranchName.ts
watcher = fs.watch(gitLogsHeadPath, (eventType: string) => { ... });

Watches .git/logs/HEAD to detect branch name changes in real-time.

6.7 Other

System information: Uses systeminformation package for system info gathering.

Process signal handling: Handles SIGINT/SIGTERM for graceful shutdown.

DNS resolution: Standard Node.js dns module (implicit).

7. Extension Points

7.1 Hook/Lifecycle System

None identified.

7.2 Plugin/Extension Architecture

  • Extensions directory: .gemini/extensions/ with gemini-extension.json config
  • Custom commands: User-defined commands in ~/.gemini/commands/ and .gemini/commands/
  • Skills: User-defined skills in ~/.gemini/skills/ and .gemini/skills/
  • Agents: User agent definitions in ~/.gemini/agents/ and .gemini/agents/
  • Policies: User policies (TOML) in ~/.gemini/policies/ and system-level policies

7.3 MCP Integration

Uses @modelcontextprotocol/sdk for MCP server connections:

  • Stdio transport -- Spawns MCP server processes as child processes
  • SSE transport -- Connects to HTTP-based MCP servers
  • Streamable HTTP transport -- For newer HTTP protocol
  • MCP OAuth -- Token storage via keychain or encrypted file

7.4 Custom Commands/Skills/Agents

  • Custom commands in ~/.gemini/commands/ and .gemini/commands/
  • Custom skills in ~/.gemini/skills/ and .gemini/skills/
  • Agent definitions in ~/.gemini/agents/, .gemini/agents/, ~/.agents/
  • Custom system prompt via .gemini/system.md
  • Memory files: ~/.gemini/memory.md and .gemini/memory.md

7.5 SDK/API Surface

  • A2A Server (@google/gemini-cli-a2a-server) -- HTTP server for Agent-to-Agent protocol
  • VSCode IDE Companion (gemini-cli-vscode-ide-companion) -- Local HTTP server for IDE integration
  • DevTools service -- WebSocket server for development tools integration

8. Sandbox & Security Model

8.1 Built-in Sandboxing

Gemini CLI has three built-in sandbox mechanisms:

a. macOS Seatbelt (sandbox-exec):

On macOS, Seatbelt is the default sandbox when sandbox-exec is available. Six built-in profiles:

ProfileDescription
permissive-openDefault. Permissive with network access
permissive-closedPermissive without network access
permissive-proxiedPermissive with proxy-only network
restrictive-openRestrictive with network access
restrictive-closedRestrictive without network access
restrictive-proxiedRestrictive with proxy-only network

Profile files: packages/cli/src/utils/sandbox-macos-*.sb

Variables passed to sandbox profiles:

  • TARGET_DIR - current working directory
  • TMP_DIR - system temp directory
  • HOME_DIR - user home directory
  • CACHE_DIR - Darwin user cache directory
  • INCLUDE_DIR_0 through INCLUDE_DIR_4 - additional workspace directories

Configurable via:

  • SEATBELT_PROFILE env var
  • Custom .sb files in .gemini/ directory

b. Docker:

Container sandbox using Docker. Mounts:

  • Working directory
  • ~/.gemini/ settings directory
  • os.tmpdir() temp directory
  • Home directory
  • ~/.config/gcloud/ (read-only, if exists)
  • GOOGLE_APPLICATION_CREDENTIALS file (read-only)
  • Additional mounts from SANDBOX_MOUNTS env var

c. Podman:

Same as Docker but using Podman runtime.

The root package.json references a sandbox Docker image:

json
"config": {
  "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.30.0-nightly.20260210.a2174751d"
}

8.2 Permission System

N/A -- Gemini CLI relies on its sandbox mechanisms rather than a granular permission system for individual tool calls.

8.3 Safety Mechanisms

Environment Variable Sanitization:

Shell commands spawned by the AI have their environment sanitized to prevent credential leakage:

  • Always allowed: PATH, HOME, SHELL, TMPDIR, USER, LANG, etc.
  • Always blocked: Variables matching patterns like TOKEN, SECRET, PASSWORD, KEY, AUTH, CREDENTIAL
  • Value-pattern blocked: PEM keys, JWT tokens, GitHub PATs, AWS keys, etc.

Safety checker: Spawns safety checker processes for content moderation.

Private IP blocking: Web fetch tool blocks access to private IP addresses.

8.4 Known Vulnerabilities

None identified.

8.5 Enterprise/Managed Security Controls

System-level settings and policies:

  • /Library/Application Support/GeminiCli/settings.json (macOS)
  • /Library/Application Support/GeminiCli/policies/ (macOS)
  • /etc/gemini-cli/settings.json (Linux)
  • /etc/gemini-cli/policies/ (Linux)
  • C:\ProgramData\gemini-cli\settings.json (Windows)

9. Key Dependencies

From packages/cli/package.json:

DependencySystem Impact
ink (@jrichman/ink@6.4.10)Terminal UI rendering (raw mode, alternate screen buffer)
clipboardySystem clipboard read/write
openLaunches default browser
wsWebSocket client (DevTools)
dotenvReads .env files
shell-quoteShell command parsing/quoting
command-existsChecks if commands exist on PATH
extract-zipZip extraction (for ripgrep download)
tarTar extraction
undiciHTTP client

From packages/core/package.json:

DependencySystem Impact
google-auth-libraryGoogle OAuth2, ADC, Compute auth
@google/genaiGemini API SDK (network requests)
@modelcontextprotocol/sdkMCP server stdio/SSE/HTTP transport (spawns processes)
keytar (optional)macOS Keychain / Linux Secret Service / Windows Credential Manager
@lydell/node-pty (optional)Pseudo-terminal for shell commands
node-pty (optional)Alternative PTY implementation
simple-gitGit operations
@joshua.litt/get-ripgrepDownloads ripgrep binary
systeminformationSystem info gathering
web-tree-sitterCode parsing (may access WASM files)
@xterm/headlessTerminal emulation for command output
openBrowser launching
https-proxy-agentHTTP proxy support
@google-cloud/loggingGCP logging
@opentelemetry/*Telemetry collection and export
fdirFast directory traversal

10. Environment Variables

Auth & API

VariableUsage
GEMINI_API_KEYGemini API key
GOOGLE_API_KEYGoogle API key (Vertex express)
GOOGLE_CLOUD_PROJECTGCP project ID
GOOGLE_CLOUD_LOCATIONGCP location
GOOGLE_APPLICATION_CREDENTIALSPath to ADC key file
GOOGLE_CLOUD_ACCESS_TOKENDirect access token
GOOGLE_GENAI_USE_GCAUse Google Code Assist
GOOGLE_GENAI_USE_VERTEXAIUse Vertex AI
GOOGLE_GEMINI_BASE_URLCustom Gemini API base URL
GOOGLE_VERTEX_BASE_URLCustom Vertex AI base URL
CODE_ASSIST_ENDPOINTCustom Code Assist endpoint

Sandbox

VariableUsage
GEMINI_SANDBOXSandbox mode: false, true, docker, podman, sandbox-exec
SANDBOXSet inside sandbox to container name (sentinel: if set, don't re-sandbox)
SEATBELT_PROFILEmacOS Seatbelt profile name
GEMINI_SANDBOX_IMAGECustom sandbox Docker image
GEMINI_SANDBOX_PROXY_COMMANDProxy command for sandbox
SANDBOX_FLAGSAdditional Docker/Podman flags
SANDBOX_MOUNTSAdditional volume mounts (comma-separated from:to:opts)
SANDBOX_ENVAdditional env vars for sandbox (comma-separated key=value)
SANDBOX_SET_UID_GIDForce UID/GID mapping in container
BUILD_SANDBOXBuild sandbox image from source

Telemetry

VariableUsage
GEMINI_TELEMETRY_ENABLEDEnable/disable telemetry
GEMINI_TELEMETRY_TARGETTelemetry target (e.g., gcp)
GEMINI_TELEMETRY_OTLP_ENDPOINTOTLP endpoint URL
GEMINI_TELEMETRY_OTLP_PROTOCOLOTLP protocol
GEMINI_TELEMETRY_LOG_PROMPTSLog prompt content
GEMINI_TELEMETRY_OUTFILETelemetry output file path
GEMINI_TELEMETRY_USE_COLLECTORUse collector
OTEL_EXPORTER_OTLP_ENDPOINTStandard OTLP endpoint fallback

Configuration

VariableUsage
GEMINI_CLI_HOMEOverride home directory
GEMINI_CLI_SYSTEM_SETTINGS_PATHOverride system settings path
GEMINI_CLI_SYSTEM_DEFAULTS_PATHOverride system defaults path
GEMINI_MODELOverride model selection
GEMINI_FOLDER_TRUSTTrust current folder
GEMINI_YOLO_MODEAuto-approve all tool calls
GEMINI_FORCE_FILE_STORAGEForce file-based token storage
FORCE_ENCRYPTED_FILEUse encrypted storage for OAuth credentials

OAuth

VariableUsage
NO_BROWSERSuppress browser launch for OAuth
OAUTH_CALLBACK_HOSTOverride OAuth callback bind address (default 127.0.0.1)
OAUTH_CALLBACK_PORTOverride OAuth callback port

IDE Integration

VariableUsage
GEMINI_CLI_IDE_SERVER_PORTIDE companion server port
GEMINI_CLI_IDE_WORKSPACE_PATHIDE workspace path
GEMINI_CLI_IDE_AUTH_TOKENIDE auth token
TERM_PROGRAMTerminal program detection

Proxy

VariableUsage
HTTPS_PROXY / https_proxyHTTPS proxy URL
HTTP_PROXY / http_proxyHTTP proxy URL
NO_PROXY / no_proxyProxy bypass list

Misc

VariableUsage
DEBUGEnable debug mode
DEBUG_PORTDebug port for Node.js inspector
BROWSERBrowser override (blocklist check)
CLOUD_SHELLGoogle Cloud Shell detection
GEMINI_CLI_ACTIVITY_LOG_TARGETActivity logging output path
GEMINI_CLI_INTEGRATION_TESTIntegration test mode

11. Summary Tables

11.1 All Filesystem Paths Accessed

PathAccessPurposeCreated by Agent?
~/.gemini/R/WMain config directoryYes
~/.gemini/settings.jsonR/WUser settingsYes
~/.gemini/oauth_creds.jsonR/WOAuth credentials (legacy)Yes
~/.gemini/mcp-oauth-tokens-v2.jsonR/WEncrypted MCP tokensYes
~/.gemini/google_accounts.jsonR/WGoogle account cacheYes
~/.gemini/installation_idR/WInstallation IDYes
~/.gemini/memory.mdR/WGlobal memoryYes
~/.gemini/projects.jsonR/WProject registryYes
~/.gemini/tmp/**R/WTemp data, downloaded binariesYes
~/.gemini/history/**R/WSession historyYes
~/.gemini/commands/RCustom commandsNo
~/.gemini/skills/RCustom skillsNo
~/.gemini/agents/RCustom agentsNo
~/.gemini/policies/RCustom policiesNo
~/.agents/RAgent definitionsNo
<cwd>/.gemini/R/WWorkspace configNo
<cwd>/.geminiignoreRIgnore patternsNo
<cwd>/.envREnvironment variablesNo
/Library/Application Support/GeminiCli/RSystem settings (macOS)No
/etc/gemini-cli/RSystem settings (Linux)No
/tmp/gemini/ide/R/WIDE server port filesYes
~/.config/gcloud/RGCloud configNo
macOS KeychainR/WOAuth tokens (via keytar)Yes

11.2 All Network Endpoints

EndpointPurposeWhen Triggered
generativelanguage.googleapis.comGemini APILLM requests (configurable via GOOGLE_GEMINI_BASE_URL)
aiplatform.googleapis.comVertex AILLM requests (configurable via GOOGLE_VERTEX_BASE_URL)
cloudcode-pa.googleapis.comCode AssistCode Assist requests (configurable via CODE_ASSIST_ENDPOINT)
accounts.google.comOAuth2 authorizationOAuth flow
oauth2.googleapis.comOAuth2 token exchangeOAuth flow
www.googleapis.com/oauth2/v2/userinfoUser infoAfter OAuth
play.googleapis.com/logClearcut telemetryTelemetry events
Configurable OTLP endpointOpenTelemetryTelemetry events (configurable via GEMINI_TELEMETRY_OTLP_ENDPOINT)
developers.google.com/gemini-code-assist/auth_*Auth redirectOAuth flow
codeassist.google.com/authcodeUser-code authOAuth flow
registry.npmjs.orgUpdate checksOn startup
Arbitrary HTTP/HTTPS URLsWeb fetch toolAI-driven web fetch
MCP server URLsSSE/HTTP MCP transportsMCP communication

11.3 All System Interactions

TypeMechanismDetails
Shell command executionnode-pty / child_process spawnAI-triggered, env sanitized, GEMINI_CLI=1 set
File read/write/editNode.js fs moduleAI-triggered
Git operationssimple-git / spawn gitAI-triggered
Gemini API calls@google/genai SDKImplicit on every prompt
Code Assist API callsgoogle-auth-library HTTPImplicit
Web page fetchingundici/fetchAI-triggered, private IPs blocked
MCP server launch@modelcontextprotocol/sdk stdioConfig-driven
Browser launch (OAuth)open npm packageUser-triggered
Browser launch (docs/bug)open npm packageUser-triggered
Clipboard read/writeclipboardy / osascriptUser-triggered
Keychain accesskeytarImplicit on auth
Telemetry HTTP POSTClearcut / OTLPImplicit
DevTools WebSocketwsOpt-in
Sandbox container launchdocker/podman/sandbox-execConfig-driven
Ripgrep downloadHTTP fetchOn first grep
Editor launchspawn (code/vim/etc)AI-triggered (diff review)
Port bindingnet.createServerOAuth, IDE companion, A2A server
fs.watchNode.js fs.git/logs/HEAD monitoring
System infosysteminformationImplicit
Process signal handlingprocess.kill, SIGINT/SIGTERMImplicit
DNS resolutionNode.js dnsImplicit

12. Sandboxing Recommendations

  1. Use built-in sandboxing -- Gemini CLI already provides macOS Seatbelt, Docker, and Podman sandboxes. Enable the appropriate one for the deployment environment.
  2. Prefer restrictive profiles -- Use restrictive-closed or restrictive-proxied Seatbelt profiles instead of the default permissive-open for higher security.
  3. Network restrictions -- The permissive-open default allows all network access. Use *-closed or *-proxied profiles to restrict AI-driven network requests.
  4. Protect credentials -- Keychain/encrypted file tokens and OAuth credentials are accessible; ensure sandbox restricts access to ~/.gemini/oauth_creds.json and keychain from AI-spawned processes.
  5. Environment sanitization is good but not perfect -- The built-in env sanitization blocks many credential patterns but relies on pattern matching; custom credentials with non-standard names may leak.
  6. Control web fetch -- The web fetch tool blocks private IPs but allows arbitrary public URLs; consider restricting further in sensitive environments.
  7. MCP server audit -- MCP servers are spawned as child processes with their own environment; audit configured servers and their permissions.
  8. Restrict clipboard access -- Clipboard operations use platform-specific tools (osascript, xclip); sandbox should control access to these.
  9. Limit port binding -- OAuth callback, DevTools, IDE companion, and A2A server all bind ports; restrict to only what is needed.
  10. Telemetry -- Clearcut and OTLP telemetry send data to Google endpoints; block if not desired with GEMINI_TELEMETRY_ENABLED=false.

Open source under the Apache 2.0 License.