# https://github.com/google-gemini/gemini-cli 项目说明书

生成时间：2026-05-16 02:07:33 UTC

## 目录

- [Architecture Overview](#architecture-overview)
- [Agent System](#agent-system)
- [Context and Memory Management](#context-pipeline)
- [Tools Reference](#tools-reference)
- [MCP Integration](#mcp-integration)
- [Skills and Extensions](#skills-extensions)
- [Sandboxing and Security](#sandboxing-security)
- [Policy Engine](#policy-engine)
- [Terminal UI Components](#terminal-ui)
- [Session Management](#session-management)

<a id='architecture-overview'></a>

## Architecture Overview

### 相关页面

相关主题：[Agent System](#agent-system), [Context and Memory Management](#context-pipeline)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx)
- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)
- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)
- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)
- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)
- [packages/core/src/skills/builtin/skill-creator/SKILL.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/builtin/skill-creator/SKILL.md)
- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)
- [packages/core/src/agents/skill-extraction-agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/skill-extraction-agent.ts)
- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)
- [packages/core/src/agents/cli-help-agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/cli-help-agent.ts)
- [packages/cli/src/commands/extensions/examples/policies/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/commands/extensions/examples/policies/README.md)
- [packages/cli/src/ui/components/views/ExtensionDetails.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/views/ExtensionDetails.tsx)
- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)
- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)
</details>

# Architecture Overview

Gemini CLI is Google's official command-line interface for Gemini, designed to enable developers to interact with AI models directly from their terminal. The architecture follows a modular, package-based design that separates concerns between the core AI processing engine, the CLI interface, and an optional A2A server component.

## Package Structure

The repository is organized into three primary packages under the `packages/` directory:

| Package | Purpose | Key Responsibilities |
|---------|---------|---------------------|
| `packages/core` | Core AI engine | Agents, skills, context management, chat recording |
| `packages/cli` | Terminal interface | UI components, commands, authentication, user interactions |
| `packages/a2a-server` | Protocol server | Agent-to-Agent communication protocol support |

资料来源：[README.md:1-50](https://github.com/google-gemini/gemini-cli/blob/main/README.md)

## System Architecture

```mermaid
graph TD
    subgraph "CLI Layer (packages/cli)"
        UI[UI Components]
        AUTH[Auth Dialog]
        CMDS[Commands]
        EXT[Extensions]
    end
    
    subgraph "Core Layer (packages/core)"
        AGENTS[Agent System]
        SKILLS[Skills Engine]
        CONTEXT[Context Graph]
        RECORDING[Chat Recording]
    end
    
    subgraph "External"
        GEMINI_API[Gemini API]
        MCP[MCP Servers]
        FS[File System]
    end
    
    UI --> AGENTS
    AUTH --> AGENTS
    CMDS --> AGENTS
    EXT --> AGENTS
    AGENTS --> SKILLS
    AGENTS --> CONTEXT
    AGENTS --> RECORDING
    AGENTS --> GEMINI_API
    SKILLS --> MCP
    SKILLS --> FS
    CONTEXT --> FS
```

## Core Package Architecture

### Agents System

The agent system forms the brain of Gemini CLI. The core package implements multiple specialized agents:

#### CLI Help Agent

The `CliHelpAgent` provides contextual assistance about Gemini CLI features, configuration, and current state. It operates as an expert system that can retrieve internal documentation and provide precise answers.

```typescript
// Agent configuration and runtime context
const CLI_HELP_AGENT_SYSTEM_PROMPT = `**CLI Help Agent**, an expert on Gemini CLI. Your purpose is to provide accurate information about Gemini CLI's features, configuration, and current state.

### Runtime Context
- **CLI Version:** ${cliVersion}
- **Active Model:** ${activeModel}
- **Today's Date:** ${today}

### Instructions
1. **Explore Documentation**: Use the \`get_internal_docs\` tool to find answers.
2. **Be Precise**: Use the provided runtime context and documentation.
3. **Cite Sources**: Include specific documentation files in your report.
4. **Non-Interactive**: Answer as best you can with available information.
```

资料来源：[packages/core/src/agents/cli-help-agent.ts:1-30](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/cli-help-agent.ts)

#### Skill Extraction Agent

The `SkillExtractionAgent` enables dynamic skill creation. It processes user interactions and extracts patterns that can be converted into reusable skills. The agent uses a patch-based format for creating skill files:

```typescript
// Patch format for skill creation
const PATCH_FORMAT = `
1. Update an existing file:

     --- /absolute/path/to/target.md
     +++ /absolute/path/to/target.md
     @@ -<start>,<count> +<newStart>,<newCount> @@
     <unchanged context line>
    -<removed line>
    +<added line>

2. Create a brand-new file (no existing target):

     --- /dev/null
     +++ /absolute/path/to/new-target.md
     @@ -0,0 +1,<count> @@
`;
```

资料来源：[packages/core/src/agents/skill-extraction-agent.ts:1-50](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/skill-extraction-agent.ts)

### Context Graph System

The context graph manages conversation history and session state. It builds a structured representation of the conversation with stable identifiers for each message turn.

```mermaid
graph TD
    subgraph "Context Building"
        HIST[History Array] --> TURN[For Each Turn]
        TURN --> HASH[Generate MD5 Hash]
        HASH --> SALT[Add Turn Salt]
        SALT --> ID[Stable ID Generation]
    end
    
    subgraph "Message Processing"
        MSG[Message] --> ROLE{Message Role}
        ROLE -->|user| USER[User Turn]
        ROLE -->|model| MODEL[Model Turn]
        USER --> PARTS[Process Parts]
        MODEL --> PARTS
    end
```

Key features of the context graph:

- **Stable ID Generation**: Uses MD5 hashing combined with turn salt for deterministic message identification
- **Legacy Header Handling**: Skips legacy environment headers automatically
- **Role-based Processing**: Differentiates between user and model messages

资料来源：[packages/core/src/context/graph/toGraph.ts:1-60](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)

### Skills Engine

The skills system provides extensible capabilities through a standardized structure:

```
skill-name/
├── SKILL.md           # Required: Frontmatter + Instructions
├── REFERENCE.md       # Optional: Loaded on demand
├── EXAMPLES.md        # Optional: Common patterns
├── FORMS.md           # Optional: User input forms
├── scripts/           # Executable code (Node.js/Python/Bash)
└── references/        # Domain-specific documentation
```

#### SKILL.md Structure

Every skill requires a `SKILL.md` file with YAML frontmatter:

```yaml
---
name: skill-name
description: Clear description of when this skill should be used
---
# Skill body with instructions
```

#### Organization Patterns

**Pattern 1: Flat Organization**
Simple skills with related files in a single directory.

**Pattern 2: Domain-specific Organization**
For multi-domain skills, organize by domain:
```
cloud-deploy/
├── SKILL.md
└── references/
    ├── aws.md
    ├── gcp.md
    └── azure.md
```

**Pattern 3: Conditional Details**
Basic content with links to advanced topics loaded only when needed.

资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md:1-100](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/builtin/skill-creator/SKILL.md)

### Chat Recording Service

The `ChatRecordingService` persists conversation history and metadata:

```typescript
interface ConversationRecord {
  sessionId: string;
  projectHash: string;
  startTime: string;
  lastUpdated: string;
  summary?: string;
  memoryScratchpad?: string;
  directories: string[];
  kind: string;
  messages: Message[];
  messageCount: number;
  userMessageCount: number;
  memoryScratchpadIsStale?: boolean;
  firstUserMessage?: string;
  hasUserOrAssistantMessage: boolean;
}
```

The service manages:
- Session persistence to JSONL files
- Message loading with metadata filtering
- Memory scratchpad tracking with freshness indicators

资料来源：[packages/core/src/services/chatRecordingService.ts:1-100](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)

## CLI Package Architecture

### UI Component System

The CLI package implements a terminal-based UI using a custom component system:

```mermaid
graph TD
    APP[AppHeader] --> CONTENT[Main Content Area]
    CONTENT --> ABOUT[AboutBox]
    CONTENT --> MODEL[ModelDialog]
    CONTENT --> AUTH[AuthDialog]
    CONTENT --> TRUST[FolderTrustDialog]
    CONTENT --> EXT[ExtensionDetails]
    
    subgraph "Privacy System"
        PRIVACY[Privacy Notices]
        PRIVACY --> GEMINI[GeminiPrivacyNotice]
        PRIVACY --> CLOUD_FREE[CloudFreePrivacyNotice]
    end
```

#### AppHeader Component

Displays application state including version, update status, and user identity:

```typescript
const AppHeader = (config: Config, {
  showDetails,
  isNarrow,
  terminalWidth
}: HeaderProps) => (
  <Box flexDirection="column">
    {/* Version info */}
    <Text bold>Gemini CLI</Text>
    <Text>v{version}</Text>
    
    {/* Update indicator */}
    {updateInfo?.isUpdating && (
      <Text><CliSpinner /> Updating</Text>
    )}
    
    {/* User identity (if enabled) */}
    <UserIdentity config={config} />
  </Box>
);
```

资料来源：[packages/cli/src/ui/components/AppHeader.tsx:1-50](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)

#### AboutBox Component

Displays system information:
- CLI Version
- Git Commit (if available)
- Model Version
- Sandbox Environment
- Operating System

资料来源：[packages/cli/src/ui/components/AboutBox.tsx:1-60](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)

#### Authentication Dialog

Handles user authentication with multiple options:

```typescript
const authOptions = [
  { label: 'Sign in with Google', value: 'google' },
  { label: 'Continue without signing in', value: 'anonymous' },
  { label: 'Use API Key', value: 'api_key' }
];
```

The dialog supports:
- OAuth flow with automatic CLI restart
- Anonymous mode
- Direct API key authentication

资料来源：[packages/cli/src/ui/auth/AuthDialog.tsx:1-80](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)

### Extension System

Extensions provide a plugin mechanism for extending Gemini CLI functionality:

```mermaid
graph TD
    EXT[Extension] --> MANIFEST[gemini-extension.json]
    EXT --> POLICIES[policies/]
    EXT --> COMMANDS[commands/]
    EXT --> HOOKS[hooks/]
    EXT --> SKILLS[skills/]
    EXT --> MCP[mcpServers/]
```

#### Extension Manifest Structure

```json
{
  "name": "extension-name",
  "version": "1.0.0",
  "description": "Extension description",
  "hasMCP": true,
  "hasContext": true,
  "hasHooks": true,
  "hasSkills": true,
  "hasCustomCommands": true
}
```

#### Policy Engine

Extensions can contribute security rules through TOML policy files:

```toml
# Example policy
[[rules]]
type = "confirm"
command = "rm -rf"
message = "This will permanently delete files"
```

Security features:
- Extensions can only add restrictions (not bypass them)
- `allow` decisions and `yolo` mode from extensions are ignored
- Custom safety checkers for file path validation

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-60](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/commands/extensions/examples/policies/README.md)

### Privacy System

#### Privacy Notices

Two privacy notice types exist based on user tier:

| Notice Type | Target Users | Data Usage |
|------------|--------------|------------|
| `GeminiPrivacyNotice` | API Terms users | Google AI Studio terms |
| `CloudFreePrivacyNotice` | Free tier users | Limited collection with opt-in |

#### Data Collection Options

```typescript
interface PrivacyState {
  dataCollectionOptIn: boolean;
}

// Options presented to users:
// [0] Allow Google to use data
// [1] Don't allow
```

For free tier users:
- Human reviewers may read and annotate data
- Data is disconnected from Google Account
- Retained for up to 18 months

资料来源：[packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx:1-50](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx)

### Folder Trust System

The folder trust dialog provides security boundaries for project configurations:

```typescript
interface TrustConfig {
  customCommands: boolean;
  hooks: boolean;
  mcpServers: boolean;
  agentSkills: boolean;
  settings: boolean;
}
```

Components discovered and displayed:
- Custom commands (`commands/`)
- Hooks (`hooks/`)
- MCP servers (`mcpServers/`)
- Agent skills (`skills/`)
- Settings (`settings/`)

资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:1-60](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)

### Model Selection

The `ModelDialog` component allows users to:
- View available models
- See quota information
- Select a specific model for the session

Quota buckets are displayed with available width calculation for responsive layout.

资料来源：[packages/cli/src/ui/components/ModelDialog.tsx:1-50](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)

## Extension Details View

Displays information about available extensions:

```typescript
interface ExtensionInfo {
  extensionVersion?: string;
  stars: number;
  isGoogleOwned: boolean;
  fullName: string;
  extensionDescription?: string;
  repoDescription?: string;
  hasMCP: boolean;
  hasContext: boolean;
  hasHooks: boolean;
  hasSkills: boolean;
  hasCustomCommands: boolean;
}
```

Feature badges with color coding:
- **MCP** (Primary)
- **Context file** (Error)
- **Hooks** (Warning)
- **Skills** (Success)
- **Commands** (Primary)

资料来源：[packages/cli/src/ui/components/views/ExtensionDetails.tsx:1-80](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/views/ExtensionDetails.tsx)

## Installation and Release Channels

Gemini CLI supports multiple installation methods:

| Method | Command |
|--------|---------|
| npm global | `npm install -g @google/gemini-cli` |
| Homebrew | `brew install gemini-cli` |
| MacPorts | `sudo port install gemini-cli` |
| Anaconda | Create nodejs environment, then npm install |

### Release Channels

| Channel | Schedule | Description |
|---------|----------|-------------|
| Preview | Weekly (Tue 23:59 UTC) | Untested preview builds |
| Stable | Weekly (Tue 20:00 UTC) | Promoted preview + fixes |
| Nightly | Daily (00:00 UTC) | Main branch snapshot |

资料来源：[README.md:100-150](https://github.com/google-gemini/gemini-cli/blob/main/README.md)

## Key Features Integration

### GitHub Integration

Gemini CLI integrates with GitHub through the [Gemini CLI GitHub Action](https://github.com/google-github-actions/run-gemini-cli), enabling CI/CD workflow automation.

### Multimodal Capabilities

The CLI supports processing of:
- PDFs
- Images
- Sketches

These inputs can be used for code generation and understanding tasks.

### Checkpointing

Conversations can be saved and resumed, enabling:
- Session persistence across CLI restarts
- Memory scratchpad with staleness tracking
- Project-specific context preservation

### MCP Server Support

Model Context Protocol servers extend capabilities with:
- Media generation (Imagen, Veo, Lyria)
- Custom tool integrations
- External service connections

## Summary

The Gemini CLI architecture demonstrates a well-separated design:

1. **Core Package**: Handles AI processing, skills management, and conversation state
2. **CLI Package**: Manages terminal UI, authentication, and user interactions  
3. **A2A Server**: Enables agent-to-agent communication protocols

The modular design allows each layer to be developed and tested independently while maintaining clean interfaces between components. Extensions provide a safe, sandboxed mechanism for users to customize behavior without compromising core security boundaries.

---

<a id='agent-system'></a>

## Agent System

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Tools Reference](#tools-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/src/agent/agent-session.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agent/agent-session.ts)
- [packages/core/src/agents/agent-scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/agent-scheduler.ts)
- [packages/core/src/scheduler/scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/scheduler.ts)
- [packages/core/src/scheduler/tool-executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/tool-executor.ts)
- [packages/a2a-server/src/agent/executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/a2a-server/src/agent/executor.ts)
- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)
- [packages/core/src/agents/cli-help-agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/cli-help-agent.ts)
- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)
</details>

# Agent System

## 概述

The Agent System is the core execution engine of Gemini CLI, responsible for orchestrating interactions between Large Language Models (LLMs), tools, and user interactions. It provides a comprehensive framework for managing agent lifecycles, scheduling tasks, executing tools, and maintaining conversation context across sessions.

The agent system is designed with modularity and extensibility in mind, supporting multiple agent types, custom skills, and MCP (Model Context Protocol) server integrations. It handles everything from initial prompt processing to final response delivery, including tool execution, policy enforcement, and checkpoint management.

At its core, the system follows a message-based architecture where agents communicate through well-defined interfaces, enabling loose coupling between components while maintaining tight integration for complex workflows. The scheduler coordinates execution across multiple agents, while the tool executor provides a safe sandbox environment for running external operations.

## 核心架构

The Agent System consists of five primary components that work together to provide a complete agent execution environment. Each component has distinct responsibilities and interacts with others through well-defined APIs.

```mermaid
graph TD
    A[User Input] --> B[AgentSession]
    B --> C[AgentScheduler]
    C --> D[Scheduler]
    D --> E[ToolExecutor]
    E --> F[External Tools & MCP Servers]
    D --> G[LLM API]
    G --> B
    H[ContextGraph] --> B
    I[ChatRecordingService] --> B
```

### 组件职责矩阵

| 组件 | 包路径 | 主要职责 |
|------|--------|----------|
| **AgentSession** | `packages/core/src/agent/` | 会话生命周期管理，消息历史维护 |
| **AgentScheduler** | `packages/core/src/agents/` | 多代理协调，任务分发 |
| **Scheduler** | `packages/core/src/scheduler/` | 执行调度，队列管理 |
| **ToolExecutor** | `packages/core/src/scheduler/` | 工具执行，沙箱环境 |
| **A2AExecutor** | `packages/a2a-server/src/agent/` | Agent-to-Agent通信协议 |

## AgentSession (会话管理)

### 概述

The `AgentSession` class is the central hub for managing individual agent sessions. It maintains conversation history, handles turn-taking between user and model, and coordinates with various services for persistence and context management. Each session is identified by a unique `sessionId` that allows for resumption and checkpointing.

The session class implements the `getStableId` function for generating deterministic identifiers for message turns, using MD5 hashing combined with occurrence tracking to ensure uniqueness even when duplicate messages appear in the conversation history. This is particularly important for maintaining consistent context across session resumption operations.

### 核心数据结构

```typescript
interface ConversationRecord {
  sessionId: string;
  projectHash: string;
  startTime: string;
  lastUpdated: string;
  summary?: string;
  memoryScratchpad?: string;
  directories?: string[];
  kind: 'cli' | 'api';
  messages: Message[];
  messageCount: number;
  userMessageCount: number;
  memoryScratchpadIsStale?: boolean;
  firstUserMessage?: string;
  hasUserOrAssistantMessage: boolean;
}
```

资料来源：[packages/core/src/services/chatRecordingService.ts:1-50](packages/core/src/services/chatRecordingService.ts)

### 会话ID生成机制

The session uses a stable ID generation mechanism that creates deterministic identifiers based on message content and role. The algorithm generates an MD5 hash of the turn content and combines it with an occurrence counter to handle duplicate messages:

```typescript
const turnContent = JSON.stringify(msg.parts);
const h = createHash('md5')
  .update(`${msg.role}:${turnContent}`)
  .digest('hex');
const occurrence = (seenHashes.get(h) || 0) + 1;
seenHashes.set(h, occurrence);
const turnSalt = `${h}_${occurrence}`;
```

资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)

