{
  "canonical_name": "google-gemini/gemini-cli",
  "compilation_id": "pack_ea5646740e954497ad052d08ee6a34da",
  "created_at": "2026-05-19T06:49:14.968214+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npx @google/gemini-cli` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npx @google/gemini-cli",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_a662361d9da14f2ead3ffdf9c647cb9f"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_a739e6bf97552f632a54be02f6ae89b8",
    "canonical_name": "google-gemini/gemini-cli",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/google-gemini/gemini-cli",
    "slug": "gemini-cli",
    "source_packet_id": "phit_a150ede1ae46455ca64abcc0faeb4815",
    "source_validation_id": "dval_db8319d8d7e54841875a82b94e0be05e"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 mcp_host的用户",
    "github_forks": 13621,
    "github_stars": 103838,
    "one_liner_en": "An open-source AI agent that brings the power of Gemini directly into your terminal.",
    "one_liner_zh": "An open-source AI agent that brings the power of Gemini directly into your terminal.",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "medium",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:git, cli"
    },
    "target_user": "使用 mcp_host 等宿主 AI 的用户",
    "title_en": "gemini-cli",
    "title_zh": "gemini-cli 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Browser Automation",
        "label_zh": "浏览器自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-browser-automation",
        "type": "core_capability"
      },
      {
        "label_en": "Page Observation and Action Planning",
        "label_zh": "页面观察与动作规划",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-page-observation-and-action-planning",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_a150ede1ae46455ca64abcc0faeb4815",
  "page_model": {
    "artifacts": {
      "artifact_slug": "gemini-cli",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npx @google/gemini-cli",
          "label": "Gemini CLI · 官方安装入口",
          "source": "https://github.com/google-gemini/gemini-cli#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "An open-source AI agent that brings the power of Gemini directly into your terminal."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：MCP servers not connected in -p (non-interactive) mode",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Stabilize and Enhance Internal Project Evaluations",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging"
            ],
            "severity": "high",
            "suggested_check": "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",
            "title": "失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging",
            "user_impact": "Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: Robust component level evalutions",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions"
            ],
            "severity": "high",
            "suggested_check": "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.",
            "title": "失败模式：security_permissions: Robust component level evalutions",
            "user_impact": "Developers may expose sensitive permissions or credentials: Robust component level evalutions"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Add deterministic redaction and reduce Auto Memory logging",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Assess the impact of AST-aware file reads, search, and mapping",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Missing validation for critical configuration files could lead to broken bundles",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with \"Waiting input\" after command completes",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Shell command execution gets stuck with \"Waiting input\" after command completes",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Tracking: 429 / Capacity Issues",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Bug] Proxy local bypass does not recognize environment variables",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：fata error again!",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_6345aa3da845458888c6e250cd950be0 | https://github.com/google-gemini/gemini-cli/issues/27084 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：fata error again!",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "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",
            "category": "安装坑",
            "evidence": [
              "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"
            ],
            "severity": "medium",
            "suggested_check": "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",
            "title": "失败模式：installation: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing",
            "user_impact": "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"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_d81ba1a5c929402ba842a14ce13fa62d | https://github.com/google-gemini/gemini-cli/issues/23365 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)",
            "category": "配置坑",
            "evidence": [
              "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)"
            ],
            "severity": "medium",
            "suggested_check": "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",
            "title": "失败模式：configuration: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: GeminiCLI.com Feedback: [ISSUE]",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_b159ada1eb969fa31659644535ca2fea | https://github.com/google-gemini/gemini-cli/issues/27206 | GeminiCLI.com Feedback: [ISSUE]"
            ],
            "severity": "medium",
            "suggested_check": "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.",
            "title": "失败模式：configuration: GeminiCLI.com Feedback: [ISSUE]",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: GeminiCLI.com Feedback: [ISSUE]"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: MCP servers not connected in -p (non-interactive) mode",
            "category": "配置坑",
            "evidence": [
              "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"
            ],
            "severity": "medium",
            "suggested_check": "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",
            "title": "失败模式：configuration: MCP servers not connected in -p (non-interactive) mode",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: MCP servers not connected in -p (non-interactive) mode"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 39 个潜在踩坑项，其中 11 个为 high/blocking；最高优先级：安装坑 - 来源证据：MCP servers not connected in -p (non-interactive) mode。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 666,
        "forks": 13621,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 103838
      },
      "source_url": "https://github.com/google-gemini/gemini-cli",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "An open-source AI agent that brings the power of Gemini directly into your terminal.",
      "title": "gemini-cli 能力包",
      "trial_prompt": "# gemini-cli - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for google-gemini/gemini-cli.\n\nProject:\n- Name: gemini-cli\n- Repository: https://github.com/google-gemini/gemini-cli\n- Summary: An open-source AI agent that brings the power of Gemini directly into your terminal.\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: An open-source AI agent that brings the power of Gemini directly into your terminal.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n2. agent-system: Agent System. Produce one small intermediate artifact and wait for confirmation.\n3. context-pipeline: Context and Memory Management. Produce one small intermediate artifact and wait for confirmation.\n4. tools-reference: Tools Reference. Produce one small intermediate artifact and wait for confirmation.\n5. sandboxing-security: Sandboxing and Security. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/google-gemini/gemini-cli\n- https://github.com/google-gemini/gemini-cli#readme\n- .gemini/skills/async-pr-review/SKILL.md\n- .gemini/skills/behavioral-evals/SKILL.md\n- .gemini/skills/ci/SKILL.md\n- .gemini/skills/code-reviewer/SKILL.md\n- .gemini/skills/docs-changelog/SKILL.md\n- .gemini/skills/docs-writer/SKILL.md\n- .gemini/skills/github-issue-creator/SKILL.md\n- .gemini/skills/pr-address-comments/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: Robust component level evalutions（https://github.com/google-gemini/gemini-cli/issues/24353）；github/github_issue: Shell command execution gets stuck with \"Waiting input\" after command co（https://github.com/google-gemini/gemini-cli/issues/25166）；github/github_issue: Surface or quarantine invalid Auto Memory inbox patches（https://github.com/google-gemini/gemini-cli/issues/26523）；github/github_issue: Stop Auto Memory from retrying low-signal sessions indefinitely（https://github.com/google-gemini/gemini-cli/issues/26522）；github/github_issue: Add deterministic redaction and reduce Auto Memory logging（https://github.com/google-gemini/gemini-cli/issues/26525）；github/github_issue: gemini --resume cannot detect local history sessions（https://github.com/google-gemini/gemini-cli/issues/27243）；github/github_issue: fata error again!（https://github.com/google-gemini/gemini-cli/issues/27084）；github/github_issue: Missing validation for critical configuration files could lead to broken（https://github.com/google-gemini/gemini-cli/issues/16114）；github/github_issue: Typing unmapped keys in Vim Normal mode inserts characters into input fi（https://github.com/google-gemini/gemini-cli/issues/21686）；github/github_issue: [Windows] run_shell_command always returns empty output — isBinary() fal（https://github.com/google-gemini/gemini-cli/issues/25164）；github/github_issue: Gemini CLI should periodically reflect on the trajectory and recommend t（https://github.com/google-gemini/gemini-cli/issues/21421）；github/github_issue: The write_file tool corrupts or truncates long text sequences during fil（https://github.com/google-gemini/gemini-cli/issues/27213）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Robust component level evalutions",
              "url": "https://github.com/google-gemini/gemini-cli/issues/24353"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Shell command execution gets stuck with \"Waiting input\" after command co",
              "url": "https://github.com/google-gemini/gemini-cli/issues/25166"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Surface or quarantine invalid Auto Memory inbox patches",
              "url": "https://github.com/google-gemini/gemini-cli/issues/26523"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Stop Auto Memory from retrying low-signal sessions indefinitely",
              "url": "https://github.com/google-gemini/gemini-cli/issues/26522"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Add deterministic redaction and reduce Auto Memory logging",
              "url": "https://github.com/google-gemini/gemini-cli/issues/26525"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "gemini --resume cannot detect local history sessions",
              "url": "https://github.com/google-gemini/gemini-cli/issues/27243"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "fata error again!",
              "url": "https://github.com/google-gemini/gemini-cli/issues/27084"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Missing validation for critical configuration files could lead to broken",
              "url": "https://github.com/google-gemini/gemini-cli/issues/16114"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Typing unmapped keys in Vim Normal mode inserts characters into input fi",
              "url": "https://github.com/google-gemini/gemini-cli/issues/21686"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Windows] run_shell_command always returns empty output — isBinary() fal",
              "url": "https://github.com/google-gemini/gemini-cli/issues/25164"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Gemini CLI should periodically reflect on the trajectory and recommend t",
              "url": "https://github.com/google-gemini/gemini-cli/issues/21421"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "The write_file tool corrupts or truncates long text sequences during fil",
              "url": "https://github.com/google-gemini/gemini-cli/issues/27213"
            }
          ],
          "status": "已收录 15 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "An open-source AI agent that brings the power of Gemini directly into your terminal.",
      "effort": "安装已验证",
      "forks": 13621,
      "icon": "code",
      "name": "gemini-cli 能力包",
      "risk": "可发布",
      "slug": "gemini-cli",
      "stars": 103838,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/google-gemini/gemini-cli 项目说明书\n\n生成时间：2026-05-16 02:07:33 UTC\n\n## 目录\n\n- [Architecture Overview](#architecture-overview)\n- [Agent System](#agent-system)\n- [Context and Memory Management](#context-pipeline)\n- [Tools Reference](#tools-reference)\n- [MCP Integration](#mcp-integration)\n- [Skills and Extensions](#skills-extensions)\n- [Sandboxing and Security](#sandboxing-security)\n- [Policy Engine](#policy-engine)\n- [Terminal UI Components](#terminal-ui)\n- [Session Management](#session-management)\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Context and Memory Management](#context-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx)\n- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [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)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [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)\n- [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)\n- [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)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)\n</details>\n\n# Architecture Overview\n\nGemini 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.\n\n## Package Structure\n\nThe repository is organized into three primary packages under the `packages/` directory:\n\n| Package | Purpose | Key Responsibilities |\n|---------|---------|---------------------|\n| `packages/core` | Core AI engine | Agents, skills, context management, chat recording |\n| `packages/cli` | Terminal interface | UI components, commands, authentication, user interactions |\n| `packages/a2a-server` | Protocol server | Agent-to-Agent communication protocol support |\n\n资料来源：[README.md:1-50](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n\n## System Architecture\n\n```mermaid\ngraph TD\n    subgraph \"CLI Layer (packages/cli)\"\n        UI[UI Components]\n        AUTH[Auth Dialog]\n        CMDS[Commands]\n        EXT[Extensions]\n    end\n    \n    subgraph \"Core Layer (packages/core)\"\n        AGENTS[Agent System]\n        SKILLS[Skills Engine]\n        CONTEXT[Context Graph]\n        RECORDING[Chat Recording]\n    end\n    \n    subgraph \"External\"\n        GEMINI_API[Gemini API]\n        MCP[MCP Servers]\n        FS[File System]\n    end\n    \n    UI --> AGENTS\n    AUTH --> AGENTS\n    CMDS --> AGENTS\n    EXT --> AGENTS\n    AGENTS --> SKILLS\n    AGENTS --> CONTEXT\n    AGENTS --> RECORDING\n    AGENTS --> GEMINI_API\n    SKILLS --> MCP\n    SKILLS --> FS\n    CONTEXT --> FS\n```\n\n## Core Package Architecture\n\n### Agents System\n\nThe agent system forms the brain of Gemini CLI. The core package implements multiple specialized agents:\n\n#### CLI Help Agent\n\nThe `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.\n\n```typescript\n// Agent configuration and runtime context\nconst 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.\n\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n\n### Instructions\n1. **Explore Documentation**: Use the \\`get_internal_docs\\` tool to find answers.\n2. **Be Precise**: Use the provided runtime context and documentation.\n3. **Cite Sources**: Include specific documentation files in your report.\n4. **Non-Interactive**: Answer as best you can with available information.\n```\n\n资料来源：[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)\n\n#### Skill Extraction Agent\n\nThe `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:\n\n```typescript\n// Patch format for skill creation\nconst PATCH_FORMAT = `\n1. Update an existing file:\n\n     --- /absolute/path/to/target.md\n     +++ /absolute/path/to/target.md\n     @@ -<start>,<count> +<newStart>,<newCount> @@\n     <unchanged context line>\n    -<removed line>\n    +<added line>\n\n2. Create a brand-new file (no existing target):\n\n     --- /dev/null\n     +++ /absolute/path/to/new-target.md\n     @@ -0,0 +1,<count> @@\n`;\n```\n\n资料来源：[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)\n\n### Context Graph System\n\nThe context graph manages conversation history and session state. It builds a structured representation of the conversation with stable identifiers for each message turn.\n\n```mermaid\ngraph TD\n    subgraph \"Context Building\"\n        HIST[History Array] --> TURN[For Each Turn]\n        TURN --> HASH[Generate MD5 Hash]\n        HASH --> SALT[Add Turn Salt]\n        SALT --> ID[Stable ID Generation]\n    end\n    \n    subgraph \"Message Processing\"\n        MSG[Message] --> ROLE{Message Role}\n        ROLE -->|user| USER[User Turn]\n        ROLE -->|model| MODEL[Model Turn]\n        USER --> PARTS[Process Parts]\n        MODEL --> PARTS\n    end\n```\n\nKey features of the context graph:\n\n- **Stable ID Generation**: Uses MD5 hashing combined with turn salt for deterministic message identification\n- **Legacy Header Handling**: Skips legacy environment headers automatically\n- **Role-based Processing**: Differentiates between user and model messages\n\n资料来源：[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)\n\n### Skills Engine\n\nThe skills system provides extensible capabilities through a standardized structure:\n\n```\nskill-name/\n├── SKILL.md           # Required: Frontmatter + Instructions\n├── REFERENCE.md       # Optional: Loaded on demand\n├── EXAMPLES.md        # Optional: Common patterns\n├── FORMS.md           # Optional: User input forms\n├── scripts/           # Executable code (Node.js/Python/Bash)\n└── references/        # Domain-specific documentation\n```\n\n#### SKILL.md Structure\n\nEvery skill requires a `SKILL.md` file with YAML frontmatter:\n\n```yaml\n---\nname: skill-name\ndescription: Clear description of when this skill should be used\n---\n# Skill body with instructions\n```\n\n#### Organization Patterns\n\n**Pattern 1: Flat Organization**\nSimple skills with related files in a single directory.\n\n**Pattern 2: Domain-specific Organization**\nFor multi-domain skills, organize by domain:\n```\ncloud-deploy/\n├── SKILL.md\n└── references/\n    ├── aws.md\n    ├── gcp.md\n    └── azure.md\n```\n\n**Pattern 3: Conditional Details**\nBasic content with links to advanced topics loaded only when needed.\n\n资料来源：[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)\n\n### Chat Recording Service\n\nThe `ChatRecordingService` persists conversation history and metadata:\n\n```typescript\ninterface ConversationRecord {\n  sessionId: string;\n  projectHash: string;\n  startTime: string;\n  lastUpdated: string;\n  summary?: string;\n  memoryScratchpad?: string;\n  directories: string[];\n  kind: string;\n  messages: Message[];\n  messageCount: number;\n  userMessageCount: number;\n  memoryScratchpadIsStale?: boolean;\n  firstUserMessage?: string;\n  hasUserOrAssistantMessage: boolean;\n}\n```\n\nThe service manages:\n- Session persistence to JSONL files\n- Message loading with metadata filtering\n- Memory scratchpad tracking with freshness indicators\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-100](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n\n## CLI Package Architecture\n\n### UI Component System\n\nThe CLI package implements a terminal-based UI using a custom component system:\n\n```mermaid\ngraph TD\n    APP[AppHeader] --> CONTENT[Main Content Area]\n    CONTENT --> ABOUT[AboutBox]\n    CONTENT --> MODEL[ModelDialog]\n    CONTENT --> AUTH[AuthDialog]\n    CONTENT --> TRUST[FolderTrustDialog]\n    CONTENT --> EXT[ExtensionDetails]\n    \n    subgraph \"Privacy System\"\n        PRIVACY[Privacy Notices]\n        PRIVACY --> GEMINI[GeminiPrivacyNotice]\n        PRIVACY --> CLOUD_FREE[CloudFreePrivacyNotice]\n    end\n```\n\n#### AppHeader Component\n\nDisplays application state including version, update status, and user identity:\n\n```typescript\nconst AppHeader = (config: Config, {\n  showDetails,\n  isNarrow,\n  terminalWidth\n}: HeaderProps) => (\n  <Box flexDirection=\"column\">\n    {/* Version info */}\n    <Text bold>Gemini CLI</Text>\n    <Text>v{version}</Text>\n    \n    {/* Update indicator */}\n    {updateInfo?.isUpdating && (\n      <Text><CliSpinner /> Updating</Text>\n    )}\n    \n    {/* User identity (if enabled) */}\n    <UserIdentity config={config} />\n  </Box>\n);\n```\n\n资料来源：[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)\n\n#### AboutBox Component\n\nDisplays system information:\n- CLI Version\n- Git Commit (if available)\n- Model Version\n- Sandbox Environment\n- Operating System\n\n资料来源：[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)\n\n#### Authentication Dialog\n\nHandles user authentication with multiple options:\n\n```typescript\nconst authOptions = [\n  { label: 'Sign in with Google', value: 'google' },\n  { label: 'Continue without signing in', value: 'anonymous' },\n  { label: 'Use API Key', value: 'api_key' }\n];\n```\n\nThe dialog supports:\n- OAuth flow with automatic CLI restart\n- Anonymous mode\n- Direct API key authentication\n\n资料来源：[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)\n\n### Extension System\n\nExtensions provide a plugin mechanism for extending Gemini CLI functionality:\n\n```mermaid\ngraph TD\n    EXT[Extension] --> MANIFEST[gemini-extension.json]\n    EXT --> POLICIES[policies/]\n    EXT --> COMMANDS[commands/]\n    EXT --> HOOKS[hooks/]\n    EXT --> SKILLS[skills/]\n    EXT --> MCP[mcpServers/]\n```\n\n#### Extension Manifest Structure\n\n```json\n{\n  \"name\": \"extension-name\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Extension description\",\n  \"hasMCP\": true,\n  \"hasContext\": true,\n  \"hasHooks\": true,\n  \"hasSkills\": true,\n  \"hasCustomCommands\": true\n}\n```\n\n#### Policy Engine\n\nExtensions can contribute security rules through TOML policy files:\n\n```toml\n# Example policy\n[[rules]]\ntype = \"confirm\"\ncommand = \"rm -rf\"\nmessage = \"This will permanently delete files\"\n```\n\nSecurity features:\n- Extensions can only add restrictions (not bypass them)\n- `allow` decisions and `yolo` mode from extensions are ignored\n- Custom safety checkers for file path validation\n\n资料来源：[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)\n\n### Privacy System\n\n#### Privacy Notices\n\nTwo privacy notice types exist based on user tier:\n\n| Notice Type | Target Users | Data Usage |\n|------------|--------------|------------|\n| `GeminiPrivacyNotice` | API Terms users | Google AI Studio terms |\n| `CloudFreePrivacyNotice` | Free tier users | Limited collection with opt-in |\n\n#### Data Collection Options\n\n```typescript\ninterface PrivacyState {\n  dataCollectionOptIn: boolean;\n}\n\n// Options presented to users:\n// [0] Allow Google to use data\n// [1] Don't allow\n```\n\nFor free tier users:\n- Human reviewers may read and annotate data\n- Data is disconnected from Google Account\n- Retained for up to 18 months\n\n资料来源：[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)\n\n### Folder Trust System\n\nThe folder trust dialog provides security boundaries for project configurations:\n\n```typescript\ninterface TrustConfig {\n  customCommands: boolean;\n  hooks: boolean;\n  mcpServers: boolean;\n  agentSkills: boolean;\n  settings: boolean;\n}\n```\n\nComponents discovered and displayed:\n- Custom commands (`commands/`)\n- Hooks (`hooks/`)\n- MCP servers (`mcpServers/`)\n- Agent skills (`skills/`)\n- Settings (`settings/`)\n\n资料来源：[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)\n\n### Model Selection\n\nThe `ModelDialog` component allows users to:\n- View available models\n- See quota information\n- Select a specific model for the session\n\nQuota buckets are displayed with available width calculation for responsive layout.\n\n资料来源：[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)\n\n## Extension Details View\n\nDisplays information about available extensions:\n\n```typescript\ninterface ExtensionInfo {\n  extensionVersion?: string;\n  stars: number;\n  isGoogleOwned: boolean;\n  fullName: string;\n  extensionDescription?: string;\n  repoDescription?: string;\n  hasMCP: boolean;\n  hasContext: boolean;\n  hasHooks: boolean;\n  hasSkills: boolean;\n  hasCustomCommands: boolean;\n}\n```\n\nFeature badges with color coding:\n- **MCP** (Primary)\n- **Context file** (Error)\n- **Hooks** (Warning)\n- **Skills** (Success)\n- **Commands** (Primary)\n\n资料来源：[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)\n\n## Installation and Release Channels\n\nGemini CLI supports multiple installation methods:\n\n| Method | Command |\n|--------|---------|\n| npm global | `npm install -g @google/gemini-cli` |\n| Homebrew | `brew install gemini-cli` |\n| MacPorts | `sudo port install gemini-cli` |\n| Anaconda | Create nodejs environment, then npm install |\n\n### Release Channels\n\n| Channel | Schedule | Description |\n|---------|----------|-------------|\n| Preview | Weekly (Tue 23:59 UTC) | Untested preview builds |\n| Stable | Weekly (Tue 20:00 UTC) | Promoted preview + fixes |\n| Nightly | Daily (00:00 UTC) | Main branch snapshot |\n\n资料来源：[README.md:100-150](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n\n## Key Features Integration\n\n### GitHub Integration\n\nGemini CLI integrates with GitHub through the [Gemini CLI GitHub Action](https://github.com/google-github-actions/run-gemini-cli), enabling CI/CD workflow automation.\n\n### Multimodal Capabilities\n\nThe CLI supports processing of:\n- PDFs\n- Images\n- Sketches\n\nThese inputs can be used for code generation and understanding tasks.\n\n### Checkpointing\n\nConversations can be saved and resumed, enabling:\n- Session persistence across CLI restarts\n- Memory scratchpad with staleness tracking\n- Project-specific context preservation\n\n### MCP Server Support\n\nModel Context Protocol servers extend capabilities with:\n- Media generation (Imagen, Veo, Lyria)\n- Custom tool integrations\n- External service connections\n\n## Summary\n\nThe Gemini CLI architecture demonstrates a well-separated design:\n\n1. **Core Package**: Handles AI processing, skills management, and conversation state\n2. **CLI Package**: Manages terminal UI, authentication, and user interactions  \n3. **A2A Server**: Enables agent-to-agent communication protocols\n\nThe 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.\n\n---\n\n<a id='agent-system'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Tools Reference](#tools-reference)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/agent/agent-session.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agent/agent-session.ts)\n- [packages/core/src/agents/agent-scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/agent-scheduler.ts)\n- [packages/core/src/scheduler/scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/scheduler.ts)\n- [packages/core/src/scheduler/tool-executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/tool-executor.ts)\n- [packages/a2a-server/src/agent/executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/a2a-server/src/agent/executor.ts)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n</details>\n\n# Agent System\n\n## 概述\n\nThe 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.\n\nThe 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.\n\nAt 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.\n\n## 核心架构\n\nThe 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.\n\n```mermaid\ngraph TD\n    A[User Input] --> B[AgentSession]\n    B --> C[AgentScheduler]\n    C --> D[Scheduler]\n    D --> E[ToolExecutor]\n    E --> F[External Tools & MCP Servers]\n    D --> G[LLM API]\n    G --> B\n    H[ContextGraph] --> B\n    I[ChatRecordingService] --> B\n```\n\n### 组件职责矩阵\n\n| 组件 | 包路径 | 主要职责 |\n|------|--------|----------|\n| **AgentSession** | `packages/core/src/agent/` | 会话生命周期管理，消息历史维护 |\n| **AgentScheduler** | `packages/core/src/agents/` | 多代理协调，任务分发 |\n| **Scheduler** | `packages/core/src/scheduler/` | 执行调度，队列管理 |\n| **ToolExecutor** | `packages/core/src/scheduler/` | 工具执行，沙箱环境 |\n| **A2AExecutor** | `packages/a2a-server/src/agent/` | Agent-to-Agent通信协议 |\n\n## AgentSession (会话管理)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 核心数据结构\n\n```typescript\ninterface ConversationRecord {\n  sessionId: string;\n  projectHash: string;\n  startTime: string;\n  lastUpdated: string;\n  summary?: string;\n  memoryScratchpad?: string;\n  directories?: string[];\n  kind: 'cli' | 'api';\n  messages: Message[];\n  messageCount: number;\n  userMessageCount: number;\n  memoryScratchpadIsStale?: boolean;\n  firstUserMessage?: string;\n  hasUserOrAssistantMessage: boolean;\n}\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-50](packages/core/src/services/chatRecordingService.ts)\n\n### 会话ID生成机制\n\nThe 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:\n\n```typescript\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5')\n  .update(`${msg.role}:${turnContent}`)\n  .digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nseenHashes.set(h, occurrence);\nconst turnSalt = `${h}_${occurrence}`;\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)\n\n### 配置管理\n\nThe session integrates with the configuration system to access runtime settings:\n\n```typescript\ngetExperimentalDynamicModelConfiguration(): boolean {\n  return this.dynamicModelConfiguration;\n}\n\ngetPendingIncludeDirectories(): string[] {\n  return this.pendingIncludeDirectories;\n}\n\nclearPendingIncludeDirectories(): void {\n  this.pendingIncludeDirectories = [];\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:1-100](packages/core/src/config/config.ts)\n\n## AgentScheduler (代理调度)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 内置代理类型\n\nThe system includes several built-in agents for common tasks:\n\n| 代理名称 | 源文件 | 功能描述 |\n|----------|--------|----------|\n| **CLI Help Agent** | `cli-help-agent.ts` | 提供CLI文档和帮助信息 |\n| **Policy Agent** | - | 安全策略执行 |\n| **Skill Agent** | - | 自定义技能执行 |\n\n### CLI Help Agent 实现\n\nThe CLI Help Agent is a specialized agent that provides accurate information about Gemini CLI features, configuration, and current state:\n\n```typescript\nconst 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.\n\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n\n### Instructions\n1. **Explore Documentation**: Use the \\`get_internal_docs\\` tool to find answers.\n2. **Be Precise**: Use the provided runtime context and documentation.\n3. **Cite Sources**: Include specific documentation files used.\n4. **Non-Interactive**: Operate in a loop without user interaction.`;\n```\n\n资料来源：[packages/core/src/agents/cli-help-agent.ts:1-30](packages/core/src/agents/cli-help-agent.ts)\n\n### 代理注册流程\n\nAgents 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.\n\n## Scheduler (任务调度)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 执行流程\n\n```mermaid\nsequenceDiagram\n    participant User as User Input\n    participant Scheduler\n    participant LLM as LLM API\n    participant ToolExec as Tool Executor\n    participant Session as AgentSession\n    \n    User->>Scheduler: Send Message\n    Scheduler->>Session: Record Message\n    Session-->>Scheduler: Acknowledge\n    Scheduler->>LLM: Generate Response\n    LLM-->>Scheduler: Tool Call Request\n    Scheduler->>ToolExec: Execute Tool\n    ToolExec-->>Scheduler: Tool Result\n    Scheduler->>LLM: Continue Generation\n    LLM-->>Scheduler: Final Response\n    Scheduler-->>User: Stream Response\n```\n\n### 工具调用处理\n\nWhen 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.\n\n## ToolExecutor (工具执行)\n\n### 概述\n\nThe `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.\n\n### 工具类型支持\n\n| 工具类型 | 执行方式 | 安全级别 |\n|----------|----------|----------|\n| **Built-in Tools** | 直接执行 | 高 |\n| **Custom Skills** | 沙箱执行 | 中 |\n| **MCP Tools** | 远程执行 | 可配置 |\n| **Shell Commands** | 隔离环境 | 高 |\n\n### 技能执行框架\n\nSkills are executed through a structured framework defined in the SKILL.md specification:\n\n```markdown\n### Bundled Resources (optional)\n\n#### Scripts (`scripts/`)\nExecutable code for deterministic tasks:\n- Token efficient execution\n- Deterministic behavior\n- LLM-friendly stdout output\n\n#### References (`references/`)\nDocumentation loaded as needed into context\n```\n\n资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md:1-50](packages/core/src/skills/builtin/skill-creator/SKILL.md)\n\n### 策略引擎集成\n\nThe tool executor integrates with the policy engine to enforce security rules. Extensions can contribute policies through TOML configuration files:\n\n```toml\n# Example policy\n[[rules]]\ntype = \"confirmation_required\"\ncommand_pattern = \"rm -rf.*\"\n\n[[rules]]\ntype = \"deny\"\ncommand_pattern = \"grep.*\\\\.env\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30](packages/cli/src/commands/extensions/examples/policies/README.md)\n\n## A2AExecutor (Agent-to-Agent通信)\n\n### 概述\n\nThe `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.\n\n### 协议消息格式\n\n```typescript\ninterface AgentMessage {\n  id: string;\n  type: 'request' | 'response' | 'event';\n  sender: string;\n  receiver: string;\n  payload: unknown;\n  timestamp: number;\n}\n```\n\n### RPC调度\n\nThe executor handles RPC method dispatching and session state management. New RPC methods are registered through the `GeminiAgent` interface:\n\n```typescript\n// Adding a new RPC method\n// 1. Add method to GeminiAgent in acpRpcDispatcher.ts\n// 2. Register in AgentSideConnection setup if necessary\n// 3. Add serialization logic to acpUtils.ts\n```\n\n资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)\n\n## 上下文管理\n\n### ContextGraph\n\nThe `ContextGraph` maintains conversation context and generates stable identifiers for message turns. It handles legacy environment header detection and removal:\n\n```typescript\n// Defensive: Skip legacy environment header\nif (msg.role === 'user' && msg.parts.length === 1) {\n  const text = msg.parts[0].text;\n  if (text?.startsWith('<session_context>') && \n      text?.includes('This is the Gemini CLI')) {\n    debugLogger.log(\n      '[ContextGraphBuilder] Skipping legacy environment header turn.',\n    );\n    continue;\n  }\n}\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)\n\n### 会话记录服务\n\nThe `ChatRecordingService` handles persistence of conversation history to JSONL format:\n\n```typescript\nexport class ChatRecordingService {\n  private conversationFile: string | null = null;\n  private cachedConversation: ConversationRecord | null = null;\n  private sessionId: string;\n  // ...\n}\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:50-100](packages/core/src/services/chatRecordingService.ts)\n\n## 执行模式与策略\n\n### 审批模式\n\nThe system supports multiple approval modes for controlling agent behavior:\n\n| 模式 | 描述 | 使用场景 |\n|------|------|----------|\n| **PLAN** | 仅生成计划，不执行 | 代码审查 |\n| **YOLO** | 直接执行所有操作 | 自动化脚本 |\n| **INTERACTIVE** | 逐个确认操作 | 谨慎操作 |\n\n```typescript\nisYoloModeDisabled(): boolean {\n  return this.disableYoloMode || !this.isTrustedFolder();\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:80-85](packages/core/src/config/config.ts)\n\n### 策略链解析\n\nThe system resolves policy chains based on model configuration:\n\n```typescript\ndescribe('resolvePolicyChain', () => {\n  it('returns a single-model chain for a custom model', () => {\n    const chain = resolvePolicyChain(config);\n    expect(chain).toHaveLength(1);\n    expect(chain[0]?.model).toBe('custom-model');\n  });\n  \n  it('returns the default chain when active model is \"auto\"', () => {\n    const chain = resolvePolicyChain(config);\n    expect(chain).toHaveLength(2);\n    // Expect default chain [Pro, Flash]\n  });\n});\n```\n\n资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50](packages/core/src/availability/policyHelpers.test.ts)\n\n## 扩展机制\n\n### MCP服务器集成\n\nThe system supports MCP (Model Context Protocol) servers for extending functionality. Configuration is stored in `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    }\n  }\n}\n```\n\n### 自定义技能\n\nSkills are defined through SKILL.md files with YAML frontmatter:\n\n```yaml\n---\nname: pdf-rotate\ndescription: Rotates PDF files by specified degrees. Use when user wants to rotate a PDF document.\n---\n```\n\n## 运行时上下文\n\n### 版本信息显示\n\nThe system displays runtime context through the About component:\n\n```typescript\n<Box flexDirection=\"row\">\n  <Box width=\"35%\">\n    <Text bold color={theme.text.link}>CLI Version</Text>\n  </Box>\n  <Box>\n    <Text color={theme.text.primary}>{cliVersion}</Text>\n  </Box>\n</Box>\n<Box flexDirection=\"row\">\n  <Box width=\"35%\">\n    <Text bold color={theme.text.link}>Model</Text>\n  </Box>\n  <Box>\n    <Text color={theme.text.primary}>{getDisplayString(modelVersion)}</Text>\n  </Box>\n</Box>\n```\n\n资料来源：[packages/cli/src/ui/components/AboutBox.tsx:1-50](packages/cli/src/ui/components/AboutBox.tsx)\n\n## 隐私与安全\n\n### 隐私通知\n\nThe system displays privacy notices and handles data collection preferences:\n\n```typescript\nWhen you use Gemini Code Assist for individuals with Gemini CLI, Google\ncollects your prompts, related code, generated output, code edits,\nrelated feature usage information, and your feedback to provide,\nimprove, and develop Google products and services and machine learning\ntechnologies.\n```\n\n资料来源：[packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx:1-50](packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx)\n\n### 安全检查\n\nThe policy engine enforces security rules for file operations and dangerous commands. Extensions can contribute security rules but cannot bypass user confirmation requirements.\n\n## 常见工作流\n\n### 单代理工作流\n\n```mermaid\ngraph LR\n    A[User Input] --> B[AgentSession]\n    B --> C[Scheduler]\n    C --> D[ToolExecutor]\n    D --> E[Result]\n    C --> F[LLM]\n    F --> G[Response]\n```\n\n### 多代理工作流\n\n```mermaid\ngraph TD\n    A[User Input] --> B[AgentScheduler]\n    B --> C[CLI Help Agent]\n    B --> D[Skill Agent]\n    B --> E[Policy Agent]\n    C --> F[Result Aggregation]\n    D --> F\n    E --> F\n    F --> G[Final Response]\n```\n\n## 调试与日志\n\n### 日志输出\n\nThe system uses structured logging for debugging:\n\n```typescript\ndebugLogger.log(\n  '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',\n);\ndebugLogger.error('Error loading conversation record from JSONL:', error);\n```\n\n### 测试框架\n\nTests are written using Vitest and can be run with workspace filtering:\n\n```bash\nnpm test -w @google/gemini-cli -- src/acp/<test-file-name>.ts\n```\n\n资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)\n\n## 总结\n\nThe 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.\n\n---\n\n<a id='context-pipeline'></a>\n\n## Context and Memory Management\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Session Management](#session-management)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [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)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [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)\n- [packages/sdk/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/README.md)\n</details>\n\n# Context and Memory Management\n\n## Overview\n\nContext 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.\n\n## Architecture Overview\n\nThe context management system consists of several interconnected components:\n\n```mermaid\ngraph TD\n    A[User Input] --> B[ContextGraphBuilder]\n    B --> C[Turn ID Generation]\n    C --> D[Context Manager]\n    D --> E[Memory Context Manager]\n    E --> F[Chat Recording Service]\n    F --> G[Session Persistence]\n    D --> H[Chat Compression Service]\n    H --> I[Rolling Summary Processor]\n    I --> J[Token Optimization]\n```\n\n## Core Components\n\n### ContextGraphBuilder\n\nThe `ContextGraphBuilder` is responsible for constructing the conversational context from message history. It processes each turn and generates stable identifiers for tracking conversation flow.\n\n**Key Responsibilities:**\n\n- Iterating through conversation history\n- Generating stable turn hashes using MD5\n- Creating unique turn IDs with salt-based occurrence tracking\n- Skipping legacy environment headers\n\n```typescript\n// Generate a stable salt for this turn based on its role and content\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5')\n  .update(`${msg.role}:${turnContent}`)\n  .digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nseenHashes.set(h, occurrence);\nconst turnSalt = `${h}_${occurrence}`;\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:31-38]()\n\n### Turn ID Generation\n\nTurn IDs are generated using a combination of message content hashing and a stable ID generation function. This ensures consistent identification across sessions.\n\n| Parameter | Type | Purpose |\n|-----------|------|---------|\n| `msg` | Message | The message object to generate ID for |\n| `nodeIdentityMap` | Map | Maps content to stable node identifiers |\n| `turnSalt` | string | Salt for hashing (includes occurrence count) |\n| `position` | number | Position hint for ID generation |\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:39]()\n\n### Legacy Header Handling\n\nThe system includes defensive logic to skip legacy environment headers that contain `<session_context>` markers. This prevents duplicate or stale context from being reintroduced.\n\n```typescript\nif (msg.role === 'user' && msg.parts.length === 1) {\n  const text = msg.parts[0].text;\n  if (\n    text?.startsWith('<session_context>') &&\n    text?.includes('This is the Gemini CLI')\n  ) {\n    debugLogger.log(\n      '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',\n    );\n    continue;\n  }\n}\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:19-29]()\n\n## Chat Recording Service\n\nThe `ChatRecordingService` manages persistent storage of conversation history and session metadata.\n\n### ConversationRecord Model\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `sessionId` | string | Unique session identifier |\n| `projectHash` | string | Hash of the project context |\n| `startTime` | ISO string | Session start timestamp |\n| `lastUpdated` | ISO string | Last update timestamp |\n| `summary` | string | Optional conversation summary |\n| `memoryScratchpad` | string | Persistent memory content |\n| `directories` | string[] | Associated working directories |\n| `messages` | Message[] | Full message history |\n| `messageCount` | number | Total message count |\n| `userMessageCount` | number | User message count |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-30]()\n\n### Session State Tracking\n\nThe service tracks whether sessions contain user or assistant messages:\n\n```typescript\nhasUserOrAssistantMessage:\n  options?.metadataOnly && metadataMessages.length > 0\n    ? metadataMessages.some(\n        (m) => m.type === 'user' || m.type === 'gemini',\n      )\n    : hasUserOrAssistant,\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:57-62]()\n\n## Progressive Disclosure Design\n\nGemini CLI implements a three-level loading system to manage context efficiently:\n\n```mermaid\ngraph LR\n    A[Metadata<br/>name + description] --> B[SKILL.md Body<br/>Instructions]\n    B --> C[Bundled Resources<br/>Scripts/References]\n```\n\n### Loading Levels\n\n| Level | Content | Token Cost | Load Trigger |\n|-------|---------|------------|--------------|\n| 1 | Metadata (name + description) | ~100 words | Always |\n| 2 | SKILL.md body | <5k words | Skill trigger |\n| 3 | Bundled resources | Unlimited | As needed |\n\n资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md]()\n\n### Bundled Resources Organization\n\n```\nscripts/       - Executable code (Node.js/Python/Bash)\nreferences/    - Documentation loaded into context\nassets/        - Files used in output (templates, icons)\n```\n\n## Memory Scratchpad\n\nThe system supports a memory scratchpad feature that persists across sessions:\n\n- **Staleness Tracking**: The system can flag when the scratchpad content becomes stale\n- **Fallback Detection**: Falls back to first user message if no user message found\n\n```typescript\nmemoryScratchpadIsStale: isTrackingMemoryScratchpadFreshness\n  ? memoryScratchpadIsStale\n  : undefined,\nfirstUserMessage: fallbackFirstUserMessage,\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:52-55]()\n\n## Folder Trust and Configuration Discovery\n\nWhen a folder is trusted, Gemini CLI loads its local configurations including:\n\n- Custom commands\n- Hooks\n- MCP servers\n- Agent skills\n- Settings\n\n```typescript\n<Box>\n  Trusting a folder allows Gemini CLI to load its local configurations,\n  including custom commands, hooks, MCP servers, agent skills, and\n  settings. These configurations could execute code on your behalf or\n  change the behavior of the CLI.\n</Box>\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()\n\n### Discovery Results\n\nThe system performs security validation on discovered configurations:\n\n| Result Type | Icon | Purpose |\n|-------------|------|---------|\n| Discovery Errors | ❌ | Configuration parsing failures |\n| Security Warnings | ⚠️ | Potential security concerns |\n\n## CLI Help Agent Memory\n\nThe CLI Help Agent provides contextual assistance with runtime awareness:\n\n```typescript\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n```\n\n资料来源：[packages/core/src/agents/cli-help-agent.ts]()\n\n### Agent Instructions\n\n1. **Explore Documentation**: Use the `get_internal_docs` tool to find answers\n2. **Be Precise**: Use provided runtime context and documentation\n3. **Cite Sources**: Include specific documentation files used\n4. **Non-Interactive**: Operate autonomously without user queries\n\n## SDK Integration\n\nThe Gemini CLI SDK provides programmatic access to the context system:\n\n```typescript\nimport { GeminiCliAgent } from '@google/gemini-cli-sdk';\n\nconst agent = new GeminiCliAgent({\n  instructions: 'You are a helpful assistant.',\n});\n\nconst stream = agent.sendStream('query', signal);\n```\n\n资料来源：[packages/sdk/README.md]()\n\n## Data Flow Summary\n\n```mermaid\ngraph TD\n    subgraph \"Input Processing\"\n        A[User Input] --> B[ContextGraphBuilder]\n        B --> C[Turn Hash Generation]\n        C --> D[Stable ID Creation]\n    end\n    \n    subgraph \"Memory Management\"\n        D --> E[Memory Context Manager]\n        E --> F[Session Metadata]\n        F --> G[Persistent Storage]\n    end\n    \n    subgraph \"Optimization\"\n        D --> H[Compression Service]\n        H --> I[Rolling Summary]\n        I --> J[Token Budget]\n    end\n    \n    subgraph \"Retrieval\"\n        G --> K[Chat Recording Service]\n        K --> L[Conversation Record]\n        L --> M[Context Window]\n    end\n```\n\n## Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `memoryScratchpad` | string | Persistent memory content |\n| `directories` | string[] | Working directories to track |\n| `projectHash` | string | Project context identifier |\n| `sessionId` | string | Unique session identifier |\n\n## Security Considerations\n\nThe context management system includes several security measures:\n\n1. **Folder Trust**: User confirmation required before loading folder configurations\n2. **Policy Engine**: Security rules can be contributed via extensions\n3. **Path Validation**: Safety checkers validate file paths for write operations\n4. **Discovery Errors**: Configuration parsing failures are surfaced to users\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Summary\n\nThe Context and Memory Management system in Gemini CLI provides:\n\n- **Stable Turn Identification**: MD5-based hashing with occurrence tracking\n- **Session Persistence**: Full conversation history with metadata\n- **Progressive Disclosure**: Three-level loading for token optimization\n- **Security**: Folder trust validation and policy enforcement\n- **SDK Access**: Programmatic interface for external agents\n\n---\n\n<a id='tools-reference'></a>\n\n## Tools Reference\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Sandboxing and Security](#sandboxing-security)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/definitions/coreTools.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/definitions/coreTools.ts)\n- [packages/core/src/tools/read-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/read-file.ts)\n- [packages/core/src/tools/write-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/write-file.ts)\n- [packages/core/src/tools/shell.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/shell.ts)\n- [packages/core/src/tools/web-search.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/web-search.ts)\n- [packages/core/src/tools/mcp-tool.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-tool.ts)\n- [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)\n- [packages/core/src/tools/grep.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/grep.ts)\n- [packages/core/src/tools/glob.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/glob.ts)\n- [packages/core/src/tools/list-directory.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/list-directory.ts)\n</details>\n\n# Tools Reference\n\n## Overview\n\nThe 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.\n\nTools 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.\n\n资料来源：[packages/core/src/tools/definitions/coreTools.ts:1-50]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Request] --> B[GeminiAgent]\n    B --> C[Tool Registry]\n    C --> D[Core Tools]\n    C --> E[MCP Tools]\n    D --> F[read_file]\n    D --> G[write_file]\n    D --> H[shell/grep/glob]\n    D --> I[web_search]\n    E --> J[MCP Server 1]\n    E --> K[MCP Server 2]\n    F --> L[Filesystem]\n    G --> L\n    H --> M[System Commands]\n    I --> N[Google Search API]\n    J --> O[External Services]\n```\n\n## Tool Registration System\n\nTools 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.\n\n资料来源：[packages/core/src/config/config.ts:150-180]()\n\n### Dynamic Tool Registration\n\n```mermaid\ngraph TD\n    A[Configuration Load] --> B{coreTools defined?}\n    B -->|Yes| C{Check tool in list}\n    B -->|No| D[Enable all by default]\n    C -->|Match found| E[Register Tool]\n    C -->|No match| F[Skip Tool]\n    D --> E\n    E --> G[Tool available to Agent]\n```\n\nThe `maybeRegister` function controls tool availability:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `toolName` | `string` | The tool identifier to check |\n| `normalizedClassName` | `string` | Normalized class name for matching |\n| `coreTools` | `string[] \\| undefined` | Configuration whitelist |\n| `registerFn` | `() => void` | Function to execute if enabled |\n\n资料来源：[packages/core/src/config/config.ts:130-150]()\n\n## Core Tools\n\nCore tools are built-in capabilities that provide filesystem access, search functionality, and command execution. These tools are optimized per model family.\n\n### Tool Categories\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| **File Operations** | `read_file`, `write_file`, `replace` | File content manipulation |\n| **Search** | `grep_search`, `grep_search_ripgrep`, `glob` | Code and file discovery |\n| **Navigation** | `list_directory` | Directory browsing |\n| **System** | `run_shell_command` | Terminal command execution |\n| **Web** | `web_search`, `web_fetch` | Internet access |\n| **Memory** | `save_memory` | Persistent context storage |\n| **Planning** | `enter_plan_mode`, `exit_plan_mode` | Planning mode control |\n| **MCP** | `read_mcp_resource`, `list_mcp_resources` | MCP server integration |\n\n资料来源：[packages/core/src/tools/definitions/coreTools.ts:40-80]()\n\n## File Operations\n\n### Read File Tool\n\nThe `read_file` tool provides controlled access to file contents with optional line range selection.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Absolute path to the file |\n| `start_line` | `number` | No | Starting line number (1-indexed) |\n| `end_line` | `number` | No | Ending line number (inclusive) |\n\n**Behavior:**\n- Returns file contents as a string\n- Supports partial file reads via line range\n- Validates file path exists before reading\n- Respects `.gemini-ignore` patterns when configured\n\n资料来源：[packages/core/src/tools/read-file.ts:1-60]()\n\n### Write File Tool\n\nThe `write_file` tool creates or overwrites files with specified content.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Absolute path for the new file |\n| `content` | `string` | Yes | File content to write |\n\n**Behavior:**\n- Creates parent directories if they don't exist\n- Overwrites existing files silently\n- Returns confirmation message on success\n- Subject to security policy checks\n\n资料来源：[packages/core/src/tools/write-file.ts:1-50]()\n\n### Edit/Replace Tool\n\nThe `replace` tool performs targeted modifications to existing files using diff/patch format.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Target file path |\n| `old_string` | `string` | Yes | Text to find and replace |\n| `new_string` | `string` | Yes | Replacement text |\n\n**Patch Format:**\n```\n--- /absolute/path/to/file\n+++ /absolute/path/to/file\n@@ -start,count +start,count @@\n context line\n -removed line\n +added line\n```\n\n资料来源：[packages/core/src/agents/skill-extraction-agent.ts:50-80]()\n\n## Search Tools\n\n### Grep Tool\n\nThe `grep_search` tool performs text pattern matching across files with extensive filtering options.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `pattern` | `string` | Yes | Regex or literal pattern to search |\n| `file_path` | `string` | No | Root directory to search |\n| `case_sensitive` | `boolean` | No | Enable case sensitivity (default: false) |\n| `include_pattern` | `string` | No | File glob to include |\n| `exclude_pattern` | `string` | No | File glob to exclude |\n| `names_only` | `boolean` | No | Return only matching filenames |\n| `max_matches_per_file` | `number` | No | Limit matches per file |\n| `total_max_matches` | `number` | No | Global match limit |\n| `fixed_strings` | `boolean` | No | Treat pattern as literal |\n| `context` | `number` | No | Lines of context around matches |\n| `after` | `number` | No | Lines after match |\n| `before` | `number` | No | Lines before match |\n| `respect_git_ignore` | `boolean` | No | Skip gitignored files (default: true) |\n| `respect_gemini_ignore` | `boolean` | No | Skip .gemini-ignore files (default: true) |\n| `no_ignore` | `boolean` | No | Disable all ignore patterns |\n\n资料来源：[packages/core/src/tools/grep.ts:1-80]()\n\n### Ripgrep Tool\n\nWhen 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.\n\n资料来源：[packages/core/src/config/config.ts:160-175]()\n\n### Glob Tool\n\nThe `glob` tool finds files matching shell-style wildcard patterns.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `pattern` | `string` | Yes | Glob pattern (e.g., `**/*.ts`) |\n| `directory` | `string` | No | Root directory for search |\n| `ignore` | `string[]` | No | Patterns to exclude |\n\n资料来源：[packages/core/src/tools/glob.ts:1-50]()\n\n## Directory Navigation\n\n### List Directory Tool\n\nThe `list_directory` tool provides directory contents with optional filtering.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `dir_path` | `string` | Yes | Directory to list |\n| `ignore` | `string[]` | No | Patterns to exclude from results |\n\n**Features:**\n- Returns file and directory names\n- Supports ignore patterns for filtering\n- Respects gitignore when configured\n\n资料来源：[packages/core/src/tools/list-directory.ts:1-50]()\n\n## Shell Command Execution\n\n### Run Shell Command Tool\n\nThe `run_shell_command` tool executes system commands in a sandboxed environment.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `command` | `string` | Yes | Command to execute |\n| ` cwd` | `string` | No | Working directory |\n| `timeout_ms` | `number` | No | Execution timeout (default: 60000) |\n| `environment` | `object` | No | Additional environment variables |\n\n**Security Features:**\n- Subject to policy engine rules\n- May require user confirmation for destructive commands\n- Path safety validation for file operations\n- Timeout protection against hanging processes\n\n资料来源：[packages/core/src/tools/shell.ts:1-100]()\n\n```mermaid\ngraph TD\n    A[Command Request] --> B{Policy Check}\n    B -->|Allowed| C[Environment Setup]\n    B -->|Denied| D[User Confirmation]\n    B -->|Blocked| E[Error Response]\n    D -->|Approved| C\n    D -->|Denied| E\n    C --> F[Spawn Process]\n    F --> G{Timeout?}\n    G -->|Yes| H[Terminate]\n    G -->|No| I[Capture Output]\n    I --> J[Return Result]\n    H --> K[Timeout Error]\n```\n\n## Web Tools\n\n### Google Web Search\n\nThe `google_web_search` tool provides real-time internet search capabilities grounded in Google Search.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | `string` | Yes | Search query string |\n\n**Behavior:**\n- Returns search results with snippets\n- May be disabled via configuration\n- Subject to rate limiting\n\n资料来源：[packages/core/src/tools/web-search.ts:1-50]()\n\n### Web Fetch\n\nThe `web_fetch` tool retrieves content from URLs.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | `string` | Yes | Target URL |\n| `prompt` | `string` | No | Guidance for content extraction |\n\n## MCP Tool Integration\n\nMCP (Model Context Protocol) tools allow integration with external MCP servers, extending Gemini CLI's capabilities.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Gemini CLI] --> B[MCP Tool Bridge]\n    B --> C[MCP Server 1]\n    B --> D[MCP Server 2]\n    B --> E[MCP Server N]\n    C --> F[External Service]\n    D --> G[Database]\n    E --> H[Custom Tools]\n    B --> I[Resource Reader]\n    B --> J[Resource Lister]\n```\n\n### MCP Tool Types\n\n| Tool | Purpose | Parameters |\n|------|---------|------------|\n| `read_mcp_resource` | Read specific MCP resource | `server_name`, `uri` |\n| `list_mcp_resources` | List available MCP resources | `server_name` |\n| `mcp__tool_name` | Execute MCP tool call | Dynamic based on server |\n\n资料来源：[packages/core/src/tools/mcp-tool.ts:1-100]()\n\n### Configuration\n\nMCP servers are configured in `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    }\n  }\n}\n```\n\n## Model-Specific Tool Manifests\n\nDifferent model families may have optimized tool definitions with adjusted descriptions and parameter schemas.\n\n### Gemini 3 Tool Manifest\n\nThe Gemini 3 family uses optimized tool definitions that may include:\n\n- Streamlined descriptions for reduced token usage\n- Adjusted parameter names for consistency\n- Model-specific capability hints\n\n资料来源：[packages/core/src/tools/definitions/gemini-3.ts:1-50]()\n\n### Tool Definition Snapshot Testing\n\nTool definitions are validated against snapshots to ensure consistency:\n\n```typescript\nconst modelIds = ['gemini-2.5-pro', 'gemini-3-pro-preview'];\nconst tools = [\n  { name: 'read_file', definition: READ_FILE_DEFINITION },\n  { name: 'write_file', definition: WRITE_FILE_DEFINITION },\n  { name: 'grep_search', definition: GREP_DEFINITION },\n  // ... more tools\n];\n```\n\n资料来源：[packages/core/src/tools/definitions/coreToolsModelSnapshots.test.ts:30-60]()\n\n## Tool Response Format\n\nAll tools return responses in a standardized format:\n\n```typescript\ninterface ToolResult {\n  tool_call_id: string;\n  result: {\n    success: boolean;\n    data?: string | object;\n    error?: string;\n  };\n}\n```\n\n## Security and Policy Engine\n\nTools are subject to security policies defined by the Policy Engine extension system.\n\n### Policy Types\n\n| Policy | Description |\n|--------|-------------|\n| **Confirmation Rules** | Require user approval for specific operations |\n| **Denial Rules** | Block certain operations entirely |\n| **Path Restrictions** | Validate paths against allowed directories |\n| **Safety Checkers** | Validate operations before execution |\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### Folder Trust and Tool Access\n\nWhen a folder is trusted, its local configurations can modify tool behavior:\n\n- Custom commands\n- MCP server configurations\n- Agent skills\n- Extension policies\n\nUntrusted folders restrict tool access to prevent potentially harmful operations.\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:20-40]()\n\n## Tool Availability Matrix\n\n| Tool | File Ops | Search | System | Web | MCP | Memory |\n|------|----------|--------|--------|-----|-----|--------|\n| read_file | ✓ | | | | | |\n| write_file | ✓ | | | | | |\n| replace | ✓ | | | | | |\n| grep_search | | ✓ | | | | |\n| glob | | ✓ | | | | |\n| list_directory | | | ✓ | | | |\n| run_shell_command | | | ✓ | | | |\n| web_search | | | | ✓ | | |\n| web_fetch | | | | ✓ | | |\n| save_memory | | | | | | ✓ |\n| enter_plan_mode | | | | | | |\n| mcp__* | | | | | ✓ | |\n\n## Extension Points\n\n### Custom Tools via MCP\n\nExternal tools can be integrated through MCP servers:\n\n```typescript\n> @github List my open pull requests\n> @slack Send a summary to #dev channel\n> @database Find inactive users\n```\n\n### Custom Commands\n\nCustom slash commands can be defined in project directories and provide task-specific tool combinations.\n\n## Best Practices\n\n1. **Use Line Ranges**: When reading large files, specify line ranges to reduce token usage\n2. **Respect Ignores**: Let tools respect `.gitignore` and `.gemini-ignore` patterns\n3. **Timeout Configuration**: Set appropriate timeouts for shell commands\n4. **MCP Security**: Only enable trusted MCP servers\n5. **Path Validation**: Use absolute paths to avoid ambiguity\n\n## Related Documentation\n\n- [Configuration Guide](https://www.geminicli.com/docs/reference/configuration)\n- [MCP Server Integration](https://www.geminicli.com/docs/tools/mcp-server)\n- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)\n- [Keyboard Shortcuts](https://www.geminicli.com/docs/reference/keyboard-shortcuts)\n\n---\n\n<a id='mcp-integration'></a>\n\n## MCP Integration\n\n### 相关页面\n\n相关主题：[Tools Reference](#tools-reference), [Skills and Extensions](#skills-extensions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/mcp-client.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-client.ts)\n- [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)\n- [packages/core/src/agents/browser/mcpToolWrapper.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/browser/mcpToolWrapper.ts)\n- [packages/cli/src/services/McpPromptLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/services/McpPromptLoader.ts)\n- [docs/tools/mcp-server.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md)\n</details>\n\n# MCP Integration\n\nModel 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.\n\n## Overview\n\nMCP Integration serves as a bridge between Gemini CLI and external tools. When configured, MCP servers can expose:\n\n- **Tools**: Executable functions that the AI can call (e.g., `fetch_posts`, database queries, GitHub operations)\n- **Prompts**: Pre-defined prompt templates for specific use cases\n- **Resources**: Static data that can be loaded into context as needed\n\nThe integration supports both sandboxed and non-sandboxed execution modes, with appropriate security measures including consent prompts and path restrictions.\n\n## Architecture\n\nThe MCP Integration system comprises several core components that work together to manage server lifecycle, tool exposure, and prompt loading.\n\n```mermaid\ngraph TD\n    A[Gemini CLI] --> B[McpClientManager]\n    B --> C[McpClient instances]\n    C --> D[MCP Servers]\n    E[McpPromptLoader] --> F[Prompts Registry]\n    G[McpToolWrapper] --> H[Tool Definitions]\n    D --> I[JSON-RPC Transport]\n    I --> C\n    H --> A\n```\n\n### Core Components\n\n| Component | Location | Responsibility |\n|-----------|----------|----------------|\n| `McpClientManager` | `packages/core/src/tools/mcp-client-manager.ts` | Manages lifecycle of all MCP client connections |\n| `McpClient` | `packages/core/src/tools/mcp-client.ts` | Handles individual server communication |\n| `McpToolWrapper` | `packages/core/src/agents/browser/mcpToolWrapper.ts` | Converts MCP tools to Gemini function declarations |\n| `McpPromptLoader` | `packages/cli/src/services/McpPromptLoader.ts` | Loads and registers MCP prompts |\n\n## MCP Client Manager\n\nThe `McpClientManager` is the central orchestrator for all MCP server connections. It handles:\n\n- Server initialization and configuration loading\n- Connection lifecycle management\n- Tool registration and updates\n- Cleanup and graceful shutdown\n\n### Server Discovery\n\nMCP servers can be configured in two ways:\n\n1. **Global Configuration**: Defined in `~/.gemini/settings.json`\n2. **Per-Project Configuration**: Defined in `~/.gemini/settings.json` for the active workspace\n\n```mermaid\ngraph TD\n    A[Load Settings] --> B[Get mcpServers config]\n    B --> C{Server enabled?}\n    C -->|Yes| D[Check enablement]\n    C -->|No| E[Skip]\n    D --> F[canLoadServer check]\n    F --> G{Allowed?}\n    G -->|Yes| H[Create MCP Client]\n    G -->|No| I[Block with message]\n    H --> J[Connect via Transport]\n    J --> K[Register tools]\n```\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:1-50]()\n\n### Configuration Schema\n\nMCP server configuration follows this structure:\n\n```typescript\ninterface MCPServerConfig {\n  command: string;           // Executable to run (e.g., 'npx', 'node')\n  args?: string[];           // Command arguments\n  env?: Record<string, string>;  // Environment variables\n  disabled?: boolean;       // Enable/disable server\n}\n```\n\nConfiguration is merged from multiple sources with appropriate precedence rules applied by the settings system.\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:30-40]()\n\n## MCP Client\n\nThe `McpClient` handles the actual communication with an MCP server using the JSON-RPC protocol over stdio transport. Each client instance maintains:\n\n- A transport connection to the server\n- Registered tool definitions\n- Server capabilities and metadata\n\n### Tool Registration Flow\n\n```mermaid\nsequenceDiagram\n    participant CLI as Gemini CLI\n    participant Manager as McpClientManager\n    participant Client as McpClient\n    participant Server as MCP Server\n    participant Browser as Browser Manager\n\n    CLI->>Manager: Initialize servers\n    Manager->>Client: Create client instance\n    Client->>Server: Initialize connection\n    Server-->>Client: Server capabilities\n    Client->>Server: List tools request\n    Server-->>Client: Tool definitions\n    Client->>Manager: Register tools\n    Manager->>Browser: Convert to FunctionDeclaration\n    Browser->>CLI: Expose tools to model\n```\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:1-50]()\n\n## Tool Wrapper\n\nThe `McpToolWrapper` transforms MCP tool definitions into Gemini-compatible function declarations. This conversion ensures that:\n\n1. Tool schemas are compatible with Gemini's function calling format\n2. Descriptions are augmented with usage hints\n3. Input schemas are properly formatted as JSON Schema\n\n### Schema Conversion\n\n```typescript\nfunction convertMcpToolToFunctionDeclaration(mcpTool: McpTool): FunctionDeclaration {\n  return {\n    name: mcpTool.name,\n    description: mcpTool.description ?? '',\n    parametersJsonSchema: mcpTool.inputSchema ?? {\n      type: 'object',\n      properties: {},\n    },\n  };\n}\n```\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:60-75]()\n\n### Description Augmentation\n\nThe wrapper augments MCP tool descriptions with semantic hints that help the model make correct tool choices:\n\n```typescript\nconst augmentedDescription = augmentToolDescription(\n  mcpTool.name,\n  mcpTool.description ?? '',\n);\n```\n\nThis approach reduces system prompt overhead by embedding usage rules directly in tool descriptions.\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:45-50]()\n\n## Prompt Loading\n\nThe `McpPromptLoader` handles loading and registering MCP prompt templates. Prompts are discovered from connected MCP servers and made available for use in conversations.\n\n### Prompt Structure\n\nMCP prompts can include:\n\n- **Name**: Unique identifier for the prompt\n- **Description**: Human-readable explanation of when to use the prompt\n- **Arguments**: Template variables that can be customized at runtime\n- **Template**: The actual prompt content with variable placeholders\n\n资料来源：[packages/cli/src/services/McpPromptLoader.ts]()\n\n## MCP Server Implementation\n\nGemini CLI provides example MCP server implementations demonstrating how to create compliant servers.\n\n### Basic Example\n\nThe basic MCP server example (`packages/cli/src/commands/extensions/examples/mcp-server`) exposes:\n\n- **Tool**: `fetch_posts` - Mock-fetches posts\n- **Prompt**: `poem-writer` - Generates poems\n\n### Extension Structure\n\n```\nmcp-server/\n├── example.js          # Server entry point\n├── gemini-extension.json  # Configuration manifest\n└── package.json        # Dependencies\n```\n\n### Server Entry Point\n\nServers implement the MCP specification using `@modelcontextprotocol/sdk`:\n\n```javascript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\nconst server = new Server(\n  { name: 'example-mcp-server', version: '1.0.0' },\n  { capabilities: { tools: {}, prompts: {} } }\n);\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/mcp-server/README.md]()\n\n## Security Model\n\nMCP Integration includes multiple security layers:\n\n### Consent and Allowlists\n\n| Security Feature | Description |\n|-----------------|-------------|\n| `canLoadServer` | Checks if server is allowed to load |\n| `applyAdminAllowlist` | Validates against admin-defined allowlist |\n| `getAdminBlockedMcpServersMessage` | Reports blocked servers to user |\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:20-25]()\n\n### Policy Engine Integration\n\nThe policy engine example extension demonstrates how to add security rules:\n\n- **Confirmation Rules**: Require user confirmation for dangerous operations (e.g., `rm -rf`)\n- **Denial Rules**: Block access to sensitive resources (e.g., searching for `.env` files)\n- **Safety Checkers**: Validate operations before execution (e.g., path validation)\n\nSecurity note: Extensions can strengthen security but cannot bypass user confirmation or enable `yolo` mode.\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Usage Examples\n\n### Configure MCP Server\n\nAdd server configuration to `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/workspace\"]\n    }\n  }\n}\n```\n\n### Using MCP Tools\n\nAfter configuration, tools are automatically available:\n\n```\n> @github List my open pull requests\n> @database Run a query to find inactive users\n```\n\n### Creating Custom Server\n\n1. Create server directory structure\n2. Implement MCP server using `@modelcontextprotocol/sdk`\n3. Add `gemini-extension.json` manifest\n4. Link extension: `gemini extensions link <path>`\n\n## Command Reference\n\n### List MCP Servers\n\n```bash\ngemini mcp list\n```\n\nDisplays all configured MCP servers with their status.\n\n资料来源：[packages/cli/src/commands/mcp/list.ts]()\n\n### MCP Server Integration Guide\n\nFor detailed setup instructions, see the [MCP Server Integration guide](https://www.geminicli.com/docs/tools/mcp-server).\n\n## See Also\n\n- [Custom Commands](https://www.geminicli.com/docs/cli/custom-commands)\n- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)\n- [Extension Development](../extensions/index.md)\n- [Official MCP Documentation](https://modelcontextprotocol.io)\n\n---\n\n<a id='skills-extensions'></a>\n\n## Skills and Extensions\n\n### 相关页面\n\n相关主题：[MCP Integration](#mcp-integration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/skills/skillManager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillManager.ts)\n- [packages/core/src/skills/skillLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillLoader.ts)\n- [packages/cli/src/config/extension-manager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/extension-manager.ts)\n- [packages/core/src/hooks/hookSystem.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/hooks/hookSystem.ts)\n- [docs/cli/skills.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/skills.md)\n- [docs/extensions/writing-extensions.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/extensions/writing-extensions.md)\n</details>\n\n# Skills and Extensions\n\n## Overview\n\nSkills 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.\n\n**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.\n\n**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.\n\n---\n\n## Skills System\n\n### What Are Skills?\n\nSkills are modular knowledge packages that help Gemini CLI handle specialized tasks. Each skill contains:\n\n- **Frontmatter**: YAML metadata defining the skill's name and trigger conditions\n- **Body**: Markdown instructions loaded after the skill triggers\n- **Scripts**: Executable code (Node.js/Python/Bash) for deterministic operations\n- **References**: Documentation loaded into context as needed\n- **Assets**: Templates, icons, fonts, and other output files\n\n### Skill Structure\n\n```\nskill-name/\n├── SKILL.md           # Required: Frontmatter + Instructions\n├── scripts/           # Optional: Executable code\n│   └── *.cjs, *.py, etc.\n├── references/        # Optional: Documentation\n│   └── *.md\n└── assets/            # Optional: Output files\n    └── templates/, icons/, etc.\n```\n\n### SKILL.md Format\n\nEvery skill requires a `SKILL.md` file with two components:\n\n**Frontmatter (YAML):**\n```yaml\n---\nname: skill-name\ndescription: Clear description of what this skill does and when it should be triggered\n---\n```\n\n**Body (Markdown):**\nInstructions and guidance for executing the skill. This content is loaded only after the skill triggers, not during initial context evaluation.\n\n### Skill Loading Mechanism\n\nSkills are discovered and loaded through the `SkillLoader` system. The system:\n\n1. Scans configured skill directories\n2. Parses SKILL.md frontmatter for name and description\n3. Makes skills available for trigger matching\n4. Loads skill content on-demand when triggered\n\n### Skill Triggering\n\nWhen 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.\n\n---\n\n## Skill Design Patterns\n\n### Pattern 1: Flat Organization\n\nFor simple skills with linear workflows:\n\n```\ncsv-processor/\n├── SKILL.md\n├── FORMS.md           # Input/output templates\n├── REFERENCE.md       # Full documentation\n└── EXAMPLES.md        # Usage examples\n```\n\nGemini CLI loads `FORMS.md`, `REFERENCE.md`, or `EXAMPLES.md` only when needed.\n\n### Pattern 2: Domain-Specific Organization\n\nFor skills supporting multiple domains or variants:\n\n```\nbigquery-skill/\n├── SKILL.md (overview + navigation)\n└── references/\n    ├── finance.md     # Revenue, billing metrics\n    ├── sales.md       # Opportunities, pipeline\n    ├── product.md     # API usage, features\n    └── marketing.md  # Campaigns, attribution\n```\n\n### Pattern 3: Conditional Details\n\nShow basic content with links to advanced topics:\n\n```markdown\n## Basic Analysis\n\nUse pandas for loading and basic queries. See [PANDAS.md](PANDAS.md).\n\n## Advanced Operations\n\nFor massive files, see [STREAMING.md](STREAMING.md). For timestamp normalization, see [TIMESTAMPS.md](TIMESTAMPS.md).\n```\n\n---\n\n## Scripts in Skills\n\nScripts provide deterministic, token-efficient execution for tasks that are repeatedly rewritten or require reliability guarantees.\n\n### When to Include Scripts\n\n| Scenario | Example |\n|----------|---------|\n| Repeatedly rewritten code | PDF rotation, image processing |\n| Deterministic reliability needed | File format conversions |\n| Token efficiency important | Complex parsing operations |\n\n### Script Requirements\n\n- **Output format**: LLM-friendly stdout\n- **Error handling**: Suppress standard tracebacks\n- **Messages**: Clear success/failure messages\n- **Pagination**: Truncate long outputs to prevent context overflow\n\n```javascript\n// Example: scripts/rotate_pdf.cjs\nconsole.log(\"Success: Rotated PDF 90 degrees clockwise\");\nconsole.log(\"Output: rotated_document.pdf\");\n```\n\n---\n\n## Extensions System\n\n### What Are Extensions?\n\nExtensions are npm packages that extend Gemini CLI through a structured manifest system. They provide programmatic capabilities beyond what markdown-based skills offer.\n\n### Extension Structure\n\n```\nextension-name/\n├── gemini-extension.json    # Required manifest\n├── src/                     # Source code\n├── commands/                # Custom slash commands\n├── policies/                # Security rules (TOML)\n└── package.json\n```\n\n### Extension Manifest\n\nThe `gemini-extension.json` manifest defines the extension's contributions:\n\n```json\n{\n  \"name\": \"my-extension\",\n  \"version\": \"1.0.0\",\n  \"commands\": [\"./commands/*.ts\"],\n  \"mcpServers\": {},\n  \"policies\": [\"./policies/*.toml\"]\n}\n```\n\n### Extension Capabilities\n\n| Capability | Description |\n|------------|-------------|\n| Custom Commands | Slash commands (`/command`) that extend CLI functionality |\n| MCP Servers | Model Context Protocol server configurations |\n| Policy Rules | Security rules and safety checkers |\n| Hooks | Pre/post execution hooks for customization |\n\n---\n\n## Policy Engine\n\nExtensions can contribute security rules through the Policy Engine.\n\n### Rule Definition (TOML)\n\n```toml\n[[rules]]\nid = \"deny-rm-rf\"\ndescription = \"Prevents dangerous recursive deletion\"\ncondition = \"command contains 'rm -rf'\"\naction = \"confirm\"\nmessage = \"This command will recursively delete files. Confirm?\"\n```\n\n### Safety Checkers\n\nExtensions can provide safety checkers that validate operations:\n\n```toml\n[[safety_checkers]]\nname = \"allowed-path\"\ndescription = \"Validates file paths for write operations\"\ncheck = \"path.startsWith(allowedDirectory)\"\n```\n\n### Security Notes\n\n- Extensions **cannot** bypass user confirmation requirements\n- `allow` decisions from extensions are ignored for security\n- `yolo` mode configurations from extensions are ignored\n- Extensions can only strengthen security, not weaken it\n\n---\n\n## MCP Server Integration\n\nExtensions can configure MCP (Model Context Protocol) servers for specialized capabilities:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n### Configuration Flow\n\n```mermaid\ngraph TD\n    A[User Request] --> B{MCP Server Configured?}\n    B -->|Yes| C[Load MCP Server]\n    B -->|No| D[Continue without MCP]\n    C --> E[Execute MCP Tools]\n    D --> F[Standard Tool Execution]\n```\n\n---\n\n## Hook System\n\nThe Hook System provides pre/post execution points for customization.\n\n### Available Hooks\n\n| Hook | Timing | Purpose |\n|------|--------|---------|\n| `preToolExecution` | Before tool call | Modify inputs, log, or validate |\n| `postToolExecution` | After tool call | Process outputs, track metrics |\n| `prePromptGeneration` | Before prompt build | Customize context |\n| `postResponseGeneration` | After response | Format or filter output |\n\n### Hook Registration\n\nExtensions register hooks through the hook system API:\n\n```typescript\nhookSystem.register('preToolExecution', async (context) => {\n  // Validate or modify before execution\n  return { modified: false, context };\n});\n```\n\n---\n\n## Creating Skills\n\n### Command\n\n```bash\ngemini skill create my-skill\n```\n\n### Generated Structure\n\n```\nmy-skill/\n├── SKILL.md\n├── scripts/\n│   └── example_script.cjs\n├── references/\n│   └── example_reference.md\n└── assets/\n    └── example_asset.txt\n```\n\n### Customization Steps\n\n1. Edit `SKILL.md` with accurate name and description\n2. Add scripts for deterministic operations\n3. Create reference documentation\n4. Place assets in the `assets/` directory\n5. Delete unused example files\n\n### Best Practices\n\n- **Description clarity**: The description determines when the skill triggers. Be specific about use cases.\n- **Script testing**: Run scripts to verify they work correctly\n- **Token efficiency**: Use scripts instead of repeated code generation\n- **Reference loading**: Only load references when needed\n\n---\n\n## Creating Extensions\n\n### Command\n\n```bash\ngemini extensions create my-extension\n```\n\n### Implementation Checklist\n\n| Step | Task |\n|------|------|\n| 1 | Define extension manifest |\n| 2 | Implement custom commands |\n| 3 | Configure MCP servers |\n| 4 | Add policy rules |\n| 5 | Register hooks |\n| 6 | Test locally with `gemini extensions link` |\n\n### Local Development\n\n```bash\n# Link extension for local testing\ngemini extensions link ./path/to/extension\n\n# Unlink when done\ngemini extensions unlink my-extension\n```\n\n---\n\n## Configuration\n\n### Skill Directories\n\nSkills are loaded from configured directories. Check `~/.gemini/settings.json`:\n\n```json\n{\n  \"skills\": {\n    \"directories\": [\"./.skills\", \"~/.gemini/skills\"]\n  }\n}\n```\n\n### Extension Settings\n\nExtensions are discovered from:\n\n- Globally installed npm packages (`@gemini-extensions/*`)\n- Locally linked directories\n- User-configured paths in `settings.json`\n\n---\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Skill Layer\"\n        A[SKILL.md] --> B[SkillLoader]\n        C[scripts/] --> D[Script Executor]\n        E[references/] --> F[Context Loader]\n    end\n    \n    subgraph \"Extension Layer\"\n        G[gemini-extension.json] --> H[ExtensionManager]\n        I[commands/] --> J[Command Registry]\n        K[policies/] --> L[Policy Engine]\n        M[mcpServers] --> N[MCP Client]\n    end\n    \n    subgraph \"Core\"\n        B --> O[Skill Manager]\n        H --> O\n        D --> O\n        L --> P[Security Layer]\n        N --> Q[Tool Executor]\n    end\n    \n    O --> Q\n    Q --> R[Response Formatter]\n```\n\n---\n\n## Summary\n\n| Feature | Skills | Extensions |\n|---------|--------|------------|\n| **Format** | Markdown-based | npm packages |\n| **Trigger** | Semantic matching | Manual invocation |\n| **Code** | Optional scripts | Full source code |\n| **Complexity** | Low-medium | Medium-high |\n| **Use case** | Guidance, patterns | Tools, policies, integrations |\n\n**Skills** provide lightweight, context-loaded guidance for specialized tasks.\n\n**Extensions** provide comprehensive programmatic extensibility through custom commands, MCP servers, policy rules, and hooks.\n\nBoth mechanisms work together to make Gemini CLI adaptable to diverse workflows and requirements.\n\n---\n\n<a id='sandboxing-security'></a>\n\n## Sandboxing and Security\n\n### 相关页面\n\n相关主题：[Policy Engine](#policy-engine), [Tools Reference](#tools-reference)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n- [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)\n- [packages/cli/src/config/trustedFolders.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/trustedFolders.ts)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [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)\n- [package.json](https://github.com/google-gemini/gemini-cli/blob/main/package.json)\n</details>\n\n# Sandboxing and Security\n\n## Overview\n\nGemini 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.\n\n## Architecture\n\nThe 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.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Config System]\n    B --> C{Path Validation}\n    C -->|Allowed| D[Sandbox Manager]\n    C -->|Denied| E[Access Rejected]\n    D --> F{Linux Sandbox}\n    D --> G{macOS Sandbox}\n    D --> H{Windows Sandbox}\n    F --> I[Docker Container]\n    G --> J[Apple Silicon / Sandbox Profile]\n    H --> K[Windows Sandbox]\n    I --> L[Tool Execution]\n    J --> L\n    K --> L\n```\n\n## Sandbox Manager Architecture\n\nThe sandbox system is orchestrated through a centralized `SandboxManager` service that delegates to platform-specific implementations.\n\n### Platform-Specific Implementations\n\n| Platform | Manager Class | Isolation Method |\n|----------|---------------|------------------|\n| Linux | `LinuxSandboxManager` | Docker containers with resource limits |\n| macOS | `MacOsSandboxManager` | App Sandbox / Process sandboxing |\n| Windows | `WindowsSandboxManager` | Windows Sandbox virtualization |\n\n### Sandbox Image Configuration\n\nSandbox environments use pre-built Docker images defined in the root `package.json`:\n\n```json\n{\n  \"config\": {\n    \"sandboxImageUri\": \"us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef\"\n  }\n}\n```\n\n资料来源：[package.json:11]()\n\n## Path Validation System\n\nThe path validation system prevents the agent from accessing files outside authorized boundaries. This is implemented in the `Config` class through two primary methods.\n\n### Access Control Logic\n\n```typescript\nisPathAllowed(absolutePath: string): boolean {\n  const resolvedPath = resolveToRealPath(absolutePath);\n  // Check inbox isolation first\n  // Check workspace boundaries\n  // Check project temp directory\n}\n\nvalidatePathAccess(absolutePath: string): string | null {\n  if (this.isPathAllowed(absolutePath)) {\n    return null;\n  }\n  return `Path not in workspace: Attempted path \"${absolutePath}\" resolves outside the allowed workspace directories`;\n}\n```\n\n资料来源：[packages/core/src/config/config.ts]()\n资料来源：[packages/core/src/tools/confirmation-policy.test.ts]()\n\n### Allowed Path Categories\n\n| Category | Description | Access Level |\n|----------|-------------|--------------|\n| Workspace directories | User-specified project roots | Full read/write |\n| Project temp directory | Temporary files for operations | Read/write within bounds |\n| Inbox directory | Auto-memory extraction staging | Restricted write access |\n\n### Inbox Isolation\n\nThe `.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:\n\n```mermaid\ngraph LR\n    A[Main Agent] -->|DENIED| B[.inbox/ directory]\n    C[Extraction Agent] -->|WRITE ALLOWED| B\n    D[Review Flow] -->|READ| B\n```\n\n资料来源：[packages/core/src/config/config.ts]()\n\n## Trusted Folders System\n\nThe trusted folders mechanism allows users to authorize specific directories for configuration loading while maintaining security boundaries.\n\n### What Trust Enables\n\nWhen a folder is trusted, Gemini CLI loads:\n\n- Custom commands\n- Hooks\n- MCP server configurations\n- Agent skills\n- Local settings\n\n### Security Dialog\n\nWhen discovering a new folder, users are presented with the `FolderTrustDialog` component that displays:\n\n```typescript\n// Security warnings and errors are displayed to the user\n{hasWarnings && (\n  <Box>\n    <Text color={theme.status.warning}>⚠️ Security Warnings:</Text>\n    {discoveryResults.securityWarnings.map((warning, i) => (\n      <Text key={i} color={theme.status.warning}>\n        • {stripAnsi(warning)}\n      </Text>\n    ))}\n  </Box>\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()\n\n### Discovery Results\n\nThe folder discovery process returns categorized items:\n\n| Group Label | Item Types |\n|-------------|------------|\n| Custom Commands | User-defined slash commands |\n| Hooks | Pre/post execution scripts |\n| MCP Servers | Model Context Protocol servers |\n| Agent Skills | Specialized skill modules |\n| Settings | Configuration overrides |\n\n## Policy Engine\n\nExtensions can contribute security rules and safety checkers through the policy engine. This allows the community to extend built-in security without modifying core code.\n\n### Rule Types\n\n| Rule Type | Purpose | Example |\n|-----------|---------|---------|\n| Confirmation Rules | Require user approval for specific operations | Confirm before `rm -rf` |\n| Denial Rules | Block specific operations entirely | Prevent `grep` for `.env` files |\n| Safety Checkers | Validate operations before execution | Path validation for writes |\n\n### Extension Policy Structure\n\n```\nextension/\n├── gemini-extension.json\n└── policies/\n    ├── confirmation-rules.toml\n    ├── denial-rules.toml\n    └── safety-checkers.toml\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n### Security Enforcement\n\n**Critical**: Gemini CLI ignores `allow` decisions and `yolo` mode configurations contributed by extensions. This ensures that:\n\n- Extensions can strengthen security\n- Extensions cannot bypass user confirmation\n- Malicious extensions cannot weaken protections\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Configuration Reference\n\n### Settings File Location\n\nUser settings are stored at `~/.gemini/settings.json`\n\n### Key Security Settings\n\n| Setting | Type | Purpose |\n|---------|------|---------|\n| `trustedFolders` | Array of paths | Authorize directories for config loading |\n| `dataCollectionOptIn` | Boolean | Control telemetry data sharing |\n\n### Workspace Context\n\n```typescript\ninterface WorkspaceContext {\n  isPathWithinWorkspace(path: string): boolean;\n  getDirectories(): string[];\n}\n```\n\nThe workspace context is queried during path validation to determine if a requested file operation falls within authorized boundaries.\n\n## Security Best Practices\n\n### For Users\n\n1. **Review folder trust requests** - Only trust folders containing code you control\n2. **Understand policy rules** - Read denial messages to understand why operations are blocked\n3. **Use workspace isolation** - Keep sensitive files outside workspace directories\n\n### For Extension Developers\n\n1. **Contribute restrictive rules** - Extensions should only add protections, never remove them\n2. **Follow policy TOML format** - Use structured definitions for predictable behavior\n3. **Test edge cases** - Validate paths resolve correctly across platforms\n\n## Summary\n\nGemini CLI's security architecture combines:\n\n- **Platform-specific sandboxing** for code execution isolation\n- **Path validation** for filesystem access control\n- **Trusted folder system** for configuration security\n- **Policy engine** for extensible rule definitions\n- **Inbox isolation** for memory extraction workflow integrity\n\nThis multi-layered approach allows the CLI to safely execute AI-generated code while giving users transparency and control over security boundaries.\n\n---\n\n<a id='policy-engine'></a>\n\n## Policy Engine\n\n### 相关页面\n\n相关主题：[Sandboxing and Security](#sandboxing-security), [Agent System](#agent-system)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [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)\n- [packages/core/src/availability/policyHelpers.test.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/availability/policyHelpers.test.ts)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n</details>\n\n# Policy Engine\n\n## Overview\n\nThe 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.\n\nThe 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.\n\n## Architecture\n\n### Core Components\n\nThe Policy Engine consists of three primary layers:\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Policy Loader | Parses and loads TOML policy files | `packages/core/src/policy/toml-loader.ts` |\n| Policy Engine | Evaluates operations against loaded policies | `packages/core/src/policy/policy-engine.ts` |\n| Policy Configuration | Manages runtime policy settings | `packages/cli/src/config/policy.ts` |\n\n### Evaluation Flow\n\n```mermaid\ngraph TD\n    A[Operation Request] --> B{Policy Engine}\n    B --> C[Load Policies from TOML]\n    C --> D[Apply Security Rules]\n    D --> E{Rule Match?}\n    E -->|Yes| F[Prompt User Confirmation]\n    E -->|No| G[Apply Safety Checkers]\n    F --> H{User Approves?}\n    H -->|Yes| G\n    H -->|No| I[Block Operation]\n    G --> J{Safety Valid?}\n    J -->|Yes| K[Execute Operation]\n    J -->|No| I\n    I --> L[Return Error/Deny Message]\n    K --> M[Operation Complete]\n```\n\n## Policy Configuration\n\n### Configuration File Location\n\nPolicy 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.\n\n### Policy Types\n\nThe Policy Engine supports two categories of policies:\n\n#### Security Rules\n\nSecurity rules define conditional logic that triggers user confirmation or denies operations based on specific patterns. Rules are evaluated before operation execution and can:\n\n- Require user confirmation for dangerous commands\n- Deny operations matching specific patterns\n- Provide custom deny messages explaining why an operation was blocked\n\n#### Safety Checkers\n\nSafety 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.\n\n## Extension Integration\n\n### Registering Policy Extensions\n\nExtensions can contribute policies by including a `policies/` directory with TOML files. The extension manifest (`gemini-extension.json`) identifies it as a policy contributor.\n\n### Security Constraints\n\nFor security, Gemini CLI enforces strict constraints on extension-contributed policies:\n\n```toml\n[security]\n# Gemini CLI ignores these configurations from extensions\nallow_decisions = false  # Ignored\nyolo_mode = false        # Ignored\n```\n\n| Extension-Provided Setting | Gemini CLI Behavior |\n|---------------------------|---------------------|\n| `allow` decisions | **Ignored** - Always treated as prompt |\n| `yolo` mode configuration | **Ignored** - Cannot bypass confirmation |\n\nThis design ensures that extensions can only strengthen security by adding more restrictive rules—they cannot weaken security by bypassing user confirmation.\n\n## Built-in Policies\n\n### rm -rf Rule Example\n\nThe following demonstrates a policy that requires confirmation for recursive directory deletion:\n\n```toml\n[[rules]]\nid = \"prevent-recursive-delete\"\ndescription = \"Require confirmation for rm -rf commands\"\n\n[rules.condition]\ncommand_pattern = \"rm.*-rf.*\"\n\n[rules.action]\ntype = \"confirm\"\nmessage = \"This will recursively delete directories. Are you sure?\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### Secret File Access Rule Example\n\nPolicies can prevent searching for sensitive files:\n\n```toml\n[[rules]]\nid = \"prevent-secret-search\"\ndescription = \"Deny grep searches for sensitive files\"\n\n[rules.condition]\ncommand_pattern = \"grep.*\\\\.env\"\n\n[rules.action]\ntype = \"deny\"\nmessage = \"Searching for .env files is not allowed for security reasons\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### File Path Safety Checker Example\n\nSafety checkers validate operation parameters:\n\n```toml\n[[safety_checkers]]\nid = \"allowed-path\"\ndescription = \"Validate file paths for write operations\"\n\n[safety_checkers.validator]\ntype = \"path_validation\"\nallowed_paths = [\"/home/user/project\", \"/tmp/uploads\"]\n```\n\n## Policy Chain Resolution\n\nThe 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.\n\n```mermaid\ngraph LR\n    A[Model Config] --> B{Is Custom Model?}\n    B -->|Yes| C[Single-Model Chain]\n    B -->|No| D{Is in Catalog?}\n    D -->|Yes| E[Use Catalog Order]\n    D -->|No| F[Default Chain: Pro → Flash]\n```\n\n| Model Scenario | Policy Chain Behavior |\n|---------------|----------------------|\n| Custom model | Single-model chain |\n| Catalog model (exists) | Preserves catalog order |\n| Auto model (`gemini-2.5-pro` or default) | Default chain: Pro, then Flash |\n\n资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50]()\n\n## Folder Trust Integration\n\nThe Policy Engine integrates with Gemini CLI's folder trust system. Policies are only loaded from trusted folders to prevent malicious configuration injection.\n\n| Trust State | Policy Loading |\n|------------|----------------|\n| Trusted folder | Full policy enforcement |\n| Untrusted folder | Policies not loaded |\n| YOLO mode disabled | Cannot enable YOLO in untrusted folders |\n\nThe `isYoloModeDisabled` method checks both the global YOLO disable flag and the folder trust status:\n\n```typescript\nisYoloModeDisabled(): boolean {\n  return this.disableYoloMode || !this.isTrustedFolder();\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:200-203]()\n\n### Security Warnings and Errors\n\nWhen loading policies from a folder, the system reports:\n\n- **Discovery Errors**: Problems parsing or loading policy files\n- **Security Warnings**: Potentially risky configurations detected\n- **Loaded Items**: Policies successfully loaded and active\n\n```typescript\ninterface DiscoveryResults {\n  discoveryErrors: string[];\n  securityWarnings: string[];\n  loadedPolicies: Policy[];\n}\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:1-60]()\n\n## Configuration Options\n\n### Core Policy Settings\n\n| Setting | Type | Default | Description |\n|---------|------|---------|-------------|\n| `disableYoloMode` | boolean | `false` | Disables YOLO mode entirely |\n| `disableAlwaysAllow` | boolean | `false` | Prevents \"always allow\" shortcuts |\n| `pendingIncludeDirectories` | string[] | `[]` | Directories pending trust approval |\n\n### Policy File Loading\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| Policy directory | `policies/` | TOML files in extension packages |\n| File format | `.toml` | TOML 1.0 specification |\n| Reload trigger | Folder trust change | Policies reload when trust state changes |\n\n## Best Practices\n\n### Writing Secure Policies\n\n1. **Use specific patterns**: Avoid overly broad patterns that could match legitimate operations\n2. **Provide clear messages**: Explain why an operation requires confirmation\n3. **Validate file paths**: Use safety checkers for path-based operations\n4. **Test edge cases**: Ensure policies don't block necessary operations\n\n### Policy Testing\n\nTo test policies contributed by extensions:\n\n```bash\n# Link the extension\ngemini extensions link packages/cli/src/commands/extensions/examples/policies\n\n# Restart Gemini CLI session\n# Policies will be loaded from the linked extension\n```\n\n### Debugging Policy Evaluation\n\nWhen policies don't behave as expected:\n\n1. Verify the extension is properly linked\n2. Check the folder is marked as trusted\n3. Review TOML syntax for parsing errors\n4. Confirm rule patterns match the actual command strings\n\n## Summary\n\nThe 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.\n\n---\n\n<a id='terminal-ui'></a>\n\n## Terminal UI Components\n\n### 相关页面\n\n相关主题：[Session Management](#session-management)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)\n- [packages/cli/src/ui/components/InboxDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/InboxDialog.tsx)\n- [packages/cli/src/ui/components/ToolConfirmationMessage.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ToolConfirmationMessage.tsx)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [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)\n</details>\n\n# Terminal UI Components\n\n## Overview\n\nThe 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.\n\nThe component architecture follows a modular design pattern, separating concerns between layout containers, interactive dialogs, informational displays, and message rendering components.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"UI Layer\"\n        A[App.tsx] --> B[AppHeader]\n        A --> C[MainContent]\n        A --> D[Composer]\n    end\n    \n    subgraph \"Dialogs\"\n        E[AuthDialog] --> F[RadioButtonSelect]\n        G[ModelDialog] --> H[ModelQuotaDisplay]\n        I[FolderTrustDialog] --> J[DiscoveryResults]\n        K[InboxDialog] --> L[ScrollableDiffViewport]\n    end\n    \n    subgraph \"Messages\"\n        M[GeminiMessage] --> N[StreamingState]\n        O[ToolConfirmationMessage] --> P[ConfirmationDetails]\n    end\n    \n    subgraph \"Theming\"\n        Q[ThemeManager] --> R[Theme Types]\n        Q --> S[Custom Extensions]\n    end\n```\n\n## Component Categories\n\n### 1. Layout Components\n\n#### AppHeader\nThe main header component displaying CLI branding, version information, and user identity.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `showHeader` | `boolean` | Controls header visibility |\n| `showDetails` | `boolean` | Shows detailed metadata |\n| `bannerVisible` | `boolean` | Displays warning/info banners |\n| `bannerText` | `string` | Banner content text |\n\n**Key Features:**\n- Dynamic layout: switches between row and column orientation based on terminal width\n- Update notifications with spinner animation during version checks\n- User identity display (email and plan information)\n- Collapsible tips section\n- Configurable branding via logo text art\n\n**Source:** [packages/cli/src/ui/components/AppHeader.tsx:1-100]()\n\n#### Composer\nInput component for user commands and messages.\n\nProvides the text input interface for interacting with Gemini CLI, supporting multi-line input and command submission.\n\n### 2. Dialog Components\n\n#### AuthDialog\nHandles user authentication flow with multiple provider options.\n\n```mermaid\ngraph LR\n    A[Launch] --> B{Auth Method?}\n    B -->|OAuth| C[Google Login]\n    B -->|Token| D[API Key Input]\n    B -->|Skip| E[Continue Anonymously]\n    C --> F[Restart CLI]\n    D --> G[Validate Token]\n    E --> H[Limited Mode]\n```\n\n**Features:**\n- Radio button selection for authentication methods\n- Error state handling with visual feedback\n- Links to Terms of Service and Privacy Notice\n- OAuth flow with automatic CLI restart\n\n**Source:** [packages/cli/src/ui/auth/AuthDialog.tsx:1-80]()\n\n#### ModelDialog\nDisplays available models with quota information and allows model selection.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `modelVersion` | `string` | Currently active model identifier |\n| `quotaDisplay` | `QuotaBucket[]` | Rate limit information |\n| `terminalWidth` | `number` | Available display width |\n\n**Source:** [packages/cli/src/ui/components/ModelDialog.tsx:1-60]()\n\n#### FolderTrustDialog\nSecurity-focused dialog for approving folder configurations.\n\n**Key Sections:**\n1. **Trust Explanation** - Documents what configurations will be loaded\n2. **Discovery Results** - Shows found extensions, commands, hooks, and skills\n3. **Security Warnings** - Highlights potentially risky configurations\n4. **Discovery Errors** - Reports parsing or loading failures\n\n**Source:** [packages/cli/src/ui/components/FolderTrustDialog.tsx:1-100]()\n\n#### InboxDialog\nDisplays notification patches and skill updates available for installation.\n\n| Display Field | Source | Format |\n|--------------|--------|--------|\n| Title | `patch.name` | `string + [origin]` |\n| Subtitle | `patch.extractedAt` | `files · date` |\n| Content Preview | `skillSections` | Scrollable diff |\n\n**Source:** [packages/cli/src/ui/components/InboxDialog.tsx:1-120]()\n\n### 3. Message Components\n\n#### GeminiMessage\nRenders AI-generated responses with markdown support.\n\n**Rendering Modes:**\n- **Markdown Rendered** (default): Full markdown parsing with syntax highlighting\n- **Raw Markdown**: Syntax highlighting without line numbers\n\n**Configuration Options:**\n```typescript\ninterface GeminiMessageProps {\n  text: string;           // Message content\n  isPending: boolean;     // Streaming indicator\n  terminalWidth: number;  // Layout adaptation\n  renderMarkdown?: boolean;\n  streamingState?: StreamingState;\n}\n```\n\n**Source:** [packages/cli/src/ui/components/messages/GeminiMessage.test.tsx:1-50]()\n\n#### ToolConfirmationMessage\nDisplays interactive confirmation prompts for tool execution.\n\n**Supported Types:**\n- `edit` - File modification operations\n- `read` - Content retrieval requests\n- `execute` - Command execution confirmations\n- `delete` - Resource removal confirmations\n\n**States:**\n- Normal confirmation view\n- In-progress indicator (\"Save and close external editor\")\n- Security warning display\n- System message overlay\n\n**Source:** [packages/cli/src/ui/components/ToolConfirmationMessage.tsx:1-100]()\n\n### 4. Information Components\n\n#### AboutBox\nDisplays system and version information.\n\n| Field | Source | Visibility |\n|-------|--------|------------|\n| CLI Version | `cliVersion` | Always |\n| Git Commit | `GIT_COMMIT_INFO` | Unless \"N/A\" |\n| Model | `modelVersion` | Always |\n| Sandbox | `sandboxEnv` | Always |\n| OS | System Info | Always |\n\n**Source:** [packages/cli/src/ui/components/AboutBox.tsx:1-60]()\n\n## Theming System\n\nThe UI supports customizable color themes that apply consistent styling across all components.\n\n### Theme Structure\n\n```typescript\ninterface Theme {\n  text: {\n    primary: string;\n    secondary: string;\n    accent: string;\n    link: string;\n  };\n  status: {\n    success: string;\n    warning: string;\n    error: string;\n  };\n  border: {\n    default: string;\n  };\n  ui: {\n    focus: string;\n  };\n}\n```\n\n### Theme Configuration\n\nUsers can create custom themes by:\n1. Creating an extension with theme definition in `gemini-extension.json`\n2. Setting the theme in `~/.gemini/settings.json`:\n   ```json\n   {\n     \"ui\": {\n       \"theme\": \"theme-name (extension-name)\"\n     }\n   }\n   ```\n\n### Available UI Settings\n\n| Setting | Type | Default | Description |\n|---------|------|---------|-------------|\n| `showUserIdentity` | `boolean` | `true` | Display email and plan |\n| `hideTips` | `boolean` | `false` | Hide tips section |\n| `renderMarkdown` | `boolean` | `true` | Enable markdown rendering |\n\n## Component Composition Patterns\n\n### Dialog Pattern\nAll dialogs follow a consistent structure:\n\n```typescript\n<Box borderStyle=\"round\" borderColor={theme.ui.focus}>\n  <Box flexDirection=\"column\">\n    {/* Title */}\n    <Text bold>{title}</Text>\n    \n    {/* Content */}\n    {children}\n    \n    {/* Footer */}\n    <DialogFooter \n      primaryAction=\"Enter to select\"\n      cancelAction=\"Esc to close\"\n    />\n  </Box>\n</Box>\n```\n\n### Responsive Layout\nComponents adapt to terminal width using:\n- Flexbox with `flexDirection` switching (row/column)\n- Percentage-based widths (`width=\"35%\"`)\n- Conditional rendering based on `terminalWidth`\n- Maximum size constraints via `MaxSizedBox`\n\n### Color Application\nComponents use semantic color tokens:\n- `theme.text.primary` - Main content text\n- `theme.text.secondary` - Supporting text\n- `theme.text.accent` - Highlighted elements\n- `theme.text.link` - Interactive links\n- `theme.status.*` - State indicators (success, warning, error)\n\n## State Management\n\n### UI State Context\nComponents access shared state through React context:\n\n```typescript\ninterface UIState {\n  renderMarkdown: boolean;\n  streamingState: StreamingState;\n  terminalWidth: number;\n}\n```\n\n### Component Communication\n| Pattern | Example | Purpose |\n|---------|---------|---------|\n| Props drilling | `AuthDialog` → `RadioButtonSelect` | Simple parent-child |\n| Context | `theme` access | Global styling |\n| Callback props | `onSelect`, `onHighlight` | Event handling |\n| State updates | `isUpdating` flag | Async operations |\n\n## Security Features\n\n### Folder Trust System\nThe `FolderTrustDialog` implements security boundaries:\n\n1. **Discovery Phase**: Scans for configuration files\n2. **Warning Phase**: Identifies potentially dangerous configurations\n3. **Approval Phase**: User explicitly approves folder access\n4. **Execution Phase**: Loads approved configurations\n\n### Data Collection Opt-In\nUsers can control whether usage data is collected:\n- UI toggle in privacy settings\n- Persisted preference in `settings.json`\n- Clear documentation in privacy notices\n\n## Testing Approach\n\nComponents use snapshot testing with `renderWithProviders`:\n\n```typescript\nit('renders pending state', async () => {\n  const { lastFrame } = await renderWithProviders(\n    <GeminiMessage {...props} isPending={true} />,\n    { uiState: { renderMarkdown: true } }\n  );\n  expect(lastFrame()).toMatchSnapshot();\n});\n```\n\nTest utilities provide:\n- Mocked Ink components\n- Theme injection\n- State context setup\n- Terminal width simulation\n\n## Best Practices\n\n### Component Guidelines\n1. **Accessibility**: Support keyboard navigation (Enter, Escape)\n2. **Responsiveness**: Adapt to variable terminal widths\n3. **Error Handling**: Display clear error messages with colors\n4. **Loading States**: Show spinners and progress indicators\n\n### Styling Guidelines\n1. Use semantic theme tokens instead of hardcoded colors\n2. Prefer flexbox layouts over absolute positioning\n3. Include proper margin and padding for visual hierarchy\n4. Use truncation for long text with `wrap=\"truncate-end\"`\n\n### Performance Considerations\n1. Minimize re-renders with proper memoization\n2. Use virtual scrolling for long lists\n3. Lazy load heavy content (skill previews)\n4. Cache discovery results when appropriate\n\n---\n\n<a id='session-management'></a>\n\n## Session Management\n\n### 相关页面\n\n相关主题：[Terminal UI Components](#terminal-ui), [Context and Memory Management](#context-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [packages/sdk/src/agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/src/agent.ts)\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n</details>\n\n# Session Management\n\n## Overview\n\nSession 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.\n\nSessions 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.\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:35-36]()\n\n## Session Lifecycle\n\n```mermaid\ngraph TD\n    A[User Starts CLI] --> B{Check for Existing Session?}\n    B -->|Yes| C[Resume Session]\n    B -->|No| D[Create New Session]\n    D --> E[Generate Session ID]\n    E --> F[Initialize Context Graph]\n    F --> G[Start Conversation]\n    C --> H[Load Session from Storage]\n    H --> G\n    G --> I[Process User Input]\n    I --> J[Record Message to ChatHistory]\n    J --> K{User Exits?}\n    K -->|No| I\n    K -->|Yes| L[Save Session Metadata]\n    L --> M[Close Session]\n```\n\n### Session Creation\n\nWhen 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:\n\n1. **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.\n\n2. **Project Hash Computation**: The system computes a hash of the current working directory to associate the session with a specific project context.\n\n3. **Storage Initialization**: The `ChatRecordingService` prepares file-based storage at a project-specific temp directory, enabling conversation persistence.\n\n资料来源：[packages/sdk/src/agent.ts:58-60]()\n\n### Session Resume\n\nThe session resume capability allows users to continue previous conversations seamlessly. When resuming a session, the system:\n\n1. Loads the complete conversation history from JSONL storage\n2. Reconstructs the context graph from stored messages\n3. Validates authentication state\n4. Restores model configuration and tool states\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant ChatRecordingService\n    participant GeminiAgent\n    \n    User->>CLI: Resume Session (sessionId)\n    CLI->>ChatRecordingService: Load Conversation Record\n    ChatRecordingService-->>CLI: ConversationRecord (messages, metadata)\n    CLI->>GeminiAgent: Initialize with Loaded State\n    GeminiAgent-->>CLI: Session Ready\n    CLI->>User: Display Last N Messages\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:45-52]()\n\n## Session Data Model\n\nThe `ConversationRecord` interface defines the complete structure of a persisted session:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `sessionId` | `string` | Unique identifier for the session |\n| `projectHash` | `string` | Hash of the project directory |\n| `startTime` | `string` (ISO 8601) | Session creation timestamp |\n| `lastUpdated` | `string` (ISO 8601) | Last modification timestamp |\n| `summary` | `string \\| undefined` | Auto-generated conversation summary |\n| `memoryScratchpad` | `string \\| undefined` | Persistent scratchpad notes |\n| `directories` | `string[]` | Working directories used in session |\n| `kind` | `string` | Session kind/type identifier |\n| `messages` | `Message[]` | Full message history |\n| `messageCount` | `number` | Total message count |\n| `userMessageCount` | `number` | Count of user messages only |\n| `memoryScratchpadIsStale` | `boolean \\| undefined` | Indicates if scratchpad needs refresh |\n| `firstUserMessage` | `string \\| undefined` | First user prompt for quick reference |\n| `hasUserOrAssistantMessage` | `boolean` | Indicates non-empty conversation |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:32-50]()\n\n### Message Structure\n\nMessages within a session follow the multi-part content model:\n\n```typescript\ninterface Message {\n  role: 'user' | 'model' | 'system' | 'tool';\n  parts: Array<{\n    text?: string;\n    functionCall?: FunctionCall;\n    functionResponse?: FunctionResponse;\n  }>;\n}\n```\n\nThe context graph builder processes each turn by:\n\n1. Generating a stable MD5 hash from role and content for deduplication\n2. Assigning an occurrence counter for repeated identical messages\n3. Creating a stable turn ID using the `getStableId()` utility\n4. Tracking function calls and responses with unique identifiers\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30]()\n\n## Storage Architecture\n\n### Chat Recording Service\n\nThe `ChatRecordingService` class manages all session persistence operations:\n\n```mermaid\ngraph LR\n    A[In-Memory Cache] -->|Write-through| B[JSONL File]\n    C[Session Load Request] --> D{Cache Hit?}\n    D -->|Yes| A\n    D -->|No| B\n    B -->|Load| A\n```\n\n**Key Responsibilities:**\n\n| Responsibility | Description |\n|----------------|-------------|\n| Conversation Recording | Writes messages to JSONL format |\n| Session Loading | Loads and reconstructs sessions from disk |\n| Metadata Management | Tracks summary, scratchpad, and timestamps |\n| Message Deduplication | Uses content hashing to identify duplicate turns |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:85-90]()\n\n### Storage Directory Structure\n\nSessions are stored in the project temp directory:\n\n```\n/tmp/gemini/\n├── conversation-{sessionId}.jsonl   # Full message history\n├── session-{sessionId}.json         # Session metadata\n├── bug-report-history-{timestamp}.json  # Bug report exports\n└── checkpoints/                     # Checkpoint snapshots\n```\n\nThe `getProjectTempDir()` method determines the storage path based on the active project context.\n\n资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:60-62]()\n\n## Session Browser Component\n\nThe `SessionBrowser` UI component provides an interactive interface for managing multiple sessions:\n\n- **Session List View**: Displays all historical sessions for a project\n- **Session Preview**: Shows message count, date range, and summary\n- **Session Actions**: Resume, rename, delete, or export sessions\n- **Search/Filter**: Find sessions by content or date\n\n```typescript\ninterface SessionBrowserProps {\n  sessions: ConversationRecord[];\n  onSelect: (sessionId: string) => void;\n  onDelete: (sessionId: string) => Promise<void>;\n  onExport: (sessionId: string) => Promise<void>;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/SessionBrowser.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/SessionBrowser.tsx)\n\n## Rewind Viewer\n\nThe `RewindViewer` component enables users to navigate and review historical conversation states:\n\n- **Timeline Navigation**: Move through conversation turns chronologically\n- **State Restoration**: View message content at any past point\n- **Diff View**: Compare changes between turns (optional)\n\nThis component leverages the turn-by-turn tracking implemented in the context graph builder to provide accurate historical snapshots.\n\n资料来源：[packages/cli/src/ui/components/RewindViewer.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/RewindViewer.tsx)\n\n## Session Operations\n\nThe `sessionOperations.ts` utility module provides core session manipulation functions:\n\n### Available Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `createSessionId()` | Generate a new unique session identifier |\n| `loadSession()` | Load session data from storage |\n| `saveSession()` | Persist session state to disk |\n| `deleteSession()` | Remove session and associated data |\n| `exportSession()` | Export session to portable format |\n| `listSessions()` | Enumerate all sessions for a project |\n\n### Session Resume Flow\n\n```mermaid\ngraph TD\n    A[Load Session Record] --> B{Valid Session?}\n    B -->|No| C[Raise Error]\n    B -->|Yes| D[Load Message History]\n    D --> E[Reconstruct Context Graph]\n    E --> F[Initialize Agent State]\n    F --> G[Ready for User Input]\n```\n\n资料来源：[packages/core/src/utils/sessionOperations.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/sessionOperations.ts)\n\n## Context Graph Integration\n\nThe context graph system maintains the semantic structure of conversations independently from raw message storage:\n\n1. **Turn Tracking**: Each user-model exchange is assigned a unique turn ID\n2. **Role Management**: Messages are tagged with roles (user, model, tool, system)\n3. **Function Call Tracking**: Tool interactions are recorded with unique IDs (`call_{id}` or `resp_{id}`)\n4. **Legacy Header Handling**: Automatically skips legacy environment headers during graph reconstruction\n\nThe graph builder generates stable identifiers using:\n\n```typescript\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5').update(`${msg.role}:${turnContent}`).digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nconst turnSalt = `${h}_${occurrence}`;\nconst turnId = getStableId(msg, this.nodeIdentityMap, turnSalt, -1);\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:18-25]()\n\n## SDK Integration\n\nThe Gemini CLI SDK exposes session management through the `GeminiCliAgent` and `GeminiCliSession` classes:\n\n```typescript\nconst agent = new GeminiCliAgent({\n  instructions: 'You are a helpful coding assistant.',\n  tools: [myTool],\n});\n\n// Create a new session\nconst session = agent.session();\nawait session.initialize();\n\n// Resume an existing session\nconst resumedSession = agent.session({ sessionId: 'existing-id' });\nawait resumedSession.initialize();\n\n// Stream messages\nfor await (const event of session.sendStream('Hello!')) {\n  console.log(event);\n}\n```\n\n资料来源：[packages/sdk/src/agent.ts:35-55]()\n\n## About Box Display\n\nSession metadata is surfaced in the CLI's About dialog:\n\n| Field | Source | Display |\n|-------|--------|---------|\n| CLI Version | Package version | Always shown |\n| Git Commit | Build-time constant | Conditional (non-N/A) |\n| Model | Active model configuration | Always shown |\n| Sandbox | Environment indicator | Always shown |\n| OS | System information | Always shown |\n\n资料来源：[packages/cli/src/ui/components/AboutBox.tsx:20-50]()\n\n## Configuration\n\n### Session-Related Settings\n\n| Setting | Description | Default |\n|---------|-------------|---------|\n| `sessionStorageDir` | Override default temp storage | `/tmp/gemini` |\n| `maxSessions` | Maximum sessions per project | 50 |\n| `autoSaveInterval` | Auto-save frequency (ms) | 30000 |\n| `sessionId` | Specific session to resume | (none) |\n\n### Bug Report Integration\n\nWhen submitting bug reports via `/bug`, the session automatically exports chat history:\n\n```typescript\nconst history = geminiClient.getChat().getHistory();\nconst bugReportPath = path.join(\n  storage.getProjectTempDir(),\n  `bug-report-history-${Date.now()}.json`\n);\nawait exportHistoryToFile({ history, filePath: bugReportPath });\n```\n\nThe exported history includes the full conversation record and is attached to the GitHub issue for diagnostic purposes.\n\n资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:45-65]()\n\n## Checkpointing\n\nSessions support checkpointing for disaster recovery and long-running task management:\n\n- **Automatic Checkpoints**: Created at significant conversation milestones\n- **Manual Checkpoints**: User-triggered via `/checkpoint` command\n- **Checkpoint Restoration**: Resume from any saved checkpoint state\n\nCheckpoints are stored alongside regular session data and include complete message history plus agent state snapshots.\n\n资料来源：[docs/cli/checkpointing.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/checkpointing.md)\n\n## Best Practices\n\n1. **Session Isolation**: Each project should maintain its own session context\n2. **Regular Exports**: Export important sessions before cleanup\n3. **Scratchpad Usage**: Use the memory scratchpad for cross-session notes\n4. **Metadata Maintenance**: Keep session summaries accurate for quick identification\n5. **Storage Cleanup**: Periodically remove old sessions to conserve disk space\n\n## Related Commands\n\n| Command | Purpose |\n|---------|---------|\n| `/new` | Start a fresh session |\n| `/sessions` | List and manage sessions |\n| `/resume <id>` | Resume a specific session |\n| `/export` | Export session to file |\n| `/checkpoint` | Create session checkpoint |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：google-gemini/gemini-cli\n\n摘要：发现 39 个潜在踩坑项，其中 11 个为 high/blocking；最高优先级：安装坑 - 来源证据：MCP servers not connected in -p (non-interactive) mode。\n\n## 1. 安装坑 · 来源证据：MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 2. 运行坑 · 来源证据：Stabilize and Enhance Internal Project Evaluations\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 安全/权限坑 · 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging\n- 建议检查：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\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging\n\n## 4. 安全/权限坑 · 失败模式：security_permissions: Robust component level evalutions\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Robust component level evalutions\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Robust component level evalutions\n- 建议检查：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.\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions\n\n## 5. 安全/权限坑 · 来源证据：Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Assess the impact of AST-aware file reads, search, and mapping\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 安全/权限坑 · 来源证据：Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 8. 安全/权限坑 · 来源证据：Shell command execution gets stuck with \"Waiting input\" after command completes\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with \"Waiting input\" after command completes\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. 安全/权限坑 · 来源证据：Tracking: 429 / Capacity Issues\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 10. 安全/权限坑 · 来源证据：[Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 11. 安全/权限坑 · 来源证据：fata error again!\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：fata error again!\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6345aa3da845458888c6e250cd950be0 | https://github.com/google-gemini/gemini-cli/issues/27084 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. 安装坑 · 失败模式：installation: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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\n- 对用户的影响：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\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 13. 安装坑 · 来源证据：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d81ba1a5c929402ba842a14ce13fa62d | https://github.com/google-gemini/gemini-cli/issues/23365 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 配置坑 · 失败模式：configuration: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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)\n\n## 15. 配置坑 · 失败模式：configuration: GeminiCLI.com Feedback: [ISSUE]\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GeminiCLI.com Feedback: [ISSUE]\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GeminiCLI.com Feedback: [ISSUE]\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_b159ada1eb969fa31659644535ca2fea | https://github.com/google-gemini/gemini-cli/issues/27206 | GeminiCLI.com Feedback: [ISSUE]\n\n## 16. 配置坑 · 失败模式：configuration: MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: MCP servers not connected in -p (non-interactive) mode\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 17. 配置坑 · 失败模式：configuration: Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Missing validation for critical configuration files could lead to broken bundles\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 18. 配置坑 · 失败模式：configuration: SLOW Response and Usage limits stop gemini CLI. = unusable\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 19. 配置坑 · 失败模式：configuration: Stop Auto Memory from retrying low-signal sessions indefinitely\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 20. 配置坑 · 失败模式：configuration: Surface or quarantine invalid Auto Memory inbox patches\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Surface or quarantine invalid Auto Memory inbox patches\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Surface or quarantine invalid Auto Memory inbox patches\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e7ea4760266f8df60623eea9a521182c | https://github.com/google-gemini/gemini-cli/issues/26523 | Surface or quarantine invalid Auto Memory inbox patches\n\n## 21. 配置坑 · 失败模式：configuration: The write_file tool corrupts or truncates long text sequences during file writes\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: The write_file tool corrupts or truncates long text sequences during file writes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: The write_file tool corrupts or truncates long text sequences during file writes\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 22. 配置坑 · 失败模式：configuration: Tracking: 429 / Capacity Issues\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Tracking: 429 / Capacity Issues\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Tracking: 429 / Capacity Issues\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tracking: 429 / Capacity Issues. Context: Observed during installation or first-run setup.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a6143043d54543ab2db0b094ce75112 | https://github.com/google-gemini/gemini-cli/issues/24937 | Tracking: 429 / Capacity Issues\n\n## 23. 配置坑 · 失败模式：configuration: Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 24. 配置坑 · 失败模式：configuration: YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: YOLO mode should override block of command-substitution in bash\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: YOLO mode should override block of command-substitution in bash\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 25. 配置坑 · 失败模式：configuration: [Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug] Proxy local bypass does not recognize environment variables\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 26. 配置坑 · 失败模式：configuration: fata error again!\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: fata error again!\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: fata error again!\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: fata error again!. Context: Observed when using linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7aa1a144aa2c7dbf177ed2e61f9c1bf4 | https://github.com/google-gemini/gemini-cli/issues/27084 | fata error again!\n\n## 27. 配置坑 · 来源证据：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47cc7af8a64b46f98a999ac7e6a42ab8 | https://github.com/google-gemini/gemini-cli/issues/25164 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 28. 能力坑 · 社区讨论暴露的待验证问题：Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：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\n\n## 29. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | README/documentation is current enough for a first validation pass.\n\n## 30. 维护坑 · 来源证据：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b6fd46e95c92462b8893c41314dc2cb9 | https://github.com/google-gemini/gemini-cli/issues/21421 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 31. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | last_activity_observed missing\n\n## 32. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 33. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 来源证据：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a69b38f144734c1c96d81d75610a66a1 | https://github.com/google-gemini/gemini-cli/issues/27192 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 35. 安全/权限坑 · 来源证据：The Gemini CLI interface keeps flickering\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The Gemini CLI interface keeps flickering\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364c1744ad1c4dc79881a9ab22c7305b | https://github.com/google-gemini/gemini-cli/issues/14708 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47b14e4e29a548d59ea09e120401bd88 | https://github.com/google-gemini/gemini-cli/issues/21686 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 37. 安全/权限坑 · 来源证据：YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：YOLO mode should override block of command-substitution in bash\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_adf70ddf872342c08ce46daccf869dba | https://github.com/google-gemini/gemini-cli/issues/6436 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 38. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | issue_or_pr_quality=unknown\n\n## 39. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | release_recency=unknown\n\n<!-- canonical_name: google-gemini/gemini-cli; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "gemini-cli",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:968197216",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/google-gemini/gemini-cli"
        },
        {
          "evidence_id": "art_bd6e7af3ffc4457586f0e469d5773faa",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/google-gemini/gemini-cli#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "gemini-cli 说明书",
      "toc": [
        "https://github.com/google-gemini/gemini-cli 项目说明书",
        "目录",
        "Architecture Overview",
        "Package Structure",
        "System Architecture",
        "Core Package Architecture",
        "Skill body with instructions",
        "CLI Package Architecture",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "747885950227fac8df996a199f61cf9de28abeb0",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "docs/index.md",
      "docs/local-development.md",
      "docs/redirects.json",
      "docs/npm.md",
      "docs/integration-tests.md",
      "docs/releases.md",
      "docs/issue-and-pr-automation.md",
      "docs/CONTRIBUTING.md",
      "docs/release-confidence.md",
      "docs/sidebar.json",
      "docs/cli/system-prompt.md",
      "docs/cli/skills-best-practices.md",
      "docs/cli/token-caching.md",
      "docs/cli/model-routing.md",
      "docs/cli/notifications.md",
      "docs/cli/acp-mode.md",
      "docs/cli/gemini-ignore.md",
      "docs/cli/git-worktrees.md",
      "docs/cli/cli-reference.md",
      "docs/cli/model-steering.md",
      "docs/cli/using-agent-skills.md",
      "docs/cli/skills.md",
      "docs/cli/headless.md",
      "docs/cli/sandbox.md",
      "docs/cli/auto-memory.md",
      "docs/cli/checkpointing.md",
      "docs/cli/custom-commands.md",
      "docs/cli/rewind.md",
      "docs/cli/enterprise.md",
      "docs/cli/gemini-md.md",
      "docs/cli/creating-skills.md",
      "docs/cli/model.md",
      "docs/cli/telemetry.md",
      "docs/cli/trusted-folders.md",
      "docs/cli/settings.md",
      "docs/cli/generation-settings.md",
      "docs/cli/plan-mode.md"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @google/gemini-cli - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @google/gemini-cli 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md`, `packages/sdk/README.md` Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `npx @google/gemini-cli` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npm install -g @google/gemini-cli` 证据：`README.md` Claim：`clm_0006` supported 0.86, `clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` supported 0.86\n- `npm install -g @google/gemini-cli@preview` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npm install -g @google/gemini-cli@latest` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `npm install -g @google/gemini-cli@nightly` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `git clone https://github.com/google-gemini/gemini-cli` 证据：`README.md` Claim：`clm_0010` supported 0.86\n- `npm install @google/gemini-cli-sdk` 证据：`packages/sdk/README.md` Claim：`clm_0011` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：仅建议沙盒试装\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：仅建议沙盒试装\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md`, `packages/sdk/README.md` Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`, `packages/sdk/README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`, `packages/sdk/README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0012` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md`, `packages/sdk/README.md` Claim：`clm_0013` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.gemini/skills/async-pr-review/SKILL.md`, `.gemini/skills/behavioral-evals/SKILL.md`, `.gemini/skills/ci/SKILL.md`, `.gemini/skills/code-reviewer/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md`, `packages/sdk/README.md` Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：2672\n- 重要文件覆盖：40/2672\n- 证据索引条目：80\n- 角色 / Skill 条目：14\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 @google/gemini-cli 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @google/gemini-cli 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @google/gemini-cli 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 14 个角色 / Skill / 项目文档条目。\n\n- **async-pr-review**（skill）：Trigger this skill when the user wants to start an asynchronous PR review, run background checks on a PR, or check the status of a previously started async PR review. 激活提示：当用户任务与“async-pr-review”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/async-pr-review/SKILL.md`\n- **behavioral-evals**（skill）：Guidance for creating, running, fixing, and promoting behavioral evaluations. Use when verifying agent decision logic, debugging failures, debugging prompt steering, or adding workspace regression tests. 激活提示：当用户任务与“behavioral-evals”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/behavioral-evals/SKILL.md`\n- **ci**（skill）：This skill enables the agent to efficiently monitor GitHub Actions, triage failures, and bridge remote CI errors to local development. It defaults to automatic replication of failures to streamline the fix cycle. 激活提示：当用户任务与“ci”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/ci/SKILL.md`\n- **code-reviewer**（skill）：This skill guides the agent in conducting professional and thorough code reviews for both local development and remote Pull Requests. 激活提示：当用户任务与“code-reviewer”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/code-reviewer/SKILL.md`\n- **docs-changelog**（skill）：- 激活提示：当用户任务与“docs-changelog”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/docs-changelog/SKILL.md`\n- **docs-writer**（skill）：As an expert technical writer and editor for the Gemini CLI project, you produce accurate, clear, and consistent documentation. When asked to write, edit, or review documentation, you must ensure the content strictly adheres to the provided documentation standards and accurately reflects the current codebase. Adhere to the contribution process in CONTRIBUTING.md and the following project standards. 激活提示：当用户任务与“docs-writer”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/docs-writer/SKILL.md`\n- **github-issue-creator**（skill）：This skill guides the creation of high-quality GitHub issues that adhere to the repository's standards and use the appropriate templates. 激活提示：当用户任务与“github-issue-creator”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/github-issue-creator/SKILL.md`\n- **pr-address-comments**（skill）：Use this skill if the user asks you to help them address GitHub PR comments for their current branch of the Gemini CLI. Requires gh CLI tool. 激活提示：当用户任务与“pr-address-comments”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/pr-address-comments/SKILL.md`\n- **pr-creator**（skill）：This skill guides the creation of high-quality Pull Requests that adhere to the repository's standards. 激活提示：当用户任务与“pr-creator”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/pr-creator/SKILL.md`\n- **review-duplication**（skill）：Use this skill during code reviews to proactively investigate the codebase for duplicated functionality, reinvented wheels, or failure to reuse existing project best practices and shared utilities. 激活提示：当用户任务与“review-duplication”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/review-duplication/SKILL.md`\n- **string-reviewer**（skill）： 激活提示：当用户任务与“string-reviewer”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.gemini/skills/string-reviewer/SKILL.md`\n- **greeter**（skill）：A friendly greeter skill 激活提示：当用户任务与“greeter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/cli/src/commands/extensions/examples/skills/skills/greeter/SKILL.md`\n- **skill-creator**（skill）：Guide for creating effective skills. This skill should be used when users want to create a new skill or update an existing skill that extends Gemini CLI's capabilities with specialized knowledge, workflows, or tool integrations. 激活提示：当用户任务与“skill-creator”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/core/src/skills/builtin/skill-creator/SKILL.md`\n- **pirate-skill**（skill）：Speak like a pirate. 激活提示：当用户任务与“pirate-skill”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/sdk/test-data/skills/pirate-skill/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Gemini CLI Project Context**（documentation）：Gemini CLI is an open-source AI agent that brings the power of Gemini directly into the terminal. It is designed to be a terminal-first, extensible, and powerful tool for developers. 证据：`GEMINI.md`\n- **Gemini CLI**（documentation）：! Gemini CLI CI https://github.com/google-gemini/gemini-cli/actions/workflows/ci.yml/badge.svg https://github.com/google-gemini/gemini-cli/actions/workflows/ci.yml ! Gemini CLI E2E Chained https://github.com/google-gemini/gemini-cli/actions/workflows/chained e2e.yml/badge.svg https://github.com/google-gemini/gemini-cli/actions/workflows/chained e2e.yml ! Version https://img.shields.io/npm/v/@google/gemini-cli https://www.npmjs.com/package/@google/gemini-cli ! License https://img.shields.io/github/license/google-gemini/gemini-cli https://github.com/google-gemini/gemini-cli/blob/main/LICENSE ! View Code Wiki https://assets.codewiki.google/readme-badge/static.svg https://codewiki.google/github… 证据：`README.md`\n- **Behavioral Evals**（documentation）：Behavioral evaluations evals are tests designed to validate the agent's behavior in response to specific prompts. They serve as a critical feedback loop for changes to system prompts, tool definitions, and other model-steering mechanisms, and as a tool for assessing feature reliability by model, and preventing regressions. 证据：`evals/README.md`\n- **CPU Performance Integration Test Harness**（documentation）：CPU Performance Integration Test Harness 证据：`perf-tests/README.md`\n- **Gemini CLI A2A Server @google/gemini-cli-a2a-server**（documentation）：Gemini CLI A2A Server @google/gemini-cli-a2a-server 证据：`packages/a2a-server/GEMINI.md`\n- **Gemini CLI A2A Server**（documentation）：All code in this package is experimental and under active development 证据：`packages/a2a-server/README.md`\n- **React & Ink CLI UI**（documentation）：- Side Effects : Use reducers for complex state transitions; avoid setState triggers in callbacks. - Always fix react-hooks/exhaustive-deps lint errors by adding the missing dependencies. - Shortcuts : only define keyboard shortcuts in packages/cli/src/ui/key/keyBindings.ts - Do not implement any logic performing custom string measurement or string truncation. Use Ink layout instead leveraging ResizeObserver as needed. When using ResizeObserver , prefer the useCallback ref pattern as seen in MaxSizedBox.tsx to ensure size measurements are captured as soon as the element is available, avoiding potential rendering timing issues. - Avoid prop drilling when at all possible. 证据：`packages/cli/GEMINI.md`\n- **Agent Client Protocol ACP Implementation**（documentation）：Agent Client Protocol ACP Implementation 证据：`packages/cli/src/acp/README.md`\n- **MCP Server Example**（documentation）：This is a basic example of an MCP Model Context Protocol server used as a Gemini CLI extension. It demonstrates how to expose tools and prompts to the Gemini CLI. 证据：`packages/cli/src/commands/extensions/examples/mcp-server/README.md`\n- **Policy engine example extension**（documentation）：This extension demonstrates how to contribute security rules and safety checkers to the Gemini CLI Policy Engine. 证据：`packages/cli/src/commands/extensions/examples/policies/README.md`\n- **Themes Example**（documentation）：This is an example of a Gemini CLI extension that adds a custom theme. 证据：`packages/cli/src/commands/extensions/examples/themes-example/README.md`\n- **Gemini CLI Core @google/gemini-cli-core**（documentation）：Gemini CLI Core @google/gemini-cli-core 证据：`packages/core/GEMINI.md`\n- **Gemini CLI DevTools**（documentation）：Integrated Developer Tools for Gemini CLI, providing a Chrome DevTools-like interface for Network and Console inspection. Launched automatically when the general.devtools setting is enabled. 证据：`packages/devtools/GEMINI.md`\n- **Gemini CLI SDK @google/gemini-cli-sdk**（documentation）：Gemini CLI SDK @google/gemini-cli-sdk 证据：`packages/sdk/GEMINI.md`\n- **@google/gemini-cli-sdk**（documentation）：The Gemini CLI SDK provides a programmatic interface to interact with Gemini models and tools. 证据：`packages/sdk/README.md`\n- **Gemini CLI VS Code Companion gemini-cli-vscode-ide-companion**（documentation）：Gemini CLI VS Code Companion gemini-cli-vscode-ide-companion 证据：`packages/vscode-ide-companion/GEMINI.md`\n- **Gemini CLI Companion**（documentation）：The Gemini CLI Companion extension pairs with Gemini CLI https://github.com/google-gemini/gemini-cli . This extension is compatible with both VS Code and VS Code forks. 证据：`packages/vscode-ide-companion/README.md`\n- **Gemini CLI Bot Cognitive Repository**（documentation）：Gemini CLI Bot Cognitive Repository 证据：`tools/gemini-cli-bot/README.md`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"engines\": { \"node\": \" =20.0.0\" }, \"type\": \"module\", \"workspaces\": \"packages/ \" , \"private\": \"true\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/google-gemini/gemini-cli.git\" }, \"config\": { \"sandboxImageUri\": \"us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef\" }, \"scripts\": { \"start\": \"cross-env NODE ENV=development node scripts/start.js\", \"start:prod\": \"cross-env NODE ENV=production node scripts/start.js\", \"start:a2a-server\": \"CODER AGENT PORT=41242 npm run start --workspace @google/gemini-cli-a2a-server\", \"debug\": \"cross-env DEBUG=1 node --inspect-brk sc… 证据：`package.json`\n- **How to contribute**（documentation）：We would love to accept your patches and contributions to this project. This document includes: 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli-a2a-server\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"description\": \"Gemini CLI A2A Server\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/google-gemini/gemini-cli.git\", \"directory\": \"packages/a2a-server\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"bin\": { \"gemini-cli-a2a-server\": \"dist/a2a-server.mjs\" }, \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"start\": \"node dist/src/http/server.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vitest run --coverage\", \"typecheck\": \"tsc --noEmit\" }, \"files\": \"dist\" , \"dependencies\": { \"@a2a-js/sdk\": \"0.3.11\", \"@google-cloud/… 证据：`packages/a2a-server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"description\": \"Gemini CLI\", \"license\": \"Apache-2.0\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/google-gemini/gemini-cli.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"bin\": { \"gemini\": \"dist/index.js\" }, \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"start\": \"node dist/index.js\", \"debug\": \"node --inspect-brk dist/index.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vitest run\", \"posttest\": \"npm run build\", \"typecheck\": \"tsc --noEmit\" }, \"files\": \"dist\" , \"config\": { \"sandboxImageUri\": \"us-docker.pkg.dev/gemini-co… 证据：`packages/cli/package.json`\n- **Package**（package_manifest）：{ \"name\": \"mcp-server-example\", \"version\": \"1.0.0\", \"description\": \"Example MCP Server for Gemini CLI Extension\", \"type\": \"module\", \"main\": \"example.js\", \"dependencies\": { \"@modelcontextprotocol/sdk\": \"^1.23.0\", \"zod\": \"^3.22.4\" } } 证据：`packages/cli/src/commands/extensions/examples/mcp-server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli-core\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"description\": \"Gemini CLI Core\", \"license\": \"Apache-2.0\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/google-gemini/gemini-cli.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"scripts\": { \"bundle:browser-mcp\": \"node scripts/bundle-browser-mcp.mjs\", \"build\": \"node ../../scripts/build package.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vitest run\", \"posttest\": \"npm run build\", \"typecheck\": \"tsc --noEmit\" }, \"files\": \"dist\" , \"dependencies\": { \"@a2a-js/sdk\": \"0.3.11\", \"@bufbuild/protobuf\": \"^2.11.0\", \"@google-cloud/logging\": \"… 证据：`packages/core/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli-devtools\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"license\": \"Apache-2.0\", \"type\": \"module\", \"main\": \"dist/src/index.js\", \"types\": \"dist/src/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/src/index.d.ts\", \"default\": \"./dist/src/index.js\" } }, \"scripts\": { \"build\": \"npm run build:client && tsc -p tsconfig.build.json\", \"build:client\": \"node esbuild.client.js\" }, \"files\": \"dist\", \"client/index.html\" , \"engines\": { \"node\": \" =20\" }, \"devDependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" }, \"dependencies\": { \"ws\": \"^8.16.0\" } } 证据：`packages/devtools/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli-sdk\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"description\": \"Gemini CLI SDK\", \"license\": \"Apache-2.0\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/google-gemini/gemini-cli.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vitest run\", \"typecheck\": \"tsc --noEmit\" }, \"files\": \"dist\" , \"dependencies\": { \"@google/gemini-cli-core\": \"file:../core\", \"zod\": \"^3.23.8\", \"zod-to-json-schema\": \"^3.23.1\" }, \"devDependencies\": { \"typescript\": \"^5.3.3\", \"vitest… 证据：`packages/sdk/package.json`\n- **Package**（package_manifest）：{ \"name\": \"gemini-cli-vscode-ide-companion\", \"displayName\": \"Gemini CLI Companion\", \"description\": \"Enable Gemini CLI with direct access to your IDE workspace.\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"publisher\": \"google\", \"icon\": \"assets/icon.png\", \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/google-gemini/gemini-cli.git\", \"directory\": \"packages/vscode-ide-companion\" }, \"engines\": { \"vscode\": \"^1.99.0\" }, \"license\": \"LICENSE\", \"preview\": true, \"categories\": \"AI\" , \"keywords\": \"gemini-cli\", \"gemini cli\", \"gemini\", \"gemini code\", \"cli\", \"ide integration\", \"ide companion\" , \"activationEvents\": \"onStartupFinished\" , \"contributes\": { \"configuration\": { \"title\": \"Gemini C… 证据：`packages/vscode-ide-companion/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@lvce-editor/ripgrep\", \"version\": \"0.0.0-dev\", \"description\": \"A module for using ripgrep in a Node project\", \"main\": \"src/index.js\", \"typings\": \"src/index.d.ts\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/lvce-editor/ripgrep\" }, \"scripts\": { \"postinstall\": \"node ./src/postinstall.js\", \"test\": \"node --experimental-vm-modules node modules/jest/bin/jest.js\", \"test:watch\": \"node --experimental-vm-modules node modules/jest/bin/jest.js --watch\", \"format\": \"prettier --write .\" }, \"keywords\": \"lvce-editor\", \"ripgrep\" , \"author\": \"Lvce Editor\", \"license\": \"MIT\", \"dependencies\": { \"@lvce-editor/verror\": \"^1.6.0\", \"execa\": \"^9.5.2\", \"extract-zip\": \"^2.0.1\",… 证据：`third_party/get-ripgrep/package.json`\n- **Async PR Review**（skill_instruction）：This skill provides a set of tools to asynchronously review a Pull Request. It will create a background job to run the project's preflight checks, execute Gemini-powered test plans, and perform a comprehensive code review using custom prompts. 证据：`.gemini/skills/async-pr-review/SKILL.md`\n- **Behavioral Evals**（skill_instruction）：Behavioral evaluations evals are tests that validate the agent's decision-making e.g., tool choice rather than pure functionality. They are critical for verifying prompt changes, debugging steerability, and preventing regressions. 证据：`.gemini/skills/behavioral-evals/SKILL.md`\n- **CI Replicate & Status**（skill_instruction）：This skill enables the agent to efficiently monitor GitHub Actions, triage failures, and bridge remote CI errors to local development. It defaults to automatic replication of failures to streamline the fix cycle. 证据：`.gemini/skills/ci/SKILL.md`\n- **Code Reviewer**（skill_instruction）：This skill guides the agent in conducting professional and thorough code reviews for both local development and remote Pull Requests. 证据：`.gemini/skills/code-reviewer/SKILL.md`\n- **Procedure: Updating Changelog for New Releases**（skill_instruction）：Procedure: Updating Changelog for New Releases 证据：`.gemini/skills/docs-changelog/SKILL.md`\n- **docs-writer skill instructions**（skill_instruction）：As an expert technical writer and editor for the Gemini CLI project, you produce accurate, clear, and consistent documentation. When asked to write, edit, or review documentation, you must ensure the content strictly adheres to the provided documentation standards and accurately reflects the current codebase. Adhere to the contribution process in CONTRIBUTING.md and the following project standards. 证据：`.gemini/skills/docs-writer/SKILL.md`\n- **GitHub Issue Creator**（skill_instruction）：This skill guides the creation of high-quality GitHub issues that adhere to the repository's standards and use the appropriate templates. 证据：`.gemini/skills/github-issue-creator/SKILL.md`\n- **Comment Review Procedure**（skill_instruction）：You are helping the user address comments on their Pull Request. These comments may have come from an automated review agent or a team member. 证据：`.gemini/skills/pr-address-comments/SKILL.md`\n- **Pull Request Creator**（skill_instruction）：This skill guides the creation of high-quality Pull Requests that adhere to the repository's standards. 证据：`.gemini/skills/pr-creator/SKILL.md`\n- **Review Duplication**（skill_instruction）：This skill provides a structured workflow for investigating a codebase during a code review to identify duplicated logic, reinvented utilities, and missed opportunities to reuse established patterns. By executing this workflow, you ensure that new code integrates seamlessly with the existing project architecture. 证据：`.gemini/skills/review-duplication/SKILL.md`\n- **String Reviewer**（skill_instruction）：Act as a Senior UX Writer. Look for user-facing strings that are too long, unclear, or inconsistent. This includes inline text, error messages, and other user-facing text. 证据：`.gemini/skills/string-reviewer/SKILL.md`\n- **Skill**（skill_instruction）：You are a friendly greeter. When the user says \"hello\" or asks for a greeting, you should reply with: \"Greetings from the skills-example extension! 👋\" 证据：`packages/cli/src/commands/extensions/examples/skills/skills/greeter/SKILL.md`\n- **Skill Creator**（skill_instruction）：This skill provides guidance for creating effective skills. 证据：`packages/core/src/skills/builtin/skill-creator/SKILL.md`\n- **Gemini CLI Test Utils @google/gemini-cli-test-utils**（documentation）：Gemini CLI Test Utils @google/gemini-cli-test-utils 证据：`packages/test-utils/GEMINI.md`\n- **Package**（package_manifest）：{ \"name\": \"@google/gemini-cli-test-utils\", \"version\": \"0.44.0-nightly.20260512.g022e8baef\", \"private\": true, \"main\": \"src/index.ts\", \"license\": \"Apache-2.0\", \"type\": \"module\", \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"typecheck\": \"tsc --noEmit\" }, \"dependencies\": { \"@google/gemini-cli-core\": \"file:../core\", \"@lydell/node-pty\": \"1.1.0\", \"asciichart\": \"^1.5.25\", \"strip-ansi\": \"^7.1.2\", \"vitest\": \"^3.2.4\" }, \"devDependencies\": { \"typescript\": \"^5.3.3\" }, \"engines\": { \"node\": \" =20\" } } 证据：`packages/test-utils/package.json`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- **Skill**（skill_instruction）：You are a pirate. Respond to everything in pirate speak. Always mention \"Arrr\". 证据：`packages/sdk/test-data/skills/pirate-skill/SKILL.md`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`packages/vscode-ide-companion/LICENSE`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`third_party/get-ripgrep/LICENSE`\n- **Gemini CLI documentation**（documentation）：Gemini CLI brings the power of Gemini models directly into your terminal. Use it to understand code, automate tasks, and build workflows with your local project context. 证据：`docs/index.md`\n- **Integration tests**（documentation）：This document provides information about the integration testing framework used in this project. 证据：`docs/integration-tests.md`\n- **Automation and triage processes**（documentation）：This document provides a detailed overview of the automated processes we use to manage and triage issues and pull requests. Our goal is to provide prompt feedback and ensure that contributions are reviewed and integrated efficiently. Understanding this automation will help you as a contributor know what to expect and how to best interact with our repository bots. 证据：`docs/issue-and-pr-automation.md`\n- **Local development guide**（documentation）：This guide provides instructions for setting up and using local development features for Gemini CLI. 证据：`docs/local-development.md`\n- **Package overview**（documentation）：This monorepo contains two main packages: @google/gemini-cli and @google/gemini-cli-core . 证据：`docs/npm.md`\n- **Release confidence strategy**（documentation）：This document outlines the strategy for gaining confidence in every release of Gemini CLI. It serves as a checklist and quality gate for release manager to ensure we are shipping a high-quality product. 证据：`docs/release-confidence.md`\n- **Gemini CLI releases**（documentation）：!IMPORTANT Coordinate with the Release Manager: The release manager is responsible for coordinating patches and releases. Please update them before performing any of the release actions described in this document. 证据：`docs/releases.md`\n- **Enterprise Admin Controls**（documentation）：Gemini CLI empowers enterprise administrators to manage and enforce security policies and configuration settings across their entire organization. Secure defaults are enabled automatically for all enterprise users, but can be customized via the Management Console https://goo.gle/manage-gemini-cli . 证据：`docs/admin/enterprise-controls.md`\n- **Gemini CLI release notes**（documentation）：Gemini CLI has three major release channels: nightly, preview, and stable. For most users, we recommend the stable release. 证据：`docs/changelogs/index.md`\n- **Latest stable release: v0.42.0**（documentation）：For most users, our latest stable release is the recommended release. Install the latest stable version with: 证据：`docs/changelogs/latest.md`\n- **Preview release: v0.43.0-preview.0**（documentation）：Our preview release includes the latest, new, and experimental features. This release may not be as stable as our latest weekly release latest.md . 证据：`docs/changelogs/preview.md`\n- **ACP Mode**（documentation）：ACP Agent Client Protocol mode is a special operational mode of Gemini CLI designed for programmatic control, primarily for IDE and other developer tool integrations. It uses a JSON-RPC protocol over stdio to communicate between Gemini CLI agent and a client. 证据：`docs/cli/acp-mode.md`\n- **Auto Memory**（documentation）：Auto Memory is an experimental feature that mines your past Gemini CLI sessions in the background and proposes durable memory updates and reusable Agent Skills ./skills.md . You review each candidate before it becomes available to future sessions: apply memory updates, promote skills, or discard anything you do not want. 证据：`docs/cli/auto-memory.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`GEMINI.md`, `README.md`, `evals/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`GEMINI.md`, `README.md`, `evals/README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Architecture Overview**：importance `high`\n  - source_paths: packages/core/index.ts, packages/cli/index.ts, packages/a2a-server/index.ts\n- **Agent System**：importance `high`\n  - source_paths: packages/core/src/agent/agent-session.ts, packages/core/src/agents/agent-scheduler.ts, packages/core/src/scheduler/scheduler.ts, packages/core/src/scheduler/tool-executor.ts, packages/a2a-server/src/agent/executor.ts\n- **Context and Memory Management**：importance `high`\n  - source_paths: packages/core/src/context/contextManager.ts, packages/core/src/context/pipeline/contextWorkingBuffer.ts, packages/core/src/context/memoryContextManager.ts, packages/core/src/context/chatCompressionService.ts, packages/core/src/context/processors/rollingSummaryProcessor.ts\n- **Tools Reference**：importance `high`\n  - source_paths: packages/core/src/tools/definitions/coreTools.ts, packages/core/src/tools/read-file.ts, packages/core/src/tools/write-file.ts, packages/core/src/tools/shell.ts, packages/core/src/tools/web-search.ts\n- **MCP Integration**：importance `medium`\n  - source_paths: packages/core/src/tools/mcp-client.ts, packages/core/src/tools/mcp-client-manager.ts, packages/core/src/agents/browser/mcpToolWrapper.ts, packages/cli/src/services/McpPromptLoader.ts, docs/tools/mcp-server.md\n- **Skills and Extensions**：importance `medium`\n  - source_paths: packages/core/src/skills/skillManager.ts, packages/core/src/skills/skillLoader.ts, packages/cli/src/config/extension-manager.ts, packages/core/src/hooks/hookSystem.ts, docs/cli/skills.md\n- **Sandboxing and Security**：importance `high`\n  - source_paths: packages/core/src/sandbox/linux/LinuxSandboxManager.ts, packages/core/src/sandbox/macos/MacOsSandboxManager.ts, packages/core/src/sandbox/windows/WindowsSandboxManager.ts, packages/core/src/services/sandboxManager.ts, packages/cli/src/config/trustedFolders.ts\n- **Policy Engine**：importance `high`\n  - source_paths: packages/core/src/policy/policy-engine.ts, packages/core/src/policy/toml-loader.ts, packages/core/src/policy/config.ts, packages/cli/src/config/policy.ts, docs/reference/policy-engine.md\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `747885950227fac8df996a199f61cf9de28abeb0`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `docs/index.md`, `docs/local-development.md`, `docs/redirects.json`, `docs/npm.md`, `docs/integration-tests.md`, `docs/releases.md`, `docs/issue-and-pr-automation.md`, `docs/CONTRIBUTING.md`, `docs/release-confidence.md`, `docs/sidebar.json`, `docs/cli/system-prompt.md`, `docs/cli/skills-best-practices.md`, `docs/cli/token-caching.md`, `docs/cli/model-routing.md`, `docs/cli/notifications.md`, `docs/cli/acp-mode.md`, `docs/cli/gemini-ignore.md`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：MCP servers not connected in -p (non-interactive) mode\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：Stabilize and Enhance Internal Project Evaluations\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging\n- Host AI rule: 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\n- Why it matters: Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging\n- Evidence: failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 失败模式：security_permissions: Robust component level evalutions\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: Robust component level evalutions\n- Host AI rule: 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.\n- Why it matters: Developers may expose sensitive permissions or credentials: Robust component level evalutions\n- Evidence: failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：Add deterministic redaction and reduce Auto Memory logging\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：Assess the impact of AST-aware file reads, search, and mapping\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：Missing validation for critical configuration files could lead to broken bundles\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 来源证据：Shell command execution gets stuck with \"Waiting input\" after command completes\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with \"Waiting input\" after command completes\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 来源证据：Tracking: 429 / Capacity Issues\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：[Bug] Proxy local bypass does not recognize environment variables\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：google-gemini/gemini-cli\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：MCP servers not connected in -p (non-interactive) mode（high）：可能影响升级、迁移或版本选择。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Stabilize and Enhance Internal Project Evaluations（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging（high）：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\n- 失败模式：security_permissions: Robust component level evalutions（high）：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.\n- 来源证据：Add deterministic redaction and reduce Auto Memory logging（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/google-gemini/gemini-cli 项目说明书\n\n生成时间：2026-05-16 02:07:33 UTC\n\n## 目录\n\n- [Architecture Overview](#architecture-overview)\n- [Agent System](#agent-system)\n- [Context and Memory Management](#context-pipeline)\n- [Tools Reference](#tools-reference)\n- [MCP Integration](#mcp-integration)\n- [Skills and Extensions](#skills-extensions)\n- [Sandboxing and Security](#sandboxing-security)\n- [Policy Engine](#policy-engine)\n- [Terminal UI Components](#terminal-ui)\n- [Session Management](#session-management)\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Context and Memory Management](#context-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx)\n- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [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)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [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)\n- [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)\n- [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)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)\n</details>\n\n# Architecture Overview\n\nGemini 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.\n\n## Package Structure\n\nThe repository is organized into three primary packages under the `packages/` directory:\n\n| Package | Purpose | Key Responsibilities |\n|---------|---------|---------------------|\n| `packages/core` | Core AI engine | Agents, skills, context management, chat recording |\n| `packages/cli` | Terminal interface | UI components, commands, authentication, user interactions |\n| `packages/a2a-server` | Protocol server | Agent-to-Agent communication protocol support |\n\n资料来源：[README.md:1-50](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n\n## System Architecture\n\n```mermaid\ngraph TD\n    subgraph \"CLI Layer (packages/cli)\"\n        UI[UI Components]\n        AUTH[Auth Dialog]\n        CMDS[Commands]\n        EXT[Extensions]\n    end\n    \n    subgraph \"Core Layer (packages/core)\"\n        AGENTS[Agent System]\n        SKILLS[Skills Engine]\n        CONTEXT[Context Graph]\n        RECORDING[Chat Recording]\n    end\n    \n    subgraph \"External\"\n        GEMINI_API[Gemini API]\n        MCP[MCP Servers]\n        FS[File System]\n    end\n    \n    UI --> AGENTS\n    AUTH --> AGENTS\n    CMDS --> AGENTS\n    EXT --> AGENTS\n    AGENTS --> SKILLS\n    AGENTS --> CONTEXT\n    AGENTS --> RECORDING\n    AGENTS --> GEMINI_API\n    SKILLS --> MCP\n    SKILLS --> FS\n    CONTEXT --> FS\n```\n\n## Core Package Architecture\n\n### Agents System\n\nThe agent system forms the brain of Gemini CLI. The core package implements multiple specialized agents:\n\n#### CLI Help Agent\n\nThe `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.\n\n```typescript\n// Agent configuration and runtime context\nconst 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.\n\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n\n### Instructions\n1. **Explore Documentation**: Use the \\`get_internal_docs\\` tool to find answers.\n2. **Be Precise**: Use the provided runtime context and documentation.\n3. **Cite Sources**: Include specific documentation files in your report.\n4. **Non-Interactive**: Answer as best you can with available information.\n```\n\n资料来源：[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)\n\n#### Skill Extraction Agent\n\nThe `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:\n\n```typescript\n// Patch format for skill creation\nconst PATCH_FORMAT = `\n1. Update an existing file:\n\n     --- /absolute/path/to/target.md\n     +++ /absolute/path/to/target.md\n     @@ -<start>,<count> +<newStart>,<newCount> @@\n     <unchanged context line>\n    -<removed line>\n    +<added line>\n\n2. Create a brand-new file (no existing target):\n\n     --- /dev/null\n     +++ /absolute/path/to/new-target.md\n     @@ -0,0 +1,<count> @@\n`;\n```\n\n资料来源：[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)\n\n### Context Graph System\n\nThe context graph manages conversation history and session state. It builds a structured representation of the conversation with stable identifiers for each message turn.\n\n```mermaid\ngraph TD\n    subgraph \"Context Building\"\n        HIST[History Array] --> TURN[For Each Turn]\n        TURN --> HASH[Generate MD5 Hash]\n        HASH --> SALT[Add Turn Salt]\n        SALT --> ID[Stable ID Generation]\n    end\n    \n    subgraph \"Message Processing\"\n        MSG[Message] --> ROLE{Message Role}\n        ROLE -->|user| USER[User Turn]\n        ROLE -->|model| MODEL[Model Turn]\n        USER --> PARTS[Process Parts]\n        MODEL --> PARTS\n    end\n```\n\nKey features of the context graph:\n\n- **Stable ID Generation**: Uses MD5 hashing combined with turn salt for deterministic message identification\n- **Legacy Header Handling**: Skips legacy environment headers automatically\n- **Role-based Processing**: Differentiates between user and model messages\n\n资料来源：[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)\n\n### Skills Engine\n\nThe skills system provides extensible capabilities through a standardized structure:\n\n```\nskill-name/\n├── SKILL.md           # Required: Frontmatter + Instructions\n├── REFERENCE.md       # Optional: Loaded on demand\n├── EXAMPLES.md        # Optional: Common patterns\n├── FORMS.md           # Optional: User input forms\n├── scripts/           # Executable code (Node.js/Python/Bash)\n└── references/        # Domain-specific documentation\n```\n\n#### SKILL.md Structure\n\nEvery skill requires a `SKILL.md` file with YAML frontmatter:\n\n```yaml\n---\nname: skill-name\ndescription: Clear description of when this skill should be used\n---\n# Skill body with instructions\n```\n\n#### Organization Patterns\n\n**Pattern 1: Flat Organization**\nSimple skills with related files in a single directory.\n\n**Pattern 2: Domain-specific Organization**\nFor multi-domain skills, organize by domain:\n```\ncloud-deploy/\n├── SKILL.md\n└── references/\n    ├── aws.md\n    ├── gcp.md\n    └── azure.md\n```\n\n**Pattern 3: Conditional Details**\nBasic content with links to advanced topics loaded only when needed.\n\n资料来源：[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)\n\n### Chat Recording Service\n\nThe `ChatRecordingService` persists conversation history and metadata:\n\n```typescript\ninterface ConversationRecord {\n  sessionId: string;\n  projectHash: string;\n  startTime: string;\n  lastUpdated: string;\n  summary?: string;\n  memoryScratchpad?: string;\n  directories: string[];\n  kind: string;\n  messages: Message[];\n  messageCount: number;\n  userMessageCount: number;\n  memoryScratchpadIsStale?: boolean;\n  firstUserMessage?: string;\n  hasUserOrAssistantMessage: boolean;\n}\n```\n\nThe service manages:\n- Session persistence to JSONL files\n- Message loading with metadata filtering\n- Memory scratchpad tracking with freshness indicators\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-100](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n\n## CLI Package Architecture\n\n### UI Component System\n\nThe CLI package implements a terminal-based UI using a custom component system:\n\n```mermaid\ngraph TD\n    APP[AppHeader] --> CONTENT[Main Content Area]\n    CONTENT --> ABOUT[AboutBox]\n    CONTENT --> MODEL[ModelDialog]\n    CONTENT --> AUTH[AuthDialog]\n    CONTENT --> TRUST[FolderTrustDialog]\n    CONTENT --> EXT[ExtensionDetails]\n    \n    subgraph \"Privacy System\"\n        PRIVACY[Privacy Notices]\n        PRIVACY --> GEMINI[GeminiPrivacyNotice]\n        PRIVACY --> CLOUD_FREE[CloudFreePrivacyNotice]\n    end\n```\n\n#### AppHeader Component\n\nDisplays application state including version, update status, and user identity:\n\n```typescript\nconst AppHeader = (config: Config, {\n  showDetails,\n  isNarrow,\n  terminalWidth\n}: HeaderProps) => (\n  <Box flexDirection=\"column\">\n    {/* Version info */}\n    <Text bold>Gemini CLI</Text>\n    <Text>v{version}</Text>\n    \n    {/* Update indicator */}\n    {updateInfo?.isUpdating && (\n      <Text><CliSpinner /> Updating</Text>\n    )}\n    \n    {/* User identity (if enabled) */}\n    <UserIdentity config={config} />\n  </Box>\n);\n```\n\n资料来源：[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)\n\n#### AboutBox Component\n\nDisplays system information:\n- CLI Version\n- Git Commit (if available)\n- Model Version\n- Sandbox Environment\n- Operating System\n\n资料来源：[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)\n\n#### Authentication Dialog\n\nHandles user authentication with multiple options:\n\n```typescript\nconst authOptions = [\n  { label: 'Sign in with Google', value: 'google' },\n  { label: 'Continue without signing in', value: 'anonymous' },\n  { label: 'Use API Key', value: 'api_key' }\n];\n```\n\nThe dialog supports:\n- OAuth flow with automatic CLI restart\n- Anonymous mode\n- Direct API key authentication\n\n资料来源：[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)\n\n### Extension System\n\nExtensions provide a plugin mechanism for extending Gemini CLI functionality:\n\n```mermaid\ngraph TD\n    EXT[Extension] --> MANIFEST[gemini-extension.json]\n    EXT --> POLICIES[policies/]\n    EXT --> COMMANDS[commands/]\n    EXT --> HOOKS[hooks/]\n    EXT --> SKILLS[skills/]\n    EXT --> MCP[mcpServers/]\n```\n\n#### Extension Manifest Structure\n\n```json\n{\n  \"name\": \"extension-name\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Extension description\",\n  \"hasMCP\": true,\n  \"hasContext\": true,\n  \"hasHooks\": true,\n  \"hasSkills\": true,\n  \"hasCustomCommands\": true\n}\n```\n\n#### Policy Engine\n\nExtensions can contribute security rules through TOML policy files:\n\n```toml\n# Example policy\n[[rules]]\ntype = \"confirm\"\ncommand = \"rm -rf\"\nmessage = \"This will permanently delete files\"\n```\n\nSecurity features:\n- Extensions can only add restrictions (not bypass them)\n- `allow` decisions and `yolo` mode from extensions are ignored\n- Custom safety checkers for file path validation\n\n资料来源：[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)\n\n### Privacy System\n\n#### Privacy Notices\n\nTwo privacy notice types exist based on user tier:\n\n| Notice Type | Target Users | Data Usage |\n|------------|--------------|------------|\n| `GeminiPrivacyNotice` | API Terms users | Google AI Studio terms |\n| `CloudFreePrivacyNotice` | Free tier users | Limited collection with opt-in |\n\n#### Data Collection Options\n\n```typescript\ninterface PrivacyState {\n  dataCollectionOptIn: boolean;\n}\n\n// Options presented to users:\n// [0] Allow Google to use data\n// [1] Don't allow\n```\n\nFor free tier users:\n- Human reviewers may read and annotate data\n- Data is disconnected from Google Account\n- Retained for up to 18 months\n\n资料来源：[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)\n\n### Folder Trust System\n\nThe folder trust dialog provides security boundaries for project configurations:\n\n```typescript\ninterface TrustConfig {\n  customCommands: boolean;\n  hooks: boolean;\n  mcpServers: boolean;\n  agentSkills: boolean;\n  settings: boolean;\n}\n```\n\nComponents discovered and displayed:\n- Custom commands (`commands/`)\n- Hooks (`hooks/`)\n- MCP servers (`mcpServers/`)\n- Agent skills (`skills/`)\n- Settings (`settings/`)\n\n资料来源：[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)\n\n### Model Selection\n\nThe `ModelDialog` component allows users to:\n- View available models\n- See quota information\n- Select a specific model for the session\n\nQuota buckets are displayed with available width calculation for responsive layout.\n\n资料来源：[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)\n\n## Extension Details View\n\nDisplays information about available extensions:\n\n```typescript\ninterface ExtensionInfo {\n  extensionVersion?: string;\n  stars: number;\n  isGoogleOwned: boolean;\n  fullName: string;\n  extensionDescription?: string;\n  repoDescription?: string;\n  hasMCP: boolean;\n  hasContext: boolean;\n  hasHooks: boolean;\n  hasSkills: boolean;\n  hasCustomCommands: boolean;\n}\n```\n\nFeature badges with color coding:\n- **MCP** (Primary)\n- **Context file** (Error)\n- **Hooks** (Warning)\n- **Skills** (Success)\n- **Commands** (Primary)\n\n资料来源：[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)\n\n## Installation and Release Channels\n\nGemini CLI supports multiple installation methods:\n\n| Method | Command |\n|--------|---------|\n| npm global | `npm install -g @google/gemini-cli` |\n| Homebrew | `brew install gemini-cli` |\n| MacPorts | `sudo port install gemini-cli` |\n| Anaconda | Create nodejs environment, then npm install |\n\n### Release Channels\n\n| Channel | Schedule | Description |\n|---------|----------|-------------|\n| Preview | Weekly (Tue 23:59 UTC) | Untested preview builds |\n| Stable | Weekly (Tue 20:00 UTC) | Promoted preview + fixes |\n| Nightly | Daily (00:00 UTC) | Main branch snapshot |\n\n资料来源：[README.md:100-150](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n\n## Key Features Integration\n\n### GitHub Integration\n\nGemini CLI integrates with GitHub through the [Gemini CLI GitHub Action](https://github.com/google-github-actions/run-gemini-cli), enabling CI/CD workflow automation.\n\n### Multimodal Capabilities\n\nThe CLI supports processing of:\n- PDFs\n- Images\n- Sketches\n\nThese inputs can be used for code generation and understanding tasks.\n\n### Checkpointing\n\nConversations can be saved and resumed, enabling:\n- Session persistence across CLI restarts\n- Memory scratchpad with staleness tracking\n- Project-specific context preservation\n\n### MCP Server Support\n\nModel Context Protocol servers extend capabilities with:\n- Media generation (Imagen, Veo, Lyria)\n- Custom tool integrations\n- External service connections\n\n## Summary\n\nThe Gemini CLI architecture demonstrates a well-separated design:\n\n1. **Core Package**: Handles AI processing, skills management, and conversation state\n2. **CLI Package**: Manages terminal UI, authentication, and user interactions  \n3. **A2A Server**: Enables agent-to-agent communication protocols\n\nThe 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.\n\n---\n\n<a id='agent-system'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Tools Reference](#tools-reference)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/agent/agent-session.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agent/agent-session.ts)\n- [packages/core/src/agents/agent-scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/agent-scheduler.ts)\n- [packages/core/src/scheduler/scheduler.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/scheduler.ts)\n- [packages/core/src/scheduler/tool-executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/scheduler/tool-executor.ts)\n- [packages/a2a-server/src/agent/executor.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/a2a-server/src/agent/executor.ts)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n</details>\n\n# Agent System\n\n## 概述\n\nThe 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.\n\nThe 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.\n\nAt 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.\n\n## 核心架构\n\nThe 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.\n\n```mermaid\ngraph TD\n    A[User Input] --> B[AgentSession]\n    B --> C[AgentScheduler]\n    C --> D[Scheduler]\n    D --> E[ToolExecutor]\n    E --> F[External Tools & MCP Servers]\n    D --> G[LLM API]\n    G --> B\n    H[ContextGraph] --> B\n    I[ChatRecordingService] --> B\n```\n\n### 组件职责矩阵\n\n| 组件 | 包路径 | 主要职责 |\n|------|--------|----------|\n| **AgentSession** | `packages/core/src/agent/` | 会话生命周期管理，消息历史维护 |\n| **AgentScheduler** | `packages/core/src/agents/` | 多代理协调，任务分发 |\n| **Scheduler** | `packages/core/src/scheduler/` | 执行调度，队列管理 |\n| **ToolExecutor** | `packages/core/src/scheduler/` | 工具执行，沙箱环境 |\n| **A2AExecutor** | `packages/a2a-server/src/agent/` | Agent-to-Agent通信协议 |\n\n## AgentSession (会话管理)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 核心数据结构\n\n```typescript\ninterface ConversationRecord {\n  sessionId: string;\n  projectHash: string;\n  startTime: string;\n  lastUpdated: string;\n  summary?: string;\n  memoryScratchpad?: string;\n  directories?: string[];\n  kind: 'cli' | 'api';\n  messages: Message[];\n  messageCount: number;\n  userMessageCount: number;\n  memoryScratchpadIsStale?: boolean;\n  firstUserMessage?: string;\n  hasUserOrAssistantMessage: boolean;\n}\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-50](packages/core/src/services/chatRecordingService.ts)\n\n### 会话ID生成机制\n\nThe 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:\n\n```typescript\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5')\n  .update(`${msg.role}:${turnContent}`)\n  .digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nseenHashes.set(h, occurrence);\nconst turnSalt = `${h}_${occurrence}`;\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)\n\n### 配置管理\n\nThe session integrates with the configuration system to access runtime settings:\n\n```typescript\ngetExperimentalDynamicModelConfiguration(): boolean {\n  return this.dynamicModelConfiguration;\n}\n\ngetPendingIncludeDirectories(): string[] {\n  return this.pendingIncludeDirectories;\n}\n\nclearPendingIncludeDirectories(): void {\n  this.pendingIncludeDirectories = [];\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:1-100](packages/core/src/config/config.ts)\n\n## AgentScheduler (代理调度)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 内置代理类型\n\nThe system includes several built-in agents for common tasks:\n\n| 代理名称 | 源文件 | 功能描述 |\n|----------|--------|----------|\n| **CLI Help Agent** | `cli-help-agent.ts` | 提供CLI文档和帮助信息 |\n| **Policy Agent** | - | 安全策略执行 |\n| **Skill Agent** | - | 自定义技能执行 |\n\n### CLI Help Agent 实现\n\nThe CLI Help Agent is a specialized agent that provides accurate information about Gemini CLI features, configuration, and current state:\n\n```typescript\nconst 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.\n\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n\n### Instructions\n1. **Explore Documentation**: Use the \\`get_internal_docs\\` tool to find answers.\n2. **Be Precise**: Use the provided runtime context and documentation.\n3. **Cite Sources**: Include specific documentation files used.\n4. **Non-Interactive**: Operate in a loop without user interaction.`;\n```\n\n资料来源：[packages/core/src/agents/cli-help-agent.ts:1-30](packages/core/src/agents/cli-help-agent.ts)\n\n### 代理注册流程\n\nAgents 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.\n\n## Scheduler (任务调度)\n\n### 概述\n\nThe `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.\n\nThe 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.\n\n### 执行流程\n\n```mermaid\nsequenceDiagram\n    participant User as User Input\n    participant Scheduler\n    participant LLM as LLM API\n    participant ToolExec as Tool Executor\n    participant Session as AgentSession\n    \n    User->>Scheduler: Send Message\n    Scheduler->>Session: Record Message\n    Session-->>Scheduler: Acknowledge\n    Scheduler->>LLM: Generate Response\n    LLM-->>Scheduler: Tool Call Request\n    Scheduler->>ToolExec: Execute Tool\n    ToolExec-->>Scheduler: Tool Result\n    Scheduler->>LLM: Continue Generation\n    LLM-->>Scheduler: Final Response\n    Scheduler-->>User: Stream Response\n```\n\n### 工具调用处理\n\nWhen 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.\n\n## ToolExecutor (工具执行)\n\n### 概述\n\nThe `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.\n\n### 工具类型支持\n\n| 工具类型 | 执行方式 | 安全级别 |\n|----------|----------|----------|\n| **Built-in Tools** | 直接执行 | 高 |\n| **Custom Skills** | 沙箱执行 | 中 |\n| **MCP Tools** | 远程执行 | 可配置 |\n| **Shell Commands** | 隔离环境 | 高 |\n\n### 技能执行框架\n\nSkills are executed through a structured framework defined in the SKILL.md specification:\n\n```markdown\n### Bundled Resources (optional)\n\n#### Scripts (`scripts/`)\nExecutable code for deterministic tasks:\n- Token efficient execution\n- Deterministic behavior\n- LLM-friendly stdout output\n\n#### References (`references/`)\nDocumentation loaded as needed into context\n```\n\n资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md:1-50](packages/core/src/skills/builtin/skill-creator/SKILL.md)\n\n### 策略引擎集成\n\nThe tool executor integrates with the policy engine to enforce security rules. Extensions can contribute policies through TOML configuration files:\n\n```toml\n# Example policy\n[[rules]]\ntype = \"confirmation_required\"\ncommand_pattern = \"rm -rf.*\"\n\n[[rules]]\ntype = \"deny\"\ncommand_pattern = \"grep.*\\\\.env\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30](packages/cli/src/commands/extensions/examples/policies/README.md)\n\n## A2AExecutor (Agent-to-Agent通信)\n\n### 概述\n\nThe `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.\n\n### 协议消息格式\n\n```typescript\ninterface AgentMessage {\n  id: string;\n  type: 'request' | 'response' | 'event';\n  sender: string;\n  receiver: string;\n  payload: unknown;\n  timestamp: number;\n}\n```\n\n### RPC调度\n\nThe executor handles RPC method dispatching and session state management. New RPC methods are registered through the `GeminiAgent` interface:\n\n```typescript\n// Adding a new RPC method\n// 1. Add method to GeminiAgent in acpRpcDispatcher.ts\n// 2. Register in AgentSideConnection setup if necessary\n// 3. Add serialization logic to acpUtils.ts\n```\n\n资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)\n\n## 上下文管理\n\n### ContextGraph\n\nThe `ContextGraph` maintains conversation context and generates stable identifiers for message turns. It handles legacy environment header detection and removal:\n\n```typescript\n// Defensive: Skip legacy environment header\nif (msg.role === 'user' && msg.parts.length === 1) {\n  const text = msg.parts[0].text;\n  if (text?.startsWith('<session_context>') && \n      text?.includes('This is the Gemini CLI')) {\n    debugLogger.log(\n      '[ContextGraphBuilder] Skipping legacy environment header turn.',\n    );\n    continue;\n  }\n}\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30](packages/core/src/context/graph/toGraph.ts)\n\n### 会话记录服务\n\nThe `ChatRecordingService` handles persistence of conversation history to JSONL format:\n\n```typescript\nexport class ChatRecordingService {\n  private conversationFile: string | null = null;\n  private cachedConversation: ConversationRecord | null = null;\n  private sessionId: string;\n  // ...\n}\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:50-100](packages/core/src/services/chatRecordingService.ts)\n\n## 执行模式与策略\n\n### 审批模式\n\nThe system supports multiple approval modes for controlling agent behavior:\n\n| 模式 | 描述 | 使用场景 |\n|------|------|----------|\n| **PLAN** | 仅生成计划，不执行 | 代码审查 |\n| **YOLO** | 直接执行所有操作 | 自动化脚本 |\n| **INTERACTIVE** | 逐个确认操作 | 谨慎操作 |\n\n```typescript\nisYoloModeDisabled(): boolean {\n  return this.disableYoloMode || !this.isTrustedFolder();\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:80-85](packages/core/src/config/config.ts)\n\n### 策略链解析\n\nThe system resolves policy chains based on model configuration:\n\n```typescript\ndescribe('resolvePolicyChain', () => {\n  it('returns a single-model chain for a custom model', () => {\n    const chain = resolvePolicyChain(config);\n    expect(chain).toHaveLength(1);\n    expect(chain[0]?.model).toBe('custom-model');\n  });\n  \n  it('returns the default chain when active model is \"auto\"', () => {\n    const chain = resolvePolicyChain(config);\n    expect(chain).toHaveLength(2);\n    // Expect default chain [Pro, Flash]\n  });\n});\n```\n\n资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50](packages/core/src/availability/policyHelpers.test.ts)\n\n## 扩展机制\n\n### MCP服务器集成\n\nThe system supports MCP (Model Context Protocol) servers for extending functionality. Configuration is stored in `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    }\n  }\n}\n```\n\n### 自定义技能\n\nSkills are defined through SKILL.md files with YAML frontmatter:\n\n```yaml\n---\nname: pdf-rotate\ndescription: Rotates PDF files by specified degrees. Use when user wants to rotate a PDF document.\n---\n```\n\n## 运行时上下文\n\n### 版本信息显示\n\nThe system displays runtime context through the About component:\n\n```typescript\n<Box flexDirection=\"row\">\n  <Box width=\"35%\">\n    <Text bold color={theme.text.link}>CLI Version</Text>\n  </Box>\n  <Box>\n    <Text color={theme.text.primary}>{cliVersion}</Text>\n  </Box>\n</Box>\n<Box flexDirection=\"row\">\n  <Box width=\"35%\">\n    <Text bold color={theme.text.link}>Model</Text>\n  </Box>\n  <Box>\n    <Text color={theme.text.primary}>{getDisplayString(modelVersion)}</Text>\n  </Box>\n</Box>\n```\n\n资料来源：[packages/cli/src/ui/components/AboutBox.tsx:1-50](packages/cli/src/ui/components/AboutBox.tsx)\n\n## 隐私与安全\n\n### 隐私通知\n\nThe system displays privacy notices and handles data collection preferences:\n\n```typescript\nWhen you use Gemini Code Assist for individuals with Gemini CLI, Google\ncollects your prompts, related code, generated output, code edits,\nrelated feature usage information, and your feedback to provide,\nimprove, and develop Google products and services and machine learning\ntechnologies.\n```\n\n资料来源：[packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx:1-50](packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx)\n\n### 安全检查\n\nThe policy engine enforces security rules for file operations and dangerous commands. Extensions can contribute security rules but cannot bypass user confirmation requirements.\n\n## 常见工作流\n\n### 单代理工作流\n\n```mermaid\ngraph LR\n    A[User Input] --> B[AgentSession]\n    B --> C[Scheduler]\n    C --> D[ToolExecutor]\n    D --> E[Result]\n    C --> F[LLM]\n    F --> G[Response]\n```\n\n### 多代理工作流\n\n```mermaid\ngraph TD\n    A[User Input] --> B[AgentScheduler]\n    B --> C[CLI Help Agent]\n    B --> D[Skill Agent]\n    B --> E[Policy Agent]\n    C --> F[Result Aggregation]\n    D --> F\n    E --> F\n    F --> G[Final Response]\n```\n\n## 调试与日志\n\n### 日志输出\n\nThe system uses structured logging for debugging:\n\n```typescript\ndebugLogger.log(\n  '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',\n);\ndebugLogger.error('Error loading conversation record from JSONL:', error);\n```\n\n### 测试框架\n\nTests are written using Vitest and can be run with workspace filtering:\n\n```bash\nnpm test -w @google/gemini-cli -- src/acp/<test-file-name>.ts\n```\n\n资料来源：[packages/cli/src/acp/README.md:1-50](packages/cli/src/acp/README.md)\n\n## 总结\n\nThe 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.\n\n---\n\n<a id='context-pipeline'></a>\n\n## Context and Memory Management\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Session Management](#session-management)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [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)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [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)\n- [packages/sdk/README.md](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/README.md)\n</details>\n\n# Context and Memory Management\n\n## Overview\n\nContext 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.\n\n## Architecture Overview\n\nThe context management system consists of several interconnected components:\n\n```mermaid\ngraph TD\n    A[User Input] --> B[ContextGraphBuilder]\n    B --> C[Turn ID Generation]\n    C --> D[Context Manager]\n    D --> E[Memory Context Manager]\n    E --> F[Chat Recording Service]\n    F --> G[Session Persistence]\n    D --> H[Chat Compression Service]\n    H --> I[Rolling Summary Processor]\n    I --> J[Token Optimization]\n```\n\n## Core Components\n\n### ContextGraphBuilder\n\nThe `ContextGraphBuilder` is responsible for constructing the conversational context from message history. It processes each turn and generates stable identifiers for tracking conversation flow.\n\n**Key Responsibilities:**\n\n- Iterating through conversation history\n- Generating stable turn hashes using MD5\n- Creating unique turn IDs with salt-based occurrence tracking\n- Skipping legacy environment headers\n\n```typescript\n// Generate a stable salt for this turn based on its role and content\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5')\n  .update(`${msg.role}:${turnContent}`)\n  .digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nseenHashes.set(h, occurrence);\nconst turnSalt = `${h}_${occurrence}`;\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:31-38]()\n\n### Turn ID Generation\n\nTurn IDs are generated using a combination of message content hashing and a stable ID generation function. This ensures consistent identification across sessions.\n\n| Parameter | Type | Purpose |\n|-----------|------|---------|\n| `msg` | Message | The message object to generate ID for |\n| `nodeIdentityMap` | Map | Maps content to stable node identifiers |\n| `turnSalt` | string | Salt for hashing (includes occurrence count) |\n| `position` | number | Position hint for ID generation |\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:39]()\n\n### Legacy Header Handling\n\nThe system includes defensive logic to skip legacy environment headers that contain `<session_context>` markers. This prevents duplicate or stale context from being reintroduced.\n\n```typescript\nif (msg.role === 'user' && msg.parts.length === 1) {\n  const text = msg.parts[0].text;\n  if (\n    text?.startsWith('<session_context>') &&\n    text?.includes('This is the Gemini CLI')\n  ) {\n    debugLogger.log(\n      '[ContextGraphBuilder] Skipping legacy environment header turn from graph.',\n    );\n    continue;\n  }\n}\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:19-29]()\n\n## Chat Recording Service\n\nThe `ChatRecordingService` manages persistent storage of conversation history and session metadata.\n\n### ConversationRecord Model\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `sessionId` | string | Unique session identifier |\n| `projectHash` | string | Hash of the project context |\n| `startTime` | ISO string | Session start timestamp |\n| `lastUpdated` | ISO string | Last update timestamp |\n| `summary` | string | Optional conversation summary |\n| `memoryScratchpad` | string | Persistent memory content |\n| `directories` | string[] | Associated working directories |\n| `messages` | Message[] | Full message history |\n| `messageCount` | number | Total message count |\n| `userMessageCount` | number | User message count |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:1-30]()\n\n### Session State Tracking\n\nThe service tracks whether sessions contain user or assistant messages:\n\n```typescript\nhasUserOrAssistantMessage:\n  options?.metadataOnly && metadataMessages.length > 0\n    ? metadataMessages.some(\n        (m) => m.type === 'user' || m.type === 'gemini',\n      )\n    : hasUserOrAssistant,\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:57-62]()\n\n## Progressive Disclosure Design\n\nGemini CLI implements a three-level loading system to manage context efficiently:\n\n```mermaid\ngraph LR\n    A[Metadata<br/>name + description] --> B[SKILL.md Body<br/>Instructions]\n    B --> C[Bundled Resources<br/>Scripts/References]\n```\n\n### Loading Levels\n\n| Level | Content | Token Cost | Load Trigger |\n|-------|---------|------------|--------------|\n| 1 | Metadata (name + description) | ~100 words | Always |\n| 2 | SKILL.md body | <5k words | Skill trigger |\n| 3 | Bundled resources | Unlimited | As needed |\n\n资料来源：[packages/core/src/skills/builtin/skill-creator/SKILL.md]()\n\n### Bundled Resources Organization\n\n```\nscripts/       - Executable code (Node.js/Python/Bash)\nreferences/    - Documentation loaded into context\nassets/        - Files used in output (templates, icons)\n```\n\n## Memory Scratchpad\n\nThe system supports a memory scratchpad feature that persists across sessions:\n\n- **Staleness Tracking**: The system can flag when the scratchpad content becomes stale\n- **Fallback Detection**: Falls back to first user message if no user message found\n\n```typescript\nmemoryScratchpadIsStale: isTrackingMemoryScratchpadFreshness\n  ? memoryScratchpadIsStale\n  : undefined,\nfirstUserMessage: fallbackFirstUserMessage,\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:52-55]()\n\n## Folder Trust and Configuration Discovery\n\nWhen a folder is trusted, Gemini CLI loads its local configurations including:\n\n- Custom commands\n- Hooks\n- MCP servers\n- Agent skills\n- Settings\n\n```typescript\n<Box>\n  Trusting a folder allows Gemini CLI to load its local configurations,\n  including custom commands, hooks, MCP servers, agent skills, and\n  settings. These configurations could execute code on your behalf or\n  change the behavior of the CLI.\n</Box>\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()\n\n### Discovery Results\n\nThe system performs security validation on discovered configurations:\n\n| Result Type | Icon | Purpose |\n|-------------|------|---------|\n| Discovery Errors | ❌ | Configuration parsing failures |\n| Security Warnings | ⚠️ | Potential security concerns |\n\n## CLI Help Agent Memory\n\nThe CLI Help Agent provides contextual assistance with runtime awareness:\n\n```typescript\n### Runtime Context\n- **CLI Version:** ${cliVersion}\n- **Active Model:** ${activeModel}\n- **Today's Date:** ${today}\n```\n\n资料来源：[packages/core/src/agents/cli-help-agent.ts]()\n\n### Agent Instructions\n\n1. **Explore Documentation**: Use the `get_internal_docs` tool to find answers\n2. **Be Precise**: Use provided runtime context and documentation\n3. **Cite Sources**: Include specific documentation files used\n4. **Non-Interactive**: Operate autonomously without user queries\n\n## SDK Integration\n\nThe Gemini CLI SDK provides programmatic access to the context system:\n\n```typescript\nimport { GeminiCliAgent } from '@google/gemini-cli-sdk';\n\nconst agent = new GeminiCliAgent({\n  instructions: 'You are a helpful assistant.',\n});\n\nconst stream = agent.sendStream('query', signal);\n```\n\n资料来源：[packages/sdk/README.md]()\n\n## Data Flow Summary\n\n```mermaid\ngraph TD\n    subgraph \"Input Processing\"\n        A[User Input] --> B[ContextGraphBuilder]\n        B --> C[Turn Hash Generation]\n        C --> D[Stable ID Creation]\n    end\n    \n    subgraph \"Memory Management\"\n        D --> E[Memory Context Manager]\n        E --> F[Session Metadata]\n        F --> G[Persistent Storage]\n    end\n    \n    subgraph \"Optimization\"\n        D --> H[Compression Service]\n        H --> I[Rolling Summary]\n        I --> J[Token Budget]\n    end\n    \n    subgraph \"Retrieval\"\n        G --> K[Chat Recording Service]\n        K --> L[Conversation Record]\n        L --> M[Context Window]\n    end\n```\n\n## Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `memoryScratchpad` | string | Persistent memory content |\n| `directories` | string[] | Working directories to track |\n| `projectHash` | string | Project context identifier |\n| `sessionId` | string | Unique session identifier |\n\n## Security Considerations\n\nThe context management system includes several security measures:\n\n1. **Folder Trust**: User confirmation required before loading folder configurations\n2. **Policy Engine**: Security rules can be contributed via extensions\n3. **Path Validation**: Safety checkers validate file paths for write operations\n4. **Discovery Errors**: Configuration parsing failures are surfaced to users\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Summary\n\nThe Context and Memory Management system in Gemini CLI provides:\n\n- **Stable Turn Identification**: MD5-based hashing with occurrence tracking\n- **Session Persistence**: Full conversation history with metadata\n- **Progressive Disclosure**: Three-level loading for token optimization\n- **Security**: Folder trust validation and policy enforcement\n- **SDK Access**: Programmatic interface for external agents\n\n---\n\n<a id='tools-reference'></a>\n\n## Tools Reference\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Sandboxing and Security](#sandboxing-security)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/definitions/coreTools.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/definitions/coreTools.ts)\n- [packages/core/src/tools/read-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/read-file.ts)\n- [packages/core/src/tools/write-file.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/write-file.ts)\n- [packages/core/src/tools/shell.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/shell.ts)\n- [packages/core/src/tools/web-search.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/web-search.ts)\n- [packages/core/src/tools/mcp-tool.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-tool.ts)\n- [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)\n- [packages/core/src/tools/grep.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/grep.ts)\n- [packages/core/src/tools/glob.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/glob.ts)\n- [packages/core/src/tools/list-directory.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/list-directory.ts)\n</details>\n\n# Tools Reference\n\n## Overview\n\nThe 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.\n\nTools 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.\n\n资料来源：[packages/core/src/tools/definitions/coreTools.ts:1-50]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Request] --> B[GeminiAgent]\n    B --> C[Tool Registry]\n    C --> D[Core Tools]\n    C --> E[MCP Tools]\n    D --> F[read_file]\n    D --> G[write_file]\n    D --> H[shell/grep/glob]\n    D --> I[web_search]\n    E --> J[MCP Server 1]\n    E --> K[MCP Server 2]\n    F --> L[Filesystem]\n    G --> L\n    H --> M[System Commands]\n    I --> N[Google Search API]\n    J --> O[External Services]\n```\n\n## Tool Registration System\n\nTools 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.\n\n资料来源：[packages/core/src/config/config.ts:150-180]()\n\n### Dynamic Tool Registration\n\n```mermaid\ngraph TD\n    A[Configuration Load] --> B{coreTools defined?}\n    B -->|Yes| C{Check tool in list}\n    B -->|No| D[Enable all by default]\n    C -->|Match found| E[Register Tool]\n    C -->|No match| F[Skip Tool]\n    D --> E\n    E --> G[Tool available to Agent]\n```\n\nThe `maybeRegister` function controls tool availability:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `toolName` | `string` | The tool identifier to check |\n| `normalizedClassName` | `string` | Normalized class name for matching |\n| `coreTools` | `string[] \\| undefined` | Configuration whitelist |\n| `registerFn` | `() => void` | Function to execute if enabled |\n\n资料来源：[packages/core/src/config/config.ts:130-150]()\n\n## Core Tools\n\nCore tools are built-in capabilities that provide filesystem access, search functionality, and command execution. These tools are optimized per model family.\n\n### Tool Categories\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| **File Operations** | `read_file`, `write_file`, `replace` | File content manipulation |\n| **Search** | `grep_search`, `grep_search_ripgrep`, `glob` | Code and file discovery |\n| **Navigation** | `list_directory` | Directory browsing |\n| **System** | `run_shell_command` | Terminal command execution |\n| **Web** | `web_search`, `web_fetch` | Internet access |\n| **Memory** | `save_memory` | Persistent context storage |\n| **Planning** | `enter_plan_mode`, `exit_plan_mode` | Planning mode control |\n| **MCP** | `read_mcp_resource`, `list_mcp_resources` | MCP server integration |\n\n资料来源：[packages/core/src/tools/definitions/coreTools.ts:40-80]()\n\n## File Operations\n\n### Read File Tool\n\nThe `read_file` tool provides controlled access to file contents with optional line range selection.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Absolute path to the file |\n| `start_line` | `number` | No | Starting line number (1-indexed) |\n| `end_line` | `number` | No | Ending line number (inclusive) |\n\n**Behavior:**\n- Returns file contents as a string\n- Supports partial file reads via line range\n- Validates file path exists before reading\n- Respects `.gemini-ignore` patterns when configured\n\n资料来源：[packages/core/src/tools/read-file.ts:1-60]()\n\n### Write File Tool\n\nThe `write_file` tool creates or overwrites files with specified content.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Absolute path for the new file |\n| `content` | `string` | Yes | File content to write |\n\n**Behavior:**\n- Creates parent directories if they don't exist\n- Overwrites existing files silently\n- Returns confirmation message on success\n- Subject to security policy checks\n\n资料来源：[packages/core/src/tools/write-file.ts:1-50]()\n\n### Edit/Replace Tool\n\nThe `replace` tool performs targeted modifications to existing files using diff/patch format.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `file_path` | `string` | Yes | Target file path |\n| `old_string` | `string` | Yes | Text to find and replace |\n| `new_string` | `string` | Yes | Replacement text |\n\n**Patch Format:**\n```\n--- /absolute/path/to/file\n+++ /absolute/path/to/file\n@@ -start,count +start,count @@\n context line\n -removed line\n +added line\n```\n\n资料来源：[packages/core/src/agents/skill-extraction-agent.ts:50-80]()\n\n## Search Tools\n\n### Grep Tool\n\nThe `grep_search` tool performs text pattern matching across files with extensive filtering options.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `pattern` | `string` | Yes | Regex or literal pattern to search |\n| `file_path` | `string` | No | Root directory to search |\n| `case_sensitive` | `boolean` | No | Enable case sensitivity (default: false) |\n| `include_pattern` | `string` | No | File glob to include |\n| `exclude_pattern` | `string` | No | File glob to exclude |\n| `names_only` | `boolean` | No | Return only matching filenames |\n| `max_matches_per_file` | `number` | No | Limit matches per file |\n| `total_max_matches` | `number` | No | Global match limit |\n| `fixed_strings` | `boolean` | No | Treat pattern as literal |\n| `context` | `number` | No | Lines of context around matches |\n| `after` | `number` | No | Lines after match |\n| `before` | `number` | No | Lines before match |\n| `respect_git_ignore` | `boolean` | No | Skip gitignored files (default: true) |\n| `respect_gemini_ignore` | `boolean` | No | Skip .gemini-ignore files (default: true) |\n| `no_ignore` | `boolean` | No | Disable all ignore patterns |\n\n资料来源：[packages/core/src/tools/grep.ts:1-80]()\n\n### Ripgrep Tool\n\nWhen 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.\n\n资料来源：[packages/core/src/config/config.ts:160-175]()\n\n### Glob Tool\n\nThe `glob` tool finds files matching shell-style wildcard patterns.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `pattern` | `string` | Yes | Glob pattern (e.g., `**/*.ts`) |\n| `directory` | `string` | No | Root directory for search |\n| `ignore` | `string[]` | No | Patterns to exclude |\n\n资料来源：[packages/core/src/tools/glob.ts:1-50]()\n\n## Directory Navigation\n\n### List Directory Tool\n\nThe `list_directory` tool provides directory contents with optional filtering.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `dir_path` | `string` | Yes | Directory to list |\n| `ignore` | `string[]` | No | Patterns to exclude from results |\n\n**Features:**\n- Returns file and directory names\n- Supports ignore patterns for filtering\n- Respects gitignore when configured\n\n资料来源：[packages/core/src/tools/list-directory.ts:1-50]()\n\n## Shell Command Execution\n\n### Run Shell Command Tool\n\nThe `run_shell_command` tool executes system commands in a sandboxed environment.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `command` | `string` | Yes | Command to execute |\n| ` cwd` | `string` | No | Working directory |\n| `timeout_ms` | `number` | No | Execution timeout (default: 60000) |\n| `environment` | `object` | No | Additional environment variables |\n\n**Security Features:**\n- Subject to policy engine rules\n- May require user confirmation for destructive commands\n- Path safety validation for file operations\n- Timeout protection against hanging processes\n\n资料来源：[packages/core/src/tools/shell.ts:1-100]()\n\n```mermaid\ngraph TD\n    A[Command Request] --> B{Policy Check}\n    B -->|Allowed| C[Environment Setup]\n    B -->|Denied| D[User Confirmation]\n    B -->|Blocked| E[Error Response]\n    D -->|Approved| C\n    D -->|Denied| E\n    C --> F[Spawn Process]\n    F --> G{Timeout?}\n    G -->|Yes| H[Terminate]\n    G -->|No| I[Capture Output]\n    I --> J[Return Result]\n    H --> K[Timeout Error]\n```\n\n## Web Tools\n\n### Google Web Search\n\nThe `google_web_search` tool provides real-time internet search capabilities grounded in Google Search.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | `string` | Yes | Search query string |\n\n**Behavior:**\n- Returns search results with snippets\n- May be disabled via configuration\n- Subject to rate limiting\n\n资料来源：[packages/core/src/tools/web-search.ts:1-50]()\n\n### Web Fetch\n\nThe `web_fetch` tool retrieves content from URLs.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | `string` | Yes | Target URL |\n| `prompt` | `string` | No | Guidance for content extraction |\n\n## MCP Tool Integration\n\nMCP (Model Context Protocol) tools allow integration with external MCP servers, extending Gemini CLI's capabilities.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Gemini CLI] --> B[MCP Tool Bridge]\n    B --> C[MCP Server 1]\n    B --> D[MCP Server 2]\n    B --> E[MCP Server N]\n    C --> F[External Service]\n    D --> G[Database]\n    E --> H[Custom Tools]\n    B --> I[Resource Reader]\n    B --> J[Resource Lister]\n```\n\n### MCP Tool Types\n\n| Tool | Purpose | Parameters |\n|------|---------|------------|\n| `read_mcp_resource` | Read specific MCP resource | `server_name`, `uri` |\n| `list_mcp_resources` | List available MCP resources | `server_name` |\n| `mcp__tool_name` | Execute MCP tool call | Dynamic based on server |\n\n资料来源：[packages/core/src/tools/mcp-tool.ts:1-100]()\n\n### Configuration\n\nMCP servers are configured in `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    }\n  }\n}\n```\n\n## Model-Specific Tool Manifests\n\nDifferent model families may have optimized tool definitions with adjusted descriptions and parameter schemas.\n\n### Gemini 3 Tool Manifest\n\nThe Gemini 3 family uses optimized tool definitions that may include:\n\n- Streamlined descriptions for reduced token usage\n- Adjusted parameter names for consistency\n- Model-specific capability hints\n\n资料来源：[packages/core/src/tools/definitions/gemini-3.ts:1-50]()\n\n### Tool Definition Snapshot Testing\n\nTool definitions are validated against snapshots to ensure consistency:\n\n```typescript\nconst modelIds = ['gemini-2.5-pro', 'gemini-3-pro-preview'];\nconst tools = [\n  { name: 'read_file', definition: READ_FILE_DEFINITION },\n  { name: 'write_file', definition: WRITE_FILE_DEFINITION },\n  { name: 'grep_search', definition: GREP_DEFINITION },\n  // ... more tools\n];\n```\n\n资料来源：[packages/core/src/tools/definitions/coreToolsModelSnapshots.test.ts:30-60]()\n\n## Tool Response Format\n\nAll tools return responses in a standardized format:\n\n```typescript\ninterface ToolResult {\n  tool_call_id: string;\n  result: {\n    success: boolean;\n    data?: string | object;\n    error?: string;\n  };\n}\n```\n\n## Security and Policy Engine\n\nTools are subject to security policies defined by the Policy Engine extension system.\n\n### Policy Types\n\n| Policy | Description |\n|--------|-------------|\n| **Confirmation Rules** | Require user approval for specific operations |\n| **Denial Rules** | Block certain operations entirely |\n| **Path Restrictions** | Validate paths against allowed directories |\n| **Safety Checkers** | Validate operations before execution |\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### Folder Trust and Tool Access\n\nWhen a folder is trusted, its local configurations can modify tool behavior:\n\n- Custom commands\n- MCP server configurations\n- Agent skills\n- Extension policies\n\nUntrusted folders restrict tool access to prevent potentially harmful operations.\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:20-40]()\n\n## Tool Availability Matrix\n\n| Tool | File Ops | Search | System | Web | MCP | Memory |\n|------|----------|--------|--------|-----|-----|--------|\n| read_file | ✓ | | | | | |\n| write_file | ✓ | | | | | |\n| replace | ✓ | | | | | |\n| grep_search | | ✓ | | | | |\n| glob | | ✓ | | | | |\n| list_directory | | | ✓ | | | |\n| run_shell_command | | | ✓ | | | |\n| web_search | | | | ✓ | | |\n| web_fetch | | | | ✓ | | |\n| save_memory | | | | | | ✓ |\n| enter_plan_mode | | | | | | |\n| mcp__* | | | | | ✓ | |\n\n## Extension Points\n\n### Custom Tools via MCP\n\nExternal tools can be integrated through MCP servers:\n\n```typescript\n> @github List my open pull requests\n> @slack Send a summary to #dev channel\n> @database Find inactive users\n```\n\n### Custom Commands\n\nCustom slash commands can be defined in project directories and provide task-specific tool combinations.\n\n## Best Practices\n\n1. **Use Line Ranges**: When reading large files, specify line ranges to reduce token usage\n2. **Respect Ignores**: Let tools respect `.gitignore` and `.gemini-ignore` patterns\n3. **Timeout Configuration**: Set appropriate timeouts for shell commands\n4. **MCP Security**: Only enable trusted MCP servers\n5. **Path Validation**: Use absolute paths to avoid ambiguity\n\n## Related Documentation\n\n- [Configuration Guide](https://www.geminicli.com/docs/reference/configuration)\n- [MCP Server Integration](https://www.geminicli.com/docs/tools/mcp-server)\n- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)\n- [Keyboard Shortcuts](https://www.geminicli.com/docs/reference/keyboard-shortcuts)\n\n---\n\n<a id='mcp-integration'></a>\n\n## MCP Integration\n\n### 相关页面\n\n相关主题：[Tools Reference](#tools-reference), [Skills and Extensions](#skills-extensions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/mcp-client.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/mcp-client.ts)\n- [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)\n- [packages/core/src/agents/browser/mcpToolWrapper.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/agents/browser/mcpToolWrapper.ts)\n- [packages/cli/src/services/McpPromptLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/services/McpPromptLoader.ts)\n- [docs/tools/mcp-server.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md)\n</details>\n\n# MCP Integration\n\nModel 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.\n\n## Overview\n\nMCP Integration serves as a bridge between Gemini CLI and external tools. When configured, MCP servers can expose:\n\n- **Tools**: Executable functions that the AI can call (e.g., `fetch_posts`, database queries, GitHub operations)\n- **Prompts**: Pre-defined prompt templates for specific use cases\n- **Resources**: Static data that can be loaded into context as needed\n\nThe integration supports both sandboxed and non-sandboxed execution modes, with appropriate security measures including consent prompts and path restrictions.\n\n## Architecture\n\nThe MCP Integration system comprises several core components that work together to manage server lifecycle, tool exposure, and prompt loading.\n\n```mermaid\ngraph TD\n    A[Gemini CLI] --> B[McpClientManager]\n    B --> C[McpClient instances]\n    C --> D[MCP Servers]\n    E[McpPromptLoader] --> F[Prompts Registry]\n    G[McpToolWrapper] --> H[Tool Definitions]\n    D --> I[JSON-RPC Transport]\n    I --> C\n    H --> A\n```\n\n### Core Components\n\n| Component | Location | Responsibility |\n|-----------|----------|----------------|\n| `McpClientManager` | `packages/core/src/tools/mcp-client-manager.ts` | Manages lifecycle of all MCP client connections |\n| `McpClient` | `packages/core/src/tools/mcp-client.ts` | Handles individual server communication |\n| `McpToolWrapper` | `packages/core/src/agents/browser/mcpToolWrapper.ts` | Converts MCP tools to Gemini function declarations |\n| `McpPromptLoader` | `packages/cli/src/services/McpPromptLoader.ts` | Loads and registers MCP prompts |\n\n## MCP Client Manager\n\nThe `McpClientManager` is the central orchestrator for all MCP server connections. It handles:\n\n- Server initialization and configuration loading\n- Connection lifecycle management\n- Tool registration and updates\n- Cleanup and graceful shutdown\n\n### Server Discovery\n\nMCP servers can be configured in two ways:\n\n1. **Global Configuration**: Defined in `~/.gemini/settings.json`\n2. **Per-Project Configuration**: Defined in `~/.gemini/settings.json` for the active workspace\n\n```mermaid\ngraph TD\n    A[Load Settings] --> B[Get mcpServers config]\n    B --> C{Server enabled?}\n    C -->|Yes| D[Check enablement]\n    C -->|No| E[Skip]\n    D --> F[canLoadServer check]\n    F --> G{Allowed?}\n    G -->|Yes| H[Create MCP Client]\n    G -->|No| I[Block with message]\n    H --> J[Connect via Transport]\n    J --> K[Register tools]\n```\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:1-50]()\n\n### Configuration Schema\n\nMCP server configuration follows this structure:\n\n```typescript\ninterface MCPServerConfig {\n  command: string;           // Executable to run (e.g., 'npx', 'node')\n  args?: string[];           // Command arguments\n  env?: Record<string, string>;  // Environment variables\n  disabled?: boolean;       // Enable/disable server\n}\n```\n\nConfiguration is merged from multiple sources with appropriate precedence rules applied by the settings system.\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:30-40]()\n\n## MCP Client\n\nThe `McpClient` handles the actual communication with an MCP server using the JSON-RPC protocol over stdio transport. Each client instance maintains:\n\n- A transport connection to the server\n- Registered tool definitions\n- Server capabilities and metadata\n\n### Tool Registration Flow\n\n```mermaid\nsequenceDiagram\n    participant CLI as Gemini CLI\n    participant Manager as McpClientManager\n    participant Client as McpClient\n    participant Server as MCP Server\n    participant Browser as Browser Manager\n\n    CLI->>Manager: Initialize servers\n    Manager->>Client: Create client instance\n    Client->>Server: Initialize connection\n    Server-->>Client: Server capabilities\n    Client->>Server: List tools request\n    Server-->>Client: Tool definitions\n    Client->>Manager: Register tools\n    Manager->>Browser: Convert to FunctionDeclaration\n    Browser->>CLI: Expose tools to model\n```\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:1-50]()\n\n## Tool Wrapper\n\nThe `McpToolWrapper` transforms MCP tool definitions into Gemini-compatible function declarations. This conversion ensures that:\n\n1. Tool schemas are compatible with Gemini's function calling format\n2. Descriptions are augmented with usage hints\n3. Input schemas are properly formatted as JSON Schema\n\n### Schema Conversion\n\n```typescript\nfunction convertMcpToolToFunctionDeclaration(mcpTool: McpTool): FunctionDeclaration {\n  return {\n    name: mcpTool.name,\n    description: mcpTool.description ?? '',\n    parametersJsonSchema: mcpTool.inputSchema ?? {\n      type: 'object',\n      properties: {},\n    },\n  };\n}\n```\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:60-75]()\n\n### Description Augmentation\n\nThe wrapper augments MCP tool descriptions with semantic hints that help the model make correct tool choices:\n\n```typescript\nconst augmentedDescription = augmentToolDescription(\n  mcpTool.name,\n  mcpTool.description ?? '',\n);\n```\n\nThis approach reduces system prompt overhead by embedding usage rules directly in tool descriptions.\n\n资料来源：[packages/core/src/agents/browser/mcpToolWrapper.ts:45-50]()\n\n## Prompt Loading\n\nThe `McpPromptLoader` handles loading and registering MCP prompt templates. Prompts are discovered from connected MCP servers and made available for use in conversations.\n\n### Prompt Structure\n\nMCP prompts can include:\n\n- **Name**: Unique identifier for the prompt\n- **Description**: Human-readable explanation of when to use the prompt\n- **Arguments**: Template variables that can be customized at runtime\n- **Template**: The actual prompt content with variable placeholders\n\n资料来源：[packages/cli/src/services/McpPromptLoader.ts]()\n\n## MCP Server Implementation\n\nGemini CLI provides example MCP server implementations demonstrating how to create compliant servers.\n\n### Basic Example\n\nThe basic MCP server example (`packages/cli/src/commands/extensions/examples/mcp-server`) exposes:\n\n- **Tool**: `fetch_posts` - Mock-fetches posts\n- **Prompt**: `poem-writer` - Generates poems\n\n### Extension Structure\n\n```\nmcp-server/\n├── example.js          # Server entry point\n├── gemini-extension.json  # Configuration manifest\n└── package.json        # Dependencies\n```\n\n### Server Entry Point\n\nServers implement the MCP specification using `@modelcontextprotocol/sdk`:\n\n```javascript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\nconst server = new Server(\n  { name: 'example-mcp-server', version: '1.0.0' },\n  { capabilities: { tools: {}, prompts: {} } }\n);\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/mcp-server/README.md]()\n\n## Security Model\n\nMCP Integration includes multiple security layers:\n\n### Consent and Allowlists\n\n| Security Feature | Description |\n|-----------------|-------------|\n| `canLoadServer` | Checks if server is allowed to load |\n| `applyAdminAllowlist` | Validates against admin-defined allowlist |\n| `getAdminBlockedMcpServersMessage` | Reports blocked servers to user |\n\n资料来源：[packages/cli/src/commands/mcp/list.ts:20-25]()\n\n### Policy Engine Integration\n\nThe policy engine example extension demonstrates how to add security rules:\n\n- **Confirmation Rules**: Require user confirmation for dangerous operations (e.g., `rm -rf`)\n- **Denial Rules**: Block access to sensitive resources (e.g., searching for `.env` files)\n- **Safety Checkers**: Validate operations before execution (e.g., path validation)\n\nSecurity note: Extensions can strengthen security but cannot bypass user confirmation or enable `yolo` mode.\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Usage Examples\n\n### Configure MCP Server\n\nAdd server configuration to `~/.gemini/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/workspace\"]\n    }\n  }\n}\n```\n\n### Using MCP Tools\n\nAfter configuration, tools are automatically available:\n\n```\n> @github List my open pull requests\n> @database Run a query to find inactive users\n```\n\n### Creating Custom Server\n\n1. Create server directory structure\n2. Implement MCP server using `@modelcontextprotocol/sdk`\n3. Add `gemini-extension.json` manifest\n4. Link extension: `gemini extensions link <path>`\n\n## Command Reference\n\n### List MCP Servers\n\n```bash\ngemini mcp list\n```\n\nDisplays all configured MCP servers with their status.\n\n资料来源：[packages/cli/src/commands/mcp/list.ts]()\n\n### MCP Server Integration Guide\n\nFor detailed setup instructions, see the [MCP Server Integration guide](https://www.geminicli.com/docs/tools/mcp-server).\n\n## See Also\n\n- [Custom Commands](https://www.geminicli.com/docs/cli/custom-commands)\n- [Policy Engine](https://www.geminicli.com/docs/tools/policy-engine)\n- [Extension Development](../extensions/index.md)\n- [Official MCP Documentation](https://modelcontextprotocol.io)\n\n---\n\n<a id='skills-extensions'></a>\n\n## Skills and Extensions\n\n### 相关页面\n\n相关主题：[MCP Integration](#mcp-integration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/skills/skillManager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillManager.ts)\n- [packages/core/src/skills/skillLoader.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/skills/skillLoader.ts)\n- [packages/cli/src/config/extension-manager.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/extension-manager.ts)\n- [packages/core/src/hooks/hookSystem.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/hooks/hookSystem.ts)\n- [docs/cli/skills.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/skills.md)\n- [docs/extensions/writing-extensions.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/extensions/writing-extensions.md)\n</details>\n\n# Skills and Extensions\n\n## Overview\n\nSkills 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.\n\n**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.\n\n**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.\n\n---\n\n## Skills System\n\n### What Are Skills?\n\nSkills are modular knowledge packages that help Gemini CLI handle specialized tasks. Each skill contains:\n\n- **Frontmatter**: YAML metadata defining the skill's name and trigger conditions\n- **Body**: Markdown instructions loaded after the skill triggers\n- **Scripts**: Executable code (Node.js/Python/Bash) for deterministic operations\n- **References**: Documentation loaded into context as needed\n- **Assets**: Templates, icons, fonts, and other output files\n\n### Skill Structure\n\n```\nskill-name/\n├── SKILL.md           # Required: Frontmatter + Instructions\n├── scripts/           # Optional: Executable code\n│   └── *.cjs, *.py, etc.\n├── references/        # Optional: Documentation\n│   └── *.md\n└── assets/            # Optional: Output files\n    └── templates/, icons/, etc.\n```\n\n### SKILL.md Format\n\nEvery skill requires a `SKILL.md` file with two components:\n\n**Frontmatter (YAML):**\n```yaml\n---\nname: skill-name\ndescription: Clear description of what this skill does and when it should be triggered\n---\n```\n\n**Body (Markdown):**\nInstructions and guidance for executing the skill. This content is loaded only after the skill triggers, not during initial context evaluation.\n\n### Skill Loading Mechanism\n\nSkills are discovered and loaded through the `SkillLoader` system. The system:\n\n1. Scans configured skill directories\n2. Parses SKILL.md frontmatter for name and description\n3. Makes skills available for trigger matching\n4. Loads skill content on-demand when triggered\n\n### Skill Triggering\n\nWhen 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.\n\n---\n\n## Skill Design Patterns\n\n### Pattern 1: Flat Organization\n\nFor simple skills with linear workflows:\n\n```\ncsv-processor/\n├── SKILL.md\n├── FORMS.md           # Input/output templates\n├── REFERENCE.md       # Full documentation\n└── EXAMPLES.md        # Usage examples\n```\n\nGemini CLI loads `FORMS.md`, `REFERENCE.md`, or `EXAMPLES.md` only when needed.\n\n### Pattern 2: Domain-Specific Organization\n\nFor skills supporting multiple domains or variants:\n\n```\nbigquery-skill/\n├── SKILL.md (overview + navigation)\n└── references/\n    ├── finance.md     # Revenue, billing metrics\n    ├── sales.md       # Opportunities, pipeline\n    ├── product.md     # API usage, features\n    └── marketing.md  # Campaigns, attribution\n```\n\n### Pattern 3: Conditional Details\n\nShow basic content with links to advanced topics:\n\n```markdown\n## Basic Analysis\n\nUse pandas for loading and basic queries. See [PANDAS.md](PANDAS.md).\n\n## Advanced Operations\n\nFor massive files, see [STREAMING.md](STREAMING.md). For timestamp normalization, see [TIMESTAMPS.md](TIMESTAMPS.md).\n```\n\n---\n\n## Scripts in Skills\n\nScripts provide deterministic, token-efficient execution for tasks that are repeatedly rewritten or require reliability guarantees.\n\n### When to Include Scripts\n\n| Scenario | Example |\n|----------|---------|\n| Repeatedly rewritten code | PDF rotation, image processing |\n| Deterministic reliability needed | File format conversions |\n| Token efficiency important | Complex parsing operations |\n\n### Script Requirements\n\n- **Output format**: LLM-friendly stdout\n- **Error handling**: Suppress standard tracebacks\n- **Messages**: Clear success/failure messages\n- **Pagination**: Truncate long outputs to prevent context overflow\n\n```javascript\n// Example: scripts/rotate_pdf.cjs\nconsole.log(\"Success: Rotated PDF 90 degrees clockwise\");\nconsole.log(\"Output: rotated_document.pdf\");\n```\n\n---\n\n## Extensions System\n\n### What Are Extensions?\n\nExtensions are npm packages that extend Gemini CLI through a structured manifest system. They provide programmatic capabilities beyond what markdown-based skills offer.\n\n### Extension Structure\n\n```\nextension-name/\n├── gemini-extension.json    # Required manifest\n├── src/                     # Source code\n├── commands/                # Custom slash commands\n├── policies/                # Security rules (TOML)\n└── package.json\n```\n\n### Extension Manifest\n\nThe `gemini-extension.json` manifest defines the extension's contributions:\n\n```json\n{\n  \"name\": \"my-extension\",\n  \"version\": \"1.0.0\",\n  \"commands\": [\"./commands/*.ts\"],\n  \"mcpServers\": {},\n  \"policies\": [\"./policies/*.toml\"]\n}\n```\n\n### Extension Capabilities\n\n| Capability | Description |\n|------------|-------------|\n| Custom Commands | Slash commands (`/command`) that extend CLI functionality |\n| MCP Servers | Model Context Protocol server configurations |\n| Policy Rules | Security rules and safety checkers |\n| Hooks | Pre/post execution hooks for customization |\n\n---\n\n## Policy Engine\n\nExtensions can contribute security rules through the Policy Engine.\n\n### Rule Definition (TOML)\n\n```toml\n[[rules]]\nid = \"deny-rm-rf\"\ndescription = \"Prevents dangerous recursive deletion\"\ncondition = \"command contains 'rm -rf'\"\naction = \"confirm\"\nmessage = \"This command will recursively delete files. Confirm?\"\n```\n\n### Safety Checkers\n\nExtensions can provide safety checkers that validate operations:\n\n```toml\n[[safety_checkers]]\nname = \"allowed-path\"\ndescription = \"Validates file paths for write operations\"\ncheck = \"path.startsWith(allowedDirectory)\"\n```\n\n### Security Notes\n\n- Extensions **cannot** bypass user confirmation requirements\n- `allow` decisions from extensions are ignored for security\n- `yolo` mode configurations from extensions are ignored\n- Extensions can only strengthen security, not weaken it\n\n---\n\n## MCP Server Integration\n\nExtensions can configure MCP (Model Context Protocol) servers for specialized capabilities:\n\n```json\n{\n  \"mcpServers\": {\n    \"@github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n### Configuration Flow\n\n```mermaid\ngraph TD\n    A[User Request] --> B{MCP Server Configured?}\n    B -->|Yes| C[Load MCP Server]\n    B -->|No| D[Continue without MCP]\n    C --> E[Execute MCP Tools]\n    D --> F[Standard Tool Execution]\n```\n\n---\n\n## Hook System\n\nThe Hook System provides pre/post execution points for customization.\n\n### Available Hooks\n\n| Hook | Timing | Purpose |\n|------|--------|---------|\n| `preToolExecution` | Before tool call | Modify inputs, log, or validate |\n| `postToolExecution` | After tool call | Process outputs, track metrics |\n| `prePromptGeneration` | Before prompt build | Customize context |\n| `postResponseGeneration` | After response | Format or filter output |\n\n### Hook Registration\n\nExtensions register hooks through the hook system API:\n\n```typescript\nhookSystem.register('preToolExecution', async (context) => {\n  // Validate or modify before execution\n  return { modified: false, context };\n});\n```\n\n---\n\n## Creating Skills\n\n### Command\n\n```bash\ngemini skill create my-skill\n```\n\n### Generated Structure\n\n```\nmy-skill/\n├── SKILL.md\n├── scripts/\n│   └── example_script.cjs\n├── references/\n│   └── example_reference.md\n└── assets/\n    └── example_asset.txt\n```\n\n### Customization Steps\n\n1. Edit `SKILL.md` with accurate name and description\n2. Add scripts for deterministic operations\n3. Create reference documentation\n4. Place assets in the `assets/` directory\n5. Delete unused example files\n\n### Best Practices\n\n- **Description clarity**: The description determines when the skill triggers. Be specific about use cases.\n- **Script testing**: Run scripts to verify they work correctly\n- **Token efficiency**: Use scripts instead of repeated code generation\n- **Reference loading**: Only load references when needed\n\n---\n\n## Creating Extensions\n\n### Command\n\n```bash\ngemini extensions create my-extension\n```\n\n### Implementation Checklist\n\n| Step | Task |\n|------|------|\n| 1 | Define extension manifest |\n| 2 | Implement custom commands |\n| 3 | Configure MCP servers |\n| 4 | Add policy rules |\n| 5 | Register hooks |\n| 6 | Test locally with `gemini extensions link` |\n\n### Local Development\n\n```bash\n# Link extension for local testing\ngemini extensions link ./path/to/extension\n\n# Unlink when done\ngemini extensions unlink my-extension\n```\n\n---\n\n## Configuration\n\n### Skill Directories\n\nSkills are loaded from configured directories. Check `~/.gemini/settings.json`:\n\n```json\n{\n  \"skills\": {\n    \"directories\": [\"./.skills\", \"~/.gemini/skills\"]\n  }\n}\n```\n\n### Extension Settings\n\nExtensions are discovered from:\n\n- Globally installed npm packages (`@gemini-extensions/*`)\n- Locally linked directories\n- User-configured paths in `settings.json`\n\n---\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Skill Layer\"\n        A[SKILL.md] --> B[SkillLoader]\n        C[scripts/] --> D[Script Executor]\n        E[references/] --> F[Context Loader]\n    end\n    \n    subgraph \"Extension Layer\"\n        G[gemini-extension.json] --> H[ExtensionManager]\n        I[commands/] --> J[Command Registry]\n        K[policies/] --> L[Policy Engine]\n        M[mcpServers] --> N[MCP Client]\n    end\n    \n    subgraph \"Core\"\n        B --> O[Skill Manager]\n        H --> O\n        D --> O\n        L --> P[Security Layer]\n        N --> Q[Tool Executor]\n    end\n    \n    O --> Q\n    Q --> R[Response Formatter]\n```\n\n---\n\n## Summary\n\n| Feature | Skills | Extensions |\n|---------|--------|------------|\n| **Format** | Markdown-based | npm packages |\n| **Trigger** | Semantic matching | Manual invocation |\n| **Code** | Optional scripts | Full source code |\n| **Complexity** | Low-medium | Medium-high |\n| **Use case** | Guidance, patterns | Tools, policies, integrations |\n\n**Skills** provide lightweight, context-loaded guidance for specialized tasks.\n\n**Extensions** provide comprehensive programmatic extensibility through custom commands, MCP servers, policy rules, and hooks.\n\nBoth mechanisms work together to make Gemini CLI adaptable to diverse workflows and requirements.\n\n---\n\n<a id='sandboxing-security'></a>\n\n## Sandboxing and Security\n\n### 相关页面\n\n相关主题：[Policy Engine](#policy-engine), [Tools Reference](#tools-reference)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n- [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)\n- [packages/cli/src/config/trustedFolders.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/trustedFolders.ts)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [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)\n- [package.json](https://github.com/google-gemini/gemini-cli/blob/main/package.json)\n</details>\n\n# Sandboxing and Security\n\n## Overview\n\nGemini 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.\n\n## Architecture\n\nThe 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.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Config System]\n    B --> C{Path Validation}\n    C -->|Allowed| D[Sandbox Manager]\n    C -->|Denied| E[Access Rejected]\n    D --> F{Linux Sandbox}\n    D --> G{macOS Sandbox}\n    D --> H{Windows Sandbox}\n    F --> I[Docker Container]\n    G --> J[Apple Silicon / Sandbox Profile]\n    H --> K[Windows Sandbox]\n    I --> L[Tool Execution]\n    J --> L\n    K --> L\n```\n\n## Sandbox Manager Architecture\n\nThe sandbox system is orchestrated through a centralized `SandboxManager` service that delegates to platform-specific implementations.\n\n### Platform-Specific Implementations\n\n| Platform | Manager Class | Isolation Method |\n|----------|---------------|------------------|\n| Linux | `LinuxSandboxManager` | Docker containers with resource limits |\n| macOS | `MacOsSandboxManager` | App Sandbox / Process sandboxing |\n| Windows | `WindowsSandboxManager` | Windows Sandbox virtualization |\n\n### Sandbox Image Configuration\n\nSandbox environments use pre-built Docker images defined in the root `package.json`:\n\n```json\n{\n  \"config\": {\n    \"sandboxImageUri\": \"us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef\"\n  }\n}\n```\n\n资料来源：[package.json:11]()\n\n## Path Validation System\n\nThe path validation system prevents the agent from accessing files outside authorized boundaries. This is implemented in the `Config` class through two primary methods.\n\n### Access Control Logic\n\n```typescript\nisPathAllowed(absolutePath: string): boolean {\n  const resolvedPath = resolveToRealPath(absolutePath);\n  // Check inbox isolation first\n  // Check workspace boundaries\n  // Check project temp directory\n}\n\nvalidatePathAccess(absolutePath: string): string | null {\n  if (this.isPathAllowed(absolutePath)) {\n    return null;\n  }\n  return `Path not in workspace: Attempted path \"${absolutePath}\" resolves outside the allowed workspace directories`;\n}\n```\n\n资料来源：[packages/core/src/config/config.ts]()\n资料来源：[packages/core/src/tools/confirmation-policy.test.ts]()\n\n### Allowed Path Categories\n\n| Category | Description | Access Level |\n|----------|-------------|--------------|\n| Workspace directories | User-specified project roots | Full read/write |\n| Project temp directory | Temporary files for operations | Read/write within bounds |\n| Inbox directory | Auto-memory extraction staging | Restricted write access |\n\n### Inbox Isolation\n\nThe `.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:\n\n```mermaid\ngraph LR\n    A[Main Agent] -->|DENIED| B[.inbox/ directory]\n    C[Extraction Agent] -->|WRITE ALLOWED| B\n    D[Review Flow] -->|READ| B\n```\n\n资料来源：[packages/core/src/config/config.ts]()\n\n## Trusted Folders System\n\nThe trusted folders mechanism allows users to authorize specific directories for configuration loading while maintaining security boundaries.\n\n### What Trust Enables\n\nWhen a folder is trusted, Gemini CLI loads:\n\n- Custom commands\n- Hooks\n- MCP server configurations\n- Agent skills\n- Local settings\n\n### Security Dialog\n\nWhen discovering a new folder, users are presented with the `FolderTrustDialog` component that displays:\n\n```typescript\n// Security warnings and errors are displayed to the user\n{hasWarnings && (\n  <Box>\n    <Text color={theme.status.warning}>⚠️ Security Warnings:</Text>\n    {discoveryResults.securityWarnings.map((warning, i) => (\n      <Text key={i} color={theme.status.warning}>\n        • {stripAnsi(warning)}\n      </Text>\n    ))}\n  </Box>\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx]()\n\n### Discovery Results\n\nThe folder discovery process returns categorized items:\n\n| Group Label | Item Types |\n|-------------|------------|\n| Custom Commands | User-defined slash commands |\n| Hooks | Pre/post execution scripts |\n| MCP Servers | Model Context Protocol servers |\n| Agent Skills | Specialized skill modules |\n| Settings | Configuration overrides |\n\n## Policy Engine\n\nExtensions can contribute security rules and safety checkers through the policy engine. This allows the community to extend built-in security without modifying core code.\n\n### Rule Types\n\n| Rule Type | Purpose | Example |\n|-----------|---------|---------|\n| Confirmation Rules | Require user approval for specific operations | Confirm before `rm -rf` |\n| Denial Rules | Block specific operations entirely | Prevent `grep` for `.env` files |\n| Safety Checkers | Validate operations before execution | Path validation for writes |\n\n### Extension Policy Structure\n\n```\nextension/\n├── gemini-extension.json\n└── policies/\n    ├── confirmation-rules.toml\n    ├── denial-rules.toml\n    └── safety-checkers.toml\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n### Security Enforcement\n\n**Critical**: Gemini CLI ignores `allow` decisions and `yolo` mode configurations contributed by extensions. This ensures that:\n\n- Extensions can strengthen security\n- Extensions cannot bypass user confirmation\n- Malicious extensions cannot weaken protections\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md]()\n\n## Configuration Reference\n\n### Settings File Location\n\nUser settings are stored at `~/.gemini/settings.json`\n\n### Key Security Settings\n\n| Setting | Type | Purpose |\n|---------|------|---------|\n| `trustedFolders` | Array of paths | Authorize directories for config loading |\n| `dataCollectionOptIn` | Boolean | Control telemetry data sharing |\n\n### Workspace Context\n\n```typescript\ninterface WorkspaceContext {\n  isPathWithinWorkspace(path: string): boolean;\n  getDirectories(): string[];\n}\n```\n\nThe workspace context is queried during path validation to determine if a requested file operation falls within authorized boundaries.\n\n## Security Best Practices\n\n### For Users\n\n1. **Review folder trust requests** - Only trust folders containing code you control\n2. **Understand policy rules** - Read denial messages to understand why operations are blocked\n3. **Use workspace isolation** - Keep sensitive files outside workspace directories\n\n### For Extension Developers\n\n1. **Contribute restrictive rules** - Extensions should only add protections, never remove them\n2. **Follow policy TOML format** - Use structured definitions for predictable behavior\n3. **Test edge cases** - Validate paths resolve correctly across platforms\n\n## Summary\n\nGemini CLI's security architecture combines:\n\n- **Platform-specific sandboxing** for code execution isolation\n- **Path validation** for filesystem access control\n- **Trusted folder system** for configuration security\n- **Policy engine** for extensible rule definitions\n- **Inbox isolation** for memory extraction workflow integrity\n\nThis multi-layered approach allows the CLI to safely execute AI-generated code while giving users transparency and control over security boundaries.\n\n---\n\n<a id='policy-engine'></a>\n\n## Policy Engine\n\n### 相关页面\n\n相关主题：[Sandboxing and Security](#sandboxing-security), [Agent System](#agent-system)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [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)\n- [packages/core/src/availability/policyHelpers.test.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/availability/policyHelpers.test.ts)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/core/src/config/config.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/config.ts)\n</details>\n\n# Policy Engine\n\n## Overview\n\nThe 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.\n\nThe 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.\n\n## Architecture\n\n### Core Components\n\nThe Policy Engine consists of three primary layers:\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Policy Loader | Parses and loads TOML policy files | `packages/core/src/policy/toml-loader.ts` |\n| Policy Engine | Evaluates operations against loaded policies | `packages/core/src/policy/policy-engine.ts` |\n| Policy Configuration | Manages runtime policy settings | `packages/cli/src/config/policy.ts` |\n\n### Evaluation Flow\n\n```mermaid\ngraph TD\n    A[Operation Request] --> B{Policy Engine}\n    B --> C[Load Policies from TOML]\n    C --> D[Apply Security Rules]\n    D --> E{Rule Match?}\n    E -->|Yes| F[Prompt User Confirmation]\n    E -->|No| G[Apply Safety Checkers]\n    F --> H{User Approves?}\n    H -->|Yes| G\n    H -->|No| I[Block Operation]\n    G --> J{Safety Valid?}\n    J -->|Yes| K[Execute Operation]\n    J -->|No| I\n    I --> L[Return Error/Deny Message]\n    K --> M[Operation Complete]\n```\n\n## Policy Configuration\n\n### Configuration File Location\n\nPolicy 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.\n\n### Policy Types\n\nThe Policy Engine supports two categories of policies:\n\n#### Security Rules\n\nSecurity rules define conditional logic that triggers user confirmation or denies operations based on specific patterns. Rules are evaluated before operation execution and can:\n\n- Require user confirmation for dangerous commands\n- Deny operations matching specific patterns\n- Provide custom deny messages explaining why an operation was blocked\n\n#### Safety Checkers\n\nSafety 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.\n\n## Extension Integration\n\n### Registering Policy Extensions\n\nExtensions can contribute policies by including a `policies/` directory with TOML files. The extension manifest (`gemini-extension.json`) identifies it as a policy contributor.\n\n### Security Constraints\n\nFor security, Gemini CLI enforces strict constraints on extension-contributed policies:\n\n```toml\n[security]\n# Gemini CLI ignores these configurations from extensions\nallow_decisions = false  # Ignored\nyolo_mode = false        # Ignored\n```\n\n| Extension-Provided Setting | Gemini CLI Behavior |\n|---------------------------|---------------------|\n| `allow` decisions | **Ignored** - Always treated as prompt |\n| `yolo` mode configuration | **Ignored** - Cannot bypass confirmation |\n\nThis design ensures that extensions can only strengthen security by adding more restrictive rules—they cannot weaken security by bypassing user confirmation.\n\n## Built-in Policies\n\n### rm -rf Rule Example\n\nThe following demonstrates a policy that requires confirmation for recursive directory deletion:\n\n```toml\n[[rules]]\nid = \"prevent-recursive-delete\"\ndescription = \"Require confirmation for rm -rf commands\"\n\n[rules.condition]\ncommand_pattern = \"rm.*-rf.*\"\n\n[rules.action]\ntype = \"confirm\"\nmessage = \"This will recursively delete directories. Are you sure?\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### Secret File Access Rule Example\n\nPolicies can prevent searching for sensitive files:\n\n```toml\n[[rules]]\nid = \"prevent-secret-search\"\ndescription = \"Deny grep searches for sensitive files\"\n\n[rules.condition]\ncommand_pattern = \"grep.*\\\\.env\"\n\n[rules.action]\ntype = \"deny\"\nmessage = \"Searching for .env files is not allowed for security reasons\"\n```\n\n资料来源：[packages/cli/src/commands/extensions/examples/policies/README.md:1-30]()\n\n### File Path Safety Checker Example\n\nSafety checkers validate operation parameters:\n\n```toml\n[[safety_checkers]]\nid = \"allowed-path\"\ndescription = \"Validate file paths for write operations\"\n\n[safety_checkers.validator]\ntype = \"path_validation\"\nallowed_paths = [\"/home/user/project\", \"/tmp/uploads\"]\n```\n\n## Policy Chain Resolution\n\nThe 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.\n\n```mermaid\ngraph LR\n    A[Model Config] --> B{Is Custom Model?}\n    B -->|Yes| C[Single-Model Chain]\n    B -->|No| D{Is in Catalog?}\n    D -->|Yes| E[Use Catalog Order]\n    D -->|No| F[Default Chain: Pro → Flash]\n```\n\n| Model Scenario | Policy Chain Behavior |\n|---------------|----------------------|\n| Custom model | Single-model chain |\n| Catalog model (exists) | Preserves catalog order |\n| Auto model (`gemini-2.5-pro` or default) | Default chain: Pro, then Flash |\n\n资料来源：[packages/core/src/availability/policyHelpers.test.ts:1-50]()\n\n## Folder Trust Integration\n\nThe Policy Engine integrates with Gemini CLI's folder trust system. Policies are only loaded from trusted folders to prevent malicious configuration injection.\n\n| Trust State | Policy Loading |\n|------------|----------------|\n| Trusted folder | Full policy enforcement |\n| Untrusted folder | Policies not loaded |\n| YOLO mode disabled | Cannot enable YOLO in untrusted folders |\n\nThe `isYoloModeDisabled` method checks both the global YOLO disable flag and the folder trust status:\n\n```typescript\nisYoloModeDisabled(): boolean {\n  return this.disableYoloMode || !this.isTrustedFolder();\n}\n```\n\n资料来源：[packages/core/src/config/config.ts:200-203]()\n\n### Security Warnings and Errors\n\nWhen loading policies from a folder, the system reports:\n\n- **Discovery Errors**: Problems parsing or loading policy files\n- **Security Warnings**: Potentially risky configurations detected\n- **Loaded Items**: Policies successfully loaded and active\n\n```typescript\ninterface DiscoveryResults {\n  discoveryErrors: string[];\n  securityWarnings: string[];\n  loadedPolicies: Policy[];\n}\n```\n\n资料来源：[packages/cli/src/ui/components/FolderTrustDialog.tsx:1-60]()\n\n## Configuration Options\n\n### Core Policy Settings\n\n| Setting | Type | Default | Description |\n|---------|------|---------|-------------|\n| `disableYoloMode` | boolean | `false` | Disables YOLO mode entirely |\n| `disableAlwaysAllow` | boolean | `false` | Prevents \"always allow\" shortcuts |\n| `pendingIncludeDirectories` | string[] | `[]` | Directories pending trust approval |\n\n### Policy File Loading\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| Policy directory | `policies/` | TOML files in extension packages |\n| File format | `.toml` | TOML 1.0 specification |\n| Reload trigger | Folder trust change | Policies reload when trust state changes |\n\n## Best Practices\n\n### Writing Secure Policies\n\n1. **Use specific patterns**: Avoid overly broad patterns that could match legitimate operations\n2. **Provide clear messages**: Explain why an operation requires confirmation\n3. **Validate file paths**: Use safety checkers for path-based operations\n4. **Test edge cases**: Ensure policies don't block necessary operations\n\n### Policy Testing\n\nTo test policies contributed by extensions:\n\n```bash\n# Link the extension\ngemini extensions link packages/cli/src/commands/extensions/examples/policies\n\n# Restart Gemini CLI session\n# Policies will be loaded from the linked extension\n```\n\n### Debugging Policy Evaluation\n\nWhen policies don't behave as expected:\n\n1. Verify the extension is properly linked\n2. Check the folder is marked as trusted\n3. Review TOML syntax for parsing errors\n4. Confirm rule patterns match the actual command strings\n\n## Summary\n\nThe 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.\n\n---\n\n<a id='terminal-ui'></a>\n\n## Terminal UI Components\n\n### 相关页面\n\n相关主题：[Session Management](#session-management)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [packages/cli/src/ui/components/AppHeader.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AppHeader.tsx)\n- [packages/cli/src/ui/components/FolderTrustDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/FolderTrustDialog.tsx)\n- [packages/cli/src/ui/components/ModelDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ModelDialog.tsx)\n- [packages/cli/src/ui/components/InboxDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/InboxDialog.tsx)\n- [packages/cli/src/ui/components/ToolConfirmationMessage.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/ToolConfirmationMessage.tsx)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [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)\n</details>\n\n# Terminal UI Components\n\n## Overview\n\nThe 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.\n\nThe component architecture follows a modular design pattern, separating concerns between layout containers, interactive dialogs, informational displays, and message rendering components.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"UI Layer\"\n        A[App.tsx] --> B[AppHeader]\n        A --> C[MainContent]\n        A --> D[Composer]\n    end\n    \n    subgraph \"Dialogs\"\n        E[AuthDialog] --> F[RadioButtonSelect]\n        G[ModelDialog] --> H[ModelQuotaDisplay]\n        I[FolderTrustDialog] --> J[DiscoveryResults]\n        K[InboxDialog] --> L[ScrollableDiffViewport]\n    end\n    \n    subgraph \"Messages\"\n        M[GeminiMessage] --> N[StreamingState]\n        O[ToolConfirmationMessage] --> P[ConfirmationDetails]\n    end\n    \n    subgraph \"Theming\"\n        Q[ThemeManager] --> R[Theme Types]\n        Q --> S[Custom Extensions]\n    end\n```\n\n## Component Categories\n\n### 1. Layout Components\n\n#### AppHeader\nThe main header component displaying CLI branding, version information, and user identity.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `showHeader` | `boolean` | Controls header visibility |\n| `showDetails` | `boolean` | Shows detailed metadata |\n| `bannerVisible` | `boolean` | Displays warning/info banners |\n| `bannerText` | `string` | Banner content text |\n\n**Key Features:**\n- Dynamic layout: switches between row and column orientation based on terminal width\n- Update notifications with spinner animation during version checks\n- User identity display (email and plan information)\n- Collapsible tips section\n- Configurable branding via logo text art\n\n**Source:** [packages/cli/src/ui/components/AppHeader.tsx:1-100]()\n\n#### Composer\nInput component for user commands and messages.\n\nProvides the text input interface for interacting with Gemini CLI, supporting multi-line input and command submission.\n\n### 2. Dialog Components\n\n#### AuthDialog\nHandles user authentication flow with multiple provider options.\n\n```mermaid\ngraph LR\n    A[Launch] --> B{Auth Method?}\n    B -->|OAuth| C[Google Login]\n    B -->|Token| D[API Key Input]\n    B -->|Skip| E[Continue Anonymously]\n    C --> F[Restart CLI]\n    D --> G[Validate Token]\n    E --> H[Limited Mode]\n```\n\n**Features:**\n- Radio button selection for authentication methods\n- Error state handling with visual feedback\n- Links to Terms of Service and Privacy Notice\n- OAuth flow with automatic CLI restart\n\n**Source:** [packages/cli/src/ui/auth/AuthDialog.tsx:1-80]()\n\n#### ModelDialog\nDisplays available models with quota information and allows model selection.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `modelVersion` | `string` | Currently active model identifier |\n| `quotaDisplay` | `QuotaBucket[]` | Rate limit information |\n| `terminalWidth` | `number` | Available display width |\n\n**Source:** [packages/cli/src/ui/components/ModelDialog.tsx:1-60]()\n\n#### FolderTrustDialog\nSecurity-focused dialog for approving folder configurations.\n\n**Key Sections:**\n1. **Trust Explanation** - Documents what configurations will be loaded\n2. **Discovery Results** - Shows found extensions, commands, hooks, and skills\n3. **Security Warnings** - Highlights potentially risky configurations\n4. **Discovery Errors** - Reports parsing or loading failures\n\n**Source:** [packages/cli/src/ui/components/FolderTrustDialog.tsx:1-100]()\n\n#### InboxDialog\nDisplays notification patches and skill updates available for installation.\n\n| Display Field | Source | Format |\n|--------------|--------|--------|\n| Title | `patch.name` | `string + [origin]` |\n| Subtitle | `patch.extractedAt` | `files · date` |\n| Content Preview | `skillSections` | Scrollable diff |\n\n**Source:** [packages/cli/src/ui/components/InboxDialog.tsx:1-120]()\n\n### 3. Message Components\n\n#### GeminiMessage\nRenders AI-generated responses with markdown support.\n\n**Rendering Modes:**\n- **Markdown Rendered** (default): Full markdown parsing with syntax highlighting\n- **Raw Markdown**: Syntax highlighting without line numbers\n\n**Configuration Options:**\n```typescript\ninterface GeminiMessageProps {\n  text: string;           // Message content\n  isPending: boolean;     // Streaming indicator\n  terminalWidth: number;  // Layout adaptation\n  renderMarkdown?: boolean;\n  streamingState?: StreamingState;\n}\n```\n\n**Source:** [packages/cli/src/ui/components/messages/GeminiMessage.test.tsx:1-50]()\n\n#### ToolConfirmationMessage\nDisplays interactive confirmation prompts for tool execution.\n\n**Supported Types:**\n- `edit` - File modification operations\n- `read` - Content retrieval requests\n- `execute` - Command execution confirmations\n- `delete` - Resource removal confirmations\n\n**States:**\n- Normal confirmation view\n- In-progress indicator (\"Save and close external editor\")\n- Security warning display\n- System message overlay\n\n**Source:** [packages/cli/src/ui/components/ToolConfirmationMessage.tsx:1-100]()\n\n### 4. Information Components\n\n#### AboutBox\nDisplays system and version information.\n\n| Field | Source | Visibility |\n|-------|--------|------------|\n| CLI Version | `cliVersion` | Always |\n| Git Commit | `GIT_COMMIT_INFO` | Unless \"N/A\" |\n| Model | `modelVersion` | Always |\n| Sandbox | `sandboxEnv` | Always |\n| OS | System Info | Always |\n\n**Source:** [packages/cli/src/ui/components/AboutBox.tsx:1-60]()\n\n## Theming System\n\nThe UI supports customizable color themes that apply consistent styling across all components.\n\n### Theme Structure\n\n```typescript\ninterface Theme {\n  text: {\n    primary: string;\n    secondary: string;\n    accent: string;\n    link: string;\n  };\n  status: {\n    success: string;\n    warning: string;\n    error: string;\n  };\n  border: {\n    default: string;\n  };\n  ui: {\n    focus: string;\n  };\n}\n```\n\n### Theme Configuration\n\nUsers can create custom themes by:\n1. Creating an extension with theme definition in `gemini-extension.json`\n2. Setting the theme in `~/.gemini/settings.json`:\n   ```json\n   {\n     \"ui\": {\n       \"theme\": \"theme-name (extension-name)\"\n     }\n   }\n   ```\n\n### Available UI Settings\n\n| Setting | Type | Default | Description |\n|---------|------|---------|-------------|\n| `showUserIdentity` | `boolean` | `true` | Display email and plan |\n| `hideTips` | `boolean` | `false` | Hide tips section |\n| `renderMarkdown` | `boolean` | `true` | Enable markdown rendering |\n\n## Component Composition Patterns\n\n### Dialog Pattern\nAll dialogs follow a consistent structure:\n\n```typescript\n<Box borderStyle=\"round\" borderColor={theme.ui.focus}>\n  <Box flexDirection=\"column\">\n    {/* Title */}\n    <Text bold>{title}</Text>\n    \n    {/* Content */}\n    {children}\n    \n    {/* Footer */}\n    <DialogFooter \n      primaryAction=\"Enter to select\"\n      cancelAction=\"Esc to close\"\n    />\n  </Box>\n</Box>\n```\n\n### Responsive Layout\nComponents adapt to terminal width using:\n- Flexbox with `flexDirection` switching (row/column)\n- Percentage-based widths (`width=\"35%\"`)\n- Conditional rendering based on `terminalWidth`\n- Maximum size constraints via `MaxSizedBox`\n\n### Color Application\nComponents use semantic color tokens:\n- `theme.text.primary` - Main content text\n- `theme.text.secondary` - Supporting text\n- `theme.text.accent` - Highlighted elements\n- `theme.text.link` - Interactive links\n- `theme.status.*` - State indicators (success, warning, error)\n\n## State Management\n\n### UI State Context\nComponents access shared state through React context:\n\n```typescript\ninterface UIState {\n  renderMarkdown: boolean;\n  streamingState: StreamingState;\n  terminalWidth: number;\n}\n```\n\n### Component Communication\n| Pattern | Example | Purpose |\n|---------|---------|---------|\n| Props drilling | `AuthDialog` → `RadioButtonSelect` | Simple parent-child |\n| Context | `theme` access | Global styling |\n| Callback props | `onSelect`, `onHighlight` | Event handling |\n| State updates | `isUpdating` flag | Async operations |\n\n## Security Features\n\n### Folder Trust System\nThe `FolderTrustDialog` implements security boundaries:\n\n1. **Discovery Phase**: Scans for configuration files\n2. **Warning Phase**: Identifies potentially dangerous configurations\n3. **Approval Phase**: User explicitly approves folder access\n4. **Execution Phase**: Loads approved configurations\n\n### Data Collection Opt-In\nUsers can control whether usage data is collected:\n- UI toggle in privacy settings\n- Persisted preference in `settings.json`\n- Clear documentation in privacy notices\n\n## Testing Approach\n\nComponents use snapshot testing with `renderWithProviders`:\n\n```typescript\nit('renders pending state', async () => {\n  const { lastFrame } = await renderWithProviders(\n    <GeminiMessage {...props} isPending={true} />,\n    { uiState: { renderMarkdown: true } }\n  );\n  expect(lastFrame()).toMatchSnapshot();\n});\n```\n\nTest utilities provide:\n- Mocked Ink components\n- Theme injection\n- State context setup\n- Terminal width simulation\n\n## Best Practices\n\n### Component Guidelines\n1. **Accessibility**: Support keyboard navigation (Enter, Escape)\n2. **Responsiveness**: Adapt to variable terminal widths\n3. **Error Handling**: Display clear error messages with colors\n4. **Loading States**: Show spinners and progress indicators\n\n### Styling Guidelines\n1. Use semantic theme tokens instead of hardcoded colors\n2. Prefer flexbox layouts over absolute positioning\n3. Include proper margin and padding for visual hierarchy\n4. Use truncation for long text with `wrap=\"truncate-end\"`\n\n### Performance Considerations\n1. Minimize re-renders with proper memoization\n2. Use virtual scrolling for long lists\n3. Lazy load heavy content (skill previews)\n4. Cache discovery results when appropriate\n\n---\n\n<a id='session-management'></a>\n\n## Session Management\n\n### 相关页面\n\n相关主题：[Terminal UI Components](#terminal-ui), [Context and Memory Management](#context-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [packages/core/src/context/graph/toGraph.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/context/graph/toGraph.ts)\n- [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)\n- [packages/core/src/services/chatRecordingService.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts)\n- [packages/sdk/src/agent.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/sdk/src/agent.ts)\n- [packages/cli/src/ui/components/AboutBox.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/AboutBox.tsx)\n- [README.md](https://github.com/google-gemini/gemini-cli/blob/main/README.md)\n</details>\n\n# Session Management\n\n## Overview\n\nSession 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.\n\nSessions 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.\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:35-36]()\n\n## Session Lifecycle\n\n```mermaid\ngraph TD\n    A[User Starts CLI] --> B{Check for Existing Session?}\n    B -->|Yes| C[Resume Session]\n    B -->|No| D[Create New Session]\n    D --> E[Generate Session ID]\n    E --> F[Initialize Context Graph]\n    F --> G[Start Conversation]\n    C --> H[Load Session from Storage]\n    H --> G\n    G --> I[Process User Input]\n    I --> J[Record Message to ChatHistory]\n    J --> K{User Exits?}\n    K -->|No| I\n    K -->|Yes| L[Save Session Metadata]\n    L --> M[Close Session]\n```\n\n### Session Creation\n\nWhen 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:\n\n1. **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.\n\n2. **Project Hash Computation**: The system computes a hash of the current working directory to associate the session with a specific project context.\n\n3. **Storage Initialization**: The `ChatRecordingService` prepares file-based storage at a project-specific temp directory, enabling conversation persistence.\n\n资料来源：[packages/sdk/src/agent.ts:58-60]()\n\n### Session Resume\n\nThe session resume capability allows users to continue previous conversations seamlessly. When resuming a session, the system:\n\n1. Loads the complete conversation history from JSONL storage\n2. Reconstructs the context graph from stored messages\n3. Validates authentication state\n4. Restores model configuration and tool states\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant ChatRecordingService\n    participant GeminiAgent\n    \n    User->>CLI: Resume Session (sessionId)\n    CLI->>ChatRecordingService: Load Conversation Record\n    ChatRecordingService-->>CLI: ConversationRecord (messages, metadata)\n    CLI->>GeminiAgent: Initialize with Loaded State\n    GeminiAgent-->>CLI: Session Ready\n    CLI->>User: Display Last N Messages\n```\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:45-52]()\n\n## Session Data Model\n\nThe `ConversationRecord` interface defines the complete structure of a persisted session:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `sessionId` | `string` | Unique identifier for the session |\n| `projectHash` | `string` | Hash of the project directory |\n| `startTime` | `string` (ISO 8601) | Session creation timestamp |\n| `lastUpdated` | `string` (ISO 8601) | Last modification timestamp |\n| `summary` | `string \\| undefined` | Auto-generated conversation summary |\n| `memoryScratchpad` | `string \\| undefined` | Persistent scratchpad notes |\n| `directories` | `string[]` | Working directories used in session |\n| `kind` | `string` | Session kind/type identifier |\n| `messages` | `Message[]` | Full message history |\n| `messageCount` | `number` | Total message count |\n| `userMessageCount` | `number` | Count of user messages only |\n| `memoryScratchpadIsStale` | `boolean \\| undefined` | Indicates if scratchpad needs refresh |\n| `firstUserMessage` | `string \\| undefined` | First user prompt for quick reference |\n| `hasUserOrAssistantMessage` | `boolean` | Indicates non-empty conversation |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:32-50]()\n\n### Message Structure\n\nMessages within a session follow the multi-part content model:\n\n```typescript\ninterface Message {\n  role: 'user' | 'model' | 'system' | 'tool';\n  parts: Array<{\n    text?: string;\n    functionCall?: FunctionCall;\n    functionResponse?: FunctionResponse;\n  }>;\n}\n```\n\nThe context graph builder processes each turn by:\n\n1. Generating a stable MD5 hash from role and content for deduplication\n2. Assigning an occurrence counter for repeated identical messages\n3. Creating a stable turn ID using the `getStableId()` utility\n4. Tracking function calls and responses with unique identifiers\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:1-30]()\n\n## Storage Architecture\n\n### Chat Recording Service\n\nThe `ChatRecordingService` class manages all session persistence operations:\n\n```mermaid\ngraph LR\n    A[In-Memory Cache] -->|Write-through| B[JSONL File]\n    C[Session Load Request] --> D{Cache Hit?}\n    D -->|Yes| A\n    D -->|No| B\n    B -->|Load| A\n```\n\n**Key Responsibilities:**\n\n| Responsibility | Description |\n|----------------|-------------|\n| Conversation Recording | Writes messages to JSONL format |\n| Session Loading | Loads and reconstructs sessions from disk |\n| Metadata Management | Tracks summary, scratchpad, and timestamps |\n| Message Deduplication | Uses content hashing to identify duplicate turns |\n\n资料来源：[packages/core/src/services/chatRecordingService.ts:85-90]()\n\n### Storage Directory Structure\n\nSessions are stored in the project temp directory:\n\n```\n/tmp/gemini/\n├── conversation-{sessionId}.jsonl   # Full message history\n├── session-{sessionId}.json         # Session metadata\n├── bug-report-history-{timestamp}.json  # Bug report exports\n└── checkpoints/                     # Checkpoint snapshots\n```\n\nThe `getProjectTempDir()` method determines the storage path based on the active project context.\n\n资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:60-62]()\n\n## Session Browser Component\n\nThe `SessionBrowser` UI component provides an interactive interface for managing multiple sessions:\n\n- **Session List View**: Displays all historical sessions for a project\n- **Session Preview**: Shows message count, date range, and summary\n- **Session Actions**: Resume, rename, delete, or export sessions\n- **Search/Filter**: Find sessions by content or date\n\n```typescript\ninterface SessionBrowserProps {\n  sessions: ConversationRecord[];\n  onSelect: (sessionId: string) => void;\n  onDelete: (sessionId: string) => Promise<void>;\n  onExport: (sessionId: string) => Promise<void>;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/SessionBrowser.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/SessionBrowser.tsx)\n\n## Rewind Viewer\n\nThe `RewindViewer` component enables users to navigate and review historical conversation states:\n\n- **Timeline Navigation**: Move through conversation turns chronologically\n- **State Restoration**: View message content at any past point\n- **Diff View**: Compare changes between turns (optional)\n\nThis component leverages the turn-by-turn tracking implemented in the context graph builder to provide accurate historical snapshots.\n\n资料来源：[packages/cli/src/ui/components/RewindViewer.tsx](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/ui/components/RewindViewer.tsx)\n\n## Session Operations\n\nThe `sessionOperations.ts` utility module provides core session manipulation functions:\n\n### Available Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `createSessionId()` | Generate a new unique session identifier |\n| `loadSession()` | Load session data from storage |\n| `saveSession()` | Persist session state to disk |\n| `deleteSession()` | Remove session and associated data |\n| `exportSession()` | Export session to portable format |\n| `listSessions()` | Enumerate all sessions for a project |\n\n### Session Resume Flow\n\n```mermaid\ngraph TD\n    A[Load Session Record] --> B{Valid Session?}\n    B -->|No| C[Raise Error]\n    B -->|Yes| D[Load Message History]\n    D --> E[Reconstruct Context Graph]\n    E --> F[Initialize Agent State]\n    F --> G[Ready for User Input]\n```\n\n资料来源：[packages/core/src/utils/sessionOperations.ts](https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/sessionOperations.ts)\n\n## Context Graph Integration\n\nThe context graph system maintains the semantic structure of conversations independently from raw message storage:\n\n1. **Turn Tracking**: Each user-model exchange is assigned a unique turn ID\n2. **Role Management**: Messages are tagged with roles (user, model, tool, system)\n3. **Function Call Tracking**: Tool interactions are recorded with unique IDs (`call_{id}` or `resp_{id}`)\n4. **Legacy Header Handling**: Automatically skips legacy environment headers during graph reconstruction\n\nThe graph builder generates stable identifiers using:\n\n```typescript\nconst turnContent = JSON.stringify(msg.parts);\nconst h = createHash('md5').update(`${msg.role}:${turnContent}`).digest('hex');\nconst occurrence = (seenHashes.get(h) || 0) + 1;\nconst turnSalt = `${h}_${occurrence}`;\nconst turnId = getStableId(msg, this.nodeIdentityMap, turnSalt, -1);\n```\n\n资料来源：[packages/core/src/context/graph/toGraph.ts:18-25]()\n\n## SDK Integration\n\nThe Gemini CLI SDK exposes session management through the `GeminiCliAgent` and `GeminiCliSession` classes:\n\n```typescript\nconst agent = new GeminiCliAgent({\n  instructions: 'You are a helpful coding assistant.',\n  tools: [myTool],\n});\n\n// Create a new session\nconst session = agent.session();\nawait session.initialize();\n\n// Resume an existing session\nconst resumedSession = agent.session({ sessionId: 'existing-id' });\nawait resumedSession.initialize();\n\n// Stream messages\nfor await (const event of session.sendStream('Hello!')) {\n  console.log(event);\n}\n```\n\n资料来源：[packages/sdk/src/agent.ts:35-55]()\n\n## About Box Display\n\nSession metadata is surfaced in the CLI's About dialog:\n\n| Field | Source | Display |\n|-------|--------|---------|\n| CLI Version | Package version | Always shown |\n| Git Commit | Build-time constant | Conditional (non-N/A) |\n| Model | Active model configuration | Always shown |\n| Sandbox | Environment indicator | Always shown |\n| OS | System information | Always shown |\n\n资料来源：[packages/cli/src/ui/components/AboutBox.tsx:20-50]()\n\n## Configuration\n\n### Session-Related Settings\n\n| Setting | Description | Default |\n|---------|-------------|---------|\n| `sessionStorageDir` | Override default temp storage | `/tmp/gemini` |\n| `maxSessions` | Maximum sessions per project | 50 |\n| `autoSaveInterval` | Auto-save frequency (ms) | 30000 |\n| `sessionId` | Specific session to resume | (none) |\n\n### Bug Report Integration\n\nWhen submitting bug reports via `/bug`, the session automatically exports chat history:\n\n```typescript\nconst history = geminiClient.getChat().getHistory();\nconst bugReportPath = path.join(\n  storage.getProjectTempDir(),\n  `bug-report-history-${Date.now()}.json`\n);\nawait exportHistoryToFile({ history, filePath: bugReportPath });\n```\n\nThe exported history includes the full conversation record and is attached to the GitHub issue for diagnostic purposes.\n\n资料来源：[packages/cli/src/ui/commands/bugCommand.test.ts:45-65]()\n\n## Checkpointing\n\nSessions support checkpointing for disaster recovery and long-running task management:\n\n- **Automatic Checkpoints**: Created at significant conversation milestones\n- **Manual Checkpoints**: User-triggered via `/checkpoint` command\n- **Checkpoint Restoration**: Resume from any saved checkpoint state\n\nCheckpoints are stored alongside regular session data and include complete message history plus agent state snapshots.\n\n资料来源：[docs/cli/checkpointing.md](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/checkpointing.md)\n\n## Best Practices\n\n1. **Session Isolation**: Each project should maintain its own session context\n2. **Regular Exports**: Export important sessions before cleanup\n3. **Scratchpad Usage**: Use the memory scratchpad for cross-session notes\n4. **Metadata Maintenance**: Keep session summaries accurate for quick identification\n5. **Storage Cleanup**: Periodically remove old sessions to conserve disk space\n\n## Related Commands\n\n| Command | Purpose |\n|---------|---------|\n| `/new` | Start a fresh session |\n| `/sessions` | List and manage sessions |\n| `/resume <id>` | Resume a specific session |\n| `/export` | Export session to file |\n| `/checkpoint` | Create session checkpoint |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：google-gemini/gemini-cli\n\n摘要：发现 39 个潜在踩坑项，其中 11 个为 high/blocking；最高优先级：安装坑 - 来源证据：MCP servers not connected in -p (non-interactive) mode。\n\n## 1. 安装坑 · 来源证据：MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 2. 运行坑 · 来源证据：Stabilize and Enhance Internal Project Evaluations\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 安全/权限坑 · 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging\n- 建议检查：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\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging\n\n## 4. 安全/权限坑 · 失败模式：security_permissions: Robust component level evalutions\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Robust component level evalutions\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Robust component level evalutions\n- 建议检查：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.\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions\n\n## 5. 安全/权限坑 · 来源证据：Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Assess the impact of AST-aware file reads, search, and mapping\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 安全/权限坑 · 来源证据：Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 8. 安全/权限坑 · 来源证据：Shell command execution gets stuck with \"Waiting input\" after command completes\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with \"Waiting input\" after command completes\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. 安全/权限坑 · 来源证据：Tracking: 429 / Capacity Issues\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 10. 安全/权限坑 · 来源证据：[Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 11. 安全/权限坑 · 来源证据：fata error again!\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：fata error again!\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6345aa3da845458888c6e250cd950be0 | https://github.com/google-gemini/gemini-cli/issues/27084 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. 安装坑 · 失败模式：installation: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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\n- 对用户的影响：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\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 13. 安装坑 · 来源证据：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d81ba1a5c929402ba842a14ce13fa62d | https://github.com/google-gemini/gemini-cli/issues/23365 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 配置坑 · 失败模式：configuration: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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)\n\n## 15. 配置坑 · 失败模式：configuration: GeminiCLI.com Feedback: [ISSUE]\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GeminiCLI.com Feedback: [ISSUE]\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GeminiCLI.com Feedback: [ISSUE]\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_b159ada1eb969fa31659644535ca2fea | https://github.com/google-gemini/gemini-cli/issues/27206 | GeminiCLI.com Feedback: [ISSUE]\n\n## 16. 配置坑 · 失败模式：configuration: MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: MCP servers not connected in -p (non-interactive) mode\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 17. 配置坑 · 失败模式：configuration: Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Missing validation for critical configuration files could lead to broken bundles\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 18. 配置坑 · 失败模式：configuration: SLOW Response and Usage limits stop gemini CLI. = unusable\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 19. 配置坑 · 失败模式：configuration: Stop Auto Memory from retrying low-signal sessions indefinitely\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 20. 配置坑 · 失败模式：configuration: Surface or quarantine invalid Auto Memory inbox patches\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Surface or quarantine invalid Auto Memory inbox patches\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Surface or quarantine invalid Auto Memory inbox patches\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e7ea4760266f8df60623eea9a521182c | https://github.com/google-gemini/gemini-cli/issues/26523 | Surface or quarantine invalid Auto Memory inbox patches\n\n## 21. 配置坑 · 失败模式：configuration: The write_file tool corrupts or truncates long text sequences during file writes\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: The write_file tool corrupts or truncates long text sequences during file writes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: The write_file tool corrupts or truncates long text sequences during file writes\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 22. 配置坑 · 失败模式：configuration: Tracking: 429 / Capacity Issues\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Tracking: 429 / Capacity Issues\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Tracking: 429 / Capacity Issues\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tracking: 429 / Capacity Issues. Context: Observed during installation or first-run setup.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a6143043d54543ab2db0b094ce75112 | https://github.com/google-gemini/gemini-cli/issues/24937 | Tracking: 429 / Capacity Issues\n\n## 23. 配置坑 · 失败模式：configuration: Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 24. 配置坑 · 失败模式：configuration: YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: YOLO mode should override block of command-substitution in bash\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: YOLO mode should override block of command-substitution in bash\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 25. 配置坑 · 失败模式：configuration: [Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug] Proxy local bypass does not recognize environment variables\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 26. 配置坑 · 失败模式：configuration: fata error again!\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: fata error again!\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: fata error again!\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: fata error again!. Context: Observed when using linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7aa1a144aa2c7dbf177ed2e61f9c1bf4 | https://github.com/google-gemini/gemini-cli/issues/27084 | fata error again!\n\n## 27. 配置坑 · 来源证据：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47cc7af8a64b46f98a999ac7e6a42ab8 | https://github.com/google-gemini/gemini-cli/issues/25164 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 28. 能力坑 · 社区讨论暴露的待验证问题：Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：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\n\n## 29. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | README/documentation is current enough for a first validation pass.\n\n## 30. 维护坑 · 来源证据：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b6fd46e95c92462b8893c41314dc2cb9 | https://github.com/google-gemini/gemini-cli/issues/21421 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 31. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | last_activity_observed missing\n\n## 32. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 33. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 来源证据：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a69b38f144734c1c96d81d75610a66a1 | https://github.com/google-gemini/gemini-cli/issues/27192 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 35. 安全/权限坑 · 来源证据：The Gemini CLI interface keeps flickering\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The Gemini CLI interface keeps flickering\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364c1744ad1c4dc79881a9ab22c7305b | https://github.com/google-gemini/gemini-cli/issues/14708 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47b14e4e29a548d59ea09e120401bd88 | https://github.com/google-gemini/gemini-cli/issues/21686 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 37. 安全/权限坑 · 来源证据：YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：YOLO mode should override block of command-substitution in bash\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_adf70ddf872342c08ce46daccf869dba | https://github.com/google-gemini/gemini-cli/issues/6436 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 38. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | issue_or_pr_quality=unknown\n\n## 39. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | release_recency=unknown\n\n<!-- canonical_name: google-gemini/gemini-cli; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：google-gemini/gemini-cli\n\n摘要：发现 39 个潜在踩坑项，其中 11 个为 high/blocking；最高优先级：安装坑 - 来源证据：MCP servers not connected in -p (non-interactive) mode。\n\n## 1. 安装坑 · 来源证据：MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b804d980e70041d494afeafb3b4e53e1 | https://github.com/google-gemini/gemini-cli/issues/26021 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 2. 运行坑 · 来源证据：Stabilize and Enhance Internal Project Evaluations\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Stabilize and Enhance Internal Project Evaluations\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_956e395bc08348c5a7d5271a26c7c3d3 | https://github.com/google-gemini/gemini-cli/issues/23166 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 安全/权限坑 · 失败模式：security_permissions: Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Add deterministic redaction and reduce Auto Memory logging\n- 建议检查：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\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_aad664537e9ef9632034c0b355326a33 | https://github.com/google-gemini/gemini-cli/issues/26525 | Add deterministic redaction and reduce Auto Memory logging\n\n## 4. 安全/权限坑 · 失败模式：security_permissions: Robust component level evalutions\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: Robust component level evalutions\n- 对用户的影响：Developers may expose sensitive permissions or credentials: Robust component level evalutions\n- 建议检查：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.\n- 防护动作：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\n- 证据：failure_mode_cluster:github_issue | fmev_6de3f9226413accc4a19c695e4fdeb48 | https://github.com/google-gemini/gemini-cli/issues/24353 | Robust component level evalutions\n\n## 5. 安全/权限坑 · 来源证据：Add deterministic redaction and reduce Auto Memory logging\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add deterministic redaction and reduce Auto Memory logging\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5d4c1c695f4a4461b02d345ad871eee8 | https://github.com/google-gemini/gemini-cli/issues/26525 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Assess the impact of AST-aware file reads, search, and mapping\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Assess the impact of AST-aware file reads, search, and mapping\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eb8ea29736be4a9bb9d06da0f795e211 | https://github.com/google-gemini/gemini-cli/issues/22745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 安全/权限坑 · 来源证据：Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c39c655f9cb493b882742836ffcd22b | https://github.com/google-gemini/gemini-cli/issues/16114 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 8. 安全/权限坑 · 来源证据：Shell command execution gets stuck with \"Waiting input\" after command completes\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Shell command execution gets stuck with \"Waiting input\" after command completes\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_95f7bea3f2174e39a3a23c6529ea04d7 | https://github.com/google-gemini/gemini-cli/issues/25166 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. 安全/权限坑 · 来源证据：Tracking: 429 / Capacity Issues\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tracking: 429 / Capacity Issues\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e4866d4ab82a4b4ab8825ce37ba23de6 | https://github.com/google-gemini/gemini-cli/issues/24937 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 10. 安全/权限坑 · 来源证据：[Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab66f1b2c2ec486386365fb0cb4d100e | https://github.com/google-gemini/gemini-cli/issues/23372 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 11. 安全/权限坑 · 来源证据：fata error again!\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：fata error again!\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6345aa3da845458888c6e250cd950be0 | https://github.com/google-gemini/gemini-cli/issues/27084 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. 安装坑 · 失败模式：installation: The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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\n- 对用户的影响：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\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 13. 安装坑 · 来源证据：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[☀️ Google Summer Of Code ] Terminal-Integrated Performance & Memory Investigation Companion\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d81ba1a5c929402ba842a14ce13fa62d | https://github.com/google-gemini/gemini-cli/issues/23365 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 配置坑 · 失败模式：configuration: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GEMINI CLI aggressively scans .venv in custom skills (ignores .gitignore / .geminiignore)\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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)\n\n## 15. 配置坑 · 失败模式：configuration: GeminiCLI.com Feedback: [ISSUE]\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: GeminiCLI.com Feedback: [ISSUE]\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: GeminiCLI.com Feedback: [ISSUE]\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_b159ada1eb969fa31659644535ca2fea | https://github.com/google-gemini/gemini-cli/issues/27206 | GeminiCLI.com Feedback: [ISSUE]\n\n## 16. 配置坑 · 失败模式：configuration: MCP servers not connected in -p (non-interactive) mode\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: MCP servers not connected in -p (non-interactive) mode\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: MCP servers not connected in -p (non-interactive) mode\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 17. 配置坑 · 失败模式：configuration: Missing validation for critical configuration files could lead to broken bundles\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Missing validation for critical configuration files could lead to broken bundles\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Missing validation for critical configuration files could lead to broken bundles\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 18. 配置坑 · 失败模式：configuration: SLOW Response and Usage limits stop gemini CLI. = unusable\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: SLOW Response and Usage limits stop gemini CLI. = unusable\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 19. 配置坑 · 失败模式：configuration: Stop Auto Memory from retrying low-signal sessions indefinitely\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Stop Auto Memory from retrying low-signal sessions indefinitely\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 20. 配置坑 · 失败模式：configuration: Surface or quarantine invalid Auto Memory inbox patches\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Surface or quarantine invalid Auto Memory inbox patches\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Surface or quarantine invalid Auto Memory inbox patches\n- 建议检查：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.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e7ea4760266f8df60623eea9a521182c | https://github.com/google-gemini/gemini-cli/issues/26523 | Surface or quarantine invalid Auto Memory inbox patches\n\n## 21. 配置坑 · 失败模式：configuration: The write_file tool corrupts or truncates long text sequences during file writes\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: The write_file tool corrupts or truncates long text sequences during file writes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: The write_file tool corrupts or truncates long text sequences during file writes\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 22. 配置坑 · 失败模式：configuration: Tracking: 429 / Capacity Issues\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Tracking: 429 / Capacity Issues\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Tracking: 429 / Capacity Issues\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tracking: 429 / Capacity Issues. Context: Observed during installation or first-run setup.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a6143043d54543ab2db0b094ce75112 | https://github.com/google-gemini/gemini-cli/issues/24937 | Tracking: 429 / Capacity Issues\n\n## 23. 配置坑 · 失败模式：configuration: Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 24. 配置坑 · 失败模式：configuration: YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: YOLO mode should override block of command-substitution in bash\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: YOLO mode should override block of command-substitution in bash\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 25. 配置坑 · 失败模式：configuration: [Bug] Proxy local bypass does not recognize environment variables\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug] Proxy local bypass does not recognize environment variables\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug] Proxy local bypass does not recognize environment variables\n- 建议检查：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\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：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\n\n## 26. 配置坑 · 失败模式：configuration: fata error again!\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: fata error again!\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: fata error again!\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: fata error again!. Context: Observed when using linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7aa1a144aa2c7dbf177ed2e61f9c1bf4 | https://github.com/google-gemini/gemini-cli/issues/27084 | fata error again!\n\n## 27. 配置坑 · 来源证据：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Windows] run_shell_command always returns empty output — isBinary() false-positive on node-pty PTY stream\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47cc7af8a64b46f98a999ac7e6a42ab8 | https://github.com/google-gemini/gemini-cli/issues/25164 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 28. 能力坑 · 社区讨论暴露的待验证问题：Open Source Claude Coder alternative? : r/LocalLLaMA - Reddit\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：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\n\n## 29. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | README/documentation is current enough for a first validation pass.\n\n## 30. 维护坑 · 来源证据：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Gemini CLI should periodically reflect on the trajectory and recommend the creation or update of skills\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b6fd46e95c92462b8893c41314dc2cb9 | https://github.com/google-gemini/gemini-cli/issues/21421 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 31. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | last_activity_observed missing\n\n## 32. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 33. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 来源证据：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The CLI doesn't fall back to the system's ripgrep installation when the bundled one is missing\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a69b38f144734c1c96d81d75610a66a1 | https://github.com/google-gemini/gemini-cli/issues/27192 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 35. 安全/权限坑 · 来源证据：The Gemini CLI interface keeps flickering\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：The Gemini CLI interface keeps flickering\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364c1744ad1c4dc79881a9ab22c7305b | https://github.com/google-gemini/gemini-cli/issues/14708 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：Typing unmapped keys in Vim Normal mode inserts characters into input field\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Typing unmapped keys in Vim Normal mode inserts characters into input field\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47b14e4e29a548d59ea09e120401bd88 | https://github.com/google-gemini/gemini-cli/issues/21686 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 37. 安全/权限坑 · 来源证据：YOLO mode should override block of command-substitution in bash\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：YOLO mode should override block of command-substitution in bash\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_adf70ddf872342c08ce46daccf869dba | https://github.com/google-gemini/gemini-cli/issues/6436 | 来源讨论提到 linux 相关条件，需在安装/试用前复核。\n\n## 38. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | issue_or_pr_quality=unknown\n\n## 39. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:968197216 | https://github.com/google-gemini/gemini-cli | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# gemini-cli - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for google-gemini/gemini-cli.\n\nProject:\n- Name: gemini-cli\n- Repository: https://github.com/google-gemini/gemini-cli\n- Summary: An open-source AI agent that brings the power of Gemini directly into your terminal.\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: An open-source AI agent that brings the power of Gemini directly into your terminal.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n2. agent-system: Agent System. Produce one small intermediate artifact and wait for confirmation.\n3. context-pipeline: Context and Memory Management. Produce one small intermediate artifact and wait for confirmation.\n4. tools-reference: Tools Reference. Produce one small intermediate artifact and wait for confirmation.\n5. sandboxing-security: Sandboxing and Security. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/google-gemini/gemini-cli\n- https://github.com/google-gemini/gemini-cli#readme\n- .gemini/skills/async-pr-review/SKILL.md\n- .gemini/skills/behavioral-evals/SKILL.md\n- .gemini/skills/ci/SKILL.md\n- .gemini/skills/code-reviewer/SKILL.md\n- .gemini/skills/docs-changelog/SKILL.md\n- .gemini/skills/docs-writer/SKILL.md\n- .gemini/skills/github-issue-creator/SKILL.md\n- .gemini/skills/pr-address-comments/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：google-gemini/gemini-cli\n\n## 官方安装入口\n\n### Gemini CLI · 官方安装入口\n\n```bash\nnpx @google/gemini-cli\n```\n\n来源：https://github.com/google-gemini/gemini-cli#readme\n\n## 来源\n\n- repo: https://github.com/google-gemini/gemini-cli\n- docs: https://github.com/google-gemini/gemini-cli#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_db8319d8d7e54841875a82b94e0be05e"
}