### 配置管理

The session integrates with the configuration system to access runtime settings:

```typescript
getExperimentalDynamicModelConfiguration(): boolean {
  return this.dynamicModelConfiguration;
}

getPendingIncludeDirectories(): string[] {
  return this.pendingIncludeDirectories;
}

clearPendingIncludeDirectories(): void {
  this.pendingIncludeDirectories = [];
}
```

资料来源：[packages/core/src/config/config.ts:1-100](packages/core/src/config/config.ts)

## AgentScheduler (代理调度)

### 概述

The `AgentScheduler` is responsible for coordinating multiple agents within the system. It manages agent registration, task distribution, and result aggregation. When multiple agents are involved in a workflow, the scheduler determines execution order and handles inter-agent communication.

The scheduler supports both sequential and parallel agent execution modes, allowing complex workflows to be composed from simpler agent tasks. It maintains a registry of available agents and their capabilities, enabling dynamic routing of requests to appropriate agents.

### 内置代理类型

The system includes several built-in agents for common tasks:

| 代理名称 | 源文件 | 功能描述 |
|----------|--------|----------|
| **CLI Help Agent** | `cli-help-agent.ts` | 提供CLI文档和帮助信息 |
| **Policy Agent** | - | 安全策略执行 |
| **Skill Agent** | - | 自定义技能执行 |

### CLI Help Agent 实现

The CLI Help Agent is a specialized agent that provides accurate information about Gemini CLI features, configuration, and current state:

```typescript
const SYSTEM_INSTRUCTION = `You are the **CLI Help Agent**, an expert on Gemini CLI. Your purpose is to provide accurate information about Gemini CLI's features, configuration, and current state.

### Runtime Context
- **CLI Version:** ${cliVersion}
- **Active Model:** ${activeModel}
- **Today's Date:** ${today}

### Instructions
1. **Explore Documentation**: Use the \`get_internal_docs\` tool to find answers.
2. **Be Precise**: Use the provided runtime context and documentation.
3. **Cite Sources**: Include specific documentation files used.
4. **Non-Interactive**: Operate in a loop without user interaction.`;
```

资料来源：[packages/core/src/agents/cli-help-agent.ts:1-30](packages/core/src/agents/cli-help-agent.ts)

### 代理注册流程

Agents register with the scheduler using a standard interface that includes system instructions, available tools, and configuration options. The scheduler maintains agent metadata including version, capabilities, and current status.

## Scheduler (任务调度)

### 概述

The `Scheduler` component is responsible for managing the execution queue of tasks within an agent session. It handles turn orchestration, message processing, and response streaming. The scheduler coordinates between the LLM API and tool execution, ensuring proper sequencing of operations.

The scheduler implements a state machine that tracks the current execution phase and manages transitions between different states such as thinking, tool execution, and response generation.

### 执行流程

```mermaid
sequenceDiagram
    participant User as User Input
    participant Scheduler
    participant LLM as LLM API
    participant ToolExec as Tool Executor
    participant Session as AgentSession
    
    User->>Scheduler: Send Message
    Scheduler->>Session: Record Message
    Session-->>Scheduler: Acknowledge
    Scheduler->>LLM: Generate Response
    LLM-->>Scheduler: Tool Call Request
    Scheduler->>ToolExec: Execute Tool
    ToolExec-->>Scheduler: Tool Result
    Scheduler->>LLM: Continue Generation
    LLM-->>Scheduler: Final Response
    Scheduler-->>User: Stream Response
```

### 工具调用处理

When the LLM generates a tool call, the scheduler intercepts this and delegates to the ToolExecutor. The scheduler manages the execution context, including tool parameters, authentication tokens, and retry logic.

## ToolExecutor (工具执行)

### 概述

The `ToolExecutor` provides a secure execution environment for tools and external operations. It handles tool discovery, parameter validation, execution, and result formatting. The executor supports multiple tool types including built-in tools, custom skills, and MCP server tools.

### 工具类型支持

| 工具类型 | 执行方式 | 安全级别 |
|----------|----------|----------|
| **Built-in Tools** | 直接执行 | 高 |
| **Custom Skills** | 沙箱执行 | 中 |
| **MCP Tools** | 远程执行 | 可配置 |
| **Shell Commands** | 隔离环境 | 高 |

### 技能执行框架

Skills are executed through a structured framework defined in the SKILL.md specification:

```markdown
### Bundled Resources (optional)

#### Scripts (`scripts/`)
Executable code for deterministic tasks:
- Token efficient execution
- Deterministic behavior
- LLM-friendly stdout output

#### References (`references/`)
Documentation loaded as needed into context
```

资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md:1-50](packages/core/src/skills/builtin/skill-creator/SKILL.md)

### 策略引擎集成

The tool executor integrates with the policy engine to enforce security rules. Extensions can contribute policies through TOML configuration files:

```toml
# Example policy
[[rules]]
type = "confirmation_required"
command_pattern = "rm -rf.*"

[[rules]]
type = "deny"
command_pattern = "grep.*\\.env"
```

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30](packages/cli/src/commands/extensions/examples/policies/README.md)

## A2AExecutor (Agent-to-Agent通信)

### 概述

The `A2AExecutor` implements the Agent-to-Agent protocol, enabling communication between different agent instances. This is essential for distributed agent systems where multiple agents may run on different processes or machines.

### 协议消息格式

```typescript
interface AgentMessage {
  id: string;
  type: 'request' | 'response' | 'event';
  sender: string;
  receiver: string;
  payload: unknown;
  timestamp: number;
}
```

### RPC调度

The executor handles RPC method dispatching and session state management. New RPC methods are registered through the `GeminiAgent` interface:

```typescript
// Adding a new RPC method
// 1. Add method to GeminiAgent in acpRpcDispatcher.ts
// 2. Register in AgentSideConnection setup if necessary
// 3. Add serialization logic to acpUtils.ts
```

资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)

## 上下文管理

### ContextGraph

The `ContextGraph` maintains conversation context and generates stable identifiers for message turns. It handles legacy environment header detection and removal:

```typescript
// Defensive: Skip legacy environment header
if (msg.role === 'user' && msg.parts.length === 1) {
  const text = msg.parts[0].text;
  if (text?.startsWith('<session_context>') && 
      text?.includes('This is the Gemini CLI')) {
    debugLogger.log(
      '[ContextGraphBuilder] Skipping legacy environment header turn.',
    );
    continue;
  }
}
```

资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)

### 会话记录服务

The `ChatRecordingService` handles persistence of conversation history to JSONL format:

```typescript
export class ChatRecordingService {
  private conversationFile: string | null = null;
  private cachedConversation: ConversationRecord | null = null;
  private sessionId: string;
  // ...
}
```

资料来源：[packages/core/src/services/chatRecordingService.ts:50-100](packages/core/src/services/chatRecordingService.ts)

## 执行模式与策略

### 审批模式

The system supports multiple approval modes for controlling agent behavior:

| 模式 | 描述 | 使用场景 |
|------|------|----------|
| **PLAN** | 仅生成计划，不执行 | 代码审查 |
| **YOLO** | 直接执行所有操作 | 自动化脚本 |
| **INTERACTIVE** | 逐个确认操作 | 谨慎操作 |

```typescript
isYoloModeDisabled(): boolean {
  return this.disableYoloMode || !this.isTrustedFolder();
}
```

资料来源：[packages/core/src/config/config.ts:80-85](packages/core/src/config/config.ts)

### 策略链解析

The system resolves policy chains based on model configuration:

```typescript
describe('resolvePolicyChain', () => {
  it('returns a single-model chain for a custom model', () => {
    const chain = resolvePolicyChain(config);
    expect(chain).toHaveLength(1);
    expect(chain[0]?.model).toBe('custom-model');
  });
  
  it('returns the default chain when active model is "auto"', () => {
    const chain = resolvePolicyChain(config);
    expect(chain).toHaveLength(2);
    // Expect default chain [Pro, Flash]
  });
});
```

资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50](packages/core/src/availability/policyHelpers.test.ts)

## 扩展机制

### MCP服务器集成

The system supports MCP (Model Context Protocol) servers for extending functionality. Configuration is stored in `~/.gemini/settings.json`:

```json
{
  "mcpServers": {
    "@github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"]
    }
  }
}
```

### 自定义技能

Skills are defined through SKILL.md files with YAML frontmatter:

```yaml
---
name: pdf-rotate
description: Rotates PDF files by specified degrees. Use when user wants to rotate a PDF document.
---
```

## 运行时上下文

### 版本信息显示

The system displays runtime context through the About component:

```typescript
<Box flexDirection="row">
  <Box width="35%">
    <Text bold color={theme.text.link}>CLI Version</Text>
  </Box>
  <Box>
    <Text color={theme.text.primary}>{cliVersion}</Text>
  </Box>
</Box>
<Box flexDirection="row">
  <Box width="35%">
    <Text bold color={theme.text.link}>Model</Text>
  </Box>
  <Box>
    <Text color={theme.text.primary}>{getDisplayString(modelVersion)}</Text>
  </Box>
</Box>
```

资料来源：[packages/cli/src/ui/components/AboutBox.tsx:1-50](packages/cli/src/ui/components/AboutBox.tsx)

## 隐私与安全

### 隐私通知

The system displays privacy notices and handles data collection preferences:

```typescript
When you use Gemini Code Assist for individuals with Gemini CLI, Google
collects your prompts, related code, generated output, code edits,
related feature usage information, and your feedback to provide,
improve, and develop Google products and services and machine learning
technologies.
```

资料来源：[packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx:1-50](packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx)

### 安全检查

The policy engine enforces security rules for file operations and dangerous commands. Extensions can contribute security rules but cannot bypass user confirmation requirements.

## 常见工作流

### 单代理工作流

```mermaid
graph LR
    A[User Input] --> B[AgentSession]
    B --> C[Scheduler]
    C --> D[ToolExecutor]
    D --> E[Result]
    C --> F[LLM]
    F --> G[Response]
```

### 多代理工作流

```mermaid
graph TD
    A[User Input] --> B[AgentScheduler]
    B --> C[CLI Help Agent]
    B --> D[Skill Agent]
    B --> E[Policy Agent]
    C --> F[Result Aggregation]
    D --> F
    E --> F
    F --> G[Final Response]
```

## 调试与日志

### 日志输出

The system uses structured logging for debugging:

```typescript
debugLogger.log(
  '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',
);
debugLogger.error('Error loading conversation record from JSONL:', error);
```

### 测试框架

Tests are written using Vitest and can be run with workspace filtering:

```bash
npm test -w @google/gemini-cli -- src/acp/<test-file-name>.ts
```

资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)

## 总结

The Agent System provides a comprehensive framework for building LLM-powered CLI applications. Its modular architecture enables flexible composition of agents, tools, and policies while maintaining security and usability. The system supports both simple single-agent interactions and complex multi-agent workflows, with extensive support for customization through skills, MCP servers, and policy extensions.

---

<a id='context-pipeline'></a>

## Context and Memory Management

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Session Management](#session-management)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)
- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)
- [packages/core/src/skills/builtin/skill-creator/SKILL.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/builtin/skill-creator/SKILL.md)
- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)
- [packages/core/src/agents/cli-help-agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/cli-help-agent.ts)
- [packages/sdk/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/README.md)
</details>

# Context and Memory Management

## Overview

Context and Memory Management in Gemini CLI is a sophisticated system that enables the CLI to maintain conversational state, optimize token usage, and provide persistent memory across sessions. The system handles conversation history, progressive disclosure of information, and intelligent compression to manage context window constraints.

## Architecture Overview

The context management system consists of several interconnected components:

```mermaid
graph TD
    A[User Input] --> B[ContextGraphBuilder]
    B --> C[Turn ID Generation]
    C --> D[Context Manager]
    D --> E[Memory Context Manager]
    E --> F[Chat Recording Service]
    F --> G[Session Persistence]
    D --> H[Chat Compression Service]
    H --> I[Rolling Summary Processor]
    I --> J[Token Optimization]
```

## Core Components

### ContextGraphBuilder

The `ContextGraphBuilder` is responsible for constructing the conversational context from message history. It processes each turn and generates stable identifiers for tracking conversation flow.

**Key Responsibilities:**

- Iterating through conversation history
- Generating stable turn hashes using MD5
- Creating unique turn IDs with salt-based occurrence tracking
- Skipping legacy environment headers

```typescript
// Generate a stable salt for this turn based on its role and content
const turnContent = JSON.stringify(msg.parts);
const h = createHash('md5')
  .update(`${msg.role}:${turnContent}`)
  .digest('hex');
const occurrence = (seenHashes.get(h) || 0) + 1;
seenHashes.set(h, occurrence);
const turnSalt = `${h}_${occurrence}`;
```

资料来源：[packages/core/src/context/graph/toGraph.ts:31-38]()

### Turn ID Generation

Turn IDs are generated using a combination of message content hashing and a stable ID generation function. This ensures consistent identification across sessions.

| Parameter | Type | Purpose |
|-----------|------|---------|
| `msg` | Message | The message object to generate ID for |
| `nodeIdentityMap` | Map | Maps content to stable node identifiers |
| `turnSalt` | string | Salt for hashing (includes occurrence count) |
| `position` | number | Position hint for ID generation |

资料来源：[packages/core/src/context/graph/toGraph.ts:39]()

### Legacy Header Handling

The system includes defensive logic to skip legacy environment headers that contain `<session_context>` markers. This prevents duplicate or stale context from being reintroduced.

```typescript
if (msg.role === 'user' && msg.parts.length === 1) {
  const text = msg.parts[0].text;
  if (
    text?.startsWith('<session_context>') &&
    text?.includes('This is the Gemini CLI')
  ) {
    debugLogger.log(
      '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',
    );
    continue;
  }
}
```

资料来源：[packages/core/src/context/graph/toGraph.ts:19-29]()

## Chat Recording Service

The `ChatRecordingService` manages persistent storage of conversation history and session metadata.

### ConversationRecord Model

| Field | Type | Description |
|-------|------|-------------|
| `sessionId` | string | Unique session identifier |
| `projectHash` | string | Hash of the project context |
| `startTime` | ISO string | Session start timestamp |
| `lastUpdated` | ISO string | Last update timestamp |
| `summary` | string | Optional conversation summary |
| `memoryScratchpad` | string | Persistent memory content |
| `directories` | string[] | Associated working directories |
| `messages` | Message[] | Full message history |
| `messageCount` | number | Total message count |
| `userMessageCount` | number | User message count |

资料来源：[packages/core/src/services/chatRecordingService.ts:1-30]()

### Session State Tracking

The service tracks whether sessions contain user or assistant messages:

```typescript
hasUserOrAssistantMessage:
  options?.metadataOnly && metadataMessages.length > 0
    ? metadataMessages.some(
        (m) => m.type === 'user' || m.type === 'gemini',
      )
    : hasUserOrAssistant,
```

资料来源：[packages/core/src/services/chatRecordingService.ts:57-62]()

## Progressive Disclosure Design

Gemini CLI implements a three-level loading system to manage context efficiently:

```mermaid
graph LR
    A[Metadata<br/>name + description] --> B[SKILL.md Body<br/>Instructions]
    B --> C[Bundled Resources<br/>Scripts/References]
```

### Loading Levels

| Level | Content | Token Cost | Load Trigger |
|-------|---------|------------|--------------|
| 1 | Metadata (name + description) | ~100 words | Always |
| 2 | SKILL.md body | <5k words | Skill trigger |
| 3 | Bundled resources | Unlimited | As needed |

资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md]()

### Bundled Resources Organization

```
scripts/       - Executable code (Node.js/Python/Bash)
references/    - Documentation loaded into context
assets/        - Files used in output (templates, icons)
```

## Memory Scratchpad

The system supports a memory scratchpad feature that persists across sessions:

- **Staleness Tracking**: The system can flag when the scratchpad content becomes stale
- **Fallback Detection**: Falls back to first user message if no user message found

```typescript
memoryScratchpadIsStale: isTrackingMemoryScratchpadFreshness
  ? memoryScratchpadIsStale
  : undefined,
firstUserMessage: fallbackFirstUserMessage,
```

资料来源：[packages/core/src/services/chatRecordingService.ts:52-55]()

## Folder Trust and Configuration Discovery

When a folder is trusted, Gemini CLI loads its local configurations including:

- Custom commands
- Hooks
- MCP servers
- Agent skills
- Settings

```typescript
<Box>
  Trusting a folder allows Gemini CLI to load its local configurations,
  including custom commands, hooks, MCP servers, agent skills, and
  settings. These configurations could execute code on your behalf or
  change the behavior of the CLI.
</Box>
```

资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()

### Discovery Results

The system performs security validation on discovered configurations:

| Result Type | Icon | Purpose |
|-------------|------|---------|
| Discovery Errors | ❌ | Configuration parsing failures |
| Security Warnings | ⚠️ | Potential security concerns |

## CLI Help Agent Memory

The CLI Help Agent provides contextual assistance with runtime awareness:

```typescript
### Runtime Context
- **CLI Version:** ${cliVersion}
- **Active Model:** ${activeModel}
- **Today's Date:** ${today}
```

资料来源：[packages/core/src/agents/cli-help-agent.ts]()

### Agent Instructions

1. **Explore Documentation**: Use the `get_internal_docs` tool to find answers
2. **Be Precise**: Use provided runtime context and documentation
3. **Cite Sources**: Include specific documentation files used
4. **Non-Interactive**: Operate autonomously without user queries

## SDK Integration

The Gemini CLI SDK provides programmatic access to the context system:

```typescript
import { GeminiCliAgent } from '@google/gemini-cli-sdk';

const agent = new GeminiCliAgent({
  instructions: 'You are a helpful assistant.',
});

const stream = agent.sendStream('query', signal);
```

资料来源：[packages/sdk/README.md]()

## Data Flow Summary

```mermaid
graph TD
    subgraph "Input Processing"
        A[User Input] --> B[ContextGraphBuilder]
        B --> C[Turn Hash Generation]
        C --> D[Stable ID Creation]
    end
    
    subgraph "Memory Management"
        D --> E[Memory Context Manager]
        E --> F[Session Metadata]
        F --> G[Persistent Storage]
    end
    
    subgraph "Optimization"
        D --> H[Compression Service]
        H --> I[Rolling Summary]
        I --> J[Token Budget]
    end
    
    subgraph "Retrieval"
        G --> K[Chat Recording Service]
        K --> L[Conversation Record]
        L --> M[Context Window]
    end
```

## Configuration Options

| Option | Type | Description |
|--------|------|-------------|
| `memoryScratchpad` | string | Persistent memory content |
| `directories` | string[] | Working directories to track |
| `projectHash` | string | Project context identifier |
| `sessionId` | string | Unique session identifier |

## Security Considerations

The context management system includes several security measures:

1. **Folder Trust**: User confirmation required before loading folder configurations
2. **Policy Engine**: Security rules can be contributed via extensions
3. **Path Validation**: Safety checkers validate file paths for write operations
4. **Discovery Errors**: Configuration parsing failures are surfaced to users

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()

## Summary

The Context and Memory Management system in Gemini CLI provides:

- **Stable Turn Identification**: MD5-based hashing with occurrence tracking
- **Session Persistence**: Full conversation history with metadata
- **Progressive Disclosure**: Three-level loading for token optimization
- **Security**: Folder trust validation and policy enforcement
- **SDK Access**: Programmatic interface for external agents

---

<a id='tools-reference'></a>

## Tools Reference

### 相关页面

相关主题：[Agent System](#agent-system), [Sandboxing and Security](#sandboxing-security)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/src/tools/definitions/coreTools.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/definitions/coreTools.ts)
- [packages/core/src/tools/read-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/read-file.ts)
- [packages/core/src/tools/write-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/write-file.ts)
- [packages/core/src/tools/shell.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/shell.ts)
- [packages/core/src/tools/web-search.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/web-search.ts)
- [packages/core/src/tools/mcp-tool.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-tool.ts)
- [packages/core/src/tools/definitions/gemini-3.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/definitions/gemini-3.ts)
- [packages/core/src/tools/grep.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/grep.ts)
- [packages/core/src/tools/glob.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/glob.ts)
- [packages/core/src/tools/list-directory.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/list-directory.ts)
</details>

# Tools Reference

## Overview

The Tools system in Gemini CLI provides the foundational capabilities that enable the AI assistant to interact with filesystems, execute commands, search codebases, and connect to external services through MCP (Model Context Protocol) servers. Tools serve as the primary interface between the LLM and the operating environment, allowing the model to read, write, and manipulate files and execute system operations.

Tools are registered dynamically based on configuration and model capabilities, with model-specific optimizations for tool descriptions and schemas. The system supports both built-in core tools and extensible MCP tool integrations.

资料来源：[packages/core/src/tools/definitions/coreTools.ts:1-50]()

## Architecture Overview

```mermaid
graph TD
    A[User Request] --> B[GeminiAgent]
    B --> C[Tool Registry]
    C --> D[Core Tools]
    C --> E[MCP Tools]
    D --> F[read_file]
    D --> G[write_file]
    D --> H[shell/grep/glob]
    D --> I[web_search]
    E --> J[MCP Server 1]
    E --> K[MCP Server 2]
    F --> L[Filesystem]
    G --> L
    H --> M[System Commands]
    I --> N[Google Search API]
    J --> O[External Services]
```

## Tool Registration System

Tools are registered through a centralized `ToolRegistry` that manages availability based on configuration and platform capabilities. The registration follows a conditional pattern where tools are only registered if explicitly enabled or if no restrictions exist.

资料来源：[packages/core/src/config/config.ts:150-180]()

### Dynamic Tool Registration

```mermaid
graph TD
    A[Configuration Load] --> B{coreTools defined?}
    B -->|Yes| C{Check tool in list}
    B -->|No| D[Enable all by default]
    C -->|Match found| E[Register Tool]
    C -->|No match| F[Skip Tool]
    D --> E
    E --> G[Tool available to Agent]
```

The `maybeRegister` function controls tool availability:

| Parameter | Type | Description |
|-----------|------|-------------|
| `toolName` | `string` | The tool identifier to check |
| `normalizedClassName` | `string` | Normalized class name for matching |
| `coreTools` | `string[] \| undefined` | Configuration whitelist |
| `registerFn` | `() => void` | Function to execute if enabled |

资料来源：[packages/core/src/config/config.ts:130-150]()

## Core Tools

Core tools are built-in capabilities that provide filesystem access, search functionality, and command execution. These tools are optimized per model family.

### Tool Categories

| Category | Tools | Purpose |
|----------|-------|---------|
| **File Operations** | `read_file`, `write_file`, `replace` | File content manipulation |
| **Search** | `grep_search`, `grep_search_ripgrep`, `glob` | Code and file discovery |
| **Navigation** | `list_directory` | Directory browsing |
| **System** | `run_shell_command` | Terminal command execution |
| **Web** | `web_search`, `web_fetch` | Internet access |
| **Memory** | `save_memory` | Persistent context storage |
| **Planning** | `enter_plan_mode`, `exit_plan_mode` | Planning mode control |
| **MCP** | `read_mcp_resource`, `list_mcp_resources` | MCP server integration |

资料来源：[packages/core/src/tools/definitions/coreTools.ts:40-80]()

## File Operations

### Read File Tool

The `read_file` tool provides controlled access to file contents with optional line range selection.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_path` | `string` | Yes | Absolute path to the file |
| `start_line` | `number` | No | Starting line number (1-indexed) |
| `end_line` | `number` | No | Ending line number (inclusive) |

**Behavior:**
- Returns file contents as a string
- Supports partial file reads via line range
- Validates file path exists before reading
- Respects `.gemini-ignore` patterns when configured

资料来源：[packages/core/src/tools/read-file.ts:1-60]()

### Write File Tool

The `write_file` tool creates or overwrites files with specified content.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_path` | `string` | Yes | Absolute path for the new file |
| `content` | `string` | Yes | File content to write |

**Behavior:**
- Creates parent directories if they don't exist
- Overwrites existing files silently
- Returns confirmation message on success
- Subject to security policy checks

资料来源：[packages/core/src/tools/write-file.ts:1-50]()

### Edit/Replace Tool

The `replace` tool performs targeted modifications to existing files using diff/patch format.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_path` | `string` | Yes | Target file path |
| `old_string` | `string` | Yes | Text to find and replace |
| `new_string` | `string` | Yes | Replacement text |

**Patch Format:**
```
--- /absolute/path/to/file
+++ /absolute/path/to/file
@@ -start,count +start,count @@
 context line
 -removed line
 +added line
```

资料来源：[packages/core/src/agents/skill-extraction-agent.ts:50-80]()

## Search Tools

### Grep Tool

The `grep_search` tool performs text pattern matching across files with extensive filtering options.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `pattern` | `string` | Yes | Regex or literal pattern to search |
| `file_path` | `string` | No | Root directory to search |
| `case_sensitive` | `boolean` | No | Enable case sensitivity (default: false) |
| `include_pattern` | `string` | No | File glob to include |
| `exclude_pattern` | `string` | No | File glob to exclude |
| `names_only` | `boolean` | No | Return only matching filenames |
| `max_matches_per_file` | `number` | No | Limit matches per file |
| `total_max_matches` | `number` | No | Global match limit |
| `fixed_strings` | `boolean` | No | Treat pattern as literal |
| `context` | `number` | No | Lines of context around matches |
| `after` | `number` | No | Lines after match |
| `before` | `number` | No | Lines before match |
| `respect_git_ignore` | `boolean` | No | Skip gitignored files (default: true) |
| `respect_gemini_ignore` | `boolean` | No | Skip .gemini-ignore files (default: true) |
| `no_ignore` | `boolean` | No | Disable all ignore patterns |

资料来源：[packages/core/src/tools/grep.ts:1-80]()

### Ripgrep Tool

When available, `ripgrep` provides faster searching with the same interface as the standard Grep tool. The system automatically falls back to the standard implementation if Ripgrep is not installed.

资料来源：[packages/core/src/config/config.ts:160-175]()

### Glob Tool

The `glob` tool finds files matching shell-style wildcard patterns.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `pattern` | `string` | Yes | Glob pattern (e.g., `**/*.ts`) |
| `directory` | `string` | No | Root directory for search |
| `ignore` | `string[]` | No | Patterns to exclude |

资料来源：[packages/core/src/tools/glob.ts:1-50]()

## Directory Navigation

### List Directory Tool

The `list_directory` tool provides directory contents with optional filtering.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `dir_path` | `string` | Yes | Directory to list |
| `ignore` | `string[]` | No | Patterns to exclude from results |

**Features:**
- Returns file and directory names
- Supports ignore patterns for filtering
- Respects gitignore when configured

资料来源：[packages/core/src/tools/list-directory.ts:1-50]()

## Shell Command Execution

### Run Shell Command Tool

The `run_shell_command` tool executes system commands in a sandboxed environment.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | `string` | Yes | Command to execute |
| ` cwd` | `string` | No | Working directory |
| `timeout_ms` | `number` | No | Execution timeout (default: 60000) |
| `environment` | `object` | No | Additional environment variables |

**Security Features:**
- Subject to policy engine rules
- May require user confirmation for destructive commands
- Path safety validation for file operations
- Timeout protection against hanging processes

资料来源：[packages/core/src/tools/shell.ts:1-100]()

```mermaid
graph TD
    A[Command Request] --> B{Policy Check}
    B -->|Allowed| C[Environment Setup]
    B -->|Denied| D[User Confirmation]
    B -->|Blocked| E[Error Response]
    D -->|Approved| C
    D -->|Denied| E
    C --> F[Spawn Process]
    F --> G{Timeout?}
    G -->|Yes| H[Terminate]
    G -->|No| I[Capture Output]
    I --> J[Return Result]
    H --> K[Timeout Error]
```

## Web Tools

### Google Web Search

The `google_web_search` tool provides real-time internet search capabilities grounded in Google Search.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | `string` | Yes | Search query string |

**Behavior:**
- Returns search results with snippets
- May be disabled via configuration
- Subject to rate limiting

资料来源：[packages/core/src/tools/web-search.ts:1-50]()

### Web Fetch

The `web_fetch` tool retrieves content from URLs.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | `string` | Yes | Target URL |
| `prompt` | `string` | No | Guidance for content extraction |

## MCP Tool Integration

MCP (Model Context Protocol) tools allow integration with external MCP servers, extending Gemini CLI's capabilities.

### Architecture

```mermaid
graph TD
    A[Gemini CLI] --> B[MCP Tool Bridge]
    B --> C[MCP Server 1]
    B --> D[MCP Server 2]
    B --> E[MCP Server N]
    C --> F[External Service]
    D --> G[Database]
    E --> H[Custom Tools]
    B --> I[Resource Reader]
    B --> J[Resource Lister]
```

### MCP Tool Types

| Tool | Purpose | Parameters |
|------|---------|------------|
| `read_mcp_resource` | Read specific MCP resource | `server_name`, `uri` |
| `list_mcp_resources` | List available MCP resources | `server_name` |
| `mcp__tool_name` | Execute MCP tool call | Dynamic based on server |

资料来源：[packages/core/src/tools/mcp-tool.ts:1-100]()

### Configuration

MCP servers are configured in `~/.gemini/settings.json`:

```json
{
  "mcpServers": {
    "@github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"]
    }
  }
}
```

## Model-Specific Tool Manifests

Different model families may have optimized tool definitions with adjusted descriptions and parameter schemas.

### Gemini 3 Tool Manifest

The Gemini 3 family uses optimized tool definitions that may include:

- Streamlined descriptions for reduced token usage
- Adjusted parameter names for consistency
- Model-specific capability hints

资料来源：[packages/core/src/tools/definitions/gemini-3.ts:1-50]()

### Tool Definition Snapshot Testing

Tool definitions are validated against snapshots to ensure consistency:

```typescript
const modelIds = ['gemini-2.5-pro', 'gemini-3-pro-preview'];
const tools = [
  { name: 'read_file', definition: READ_FILE_DEFINITION },
  { name: 'write_file', definition: WRITE_FILE_DEFINITION },
  { name: 'grep_search', definition: GREP_DEFINITION },
  // ... more tools
];
```

资料来源：[packages/core/src/tools/definitions/coreToolsModelSnapshots.test.ts:30-60]()

## Tool Response Format

All tools return responses in a standardized format:

```typescript
interface ToolResult {
  tool_call_id: string;
  result: {
    success: boolean;
    data?: string | object;
    error?: string;
  };
}
```

## Security and Policy Engine

Tools are subject to security policies defined by the Policy Engine extension system.

### Policy Types

| Policy | Description |
|--------|-------------|
| **Confirmation Rules** | Require user approval for specific operations |
| **Denial Rules** | Block certain operations entirely |
| **Path Restrictions** | Validate paths against allowed directories |
| **Safety Checkers** | Validate operations before execution |

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()

### Folder Trust and Tool Access

When a folder is trusted, its local configurations can modify tool behavior:

- Custom commands
- MCP server configurations
- Agent skills
- Extension policies

Untrusted folders restrict tool access to prevent potentially harmful operations.

资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:20-40]()

## Tool Availability Matrix

| Tool | File Ops | Search | System | Web | MCP | Memory |
|------|----------|--------|--------|-----|-----|--------|
| read_file | ✓ | | | | | |
| write_file | ✓ | | | | | |
| replace | ✓ | | | | | |
| grep_search | | ✓ | | | | |
| glob | | ✓ | | | | |
| list_directory | | | ✓ | | | |
| run_shell_command | | | ✓ | | | |
| web_search | | | | ✓ | | |
| web_fetch | | | | ✓ | | |
| save_memory | | | | | | ✓ |
| enter_plan_mode | | | | | | |
| mcp__* | | | | | ✓ | |

## Extension Points

### Custom Tools via MCP

External tools can be integrated through MCP servers:

```typescript
> @github List my open pull requests
> @slack Send a summary to #dev channel
> @database Find inactive users
```

### Custom Commands

Custom slash commands can be defined in project directories and provide task-specific tool combinations.

## Best Practices

1. **Use Line Ranges**: When reading large files, specify line ranges to reduce token usage
2. **Respect Ignores**: Let tools respect `.gitignore` and `.gemini-ignore` patterns
3. **Timeout Configuration**: Set appropriate timeouts for shell commands
4. **MCP Security**: Only enable trusted MCP servers
5. **Path Validation**: Use absolute paths to avoid ambiguity

## Related Documentation

- [Configuration Guide](https://www.geminicli.com/docs/reference/configuration)
- [MCP Server Integration](https://www.geminicli.com/docs/tools/mcp-server)
- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)
- [Keyboard Shortcuts](https://www.geminicli.com/docs/reference/keyboard-shortcuts)

---

<a id='mcp-integration'></a>

## MCP Integration

### 相关页面

相关主题：[Tools Reference](#tools-reference), [Skills and Extensions](#skills-extensions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/src/tools/mcp-client.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-client.ts)
- [packages/core/src/tools/mcp-client-manager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-client-manager.ts)
- [packages/core/src/agents/browser/mcpToolWrapper.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/browser/mcpToolWrapper.ts)
- [packages/cli/src/services/McpPromptLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/services/McpPromptLoader.ts)
- [docs/tools/mcp-server.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md)
</details>

# MCP Integration

Model Context Protocol (MCP) Integration enables Gemini CLI to connect with external MCP servers, extending the CLI's capabilities with custom tools, prompts, and resources. This integration follows the MCP specification, allowing seamless communication between Gemini CLI and any compliant MCP server implementation.

## Overview

MCP Integration serves as a bridge between Gemini CLI and external tools. When configured, MCP servers can expose:

- **Tools**: Executable functions that the AI can call (e.g., `fetch_posts`, database queries, GitHub operations)
- **Prompts**: Pre-defined prompt templates for specific use cases
- **Resources**: Static data that can be loaded into context as needed

The integration supports both sandboxed and non-sandboxed execution modes, with appropriate security measures including consent prompts and path restrictions.

## Architecture

The MCP Integration system comprises several core components that work together to manage server lifecycle, tool exposure, and prompt loading.

```mermaid
graph TD
    A[Gemini CLI] --> B[McpClientManager]
    B --> C[McpClient instances]
    C --> D[MCP Servers]
    E[McpPromptLoader] --> F[Prompts Registry]
    G[McpToolWrapper] --> H[Tool Definitions]
    D --> I[JSON-RPC Transport]
    I --> C
    H --> A
```

### Core Components

| Component | Location | Responsibility |
|-----------|----------|----------------|
| `McpClientManager` | `packages/core/src/tools/mcp-client-manager.ts` | Manages lifecycle of all MCP client connections |
| `McpClient` | `packages/core/src/tools/mcp-client.ts` | Handles individual server communication |
| `McpToolWrapper` | `packages/core/src/agents/browser/mcpToolWrapper.ts` | Converts MCP tools to Gemini function declarations |
| `McpPromptLoader` | `packages/cli/src/services/McpPromptLoader.ts` | Loads and registers MCP prompts |

## MCP Client Manager

The `McpClientManager` is the central orchestrator for all MCP server connections. It handles:

- Server initialization and configuration loading
- Connection lifecycle management
- Tool registration and updates
- Cleanup and graceful shutdown

### Server Discovery

MCP servers can be configured in two ways:

1. **Global Configuration**: Defined in `~/.gemini/settings.json`
2. **Per-Project Configuration**: Defined in `~/.gemini/settings.json` for the active workspace

```mermaid
graph TD
    A[Load Settings] --> B[Get mcpServers config]
    B --> C{Server enabled?}
    C -->|Yes| D[Check enablement]
    C -->|No| E[Skip]
    D --> F[canLoadServer check]
    F --> G{Allowed?}
    G -->|Yes| H[Create MCP Client]
    G -->|No| I[Block with message]
    H --> J[Connect via Transport]
    J --> K[Register tools]
```

资料来源：[packages/cli/src/commands/mcp/list.ts:1-50]()

### Configuration Schema

MCP server configuration follows this structure:

```typescript
interface MCPServerConfig {
  command: string;           // Executable to run (e.g., 'npx', 'node')
  args?: string[];           // Command arguments
  env?: Record<string, string>;  // Environment variables
  disabled?: boolean;       // Enable/disable server
}
```

Configuration is merged from multiple sources with appropriate precedence rules applied by the settings system.

资料来源：[packages/cli/src/commands/mcp/list.ts:30-40]()

## MCP Client

The `McpClient` handles the actual communication with an MCP server using the JSON-RPC protocol over stdio transport. Each client instance maintains:

- A transport connection to the server
- Registered tool definitions
- Server capabilities and metadata

### Tool Registration Flow

```mermaid
sequenceDiagram
    participant CLI as Gemini CLI
    participant Manager as McpClientManager
    participant Client as McpClient
    participant Server as MCP Server
    participant Browser as Browser Manager

    CLI->>Manager: Initialize servers
    Manager->>Client: Create client instance
    Client->>Server: Initialize connection
    Server-->>Client: Server capabilities
    Client->>Server: List tools request
    Server-->>Client: Tool definitions
    Client->>Manager: Register tools
    Manager->>Browser: Convert to FunctionDeclaration
    Browser->>CLI: Expose tools to model
```

资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:1-50]()

## Tool Wrapper

The `McpToolWrapper` transforms MCP tool definitions into Gemini-compatible function declarations. This conversion ensures that:

1. Tool schemas are compatible with Gemini's function calling format
2. Descriptions are augmented with usage hints
3. Input schemas are properly formatted as JSON Schema

### Schema Conversion

```typescript
function convertMcpToolToFunctionDeclaration(mcpTool: McpTool): FunctionDeclaration {
  return {
    name: mcpTool.name,
    description: mcpTool.description ?? '',
    parametersJsonSchema: mcpTool.inputSchema ?? {
      type: 'object',
      properties: {},
    },
  };
}
```

资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:60-75]()

### Description Augmentation

The wrapper augments MCP tool descriptions with semantic hints that help the model make correct tool choices:

```typescript
const augmentedDescription = augmentToolDescription(
  mcpTool.name,
  mcpTool.description ?? '',
);
```

This approach reduces system prompt overhead by embedding usage rules directly in tool descriptions.

资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:45-50]()

## Prompt Loading

The `McpPromptLoader` handles loading and registering MCP prompt templates. Prompts are discovered from connected MCP servers and made available for use in conversations.

### Prompt Structure

MCP prompts can include:

- **Name**: Unique identifier for the prompt
- **Description**: Human-readable explanation of when to use the prompt
- **Arguments**: Template variables that can be customized at runtime
- **Template**: The actual prompt content with variable placeholders

资料来源：[packages/cli/src/services/McpPromptLoader.ts]()

## MCP Server Implementation

Gemini CLI provides example MCP server implementations demonstrating how to create compliant servers.

### Basic Example

The basic MCP server example (`packages/cli/src/commands/extensions/examples/mcp-server`) exposes:

- **Tool**: `fetch_posts` - Mock-fetches posts
- **Prompt**: `poem-writer` - Generates poems

### Extension Structure

```
mcp-server/
├── example.js          # Server entry point
├── gemini-extension.json  # Configuration manifest
└── package.json        # Dependencies
```

### Server Entry Point

Servers implement the MCP specification using `@modelcontextprotocol/sdk`:

```javascript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';

const server = new Server(
  { name: 'example-mcp-server', version: '1.0.0' },
  { capabilities: { tools: {}, prompts: {} } }
);
```

资料来源：[packages/cli/src/commands/extensions/examples/mcp-server/README.md]()

## Security Model

MCP Integration includes multiple security layers:

### Consent and Allowlists

| Security Feature | Description |
|-----------------|-------------|
| `canLoadServer` | Checks if server is allowed to load |
| `applyAdminAllowlist` | Validates against admin-defined allowlist |
| `getAdminBlockedMcpServersMessage` | Reports blocked servers to user |

资料来源：[packages/cli/src/commands/mcp/list.ts:20-25]()

### Policy Engine Integration

The policy engine example extension demonstrates how to add security rules:

- **Confirmation Rules**: Require user confirmation for dangerous operations (e.g., `rm -rf`)
- **Denial Rules**: Block access to sensitive resources (e.g., searching for `.env` files)
- **Safety Checkers**: Validate operations before execution (e.g., path validation)

Security note: Extensions can strengthen security but cannot bypass user confirmation or enable `yolo` mode.

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()

## Usage Examples

### Configure MCP Server

Add server configuration to `~/.gemini/settings.json`:

```json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"]
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
    }
  }
}
```

### Using MCP Tools

After configuration, tools are automatically available:

```
> @github List my open pull requests
> @database Run a query to find inactive users
```

### Creating Custom Server

1. Create server directory structure
2. Implement MCP server using `@modelcontextprotocol/sdk`
3. Add `gemini-extension.json` manifest
4. Link extension: `gemini extensions link <path>`

## Command Reference

### List MCP Servers

```bash
gemini mcp list
```

Displays all configured MCP servers with their status.

资料来源：[packages/cli/src/commands/mcp/list.ts]()

### MCP Server Integration Guide

For detailed setup instructions, see the [MCP Server Integration guide](https://www.geminicli.com/docs/tools/mcp-server).

## See Also

- [Custom Commands](https://www.geminicli.com/docs/cli/custom-commands)
- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)
- [Extension Development](../extensions/index.md)
- [Official MCP Documentation](https://modelcontextprotocol.io)

---

<a id='skills-extensions'></a>

## Skills and Extensions

### 相关页面

相关主题：[MCP Integration](#mcp-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/core/src/skills/skillManager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillManager.ts)
- [packages/core/src/skills/skillLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillLoader.ts)
- [packages/cli/src/config/extension-manager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/extension-manager.ts)
- [packages/core/src/hooks/hookSystem.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/hooks/hookSystem.ts)
- [docs/cli/skills.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/skills.md)
- [docs/extensions/writing-extensions.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/extensions/writing-extensions.md)
</details>

# Skills and Extensions

## Overview

Skills and Extensions are the two primary extensibility mechanisms in Gemini CLI. Skills enable the CLI to handle specialized, domain-specific tasks with structured guidance, while Extensions provide a comprehensive framework for contributing custom tools, policies, and integrations.

**Skills** are markdown-based packages that provide instructions and reusable resources for handling specific task types. They are loaded into context when triggered and contain documentation, scripts, and assets.

**Extensions** are npm-based packages that extend Gemini CLI's capabilities through custom commands, MCP server configurations, policy rules, and hooks. They provide a richer, more programmatic extensibility model.

---

## Skills System

### What Are Skills?

Skills are modular knowledge packages that help Gemini CLI handle specialized tasks. Each skill contains:

- **Frontmatter**: YAML metadata defining the skill's name and trigger conditions
- **Body**: Markdown instructions loaded after the skill triggers
- **Scripts**: Executable code (Node.js/Python/Bash) for deterministic operations
- **References**: Documentation loaded into context as needed
- **Assets**: Templates, icons, fonts, and other output files

### Skill Structure

```
skill-name/
├── SKILL.md           # Required: Frontmatter + Instructions
├── scripts/           # Optional: Executable code
│   └── *.cjs, *.py, etc.
├── references/        # Optional: Documentation
│   └── *.md
└── assets/            # Optional: Output files
    └── templates/, icons/, etc.
```

### SKILL.md Format

Every skill requires a `SKILL.md` file with two components:

**Frontmatter (YAML):**
```yaml
---
name: skill-name
description: Clear description of what this skill does and when it should be triggered
---
```

**Body (Markdown):**
Instructions and guidance for executing the skill. This content is loaded only after the skill triggers, not during initial context evaluation.

### Skill Loading Mechanism

Skills are discovered and loaded through the `SkillLoader` system. The system:

1. Scans configured skill directories
2. Parses SKILL.md frontmatter for name and description
3. Makes skills available for trigger matching
4. Loads skill content on-demand when triggered

### Skill Triggering

When a user request matches a skill's description, the skill's body and resources become available in context. The matching is based on semantic similarity between the user's query and the skill's description field.

---

## Skill Design Patterns

### Pattern 1: Flat Organization

For simple skills with linear workflows:

```
csv-processor/
├── SKILL.md
├── FORMS.md           # Input/output templates
├── REFERENCE.md       # Full documentation
└── EXAMPLES.md        # Usage examples
```

Gemini CLI loads `FORMS.md`, `REFERENCE.md`, or `EXAMPLES.md` only when needed.

### Pattern 2: Domain-Specific Organization

For skills supporting multiple domains or variants:

```
bigquery-skill/
├── SKILL.md (overview + navigation)
└── references/
    ├── finance.md     # Revenue, billing metrics
    ├── sales.md       # Opportunities, pipeline
    ├── product.md     # API usage, features
    └── marketing.md  # Campaigns, attribution
```

### Pattern 3: Conditional Details

Show basic content with links to advanced topics:

```markdown
## Basic Analysis

Use pandas for loading and basic queries. See [PANDAS.md](PANDAS.md).

## Advanced Operations

For massive files, see [STREAMING.md](STREAMING.md). For timestamp normalization, see [TIMESTAMPS.md](TIMESTAMPS.md).
```

---

## Scripts in Skills

Scripts provide deterministic, token-efficient execution for tasks that are repeatedly rewritten or require reliability guarantees.

### When to Include Scripts

| Scenario | Example |
|----------|---------|
| Repeatedly rewritten code | PDF rotation, image processing |
| Deterministic reliability needed | File format conversions |
| Token efficiency important | Complex parsing operations |

### Script Requirements

- **Output format**: LLM-friendly stdout
- **Error handling**: Suppress standard tracebacks
- **Messages**: Clear success/failure messages
- **Pagination**: Truncate long outputs to prevent context overflow

```javascript
// Example: scripts/rotate_pdf.cjs
console.log("Success: Rotated PDF 90 degrees clockwise");
console.log("Output: rotated_document.pdf");
```

---

## Extensions System

### What Are Extensions?

Extensions are npm packages that extend Gemini CLI through a structured manifest system. They provide programmatic capabilities beyond what markdown-based skills offer.

### Extension Structure

```
extension-name/
├── gemini-extension.json    # Required manifest
├── src/                     # Source code
├── commands/                # Custom slash commands
├── policies/                # Security rules (TOML)
└── package.json
```

### Extension Manifest

The `gemini-extension.json` manifest defines the extension's contributions:

```json
{
  "name": "my-extension",
  "version": "1.0.0",
  "commands": ["./commands/*.ts"],
  "mcpServers": {},
  "policies": ["./policies/*.toml"]
}
```

### Extension Capabilities

| Capability | Description |
|------------|-------------|
| Custom Commands | Slash commands (`/command`) that extend CLI functionality |
| MCP Servers | Model Context Protocol server configurations |
| Policy Rules | Security rules and safety checkers |
| Hooks | Pre/post execution hooks for customization |

---

## Policy Engine

Extensions can contribute security rules through the Policy Engine.

### Rule Definition (TOML)

```toml
[[rules]]
id = "deny-rm-rf"
description = "Prevents dangerous recursive deletion"
condition = "command contains 'rm -rf'"
action = "confirm"
message = "This command will recursively delete files. Confirm?"
```

### Safety Checkers

Extensions can provide safety checkers that validate operations:

```toml
[[safety_checkers]]
name = "allowed-path"
description = "Validates file paths for write operations"
check = "path.startsWith(allowedDirectory)"
```

### Security Notes

- Extensions **cannot** bypass user confirmation requirements
- `allow` decisions from extensions are ignored for security
- `yolo` mode configurations from extensions are ignored
- Extensions can only strengthen security, not weaken it

---

## MCP Server Integration

Extensions can configure MCP (Model Context Protocol) servers for specialized capabilities:

```json
{
  "mcpServers": {
    "@github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}
```

### Configuration Flow

```mermaid
graph TD
    A[User Request] --> B{MCP Server Configured?}
    B -->|Yes| C[Load MCP Server]
    B -->|No| D[Continue without MCP]
    C --> E[Execute MCP Tools]
    D --> F[Standard Tool Execution]
```

---

## Hook System

The Hook System provides pre/post execution points for customization.

### Available Hooks

| Hook | Timing | Purpose |
|------|--------|---------|
| `preToolExecution` | Before tool call | Modify inputs, log, or validate |
| `postToolExecution` | After tool call | Process outputs, track metrics |
| `prePromptGeneration` | Before prompt build | Customize context |
| `postResponseGeneration` | After response | Format or filter output |

### Hook Registration

Extensions register hooks through the hook system API:

```typescript
hookSystem.register('preToolExecution', async (context) => {
  // Validate or modify before execution
  return { modified: false, context };
});
```

---

## Creating Skills

### Command

```bash
gemini skill create my-skill
```

### Generated Structure

```
my-skill/
├── SKILL.md
├── scripts/
│   └── example_script.cjs
├── references/
│   └── example_reference.md
└── assets/
    └── example_asset.txt
```

### Customization Steps

1. Edit `SKILL.md` with accurate name and description
2. Add scripts for deterministic operations
3. Create reference documentation
4. Place assets in the `assets/` directory
5. Delete unused example files

### Best Practices

- **Description clarity**: The description determines when the skill triggers. Be specific about use cases.
- **Script testing**: Run scripts to verify they work correctly
- **Token efficiency**: Use scripts instead of repeated code generation
- **Reference loading**: Only load references when needed

---

## Creating Extensions

### Command

```bash
gemini extensions create my-extension
```

### Implementation Checklist

| Step | Task |
|------|------|
| 1 | Define extension manifest |
| 2 | Implement custom commands |
| 3 | Configure MCP servers |
| 4 | Add policy rules |
| 5 | Register hooks |
| 6 | Test locally with `gemini extensions link` |

### Local Development

```bash
# Link extension for local testing
gemini extensions link ./path/to/extension

# Unlink when done
gemini extensions unlink my-extension
```

---

## Configuration

### Skill Directories

Skills are loaded from configured directories. Check `~/.gemini/settings.json`:

```json
{
  "skills": {
    "directories": ["./.skills", "~/.gemini/skills"]
  }
}
```

### Extension Settings

Extensions are discovered from:

- Globally installed npm packages (`@gemini-extensions/*`)
- Locally linked directories
- User-configured paths in `settings.json`

---

## Architecture Diagram

```mermaid
graph TB
    subgraph "Skill Layer"
        A[SKILL.md] --> B[SkillLoader]
        C[scripts/] --> D[Script Executor]
        E[references/] --> F[Context Loader]
    end
    
    subgraph "Extension Layer"
        G[gemini-extension.json] --> H[ExtensionManager]
        I[commands/] --> J[Command Registry]
        K[policies/] --> L[Policy Engine]
        M[mcpServers] --> N[MCP Client]
    end
    
    subgraph "Core"
        B --> O[Skill Manager]
        H --> O
        D --> O
        L --> P[Security Layer]
        N --> Q[Tool Executor]
    end
    
    O --> Q
    Q --> R[Response Formatter]
```

---

## Summary

| Feature | Skills | Extensions |
|---------|--------|------------|
| **Format** | Markdown-based | npm packages |
| **Trigger** | Semantic matching | Manual invocation |
| **Code** | Optional scripts | Full source code |
| **Complexity** | Low-medium | Medium-high |
| **Use case** | Guidance, patterns | Tools, policies, integrations |

**Skills** provide lightweight, context-loaded guidance for specialized tasks.

**Extensions** provide comprehensive programmatic extensibility through custom commands, MCP servers, policy rules, and hooks.

Both mechanisms work together to make Gemini CLI adaptable to diverse workflows and requirements.

---

<a id='sandboxing-security'></a>

## Sandboxing and Security

### 相关页面

相关主题：[Policy Engine](#policy-engine), [Tools Reference](#tools-reference)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)
- [packages/core/src/tools/confirmation-policy.test.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/confirmation-policy.test.ts)
- [packages/cli/src/config/trustedFolders.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/trustedFolders.ts)
- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)
- [packages/cli/src/commands/extensions/examples/policies/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/commands/extensions/examples/policies/README.md)
- [package.json](https://github.com/google-gemini/gemini-cli/blob/main/package.json)
</details>

# Sandboxing and Security

## Overview

Gemini CLI implements a multi-layered security architecture that protects users through sandboxed execution environments, path validation, trusted folder mechanisms, and an extensible policy engine. The system is designed to execute AI-generated code and commands safely while giving users fine-grained control over security boundaries.

## Architecture

The sandboxing system uses platform-specific implementations to handle execution isolation across different operating systems. The configuration system acts as the central authority for path validation and access control.

```mermaid
graph TD
    A[User Request] --> B[Config System]
    B --> C{Path Validation}
    C -->|Allowed| D[Sandbox Manager]
    C -->|Denied| E[Access Rejected]
    D --> F{Linux Sandbox}
    D --> G{macOS Sandbox}
    D --> H{Windows Sandbox}
    F --> I[Docker Container]
    G --> J[Apple Silicon / Sandbox Profile]
    H --> K[Windows Sandbox]
    I --> L[Tool Execution]
    J --> L
    K --> L
```

## Sandbox Manager Architecture

The sandbox system is orchestrated through a centralized `SandboxManager` service that delegates to platform-specific implementations.

### Platform-Specific Implementations

| Platform | Manager Class | Isolation Method |
|----------|---------------|------------------|
| Linux | `LinuxSandboxManager` | Docker containers with resource limits |
| macOS | `MacOsSandboxManager` | App Sandbox / Process sandboxing |
| Windows | `WindowsSandboxManager` | Windows Sandbox virtualization |

### Sandbox Image Configuration

Sandbox environments use pre-built Docker images defined in the root `package.json`:

```json
{
  "config": {
    "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef"
  }
}
```

资料来源：[package.json:11]()

## Path Validation System

The path validation system prevents the agent from accessing files outside authorized boundaries. This is implemented in the `Config` class through two primary methods.

### Access Control Logic

```typescript
isPathAllowed(absolutePath: string): boolean {
  const resolvedPath = resolveToRealPath(absolutePath);
  // Check inbox isolation first
  // Check workspace boundaries
  // Check project temp directory
}

validatePathAccess(absolutePath: string): string | null {
  if (this.isPathAllowed(absolutePath)) {
    return null;
  }
  return `Path not in workspace: Attempted path "${absolutePath}" resolves outside the allowed workspace directories`;
}
```

资料来源：[packages/core/src/config/config.ts]()
资料来源：[packages/core/src/tools/confirmation-policy.test.ts]()

### Allowed Path Categories

| Category | Description | Access Level |
|----------|-------------|--------------|
| Workspace directories | User-specified project roots | Full read/write |
| Project temp directory | Temporary files for operations | Read/write within bounds |
| Inbox directory | Auto-memory extraction staging | Restricted write access |

### Inbox Isolation

The `.inbox/` directory within the project memory temp directory receives special treatment. The main agent is denied write access to prevent bypassing the memory extraction review flow:

```mermaid
graph LR
    A[Main Agent] -->|DENIED| B[.inbox/ directory]
    C[Extraction Agent] -->|WRITE ALLOWED| B
    D[Review Flow] -->|READ| B
```

资料来源：[packages/core/src/config/config.ts]()

## Trusted Folders System

The trusted folders mechanism allows users to authorize specific directories for configuration loading while maintaining security boundaries.

### What Trust Enables

When a folder is trusted, Gemini CLI loads:

- Custom commands
- Hooks
- MCP server configurations
- Agent skills
- Local settings

### Security Dialog

When discovering a new folder, users are presented with the `FolderTrustDialog` component that displays:

```typescript
// Security warnings and errors are displayed to the user
{hasWarnings && (
  <Box>
    <Text color={theme.status.warning}>⚠️ Security Warnings:</Text>
    {discoveryResults.securityWarnings.map((warning, i) => (
      <Text key={i} color={theme.status.warning}>
        • {stripAnsi(warning)}
      </Text>
    ))}
  </Box>
)}
```

资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()

### Discovery Results

The folder discovery process returns categorized items:

| Group Label | Item Types |
|-------------|------------|
| Custom Commands | User-defined slash commands |
| Hooks | Pre/post execution scripts |
| MCP Servers | Model Context Protocol servers |
| Agent Skills | Specialized skill modules |
| Settings | Configuration overrides |

## Policy Engine

Extensions can contribute security rules and safety checkers through the policy engine. This allows the community to extend built-in security without modifying core code.

### Rule Types

| Rule Type | Purpose | Example |
|-----------|---------|---------|
| Confirmation Rules | Require user approval for specific operations | Confirm before `rm -rf` |
| Denial Rules | Block specific operations entirely | Prevent `grep` for `.env` files |
| Safety Checkers | Validate operations before execution | Path validation for writes |

### Extension Policy Structure

```
extension/
├── gemini-extension.json
└── policies/
    ├── confirmation-rules.toml
    ├── denial-rules.toml
    └── safety-checkers.toml
```

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()

### Security Enforcement

**Critical**: Gemini CLI ignores `allow` decisions and `yolo` mode configurations contributed by extensions. This ensures that:

- Extensions can strengthen security
- Extensions cannot bypass user confirmation
- Malicious extensions cannot weaken protections

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()

## Configuration Reference

### Settings File Location

User settings are stored at `~/.gemini/settings.json`

### Key Security Settings

| Setting | Type | Purpose |
|---------|------|---------|
| `trustedFolders` | Array of paths | Authorize directories for config loading |
| `dataCollectionOptIn` | Boolean | Control telemetry data sharing |

### Workspace Context

```typescript
interface WorkspaceContext {
  isPathWithinWorkspace(path: string): boolean;
  getDirectories(): string[];
}
```

The workspace context is queried during path validation to determine if a requested file operation falls within authorized boundaries.

## Security Best Practices

### For Users

1. **Review folder trust requests** - Only trust folders containing code you control
2. **Understand policy rules** - Read denial messages to understand why operations are blocked
3. **Use workspace isolation** - Keep sensitive files outside workspace directories

### For Extension Developers

1. **Contribute restrictive rules** - Extensions should only add protections, never remove them
2. **Follow policy TOML format** - Use structured definitions for predictable behavior
3. **Test edge cases** - Validate paths resolve correctly across platforms

## Summary

Gemini CLI's security architecture combines:

- **Platform-specific sandboxing** for code execution isolation
- **Path validation** for filesystem access control
- **Trusted folder system** for configuration security
- **Policy engine** for extensible rule definitions
- **Inbox isolation** for memory extraction workflow integrity

This multi-layered approach allows the CLI to safely execute AI-generated code while giving users transparency and control over security boundaries.

---

<a id='policy-engine'></a>

## Policy Engine

### 相关页面

相关主题：[Sandboxing and Security](#sandboxing-security), [Agent System](#agent-system)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [packages/cli/src/commands/extensions/examples/policies/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/commands/extensions/examples/policies/README.md)
- [packages/core/src/availability/policyHelpers.test.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/availability/policyHelpers.test.ts)
- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)
- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)
</details>

# Policy Engine

## Overview

The Policy Engine is a security infrastructure component within Gemini CLI that enforces security rules and safety checks for file operations and command execution. It provides a declarative mechanism for defining policies through TOML configuration files, enabling administrators and extensions to contribute security rules without modifying core application code.

The Policy Engine operates as a late-stage validation layer, intercepting operations after the AI model has decided to execute them but before the operations are actually performed. This architecture allows for granular control over potentially dangerous operations while maintaining flexibility for extension contributions.

## Architecture

### Core Components

The Policy Engine consists of three primary layers:

| Component | Purpose | Location |
|-----------|---------|----------|
| Policy Loader | Parses and loads TOML policy files | `packages/core/src/policy/toml-loader.ts` |
| Policy Engine | Evaluates operations against loaded policies | `packages/core/src/policy/policy-engine.ts` |
| Policy Configuration | Manages runtime policy settings | `packages/cli/src/config/policy.ts` |

### Evaluation Flow

```mermaid
graph TD
    A[Operation Request] --> B{Policy Engine}
    B --> C[Load Policies from TOML]
    C --> D[Apply Security Rules]
    D --> E{Rule Match?}
    E -->|Yes| F[Prompt User Confirmation]
    E -->|No| G[Apply Safety Checkers]
    F --> H{User Approves?}
    H -->|Yes| G
    H -->|No| I[Block Operation]
    G --> J{Safety Valid?}
    J -->|Yes| K[Execute Operation]
    J -->|No| I
    I --> L[Return Error/Deny Message]
    K --> M[Operation Complete]
```

## Policy Configuration

### Configuration File Location

Policy files are stored in a `policies/` directory within extension packages. Each policy is defined as a separate `.toml` file containing rule definitions and safety checker configurations.

### Policy Types

The Policy Engine supports two categories of policies:

#### Security Rules

Security rules define conditional logic that triggers user confirmation or denies operations based on specific patterns. Rules are evaluated before operation execution and can:

- Require user confirmation for dangerous commands
- Deny operations matching specific patterns
- Provide custom deny messages explaining why an operation was blocked

#### Safety Checkers

Safety checkers perform validation on operation parameters such as file paths. Unlike rules that evaluate operation context, safety checkers focus on structural validation of operation inputs.

## Extension Integration

### Registering Policy Extensions

Extensions can contribute policies by including a `policies/` directory with TOML files. The extension manifest (`gemini-extension.json`) identifies it as a policy contributor.

### Security Constraints

For security, Gemini CLI enforces strict constraints on extension-contributed policies:

```toml
[security]
# Gemini CLI ignores these configurations from extensions
allow_decisions = false  # Ignored
yolo_mode = false        # Ignored
```

| Extension-Provided Setting | Gemini CLI Behavior |
|---------------------------|---------------------|
| `allow` decisions | **Ignored** - Always treated as prompt |
| `yolo` mode configuration | **Ignored** - Cannot bypass confirmation |

This design ensures that extensions can only strengthen security by adding more restrictive rules—they cannot weaken security by bypassing user confirmation.

## Built-in Policies

### rm -rf Rule Example

The following demonstrates a policy that requires confirmation for recursive directory deletion:

```toml
[[rules]]
id = "prevent-recursive-delete"
description = "Require confirmation for rm -rf commands"

[rules.condition]
command_pattern = "rm.*-rf.*"

[rules.action]
type = "confirm"
message = "This will recursively delete directories. Are you sure?"
```

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()

### Secret File Access Rule Example

Policies can prevent searching for sensitive files:

```toml
[[rules]]
id = "prevent-secret-search"
description = "Deny grep searches for sensitive files"

[rules.condition]
command_pattern = "grep.*\\.env"

[rules.action]
type = "deny"
message = "Searching for .env files is not allowed for security reasons"
```

资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()

### File Path Safety Checker Example

Safety checkers validate operation parameters:

```toml
[[safety_checkers]]
id = "allowed-path"
description = "Validate file paths for write operations"

[safety_checkers.validator]
type = "path_validation"
allowed_paths = ["/home/user/project", "/tmp/uploads"]
```

## Policy Chain Resolution

The Policy Engine supports model-specific policy chains, allowing different security rules based on the active AI model. The `resolvePolicyChain` function determines which policies apply for a given model configuration.

```mermaid
graph LR
    A[Model Config] --> B{Is Custom Model?}
    B -->|Yes| C[Single-Model Chain]
    B -->|No| D{Is in Catalog?}
    D -->|Yes| E[Use Catalog Order]
    D -->|No| F[Default Chain: Pro → Flash]
```

| Model Scenario | Policy Chain Behavior |
|---------------|----------------------|
| Custom model | Single-model chain |
| Catalog model (exists) | Preserves catalog order |
| Auto model (`gemini-2.5-pro` or default) | Default chain: Pro, then Flash |

资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50]()

## Folder Trust Integration

The Policy Engine integrates with Gemini CLI's folder trust system. Policies are only loaded from trusted folders to prevent malicious configuration injection.

| Trust State | Policy Loading |
|------------|----------------|
| Trusted folder | Full policy enforcement |
| Untrusted folder | Policies not loaded |
| YOLO mode disabled | Cannot enable YOLO in untrusted folders |

The `isYoloModeDisabled` method checks both the global YOLO disable flag and the folder trust status:

```typescript
isYoloModeDisabled(): boolean {
  return this.disableYoloMode || !this.isTrustedFolder();
}
```

资料来源：[packages/core/src/config/config.ts:200-203]()

### Security Warnings and Errors

When loading policies from a folder, the system reports:

- **Discovery Errors**: Problems parsing or loading policy files
- **Security Warnings**: Potentially risky configurations detected
- **Loaded Items**: Policies successfully loaded and active

```typescript
interface DiscoveryResults {
  discoveryErrors: string[];
  securityWarnings: string[];
  loadedPolicies: Policy[];
}
```

资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:1-60]()

## Configuration Options

### Core Policy Settings

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `disableYoloMode` | boolean | `false` | Disables YOLO mode entirely |
| `disableAlwaysAllow` | boolean | `false` | Prevents "always allow" shortcuts |
| `pendingIncludeDirectories` | string[] | `[]` | Directories pending trust approval |

### Policy File Loading

| Setting | Type | Description |
|---------|------|-------------|
| Policy directory | `policies/` | TOML files in extension packages |
| File format | `.toml` | TOML 1.0 specification |
| Reload trigger | Folder trust change | Policies reload when trust state changes |

## Best Practices

### Writing Secure Policies

1. **Use specific patterns**: Avoid overly broad patterns that could match legitimate operations
2. **Provide clear messages**: Explain why an operation requires confirmation
3. **Validate file paths**: Use safety checkers for path-based operations
4. **Test edge cases**: Ensure policies don't block necessary operations

### Policy Testing

To test policies contributed by extensions:

```bash
# Link the extension
gemini extensions link packages/cli/src/commands/extensions/examples/policies

# Restart Gemini CLI session
# Policies will be loaded from the linked extension
```

### Debugging Policy Evaluation

When policies don't behave as expected:

1. Verify the extension is properly linked
2. Check the folder is marked as trusted
3. Review TOML syntax for parsing errors
4. Confirm rule patterns match the actual command strings

## Summary

The Policy Engine provides a robust, extensible security framework for Gemini CLI. By supporting declarative TOML-based policy definitions, extensions can contribute security rules without modifying core code. The enforced security constraints ensure that extensions can only strengthen security—never weaken it—making the system resistant to potentially malicious extension configurations.

---

<a id='terminal-ui'></a>

## Terminal UI Components

### 相关页面

相关主题：[Session Management](#session-management)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)
- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)
- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)
- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)
- [packages/cli/src/ui/components/InboxDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/InboxDialog.tsx)
- [packages/cli/src/ui/components/ToolConfirmationMessage.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ToolConfirmationMessage.tsx)
- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)
- [packages/cli/src/ui/components/messages/GeminiMessage.test.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/messages/GeminiMessage.test.tsx)
</details>

# Terminal UI Components

## Overview

The Terminal UI Components system provides a rich, interactive command-line interface for Gemini CLI. Built on [Ink](https://github.com/vadimdemedes/ink) (React for CLIs), the UI framework delivers a modern, terminal-native experience with support for themes, dialogs, user authentication, and real-time updates.

The component architecture follows a modular design pattern, separating concerns between layout containers, interactive dialogs, informational displays, and message rendering components.

## Architecture

```mermaid
graph TD
    subgraph "UI Layer"
        A[App.tsx] --> B[AppHeader]
        A --> C[MainContent]
        A --> D[Composer]
    end
    
    subgraph "Dialogs"
        E[AuthDialog] --> F[RadioButtonSelect]
        G[ModelDialog] --> H[ModelQuotaDisplay]
        I[FolderTrustDialog] --> J[DiscoveryResults]
        K[InboxDialog] --> L[ScrollableDiffViewport]
    end
    
    subgraph "Messages"
        M[GeminiMessage] --> N[StreamingState]
        O[ToolConfirmationMessage] --> P[ConfirmationDetails]
    end
    
    subgraph "Theming"
        Q[ThemeManager] --> R[Theme Types]
        Q --> S[Custom Extensions]
    end
```

## Component Categories

### 1. Layout Components

#### AppHeader
The main header component displaying CLI branding, version information, and user identity.

| Property | Type | Description |
|----------|------|-------------|
| `showHeader` | `boolean` | Controls header visibility |
| `showDetails` | `boolean` | Shows detailed metadata |
| `bannerVisible` | `boolean` | Displays warning/info banners |
| `bannerText` | `string` | Banner content text |

**Key Features:**
- Dynamic layout: switches between row and column orientation based on terminal width
- Update notifications with spinner animation during version checks
- User identity display (email and plan information)
- Collapsible tips section
- Configurable branding via logo text art

**Source:** [packages/cli/src/ui/components/AppHeader.tsx:1-100]()

#### Composer
Input component for user commands and messages.

Provides the text input interface for interacting with Gemini CLI, supporting multi-line input and command submission.

### 2. Dialog Components

#### AuthDialog
Handles user authentication flow with multiple provider options.

```mermaid
graph LR
    A[Launch] --> B{Auth Method?}
    B -->|OAuth| C[Google Login]
    B -->|Token| D[API Key Input]
    B -->|Skip| E[Continue Anonymously]
    C --> F[Restart CLI]
    D --> G[Validate Token]
    E --> H[Limited Mode]
```

**Features:**
- Radio button selection for authentication methods
- Error state handling with visual feedback
- Links to Terms of Service and Privacy Notice
- OAuth flow with automatic CLI restart

**Source:** [packages/cli/src/ui/auth/AuthDialog.tsx:1-80]()

#### ModelDialog
Displays available models with quota information and allows model selection.

| Property | Type | Description |
|----------|------|-------------|
| `modelVersion` | `string` | Currently active model identifier |
| `quotaDisplay` | `QuotaBucket[]` | Rate limit information |
| `terminalWidth` | `number` | Available display width |

**Source:** [packages/cli/src/ui/components/ModelDialog.tsx:1-60]()

#### FolderTrustDialog
Security-focused dialog for approving folder configurations.

**Key Sections:**
1. **Trust Explanation** - Documents what configurations will be loaded
2. **Discovery Results** - Shows found extensions, commands, hooks, and skills
3. **Security Warnings** - Highlights potentially risky configurations
4. **Discovery Errors** - Reports parsing or loading failures

**Source:** [packages/cli/src/ui/components/FolderTrustDialog.tsx:1-100]()

#### InboxDialog
Displays notification patches and skill updates available for installation.

| Display Field | Source | Format |
|--------------|--------|--------|
| Title | `patch.name` | `string + [origin]` |
| Subtitle | `patch.extractedAt` | `files · date` |
| Content Preview | `skillSections` | Scrollable diff |

**Source:** [packages/cli/src/ui/components/InboxDialog.tsx:1-120]()

### 3. Message Components

#### GeminiMessage
Renders AI-generated responses with markdown support.

**Rendering Modes:**
- **Markdown Rendered** (default): Full markdown parsing with syntax highlighting
- **Raw Markdown**: Syntax highlighting without line numbers

**Configuration Options:**
```typescript
interface GeminiMessageProps {
  text: string;           // Message content
  isPending: boolean;     // Streaming indicator
  terminalWidth: number;  // Layout adaptation
  renderMarkdown?: boolean;
  streamingState?: StreamingState;
}
```

**Source:** [packages/cli/src/ui/components/messages/GeminiMessage.test.tsx:1-50]()

#### ToolConfirmationMessage
Displays interactive confirmation prompts for tool execution.

**Supported Types:**
- `edit` - File modification operations
- `read` - Content retrieval requests
- `execute` - Command execution confirmations
- `delete` - Resource removal confirmations

**States:**
- Normal confirmation view
- In-progress indicator ("Save and close external editor")
- Security warning display
- System message overlay

**Source:** [packages/cli/src/ui/components/ToolConfirmationMessage.tsx:1-100]()

### 4. Information Components

#### AboutBox
Displays system and version information.

| Field | Source | Visibility |
|-------|--------|------------|
| CLI Version | `cliVersion` | Always |
| Git Commit | `GIT_COMMIT_INFO` | Unless "N/A" |
| Model | `modelVersion` | Always |
| Sandbox | `sandboxEnv` | Always |
| OS | System Info | Always |

**Source:** [packages/cli/src/ui/components/AboutBox.tsx:1-60]()

## Theming System

The UI supports customizable color themes that apply consistent styling across all components.

### Theme Structure

```typescript
interface Theme {
  text: {
    primary: string;
    secondary: string;
    accent: string;
    link: string;
  };
  status: {
    success: string;
    warning: string;
    error: string;
  };
  border: {
    default: string;
  };
  ui: {
    focus: string;
  };
}
```

### Theme Configuration

Users can create custom themes by:
1. Creating an extension with theme definition in `gemini-extension.json`
2. Setting the theme in `~/.gemini/settings.json`:
   ```json
   {
     "ui": {
       "theme": "theme-name (extension-name)"
     }
   }
   ```

### Available UI Settings

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `showUserIdentity` | `boolean` | `true` | Display email and plan |
| `hideTips` | `boolean` | `false` | Hide tips section |
| `renderMarkdown` | `boolean` | `true` | Enable markdown rendering |

## Component Composition Patterns

### Dialog Pattern
All dialogs follow a consistent structure:

```typescript
<Box borderStyle="round" borderColor={theme.ui.focus}>
  <Box flexDirection="column">
    {/* Title */}
    <Text bold>{title}</Text>
    
    {/* Content */}
    {children}
    
    {/* Footer */}
    <DialogFooter 
      primaryAction="Enter to select"
      cancelAction="Esc to close"
    />
  </Box>
</Box>
```

### Responsive Layout
Components adapt to terminal width using:
- Flexbox with `flexDirection` switching (row/column)
- Percentage-based widths (`width="35%"`)
- Conditional rendering based on `terminalWidth`
- Maximum size constraints via `MaxSizedBox`

### Color Application
Components use semantic color tokens:
- `theme.text.primary` - Main content text
- `theme.text.secondary` - Supporting text
- `theme.text.accent` - Highlighted elements
- `theme.text.link` - Interactive links
- `theme.status.*` - State indicators (success, warning, error)

## State Management

### UI State Context
Components access shared state through React context:

```typescript
interface UIState {
  renderMarkdown: boolean;
  streamingState: StreamingState;
  terminalWidth: number;
}
```

### Component Communication
| Pattern | Example | Purpose |
|---------|---------|---------|
| Props drilling | `AuthDialog` → `RadioButtonSelect` | Simple parent-child |
| Context | `theme` access | Global styling |
| Callback props | `onSelect`, `onHighlight` | Event handling |
| State updates | `isUpdating` flag | Async operations |

## Security Features

### Folder Trust System
The `FolderTrustDialog` implements security boundaries:

1. **Discovery Phase**: Scans for configuration files
2. **Warning Phase**: Identifies potentially dangerous configurations
3. **Approval Phase**: User explicitly approves folder access
4. **Execution Phase**: Loads approved configurations

### Data Collection Opt-In
Users can control whether usage data is collected:
- UI toggle in privacy settings
- Persisted preference in `settings.json`
- Clear documentation in privacy notices

## Testing Approach

Components use snapshot testing with `renderWithProviders`:

```typescript
it('renders pending state', async () => {
  const { lastFrame } = await renderWithProviders(
    <GeminiMessage {...props} isPending={true} />,
    { uiState: { renderMarkdown: true } }
  );
  expect(lastFrame()).toMatchSnapshot();
});
```

Test utilities provide:
- Mocked Ink components
- Theme injection
- State context setup
- Terminal width simulation

## Best Practices

### Component Guidelines
1. **Accessibility**: Support keyboard navigation (Enter, Escape)
2. **Responsiveness**: Adapt to variable terminal widths
3. **Error Handling**: Display clear error messages with colors
4. **Loading States**: Show spinners and progress indicators

### Styling Guidelines
1. Use semantic theme tokens instead of hardcoded colors
2. Prefer flexbox layouts over absolute positioning
3. Include proper margin and padding for visual hierarchy
4. Use truncation for long text with `wrap="truncate-end"`

### Performance Considerations
1. Minimize re-renders with proper memoization
2. Use virtual scrolling for long lists
3. Lazy load heavy content (skill previews)
4. Cache discovery results when appropriate

---

<a id='session-management'></a>

## Session Management

### 相关页面

相关主题：[Terminal UI Components](#terminal-ui), [Context and Memory Management](#context-pipeline)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)
- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)
- [packages/cli/src/ui/commands/bugCommand.test.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/commands/bugCommand.test.ts)
- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)
- [packages/sdk/src/agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/src/agent.ts)
- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)
- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)
</details>

# Session Management

## Overview

Session Management in Gemini CLI provides persistent conversation contexts that enable users to resume work across CLI invocations, track project-specific interactions, and maintain stateful relationships between user prompts and model responses. The system orchestrates session lifecycle events including creation, storage, retrieval, resumption, and cleanup through an integrated stack spanning the core SDK, CLI UI components, and storage services.

Sessions serve as the fundamental unit of work in Gemini CLI, encapsulating all metadata and message history associated with a continuous interaction sequence. Each session is uniquely identified by a `sessionId` and tied to a specific project context via a `projectHash`, enabling the CLI to distinguish between multiple concurrent or historical conversations.

资料来源：[packages/core/src/services/chatRecordingService.ts:35-36]()

## Session Lifecycle

```mermaid
graph TD
    A[User Starts CLI] --> B{Check for Existing Session?}
    B -->|Yes| C[Resume Session]
    B -->|No| D[Create New Session]
    D --> E[Generate Session ID]
    E --> F[Initialize Context Graph]
    F --> G[Start Conversation]
    C --> H[Load Session from Storage]
    H --> G
    G --> I[Process User Input]
    I --> J[Record Message to ChatHistory]
    J --> K{User Exits?}
    K -->|No| I
    K -->|Yes| L[Save Session Metadata]
    L --> M[Close Session]
```

### Session Creation

When a user launches Gemini CLI without specifying an existing session, the system generates a new session identifier and initializes an empty conversation record. The session creation process involves:

1. **Session ID Generation**: A cryptographically stable session ID is created using the `createSessionId()` utility function. This ID persists across CLI restarts and is used to resume the same conversation.

2. **Project Hash Computation**: The system computes a hash of the current working directory to associate the session with a specific project context.

3. **Storage Initialization**: The `ChatRecordingService` prepares file-based storage at a project-specific temp directory, enabling conversation persistence.

资料来源：[packages/sdk/src/agent.ts:58-60]()

### Session Resume

The session resume capability allows users to continue previous conversations seamlessly. When resuming a session, the system:

1. Loads the complete conversation history from JSONL storage
2. Reconstructs the context graph from stored messages
3. Validates authentication state
4. Restores model configuration and tool states

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant ChatRecordingService
    participant GeminiAgent
    
    User->>CLI: Resume Session (sessionId)
    CLI->>ChatRecordingService: Load Conversation Record
    ChatRecordingService-->>CLI: ConversationRecord (messages, metadata)
    CLI->>GeminiAgent: Initialize with Loaded State
    GeminiAgent-->>CLI: Session Ready
    CLI->>User: Display Last N Messages
```

资料来源：[packages/core/src/services/chatRecordingService.ts:45-52]()

## Session Data Model

The `ConversationRecord` interface defines the complete structure of a persisted session:

| Field | Type | Description |
|-------|------|-------------|
| `sessionId` | `string` | Unique identifier for the session |
| `projectHash` | `string` | Hash of the project directory |
| `startTime` | `string` (ISO 8601) | Session creation timestamp |
| `lastUpdated` | `string` (ISO 8601) | Last modification timestamp |
| `summary` | `string \| undefined` | Auto-generated conversation summary |
| `memoryScratchpad` | `string \| undefined` | Persistent scratchpad notes |
| `directories` | `string[]` | Working directories used in session |
| `kind` | `string` | Session kind/type identifier |
| `messages` | `Message[]` | Full message history |
| `messageCount` | `number` | Total message count |
| `userMessageCount` | `number` | Count of user messages only |
| `memoryScratchpadIsStale` | `boolean \| undefined` | Indicates if scratchpad needs refresh |
| `firstUserMessage` | `string \| undefined` | First user prompt for quick reference |
| `hasUserOrAssistantMessage` | `boolean` | Indicates non-empty conversation |

资料来源：[packages/core/src/services/chatRecordingService.ts:32-50]()

### Message Structure

Messages within a session follow the multi-part content model:

```typescript
interface Message {
  role: 'user' | 'model' | 'system' | 'tool';
  parts: Array<{
    text?: string;
    functionCall?: FunctionCall;
    functionResponse?: FunctionResponse;
  }>;
}
```

The context graph builder processes each turn by:

1. Generating a stable MD5 hash from role and content for deduplication
2. Assigning an occurrence counter for repeated identical messages
3. Creating a stable turn ID using the `getStableId()` utility
4. Tracking function calls and responses with unique identifiers

资料来源：[packages/core/src/context/graph/toGraph.ts:1-30]()

## Storage Architecture

### Chat Recording Service

The `ChatRecordingService` class manages all session persistence operations:

```mermaid
graph LR
    A[In-Memory Cache] -->|Write-through| B[JSONL File]
    C[Session Load Request] --> D{Cache Hit?}
    D -->|Yes| A
    D -->|No| B
    B -->|Load| A
```

**Key Responsibilities:**

| Responsibility | Description |
|----------------|-------------|
| Conversation Recording | Writes messages to JSONL format |
| Session Loading | Loads and reconstructs sessions from disk |
| Metadata Management | Tracks summary, scratchpad, and timestamps |
| Message Deduplication | Uses content hashing to identify duplicate turns |

资料来源：[packages/core/src/services/chatRecordingService.ts:85-90]()

### Storage Directory Structure

Sessions are stored in the project temp directory:

```
/tmp/gemini/
├── conversation-{sessionId}.jsonl   # Full message history
├── session-{sessionId}.json         # Session metadata
├── bug-report-history-{timestamp}.json  # Bug report exports
└── checkpoints/                     # Checkpoint snapshots
```

The `getProjectTempDir()` method determines the storage path based on the active project context.

资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:60-62]()

## Session Browser Component

The `SessionBrowser` UI component provides an interactive interface for managing multiple sessions:

- **Session List View**: Displays all historical sessions for a project
- **Session Preview**: Shows message count, date range, and summary
- **Session Actions**: Resume, rename, delete, or export sessions
- **Search/Filter**: Find sessions by content or date

```typescript
interface SessionBrowserProps {
  sessions: ConversationRecord[];
  onSelect: (sessionId: string) => void;
  onDelete: (sessionId: string) => Promise<void>;
  onExport: (sessionId: string) => Promise<void>;
}
```

资料来源：[packages/cli/src/ui/components/SessionBrowser.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/SessionBrowser.tsx)

## Rewind Viewer

The `RewindViewer` component enables users to navigate and review historical conversation states:

- **Timeline Navigation**: Move through conversation turns chronologically
- **State Restoration**: View message content at any past point
- **Diff View**: Compare changes between turns (optional)

This component leverages the turn-by-turn tracking implemented in the context graph builder to provide accurate historical snapshots.

资料来源：[packages/cli/src/ui/components/RewindViewer.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/RewindViewer.tsx)

## Session Operations

The `sessionOperations.ts` utility module provides core session manipulation functions:

### Available Operations

| Operation | Description |
|-----------|-------------|
| `createSessionId()` | Generate a new unique session identifier |
| `loadSession()` | Load session data from storage |
| `saveSession()` | Persist session state to disk |
| `deleteSession()` | Remove session and associated data |
| `exportSession()` | Export session to portable format |
| `listSessions()` | Enumerate all sessions for a project |

### Session Resume Flow

```mermaid
graph TD
    A[Load Session Record] --> B{Valid Session?}
    B -->|No| C[Raise Error]
    B -->|Yes| D[Load Message History]
    D --> E[Reconstruct Context Graph]
    E --> F[Initialize Agent State]
    F --> G[Ready for User Input]
```

资料来源：[packages/core/src/utils/sessionOperations.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/sessionOperations.ts)

## Context Graph Integration

The context graph system maintains the semantic structure of conversations independently from raw message storage:

1. **Turn Tracking**: Each user-model exchange is assigned a unique turn ID
2. **Role Management**: Messages are tagged with roles (user, model, tool, system)
3. **Function Call Tracking**: Tool interactions are recorded with unique IDs (`call_{id}` or `resp_{id}`)
4. **Legacy Header Handling**: Automatically skips legacy environment headers during graph reconstruction

The graph builder generates stable identifiers using:

```typescript
const turnContent = JSON.stringify(msg.parts);
const h = createHash('md5').update(`${msg.role}:${turnContent}`).digest('hex');
const occurrence = (seenHashes.get(h) || 0) + 1;
const turnSalt = `${h}_${occurrence}`;
const turnId = getStableId(msg, this.nodeIdentityMap, turnSalt, -1);
```

资料来源：[packages/core/src/context/graph/toGraph.ts:18-25]()

## SDK Integration

The Gemini CLI SDK exposes session management through the `GeminiCliAgent` and `GeminiCliSession` classes:

```typescript
const agent = new GeminiCliAgent({
  instructions: 'You are a helpful coding assistant.',
  tools: [myTool],
});

// Create a new session
const session = agent.session();
await session.initialize();

// Resume an existing session
const resumedSession = agent.session({ sessionId: 'existing-id' });
await resumedSession.initialize();

// Stream messages
for await (const event of session.sendStream('Hello!')) {
  console.log(event);
}
```

资料来源：[packages/sdk/src/agent.ts:35-55]()

## About Box Display

Session metadata is surfaced in the CLI's About dialog:

| Field | Source | Display |
|-------|--------|---------|
| CLI Version | Package version | Always shown |
| Git Commit | Build-time constant | Conditional (non-N/A) |
| Model | Active model configuration | Always shown |
| Sandbox | Environment indicator | Always shown |
| OS | System information | Always shown |

资料来源：[packages/cli/src/ui/components/AboutBox.tsx:20-50]()

## Configuration

### Session-Related Settings

| Setting | Description | Default |
|---------|-------------|---------|
| `sessionStorageDir` | Override default temp storage | `/tmp/gemini` |
| `maxSessions` | Maximum sessions per project | 50 |
| `autoSaveInterval` | Auto-save frequency (ms) | 30000 |
| `sessionId` | Specific session to resume | (none) |

### Bug Report Integration

When submitting bug reports via `/bug`, the session automatically exports chat history:

```typescript
const history = geminiClient.getChat().getHistory();
const bugReportPath = path.join(
  storage.getProjectTempDir(),
  `bug-report-history-${Date.now()}.json`
);
await exportHistoryToFile({ history, filePath: bugReportPath });
```

The exported history includes the full conversation record and is attached to the GitHub issue for diagnostic purposes.

资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:45-65]()

## Checkpointing

Sessions support checkpointing for disaster recovery and long-running task management:

- **Automatic Checkpoints**: Created at significant conversation milestones
- **Manual Checkpoints**: User-triggered via `/checkpoint` command
- **Checkpoint Restoration**: Resume from any saved checkpoint state

Checkpoints are stored alongside regular session data and include complete message history plus agent state snapshots.

资料来源：[docs/cli/checkpointing.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/checkpointing.md)

## Best Practices

1. **Session Isolation**: Each project should maintain its own session context
2. **Regular Exports**: Export important sessions before cleanup
3. **Scratchpad Usage**: Use the memory scratchpad for cross-session notes
4. **Metadata Maintenance**: Keep session summaries accurate for quick identification
5. **Storage Cleanup**: Periodically remove old sessions to conserve disk space

## Related Commands

| Command | Purpose |
|---------|---------|
| `/new` | Start a fresh session |
| `/sessions` | List and manage sessions |
| `/resume <id>` | Resume a specific session |
| `/export` | Export session to file |
| `/checkpoint` | Create session checkpoint |

---

---

## Doramagic 踩坑日志

项目：google-gemini/gemini-cli

摘要：发现 39 个潜在踩坑项，其中 11 个为 high/blocking；最高优先级：安装坑 - 来源证据：MCP servers not connected in -p (non-interactive) mode。

## 1. 安装坑 · 来源证据：MCP servers not connected in -p (non-interactive) mode

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。

## 2. 运行坑 · 来源证据：Stabilize and Enhance Internal Project Evaluations

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。

## 3. 安全/权限坑 · 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging

- 严重度：high
- 证据强度：source_linked
- 发现：Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging
- 对用户的影响：Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Add deterministic redaction and reduce Auto Memory logging. Context: Observed when using node
- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/google-gemini/gemini-cli/issues/26525
- 证据：failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging

## 4. 安全/权限坑 · 失败模式：security_permissions: Robust component level evalutions

- 严重度：high
- 证据强度：source_linked
- 发现：Developers should check this security_permissions risk before relying on the project: Robust component level evalutions
- 对用户的影响：Developers may expose sensitive permissions or credentials: Robust component level evalutions
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Robust component level evalutions. Context: Source discussion did not expose a precise runtime context.
- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/google-gemini/gemini-cli/issues/24353
- 证据：failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions

## 5. 安全/权限坑 · 来源证据：Add deterministic redaction and reduce Auto Memory logging

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 6. 安全/权限坑 · 来源证据：Assess the impact of AST-aware file reads, search, and mapping

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 安全/权限坑 · 来源证据：Missing validation for critical configuration files could lead to broken bundles

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 8. 安全/权限坑 · 来源证据：Shell command execution gets stuck with "Waiting input" after command completes

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with "Waiting input" after command completes
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 9. 安全/权限坑 · 来源证据：Tracking: 429 / Capacity Issues

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。

## 10. 安全/权限坑 · 来源证据：[Bug] Proxy local bypass does not recognize environment variables

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。

## 11. 安全/权限坑 · 来源证据：fata error again!

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：fata error again!
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6345aa3da845458888c6e250cd950be0 | https://github.com/google-gemini/gemini-cli/issues/27084 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 12. 安装坑 · 失败模式：installation: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing
- 对用户的影响：Developers may fail before the first successful local run: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing. Context: Observed when using macos
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_5a9a3046d11e48e7d258f82489fe0315 | https://github.com/google-gemini/gemini-cli/issues/27192 | The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing

## 13. 安装坑 · 来源证据：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d81ba1a5c929402ba842a14ce13fa62d | https://github.com/google-gemini/gemini-cli/issues/23365 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 配置坑 · 失败模式：configuration: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore). Context: Observed when using python, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_54138499ddaf2313b5bbf47db8596fdf | https://github.com/google-gemini/gemini-cli/issues/27205 | GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)

## 15. 配置坑 · 失败模式：configuration: GeminiCLI.com Feedback: [ISSUE]

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: GeminiCLI.com Feedback: [ISSUE]
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GeminiCLI.com Feedback: [ISSUE]
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: GeminiCLI.com Feedback: [ISSUE]. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_b159ada1eb969fa31659644535ca2fea | https://github.com/google-gemini/gemini-cli/issues/27206 | GeminiCLI.com Feedback: [ISSUE]

## 16. 配置坑 · 失败模式：configuration: MCP servers not connected in -p (non-interactive) mode

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: MCP servers not connected in -p (non-interactive) mode
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: MCP servers not connected in -p (non-interactive) mode
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: MCP servers not connected in -p (non-interactive) mode. Context: Observed when using python, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_296b06c2af838c7fc803500446053d31 | https://github.com/google-gemini/gemini-cli/issues/26021 | MCP servers not connected in -p (non-interactive) mode

## 17. 配置坑 · 失败模式：configuration: Missing validation for critical configuration files could lead to broken bundles

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Missing validation for critical configuration files could lead to broken bundles
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Missing validation for critical configuration files could lead to broken bundles
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Missing validation for critical configuration files could lead to broken bundles. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_7d4479666cef0d386bd8d2eed9199700 | https://github.com/google-gemini/gemini-cli/issues/16114 | Missing validation for critical configuration files could lead to broken bundles

## 18. 配置坑 · 失败模式：configuration: SLOW Response and Usage limits stop gemini CLI. = unusable

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: SLOW Response and Usage limits stop gemini CLI. = unusable
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: SLOW Response and Usage limits stop gemini CLI. = unusable
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: SLOW Response and Usage limits stop gemini CLI. = unusable. Context: Observed when using macos
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_4b0905c8b98c8068f1e086e4c8d4283f | https://github.com/google-gemini/gemini-cli/issues/27209 | SLOW Response and Usage limits stop gemini CLI. = unusable

## 19. 配置坑 · 失败模式：configuration: Stop Auto Memory from retrying low-signal sessions indefinitely

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Stop Auto Memory from retrying low-signal sessions indefinitely
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Stop Auto Memory from retrying low-signal sessions indefinitely
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Stop Auto Memory from retrying low-signal sessions indefinitely. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_74bd0dbfbc273c5c6f5235f76b6362dd | https://github.com/google-gemini/gemini-cli/issues/26522 | Stop Auto Memory from retrying low-signal sessions indefinitely

## 20. 配置坑 · 失败模式：configuration: Surface or quarantine invalid Auto Memory inbox patches

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Surface or quarantine invalid Auto Memory inbox patches
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Surface or quarantine invalid Auto Memory inbox patches
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Surface or quarantine invalid Auto Memory inbox patches. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_e7ea4760266f8df60623eea9a521182c | https://github.com/google-gemini/gemini-cli/issues/26523 | Surface or quarantine invalid Auto Memory inbox patches

## 21. 配置坑 · 失败模式：configuration: The write_file tool corrupts or truncates long text sequences during file writes

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: The write_file tool corrupts or truncates long text sequences during file writes
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: The write_file tool corrupts or truncates long text sequences during file writes
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: The write_file tool corrupts or truncates long text sequences during file writes. Context: Observed when using linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_008c0114af36c2dc18d97f0e37dce7a5 | https://github.com/google-gemini/gemini-cli/issues/27213 | The write_file tool corrupts or truncates long text sequences during file writes

## 22. 配置坑 · 失败模式：configuration: Tracking: 429 / Capacity Issues

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Tracking: 429 / Capacity Issues
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Tracking: 429 / Capacity Issues
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tracking: 429 / Capacity Issues. Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_7a6143043d54543ab2db0b094ce75112 | https://github.com/google-gemini/gemini-cli/issues/24937 | Tracking: 429 / Capacity Issues

## 23. 配置坑 · 失败模式：configuration: Typing unmapped keys in Vim Normal mode inserts characters into input field

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Typing unmapped keys in Vim Normal mode inserts characters into input field
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Typing unmapped keys in Vim Normal mode inserts characters into input field
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Typing unmapped keys in Vim Normal mode inserts characters into input field. Context: Observed when using linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_bfe6a73a9d93357029974a8d1495ac32 | https://github.com/google-gemini/gemini-cli/issues/21686 | Typing unmapped keys in Vim Normal mode inserts characters into input field

## 24. 配置坑 · 失败模式：configuration: YOLO mode should override block of command-substitution in bash

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: YOLO mode should override block of command-substitution in bash
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: YOLO mode should override block of command-substitution in bash
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: YOLO mode should override block of command-substitution in bash. Context: Observed when using linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_f6799c6b8d0a67648c6d5a22edadb552 | https://github.com/google-gemini/gemini-cli/issues/6436 | YOLO mode should override block of command-substitution in bash

## 25. 配置坑 · 失败模式：configuration: [Bug] Proxy local bypass does not recognize environment variables

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: [Bug] Proxy local bypass does not recognize environment variables
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug] Proxy local bypass does not recognize environment variables
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug] Proxy local bypass does not recognize environment variables. Context: Observed when using linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_51d3e1e0eea75b650d21b4450e47c7f8 | https://github.com/google-gemini/gemini-cli/issues/23372 | [Bug] Proxy local bypass does not recognize environment variables

## 26. 配置坑 · 失败模式：configuration: fata error again!

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: fata error again!
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: fata error again!
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: fata error again!. Context: Observed when using linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_7aa1a144aa2c7dbf177ed2e61f9c1bf4 | https://github.com/google-gemini/gemini-cli/issues/27084 | fata error again!

## 27. 配置坑 · 来源证据：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_47cc7af8a64b46f98a999ac7e6a42ab8 | https://github.com/google-gemini/gemini-cli/issues/25164 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 28. 能力坑 · 社区讨论暴露的待验证问题：Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit

- 严重度：medium
- 证据强度：source_linked
- 发现：Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit 11 Jul 2025 · https://github.com/google-gemini/gemini-cli · https://blog.google/technology/developers/introducing-gemini-cli-open-source-ai-agent/ · Dentuam.
- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。
- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。
- 证据：social_signal:reddit | ssig_c4981b55cfdd415d980deff32dcc52a8 | https://www.reddit.com/r/LocalLLaMA/comments/1lww2w9/open_source_claude_coder_alternative/ | Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit

## 29. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | README/documentation is current enough for a first validation pass.

## 30. 维护坑 · 来源证据：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_b6fd46e95c92462b8893c41314dc2cb9 | https://github.com/google-gemini/gemini-cli/issues/21421 | 来源类型 github_issue 暴露的待验证使用条件。

## 31. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | last_activity_observed missing

## 32. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium

## 33. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium

## 34. 安全/权限坑 · 来源证据：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a69b38f144734c1c96d81d75610a66a1 | https://github.com/google-gemini/gemini-cli/issues/27192 | 来源类型 github_issue 暴露的待验证使用条件。

## 35. 安全/权限坑 · 来源证据：The Gemini CLI interface keeps flickering

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The Gemini CLI interface keeps flickering
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_364c1744ad1c4dc79881a9ab22c7305b | https://github.com/google-gemini/gemini-cli/issues/14708 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 36. 安全/权限坑 · 来源证据：Typing unmapped keys in Vim Normal mode inserts characters into input field

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Typing unmapped keys in Vim Normal mode inserts characters into input field
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_47b14e4e29a548d59ea09e120401bd88 | https://github.com/google-gemini/gemini-cli/issues/21686 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。

## 37. 安全/权限坑 · 来源证据：YOLO mode should override block of command-substitution in bash

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：YOLO mode should override block of command-substitution in bash
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_adf70ddf872342c08ce46daccf869dba | https://github.com/google-gemini/gemini-cli/issues/6436 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。

## 38. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | issue_or_pr_quality=unknown

## 39. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | release_recency=unknown

<!-- canonical_name: google-gemini/gemini-cli; human_manual_source: deepwiki_human_wiki -->
