Compare commits

...

25 Commits

Author SHA1 Message Date
Sam Roberts 98b3d6f47d Update installation.md 2026-03-19 19:58:14 -07:00
Sam Roberts bb85e970f3 Merge branch 'main' into overview-redo 2026-03-19 19:57:24 -07:00
Gaurav 8615315711 feat(core): add support for admin-forced MCP server installations (#23163) 2026-03-19 22:32:43 +00:00
matt korwel c9a336976b feat(core): implement native Windows sandboxing (#21807) 2026-03-19 22:25:22 +00:00
kevinjwang1 06a7873c51 Add ModelChain support to ModelConfigService and make ModelDialog dynamic (#22914) 2026-03-19 22:22:26 +00:00
kevinjwang1 0e66f545ca Ensure that copied extensions are writable in the user's local directory (#23016) 2026-03-19 22:22:08 +00:00
ruomeng 98d1bec99f fix(plan): clarify that plan mode policies are combined with normal mode (#23158) 2026-03-19 21:51:10 +00:00
Sri Pasumarthi 08063d7b0a feat: ACP: Add token usage metadata to the send method's return value (#23148) 2026-03-19 21:49:50 +00:00
Sam Roberts 2ebcd48a4e Update callouts to work on github. (#22245) 2026-03-19 21:11:14 +00:00
Sri Pasumarthi 36dbaa8462 fix: upgrade ACP SDK from 0.12 to 0.16.1 (#23132) 2026-03-19 21:02:33 +00:00
Sam Roberts 4fc059beb5 Update website issue template for label and title (#23036) 2026-03-19 20:51:16 +00:00
gemini-cli-robot 46ec71bf0e Changelog for v0.35.0-preview.2 (#23142)
Co-authored-by: gemini-cli-robot <224641728+gemini-cli-robot@users.noreply.github.com>
2026-03-19 19:43:48 +00:00
Sandy Tao 33f630111f feat(core): add experimental memory manager agent to replace save_memory tool (#22726)
Co-authored-by: Christian Gunderman <gundermanc@gmail.com>
2026-03-19 12:57:52 -07:00
Sam Roberts b3ebab308e Docs: Minor style updates from initial docs audit. (#22872)
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Jenna Inouye <jinouye@google.com>
2026-03-19 19:33:58 +00:00
Sandy Tao 4e5dfd0cb7 feat(core): cap JIT context upward traversal at git root (#23074) 2026-03-19 17:50:58 +00:00
Jacob Richman 524b1e39a5 Fix logging and virtual list. (#23080) 2026-03-19 17:50:49 +00:00
Abhi 32a123fc54 feat(core): inject memory and JIT context into subagents (#23032) 2026-03-19 17:16:09 +00:00
Tommaso Sciortino 23264ced9a refactor(cli): integrate real config loading into async test utils (#23040) 2026-03-19 17:05:33 +00:00
cynthialong0-0 7de0616229 fix(browser-agent): enable "Allow all server tools" session policy (#22343) 2026-03-19 16:32:35 +00:00
joshualitt 39d3b0e28c feat(cli): Partial threading of AgentLoopContext. (#22978) 2026-03-19 16:02:13 +00:00
Gaurav 5acaacad96 fix(core): narrow browser agent description to prevent stealing URL tasks from web_fetch (#23086) 2026-03-19 10:45:59 +00:00
Jason Matthew Suhari a921bcd9ef fix(core): don't persist browser consent sentinel in non-interactive mode (#23073) 2026-03-19 06:47:13 +00:00
g-samroberts c02effc0cf Fix link. 2026-03-17 18:05:09 -07:00
g-samroberts ec43305d2d Update overview to be a real overview instead of
a TOC.
2026-03-17 18:00:31 -07:00
g-samroberts 4983053ae3 Minor changes from the initial docs audit. 2026-03-17 17:51:50 -07:00
300 changed files with 7387 additions and 2622 deletions
+2 -1
View File
@@ -2,7 +2,8 @@
"experimental": {
"plan": true,
"extensionReloading": true,
"modelSteering": true
"modelSteering": true,
"memoryManager": true
},
"general": {
"devtools": true
+35 -4
View File
@@ -71,12 +71,44 @@ accessible.
tables).
- **Media:** Use lowercase hyphenated filenames. Provide descriptive alt text
for all images.
- **Details section:** Use the `<details>` tag to create a collapsible section.
This is useful for supplementary or data-heavy information that isn't critical
to the main flow.
Example:
<details>
<summary>Title</summary>
- First entry
- Second entry
</details>
- **Callouts**: Use GitHub-flavored markdown alerts to highlight important
information. To ensure the formatting is preserved by `npm run format`, place
an empty line, then the `<!-- prettier-ignore -->` comment directly before
the callout block. The callout type (`[!TYPE]`) should be on the first line,
followed by a newline, and then the content, with each subsequent line of
content starting with `>`. Available types are `NOTE`, `TIP`, `IMPORTANT`,
`WARNING`, and `CAUTION`.
Example:
<!-- prettier-ignore -->
> [!NOTE]
> This is an example of a multi-line note that will be preserved
> by Prettier.
### Structure
- **BLUF:** Start with an introduction explaining what to expect.
- **Experimental features:** If a feature is clearly noted as experimental,
add the following note immediately after the introductory paragraph:
`> **Note:** This is a preview feature currently under active development.`
add the following note immediately after the introductory paragraph:
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development.
- **Headings:** Use hierarchical headings to support the user journey.
- **Procedures:**
- Introduce lists of steps with a complete sentence.
@@ -85,8 +117,7 @@ add the following note immediately after the introductory paragraph:
- Put conditions before instructions (e.g., "On the Settings page, click...").
- Provide clear context for where the action takes place.
- Indicate optional steps clearly (e.g., "Optional: ...").
- **Elements:** Use bullet lists, tables, notes (`> **Note:**`), and warnings
(`> **Warning:**`).
- **Elements:** Use bullet lists, tables, details, and callouts.
- **Avoid using a table of contents:** If a table of contents is present, remove
it.
- **Next steps:** Conclude with a "Next steps" section if applicable.
+1
View File
@@ -0,0 +1 @@
packages/core/src/services/scripts/*.exe
+2
View File
@@ -1,7 +1,9 @@
name: 'Website issue'
description: 'Report an issue with the Gemini CLI Website and Gemini CLI Extensions Gallery'
title: 'GeminiCLI.com Feedback: [ISSUE]'
labels:
- 'area/extensions'
- 'area/documentation'
body:
- type: 'markdown'
attributes:
+61
View File
@@ -106,6 +106,67 @@ organization.
ensures users maintain final control over which permitted servers are actually
active in their environment.
#### Required MCP Servers (preview)
**Default**: empty
Allows administrators to define MCP servers that are **always injected** into
the user's environment. Unlike the allowlist (which filters user-configured
servers), required servers are automatically added regardless of the user's
local configuration.
**Required Servers Format:**
```json
{
"requiredMcpServers": {
"corp-compliance-tool": {
"url": "https://mcp.corp/compliance",
"type": "http",
"trust": true,
"description": "Corporate compliance tool"
},
"internal-registry": {
"url": "https://registry.corp/mcp",
"type": "sse",
"authProviderType": "google_credentials",
"oauth": {
"scopes": ["https://www.googleapis.com/auth/scope"]
}
}
}
}
```
**Supported Fields:**
- `url`: (Required) The full URL of the MCP server endpoint.
- `type`: (Required) The connection type (`sse` or `http`).
- `trust`: (Optional) If set to `true`, tool execution will not require user
approval. Defaults to `true` for required servers.
- `description`: (Optional) Human-readable description of the server.
- `authProviderType`: (Optional) Authentication provider (`dynamic_discovery`,
`google_credentials`, or `service_account_impersonation`).
- `oauth`: (Optional) OAuth configuration including `scopes`, `clientId`, and
`clientSecret`.
- `targetAudience`: (Optional) OAuth target audience for service-to-service
auth.
- `targetServiceAccount`: (Optional) Service account email to impersonate.
- `headers`: (Optional) Additional HTTP headers to send with requests.
- `includeTools` / `excludeTools`: (Optional) Tool filtering lists.
- `timeout`: (Optional) Timeout in milliseconds for MCP requests.
**Client Enforcement Logic:**
- Required servers are injected **after** allowlist filtering, so they are
always available even if the allowlist is active.
- If a required server has the **same name** as a locally configured server, the
admin configuration **completely overrides** the local one.
- Required servers only support remote transports (`sse`, `http`). Local
execution fields (`command`, `args`, `env`, `cwd`) are not supported.
- Required servers can coexist with allowlisted servers — both features work
independently.
### Unmanaged Capabilities
**Enabled/Disabled** | Default: disabled
+7 -3
View File
@@ -1,6 +1,6 @@
# Preview release: v0.35.0-preview.1
# Preview release: v0.35.0-preview.2
Released: March 17, 2026
Released: March 19, 2026
Our preview release includes the latest, new, and experimental features. This
release may not be as stable as our [latest weekly release](latest.md).
@@ -33,6 +33,10 @@ npm install -g @google/gemini-cli@preview
## What's Changed
- fix(patch): cherry-pick 4e5dfd0 to release/v0.35.0-preview.1-pr-23074 to patch
version v0.35.0-preview.1 and create version 0.35.0-preview.2 by
@gemini-cli-robot in
[#23134](https://github.com/google-gemini/gemini-cli/pull/23134)
- feat(cli): customizable keyboard shortcuts by @scidomino in
[#21945](https://github.com/google-gemini/gemini-cli/pull/21945)
- feat(core): Thread `AgentLoopContext` through core. by @joshualitt in
@@ -373,4 +377,4 @@ npm install -g @google/gemini-cli@preview
[#22815](https://github.com/google-gemini/gemini-cli/pull/22815)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.34.0-preview.4...v0.35.0-preview.1
https://github.com/google-gemini/gemini-cli/compare/v0.34.0-preview.4...v0.35.0-preview.2
+3 -1
View File
@@ -39,7 +39,9 @@ file in your project's temporary directory, typically located at
The Checkpointing feature is disabled by default. To enable it, you need to edit
your `settings.json` file.
> **Note:** The `--checkpointing` command-line flag was removed in version
<!-- prettier-ignore -->
> [!CAUTION]
> The `--checkpointing` command-line flag was removed in version
> 0.11.0. Checkpointing can now only be enabled through the `settings.json`
> configuration file.
+7 -5
View File
@@ -30,7 +30,9 @@ separator (`/` or `\`) being converted to a colon (`:`).
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced
command `/git:commit`.
> [!TIP] After creating or modifying `.toml` command files, run
<!-- prettier-ignore -->
> [!TIP]
> After creating or modifying `.toml` command files, run
> `/commands reload` to pick up your changes without restarting the CLI.
## TOML file format (v1)
@@ -177,10 +179,10 @@ ensure that only intended commands can be run.
automatically shell-escaped (see
[Context-Aware Injection](#1-context-aware-injection-with-args) above).
3. **Robust parsing:** The parser correctly handles complex shell commands that
include nested braces, such as JSON payloads. **Note:** The content inside
`!{...}` must have balanced braces (`{` and `}`). If you need to execute a
command containing unbalanced braces, consider wrapping it in an external
script file and calling the script within the `!{...}` block.
include nested braces, such as JSON payloads. The content inside `!{...}`
must have balanced braces (`{` and `}`). If you need to execute a command
containing unbalanced braces, consider wrapping it in an external script
file and calling the script within the `!{...}` block.
4. **Security check and confirmation:** The CLI performs a security check on
the final, resolved command (after arguments are escaped and substituted). A
dialog will appear showing the exact command(s) to be executed.
+15 -9
View File
@@ -5,9 +5,11 @@ and managing Gemini CLI in an enterprise environment. By leveraging system-level
settings, administrators can enforce security policies, manage tool access, and
ensure a consistent experience for all users.
> **A note on security:** The patterns described in this document are intended
> to help administrators create a more controlled and secure environment for
> using Gemini CLI. However, they should not be considered a foolproof security
<!-- prettier-ignore -->
> [!WARNING]
> The patterns described in this document are intended to help
> administrators create a more controlled and secure environment for using
> Gemini CLI. However, they should not be considered a foolproof security
> boundary. A determined user with sufficient privileges on their local machine
> may still be able to circumvent these configurations. These measures are
> designed to prevent accidental misuse and enforce corporate policy in a
@@ -280,10 +282,12 @@ environment to a blocklist.
}
```
**Security note:** Blocklisting with `excludeTools` is less secure than
allowlisting with `coreTools`, as it relies on blocking known-bad commands, and
clever users may find ways to bypass simple string-based blocks. **Allowlisting
is the recommended approach.**
<!-- prettier-ignore -->
> [!WARNING]
> Blocklisting with `excludeTools` is less secure than
> allowlisting with `coreTools`, as it relies on blocking known-bad commands,
> and clever users may find ways to bypass simple string-based blocks.
> **Allowlisting is the recommended approach.**
### Disabling YOLO mode
@@ -494,8 +498,10 @@ other events. For more information, see the
}
```
**Note:** Ensure that `logPrompts` is set to `false` in an enterprise setting to
avoid collecting potentially sensitive information from user prompts.
<!-- prettier-ignore -->
> [!NOTE]
> Ensure that `logPrompts` is set to `false` in an enterprise setting to
> avoid collecting potentially sensitive information from user prompts.
## Authentication
+4 -3
View File
@@ -4,9 +4,10 @@ Model steering lets you provide real-time guidance and feedback to Gemini CLI
while it is actively executing a task. This lets you correct course, add missing
context, or skip unnecessary steps without having to stop and restart the agent.
> **Note:** This is a preview feature under active development. Preview features
> may only be available in the **Preview** channel or may need to be enabled
> under `/settings`.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
Model steering is particularly useful during complex [Plan Mode](./plan-mode.md)
workflows or long-running subagent executions where you want to ensure the agent
+3 -1
View File
@@ -5,7 +5,9 @@ used by Gemini CLI, giving you more control over your results. Use **Pro**
models for complex tasks and reasoning, **Flash** models for high speed results,
or the (recommended) **Auto** setting to choose the best model for your tasks.
> **Note:** The `/model` command (and the `--model` flag) does not override the
<!-- prettier-ignore -->
> [!NOTE]
> The `/model` command (and the `--model` flag) does not override the
> model used by sub-agents. Consequently, even when using the `/model` flag you
> may see other models used in your model usage reports.
+4 -3
View File
@@ -4,9 +4,10 @@ Gemini CLI can send system notifications to alert you when a session completes
or when it needs your attention, such as when it's waiting for you to approve a
tool call.
> **Note:** This is a preview feature currently under active development.
> Preview features may be available on the **Preview** channel or may need to be
> enabled under `/settings`.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
Notifications are particularly useful when running long-running tasks or using
[Plan Mode](./plan-mode.md), letting you switch to other windows while Gemini
+8 -8
View File
@@ -35,19 +35,17 @@ To launch Gemini CLI in Plan Mode once:
To start Plan Mode while using Gemini CLI:
- **Keyboard shortcut:** Press `Shift+Tab` to cycle through approval modes
(`Default` -> `Auto-Edit` -> `Plan`).
> **Note:** Plan Mode is automatically removed from the rotation when Gemini
> CLI is actively processing or showing confirmation dialogs.
(`Default` -> `Auto-Edit` -> `Plan`). Plan Mode is automatically removed from
the rotation when Gemini CLI is actively processing or showing confirmation
dialogs.
- **Command:** Type `/plan` in the input box.
- **Natural Language:** Ask Gemini CLI to "start a plan for...". Gemini CLI
calls the
[`enter_plan_mode`](../tools/planning.md#1-enter_plan_mode-enterplanmode) tool
to switch modes.
> **Note:** This tool is not available when Gemini CLI is in
> [YOLO mode](../reference/configuration.md#command-line-arguments).
to switch modes. This tool is not available when Gemini CLI is in
[YOLO mode](../reference/configuration.md#command-line-arguments).
## How to use Plan Mode
@@ -407,7 +405,9 @@ To build a custom planning workflow, you can use:
[custom plan directories](#custom-plan-directory-and-policies) and
[custom policies](#custom-policies).
> **Note:** Use [Conductor] as a reference when building your own custom
<!-- prettier-ignore -->
> [!TIP]
> Use [Conductor] as a reference when building your own custom
> planning workflow.
By using Plan Mode as its execution environment, your custom methodology can
+24 -4
View File
@@ -50,7 +50,25 @@ Cross-platform sandboxing with complete process isolation.
**Note**: Requires building the sandbox image locally or using a published image
from your organization's registry.
### 3. gVisor / runsc (Linux only)
### 3. Windows Native Sandbox (Windows only)
... **Troubleshooting and Side Effects:**
The Windows Native sandbox uses the `icacls` command to set a "Low Mandatory
Level" on files and directories it needs to write to.
- **Persistence**: These integrity level changes are persistent on the
filesystem. Even after the sandbox session ends, files created or modified by
the sandbox will retain their "Low" integrity level.
- **Manual Reset**: If you need to reset the integrity level of a file or
directory, you can use:
```powershell
icacls "C:\path\to\dir" /setintegritylevel Medium
```
- **System Folders**: The sandbox manager automatically skips setting integrity
levels on system folders (like `C:\Windows`) for safety.
### 4. gVisor / runsc (Linux only)
Strongest isolation available: runs containers inside a user-space kernel via
[gVisor](https://github.com/google/gvisor). gVisor intercepts all container
@@ -253,9 +271,11 @@ $env:SANDBOX_SET_UID_GID="false" # Disable UID/GID mapping
DEBUG=1 gemini -s -p "debug command"
```
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect
gemini-cli due to automatic exclusion. Use `.gemini/.env` files for gemini-cli
specific debug settings.
<!-- prettier-ignore -->
> [!NOTE]
> If you have `DEBUG=true` in a project's `.env` file, it won't affect
> gemini-cli due to automatic exclusion. Use `.gemini/.env` files for
> gemini-cli specific debug settings.
### Inspect sandbox
+6 -1
View File
@@ -11,7 +11,9 @@ locations:
- **User settings**: `~/.gemini/settings.json`
- **Workspace settings**: `your-project/.gemini/settings.json`
Note: Workspace settings override user settings.
<!-- prettier-ignore -->
> [!IMPORTANT]
> Workspace settings override user settings.
## Settings reference
@@ -115,6 +117,8 @@ they appear in the UI.
| UI Label | Setting | Description | Default |
| -------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Sandbox Allowed Paths | `tools.sandboxAllowedPaths` | List of additional paths that the sandbox is allowed to access. | `[]` |
| Sandbox Network Access | `tools.sandboxNetworkAccess` | Whether the sandbox is allowed to access the network. | `false` |
| Enable Interactive Shell | `tools.shell.enableInteractiveShell` | Use node-pty for an interactive shell experience. Fallback to child_process still applies. | `true` |
| Show Color | `tools.shell.showColor` | Show color in shell output. | `false` |
| Use Ripgrep | `tools.useRipgrep` | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` |
@@ -152,6 +156,7 @@ they appear in the UI.
| Plan | `experimental.plan` | Enable Plan Mode. | `true` |
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
| Memory Manager Agent | `experimental.memoryManager` | Replace the built-in save_memory tool with a memory manager subagent that supports adding, removing, de-duplicating, and organizing memories. | `false` |
| Topic & Update Narration | `experimental.topicUpdateNarration` | Enable the experimental Topic & Update communication model for reduced chattiness and structured progress reporting. | `false` |
### Skills
+4 -2
View File
@@ -63,8 +63,10 @@ Use the `/skills` slash command to view and manage available expertise:
- `/skills enable <name>`: Re-enables a disabled skill.
- `/skills reload`: Refreshes the list of discovered skills from all tiers.
_Note: `/skills disable` and `/skills enable` default to the `user` scope. Use
`--scope workspace` to manage workspace-specific settings._
<!-- prettier-ignore -->
> [!NOTE]
> `/skills disable` and `/skills enable` default to the `user` scope. Use
> `--scope workspace` to manage workspace-specific settings.
### From the Terminal
+3 -1
View File
@@ -14,7 +14,9 @@ core instructions will apply unless you include them yourself.
This feature is intended for advanced users who need to enforce strict,
project-specific behavior or create a customized persona.
> Tip: You can export the current default system prompt to a file first, review
<!-- prettier-ignore -->
> [!TIP]
> You can export the current default system prompt to a file first, review
> it, and then selectively modify or replace it (see
> [“Export the default prompt”](#export-the-default-prompt-recommended)).
+5 -3
View File
@@ -125,9 +125,11 @@ You must complete several setup steps before enabling Google Cloud telemetry.
}
```
> **Note:** This setting requires **Direct export** (in-process exporters)
> and cannot be used when `useCollector` is `true`. If both are enabled,
> telemetry will be disabled.
<!-- prettier-ignore -->
> [!NOTE]
> This setting requires **Direct export** (in-process exporters)
> and cannot be used when `useCollector` is `true`. If both are enabled,
> telemetry will be disabled.
3. Ensure your account or service account has these IAM roles:
- Cloud Trace Agent
+12 -8
View File
@@ -36,9 +36,11 @@ using the `/theme` command within Gemini CLI:
preview or highlight as you select.
4. Confirm your selection to apply the theme.
**Note:** If a theme is defined in your `settings.json` file (either by name or
by a file path), you must remove the `"theme"` setting from the file before you
can change the theme using the `/theme` command.
<!-- prettier-ignore -->
> [!NOTE]
> If a theme is defined in your `settings.json` file (either by name or
> by a file path), you must remove the `"theme"` setting from the file before
> you can change the theme using the `/theme` command.
### Theme persistence
@@ -179,11 +181,13 @@ custom theme defined in `settings.json`.
}
```
**Security note:** For your safety, Gemini CLI will only load theme files that
are located within your home directory. If you attempt to load a theme from
outside your home directory, a warning will be displayed and the theme will not
be loaded. This is to prevent loading potentially malicious theme files from
untrusted sources.
<!-- prettier-ignore -->
> [!WARNING]
> For your safety, Gemini CLI will only load theme files that
> are located within your home directory. If you attempt to load a theme from
> outside your home directory, a warning will be displayed and the theme will
> not be loaded. This is to prevent loading potentially malicious theme files
> from untrusted sources.
### Example custom theme
+8 -6
View File
@@ -7,9 +7,9 @@ create files, and control what Gemini CLI can see.
## Prerequisites
- Gemini CLI installed and authenticated.
- A project directory to work with (e.g., a git repository).
- A project directory to work with (for example, a git repository).
## How to give the agent context (Reading files)
## Providing context by reading files
Gemini CLI will generally try to read relevant files, sometimes prompting you
for access (depending on your settings). To ensure that Gemini CLI uses a file,
@@ -58,11 +58,13 @@ You know there's a `UserProfile` component, but you don't know where it lives.
```
Gemini uses the `glob` or `list_directory` tools to search your project
structure. It will return the specific path (e.g.,
structure. It will return the specific path (for example,
`src/components/UserProfile.tsx`), which you can then use with `@` in your next
turn.
> **Tip:** You can also ask for lists of files, like "Show me all the TypeScript
<!-- prettier-ignore -->
> [!TIP]
> You can also ask for lists of files, like "Show me all the TypeScript
> configuration files in the root directory."
## How to modify code
@@ -111,8 +113,8 @@ or, better yet, run your project's tests.
`Run the tests for the UserProfile component.`
```
Gemini CLI uses the `run_shell_command` tool to execute your test runner (e.g.,
`npm test` or `jest`). This ensures the changes didn't break existing
Gemini CLI uses the `run_shell_command` tool to execute your test runner (for
example, `npm test` or `jest`). This ensures the changes didn't break existing
functionality.
## Advanced: Controlling what Gemini sees
+4 -2
View File
@@ -62,8 +62,10 @@ You tell Gemini about new servers by editing your `settings.json`.
}
```
> **Note:** The `command` is `docker`, and the rest are arguments passed to it.
> We map the local environment variable into the container so your secret isn't
<!-- prettier-ignore -->
> [!NOTE]
> The `command` is `docker`, and the rest are arguments passed to it. We
> map the local environment variable into the container so your secret isn't
> hardcoded in the config file.
## How to verify the connection
+6 -6
View File
@@ -11,8 +11,8 @@ persistent facts, and inspect the active context.
## Why manage context?
Out of the box, Gemini CLI is smart but generic. It doesn't know your preferred
testing framework, your indentation style, or that you hate using `any` in
Gemini CLI is powerful but general. It doesn't know your preferred testing
framework, your indentation style, or your preference against `any` in
TypeScript. Context management solves this by giving the agent persistent
memory.
@@ -109,11 +109,11 @@ immediately. Force a reload with:
## Best practices
- **Keep it focused:** Don't dump your entire internal wiki into `GEMINI.md`.
Keep instructions actionable and relevant to code generation.
- **Keep it focused:** Avoid adding excessive content to `GEMINI.md`. Keep
instructions actionable and relevant to code generation.
- **Use negative constraints:** Explicitly telling the agent what _not_ to do
(e.g., "Do not use class components") is often more effective than vague
positive instructions.
(for example, "Do not use class components") is often more effective than
vague positive instructions.
- **Review often:** Periodically check your `GEMINI.md` files to remove outdated
rules.
+4 -3
View File
@@ -5,9 +5,10 @@ structured environment with model steering's real-time feedback, you can guide
Gemini CLI through the research and design phases to ensure the final
implementation plan is exactly what you need.
> **Note:** This is a preview feature under active development. Preview features
> may only be available in the **Preview** channel or may need to be enabled
> under `/settings`.
<!-- prettier-ignore -->
> [!NOTE]
> This is an experimental feature currently under active development and
> may need to be enabled under `/settings`.
## Prerequisites
+3 -3
View File
@@ -7,7 +7,7 @@ automate complex workflows, and manage background processes safely.
## Prerequisites
- Gemini CLI installed and authenticated.
- Basic familiarity with your system's shell (Bash, Zsh, PowerShell, etc.).
- Basic familiarity with your system's shell (Bash, Zsh, PowerShell, and so on).
## How to run commands directly (`!`)
@@ -49,7 +49,7 @@ You want to run tests and fix any failures.
6. Gemini uses `replace` to fix the bug.
7. Gemini runs `npm test` again to verify the fix.
This loop turns Gemini into an autonomous engineer.
This loop lets Gemini work autonomously.
## How to manage background processes
@@ -75,7 +75,7 @@ confirmation prompts) by streaming the output to you. However, for highly
interactive tools (like `vim` or `top`), it's often better to run them yourself
in a separate terminal window or use the `!` prefix.
## Safety first
## Safety features
Giving an AI access to your shell is powerful but risky. Gemini CLI includes
several safety layers.
+8 -3
View File
@@ -10,7 +10,9 @@ agents in the following repositories:
- [ADK Samples (Python)](https://github.com/google/adk-samples/tree/main/python)
- [ADK Python Contributing Samples](https://github.com/google/adk-python/tree/main/contributing/samples)
> **Note: Remote subagents are currently an experimental feature.**
<!-- prettier-ignore -->
> [!NOTE]
> Remote subagents are currently an experimental feature.
## Configuration
@@ -82,7 +84,8 @@ Markdown file.
---
```
> **Note:** Mixed local and remote agents, or multiple local agents, are not
<!-- prettier-ignore -->
> [!NOTE] Mixed local and remote agents, or multiple local agents, are not
> supported in a single file; the list format is currently remote-only.
## Authentication
@@ -362,5 +365,7 @@ Users can manage subagents using the following commands within the Gemini CLI:
- `/agents enable <agent_name>`: Enables a specific subagent.
- `/agents disable <agent_name>`: Disables a specific subagent.
> **Tip:** You can use the `@cli_help` agent within Gemini CLI for assistance
<!-- prettier-ignore -->
> [!TIP]
> You can use the `@cli_help` agent within Gemini CLI for assistance
> with configuring subagents.
+21 -13
View File
@@ -5,16 +5,18 @@ session. They are designed to handle specific, complex tasks—like deep codebas
analysis, documentation lookup, or domain-specific reasoning—without cluttering
the main agent's context or toolset.
> **Note: Subagents are currently an experimental feature.**
>
> To use custom subagents, you must ensure they are enabled in your
> `settings.json` (enabled by default):
>
> ```json
> {
> "experimental": { "enableAgents": true }
> }
> ```
<!-- prettier-ignore -->
> [!NOTE]
> Subagents are currently an experimental feature.
>
To use custom subagents, you must ensure they are enabled in your
`settings.json` (enabled by default):
```json
{
"experimental": { "enableAgents": true }
}
```
## What are subagents?
@@ -114,7 +116,9 @@ Gemini CLI comes with the following built-in subagents:
the pricing table from this page," "Click the login button and enter my
credentials."
> **Note:** This is a preview feature currently under active development.
<!-- prettier-ignore -->
> [!NOTE]
> This is a preview feature currently under active development.
#### Prerequisites
@@ -217,7 +221,9 @@ captures a screenshot and sends it to the vision model for analysis. The model
returns coordinates and element descriptions that the browser agent uses with
the `click_at` tool for precise, coordinate-based interactions.
> **Note:** The visual agent requires API key or Vertex AI authentication. It is
<!-- prettier-ignore -->
> [!NOTE]
> The visual agent requires API key or Vertex AI authentication. It is
> not available when using "Sign in with Google".
## Creating custom subagents
@@ -405,7 +411,9 @@ that your subagent was called with a specific prompt and the given description.
Gemini CLI can also delegate tasks to remote subagents using the Agent-to-Agent
(A2A) protocol.
> **Note: Remote subagents are currently an experimental feature.**
<!-- prettier-ignore -->
> [!NOTE]
> Remote subagents are currently an experimental feature.
See the [Remote Subagents documentation](remote-agents) for detailed
configuration, authentication, and usage instructions.
+6 -2
View File
@@ -234,7 +234,9 @@ skill definitions in a `skills/` directory. For example,
### Sub-agents
> **Note:** Sub-agents are a preview feature currently under active development.
<!-- prettier-ignore -->
> [!NOTE]
> Sub-agents are a preview feature currently under active development.
Provide [sub-agents](../core/subagents.md) that users can delegate tasks to. Add
agent definition files (`.md`) to an `agents/` directory in your extension root.
@@ -253,7 +255,9 @@ Rules contributed by extensions run in their own tier (tier 2), alongside
workspace-defined policies. This tier has higher priority than the default rules
but lower priority than user or admin policies.
> **Warning:** For security, Gemini CLI ignores any `allow` decisions or `yolo`
<!-- prettier-ignore -->
> [!WARNING]
> For security, Gemini CLI ignores any `allow` decisions or `yolo`
> mode configurations in extension policies. This ensures that an extension
> cannot automatically approve tool calls or bypass security measures without
> your confirmation.
+60 -50
View File
@@ -4,7 +4,9 @@ To use Gemini CLI, you'll need to authenticate with Google. This guide helps you
quickly find the best way to sign in based on your account type and how you're
using the CLI.
> **Note:** Looking for a high-level comparison of all available subscriptions?
<!-- prettier-ignore -->
> [!TIP]
> Looking for a high-level comparison of all available subscriptions?
> To compare features and find the right quota for your needs, see our
> [Plans page](https://geminicli.com/plans/).
@@ -40,11 +42,11 @@ Select the authentication method that matches your situation in the table below:
If you run Gemini CLI on your local machine, the simplest authentication method
is logging in with your Google account. This method requires a web browser on a
machine that can communicate with the terminal running Gemini CLI (e.g., your
local machine).
machine that can communicate with the terminal running Gemini CLI (for example,
your local machine).
> **Important:** If you are a **Google AI Pro** or **Google AI Ultra**
> subscriber, use the Google account associated with your subscription.
If you are a **Google AI Pro** or **Google AI Ultra** subscriber, use the Google
account associated with your subscription.
To authenticate and use Gemini CLI:
@@ -107,7 +109,9 @@ To authenticate and use Gemini CLI with a Gemini API key:
4. Select **Use Gemini API key**.
> **Warning:** Treat API keys, especially for services like Gemini, as sensitive
<!-- prettier-ignore -->
> [!WARNING]
> Treat API keys, especially for services like Gemini, as sensitive
> credentials. Protect them to prevent unauthorized access and potential misuse
> of the service under your account.
@@ -130,7 +134,7 @@ For example:
**macOS/Linux**
```bash
# Replace with your project ID and desired location (e.g., us-central1)
# Replace with your project ID and desired location (for example, us-central1)
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"
```
@@ -138,7 +142,7 @@ export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"
**Windows (PowerShell)**
```powershell
# Replace with your project ID and desired location (e.g., us-central1)
# Replace with your project ID and desired location (for example, us-central1)
$env:GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
$env:GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"
```
@@ -150,20 +154,20 @@ To make any Vertex AI environment variable settings persistent, see
Consider this authentication method if you have Google Cloud CLI installed.
> **Note:** If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you
> must unset them to use ADC:
>
> **macOS/Linux**
>
> ```bash
> unset GOOGLE_API_KEY GEMINI_API_KEY
> ```
>
> **Windows (PowerShell)**
>
> ```powershell
> Remove-Item Env:\GOOGLE_API_KEY, Env:\GEMINI_API_KEY -ErrorAction Ignore
> ```
If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you must unset
them to use ADC.
**macOS/Linux**
```bash
unset GOOGLE_API_KEY GEMINI_API_KEY
```
**Windows (PowerShell)**
```powershell
Remove-Item Env:\GOOGLE_API_KEY, Env:\GEMINI_API_KEY -ErrorAction Ignore
```
1. Verify you have a Google Cloud project and Vertex AI API is enabled.
@@ -188,20 +192,20 @@ Consider this authentication method if you have Google Cloud CLI installed.
Consider this method of authentication in non-interactive environments, CI/CD
pipelines, or if your organization restricts user-based ADC or API key creation.
> **Note:** If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you
> must unset them:
>
> **macOS/Linux**
>
> ```bash
> unset GOOGLE_API_KEY GEMINI_API_KEY
> ```
>
> **Windows (PowerShell)**
>
> ```powershell
> Remove-Item Env:\GOOGLE_API_KEY, Env:\GEMINI_API_KEY -ErrorAction Ignore
> ```
If you have previously set `GOOGLE_API_KEY` or `GEMINI_API_KEY`, you must unset
them:
**macOS/Linux**
```bash
unset GOOGLE_API_KEY GEMINI_API_KEY
```
**Windows (PowerShell)**
```powershell
Remove-Item Env:\GOOGLE_API_KEY, Env:\GEMINI_API_KEY -ErrorAction Ignore
```
1. [Create a service account and key](https://cloud.google.com/iam/docs/keys-create-delete)
and download the provided JSON file. Assign the "Vertex AI User" role to the
@@ -233,8 +237,11 @@ pipelines, or if your organization restricts user-based ADC or API key creation.
```
5. Select **Vertex AI**.
> **Warning:** Protect your service account key file as it gives access to
> your resources.
<!-- prettier-ignore -->
> [!WARNING]
> Protect your service account key file as it gives access to
> your resources.
#### C. Vertex AI - Google Cloud API key
@@ -257,10 +264,9 @@ pipelines, or if your organization restricts user-based ADC or API key creation.
$env:GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
```
> **Note:** If you see errors like
> `"API keys are not supported by this API..."`, your organization might
> restrict API key usage for this service. Try the other Vertex AI
> authentication methods instead.
If you see errors like `"API keys are not supported by this API..."`, your
organization might restrict API key usage for this service. Try the other
Vertex AI authentication methods instead.
3. [Configure your Google Cloud Project](#set-gcp).
@@ -274,7 +280,9 @@ pipelines, or if your organization restricts user-based ADC or API key creation.
## Set your Google Cloud project <a id="set-gcp"></a>
> **Important:** Most individual Google accounts (free and paid) don't require a
<!-- prettier-ignore -->
> [!IMPORTANT]
> Most individual Google accounts (free and paid) don't require a
> Google Cloud project for authentication.
When you sign in using your Google account, you may need to configure a Google
@@ -325,29 +333,31 @@ persist them with the following methods:
1. **Add your environment variables to your shell configuration file:** Append
the environment variable commands to your shell's startup file.
**macOS/Linux** (e.g., `~/.bashrc`, `~/.zshrc`, or `~/.profile`):
**macOS/Linux** (for example, `~/.bashrc`, `~/.zshrc`, or `~/.profile`):
```bash
echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc
source ~/.bashrc
```
**Windows (PowerShell)** (e.g., `$PROFILE`):
**Windows (PowerShell)** (for example, `$PROFILE`):
```powershell
Add-Content -Path $PROFILE -Value '$env:GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"'
. $PROFILE
```
> **Warning:** Be aware that when you export API keys or service account
> paths in your shell configuration file, any process launched from that
> shell can read them.
<!-- prettier-ignore -->
> [!WARNING]
> Be aware that when you export API keys or service account
> paths in your shell configuration file, any process launched from that
> shell can read them.
2. **Use a `.env` file:** Create a `.gemini/.env` file in your project
directory or home directory. Gemini CLI automatically loads variables from
the first `.env` file it finds, searching up from the current directory,
then in your home directory's `.gemini/.env` (e.g., `~/.gemini/.env` or
`%USERPROFILE%\.gemini\.env`).
then in your home directory's `.gemini/.env` (for example, `~/.gemini/.env`
or `%USERPROFILE%\.gemini\.env`).
Example for user-wide settings:
+3 -1
View File
@@ -4,7 +4,9 @@ Gemini CLI helps you automate common engineering tasks by combining AI reasoning
with local system tools. This document provides examples of how to use the CLI
for file management, code analysis, and data transformation.
> **Note:** These examples demonstrate potential capabilities. Your actual
<!-- prettier-ignore -->
> [!NOTE]
> These examples demonstrate potential capabilities. Your actual
> results can vary based on the model used and your project environment.
## Rename your photographs based on content
+11 -5
View File
@@ -2,7 +2,9 @@
Gemini 3 Pro and Gemini 3 Flash are available on Gemini CLI for all users!
> **Note:** Gemini 3.1 Pro Preview is rolling out. To determine whether you have
<!-- prettier-ignore -->
> [!NOTE]
> Gemini 3.1 Pro Preview is rolling out. To determine whether you have
> access to Gemini 3.1, use the `/model` command and select **Manual**. If you
> have access, you will see `gemini-3.1-pro-preview`.
>
@@ -25,7 +27,7 @@ Get started by upgrading Gemini CLI to the latest version:
npm install -g @google/gemini-cli@latest
```
After youve confirmed your version is 0.21.1 or later:
If your version is 0.21.1 or later:
1. Run `/model`.
2. Select **Auto (Gemini 3)**.
@@ -39,7 +41,9 @@ When you encounter that limit, youll be given the option to switch to Gemini
2.5 Pro, upgrade for higher limits, or stop. Youll also be told when your usage
limit resets and Gemini 3 Pro can be used again.
> **Note:** Looking to upgrade for higher limits? To compare subscription
<!-- prettier-ignore -->
> [!TIP]
> Looking to upgrade for higher limits? To compare subscription
> options and find the right quota for your needs, see our
> [Plans page](https://geminicli.com/plans/).
@@ -52,7 +56,9 @@ There may be times when the Gemini 3 Pro model is overloaded. When that happens,
Gemini CLI will ask you to decide whether you want to keep trying Gemini 3 Pro
or fallback to Gemini 2.5 Pro.
> **Note:** The **Keep trying** option uses exponential backoff, in which Gemini
<!-- prettier-ignore -->
> [!NOTE]
> The **Keep trying** option uses exponential backoff, in which Gemini
> CLI waits longer between each retry, when the system is busy. If the retry
> doesn't happen immediately, please wait a few minutes for the request to
> process.
@@ -109,7 +115,7 @@ then:
Restart Gemini CLI and you should have access to Gemini 3.
## Need help?
## Next steps
If you need help, we recommend searching for an existing
[GitHub issue](https://github.com/google-gemini/gemini-cli/issues). If you
+3 -1
View File
@@ -143,7 +143,9 @@ Hooks are executed with a sanitized environment.
## Security and risks
> **Warning: Hooks execute arbitrary code with your user privileges.** By
<!-- prettier-ignore -->
> [!WARNING]
> Hooks execute arbitrary code with your user privileges. By
> configuring hooks, you are allowing scripts to run shell commands on your
> machine.
+5 -3
View File
@@ -132,9 +132,11 @@ to the CLI whenever the user's context changes.
}
```
**Note:** The `openFiles` list should only include files that exist on disk.
Virtual files (e.g., unsaved files without a path, editor settings pages)
**MUST** be excluded.
<!-- prettier-ignore -->
> [!NOTE]
> The `openFiles` list should only include files that exist on disk.
> Virtual files (e.g., unsaved files without a path, editor settings pages)
> **MUST** be excluded.
### How the CLI uses this context
+8 -4
View File
@@ -66,9 +66,11 @@ You can also install the extension directly from a marketplace.
Follow your editor's instructions for installing extensions from this
registry.
> NOTE: The "Gemini CLI Companion" extension may appear towards the bottom of
> search results. If you don't see it immediately, try scrolling down or sorting
> by "Newly Published".
<!-- prettier-ignore -->
> [!NOTE]
> The "Gemini CLI Companion" extension may appear towards the bottom of
> search results. If you don't see it immediately, try scrolling down or
> sorting by "Newly Published".
>
> After manually installing the extension, you must run `/ide enable` in the CLI
> to activate the integration.
@@ -103,7 +105,9 @@ IDE, run:
If connected, this command will show the IDE it's connected to and a list of
recently opened files it is aware of.
> [!NOTE] The file list is limited to 10 recently accessed files within your
<!-- prettier-ignore -->
> [!NOTE]
> The file list is limited to 10 recently accessed files within your
> workspace and only includes local files on disk.)
### Working with diffs
+50 -116
View File
@@ -1,8 +1,14 @@
# Gemini CLI documentation
# Welcome to Gemini CLI
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.
Unleash the power of Gemini models directly in your terminal. Gemini CLI is your
intelligent assistant for coding, automation, and understanding complex
projects. It seamlessly integrates with your local development environment,
empowering you to accelerate workflows, tackle challenging tasks, and explore
codebases with unprecedented ease.
Whether you're refactoring code, debugging issues, or orchestrating complex
automation, Gemini CLI works alongside you, transforming your terminal into a
highly productive AI-powered workspace.
## Install
@@ -10,132 +16,60 @@ context.
npm install -g @google/gemini-cli
```
## Get started
## Get Started in Minutes
Jump in to Gemini CLI.
Ready to boost your productivity? You can get Gemini CLI up and running right
away.
- **[Quickstart](./get-started/index.md):** Your first session with Gemini CLI.
- **[Installation](./get-started/installation.md):** How to install Gemini CLI
on your system.
- **[Authentication](./get-started/authentication.md):** Setup instructions for
personal and enterprise accounts.
- **[Examples](./get-started/examples.md):** Practical examples of Gemini CLI in
action.
- **[CLI cheatsheet](./cli/cli-reference.md):** A quick reference for common
commands and options.
- **[Gemini 3 on Gemini CLI](./get-started/gemini-3.md):** Learn about Gemini 3
support in Gemini CLI.
→ Dive into the [Quickstart Guide](./get-started/index.md) for your first
interactive session.
## Use Gemini CLI
## What Can Gemini CLI Do For You?
User-focused guides and tutorials for daily development workflows.
Gemini CLI isn't just a chatbot; it's a powerful agent capable of executing a
wide range of tasks directly within your project context.
- **[File management](./cli/tutorials/file-management.md):** How to work with
local files and directories.
- **[Get started with Agent skills](./cli/tutorials/skills-getting-started.md):**
Getting started with specialized expertise.
- **[Manage context and memory](./cli/tutorials/memory-management.md):**
Managing persistent instructions and facts.
- **[Execute shell commands](./cli/tutorials/shell-commands.md):** Executing
system commands safely.
- **[Manage sessions and history](./cli/tutorials/session-management.md):**
Resuming, managing, and rewinding conversations.
- **[Plan tasks with todos](./cli/tutorials/task-planning.md):** Using todos for
complex workflows.
- **[Web search and fetch](./cli/tutorials/web-tools.md):** Searching and
fetching content from the web.
- **[Set up an MCP server](./cli/tutorials/mcp-setup.md):** Set up an MCP
server.
- **[Automate tasks](./cli/tutorials/automation.md):** Automate tasks.
### Automate Code Refactoring and Generation
## Features
Tired of repetitive coding tasks? Let Gemini CLI handle them. It can understand
your existing code to generate new features or refactor complex sections with
ease.
Technical documentation for each capability of Gemini CLI.
→ Learn how to efficiently [Modify Code](./cli/tutorials/file-management.md).
- **[Extensions](./extensions/index.md):** Extend Gemini CLI with new tools and
capabilities.
- **[Agent Skills](./cli/skills.md):** Use specialized agents for specific
tasks.
- **[Checkpointing](./cli/checkpointing.md):** Automatic session snapshots.
- **[Headless mode](./cli/headless.md):** Programmatic and scripting interface.
- **[Hooks](./hooks/index.md):** Customize Gemini CLI behavior with scripts.
- **[IDE integration](./ide-integration/index.md):** Integrate Gemini CLI with
your favorite IDE.
- **[MCP servers](./tools/mcp-server.md):** Connect to and use remote agents.
- **[Model routing](./cli/model-routing.md):** Automatic fallback resilience.
- **[Model selection](./cli/model.md):** Choose the best model for your needs.
- **[Plan mode 🔬](./cli/plan-mode.md):** Use a safe, read-only mode for
planning complex changes.
- **[Subagents 🔬](./core/subagents.md):** Using specialized agents for specific
tasks.
- **[Remote subagents 🔬](./core/remote-agents.md):** Connecting to and using
remote agents.
- **[Rewind](./cli/rewind.md):** Rewind and replay sessions.
- **[Sandboxing](./cli/sandbox.md):** Isolate tool execution.
- **[Settings](./cli/settings.md):** Full configuration reference.
- **[Telemetry](./cli/telemetry.md):** Usage and performance metric details.
- **[Token caching](./cli/token-caching.md):** Performance optimization.
### Understand Complex Codebases
## Configuration
Navigate unfamiliar projects or quickly grasp new architectural patterns. Gemini
CLI can analyze large code repositories, explaining their purpose, structure,
and key functionalities.
Settings and customization options for Gemini CLI.
→ Explore examples of how to
[Explain a Repository by Reading its Code](./get-started/examples.md).
- **[Custom commands](./cli/custom-commands.md):** Personalized shortcuts.
- **[Enterprise configuration](./cli/enterprise.md):** Professional environment
controls.
- **[Ignore files (.geminiignore)](./cli/gemini-ignore.md):** Exclusion pattern
reference.
- **[Model configuration](./cli/generation-settings.md):** Fine-tune generation
parameters like temperature and thinking budget.
- **[Project context (GEMINI.md)](./cli/gemini-md.md):** Technical hierarchy of
context files.
- **[System prompt override](./cli/system-prompt.md):** Instruction replacement
logic.
- **[Themes](./cli/themes.md):** UI personalization technical guide.
- **[Trusted folders](./cli/trusted-folders.md):** Security permission logic.
### Streamline Your Development Workflows
## Reference
From planning tasks with TODOs to managing long-running sessions, Gemini CLI
helps you orchestrate your entire development process, making complex workflows
simpler and more efficient.
Deep technical documentation and API specifications.
→ Discover how to [Plan Tasks with ToDos](./cli/tutorials/task-planning.md) or
[Manage Sessions and History](./cli/tutorials/session-management.md).
- **[Command reference](./reference/commands.md):** Detailed slash command
guide.
- **[Configuration reference](./reference/configuration.md):** Settings and
environment variables.
- **[Keyboard shortcuts](./reference/keyboard-shortcuts.md):** Productivity
tips.
- **[Memory import processor](./reference/memport.md):** How Gemini CLI
processes memory from various sources.
- **[Policy engine](./reference/policy-engine.md):** Fine-grained execution
control.
- **[Tools reference](./reference/tools.md):** Information on how tools are
defined, registered, and used.
## Explore Key Features and Sections
## Resources
Dive deeper into Gemini CLI's capabilities and comprehensive documentation:
Support, release history, and legal information.
- **[Agent Skills](./cli/skills.md):** Extend Gemini CLI's intelligence with
specialized expertise for any domain or task.
- **[Extensions](./extensions/index.md):** Customize and enhance your CLI
experience by building or installing new tools and functionalities.
- **[Configuration](./reference/configuration.md):** Fine-tune Gemini CLI to
match your preferences and project requirements with detailed settings and
options.
- **[Command Reference](./reference/commands.md):** A complete guide to all
available CLI commands, flags, and interactive prompts.
- **[Resources](./resources/faq.md):** Find answers to frequently asked
questions, troubleshooting tips, and support information.
- **[FAQ](./resources/faq.md):** Answers to frequently asked questions.
- **[Quota and pricing](./resources/quota-and-pricing.md):** Limits and billing
details.
- **[Terms and privacy](./resources/tos-privacy.md):** Official notices and
terms.
- **[Troubleshooting](./resources/troubleshooting.md):** Common issues and
solutions.
- **[Uninstall](./resources/uninstall.md):** How to uninstall Gemini CLI.
## Development
- **[Contribution guide](/docs/contributing):** How to contribute to Gemini CLI.
- **[Integration testing](./integration-tests.md):** Running integration tests.
- **[Issue and PR automation](./issue-and-pr-automation.md):** Automation for
issues and pull requests.
- **[Local development](./local-development.md):** Setting up a local
development environment.
- **[NPM package structure](./npm.md):** The structure of the NPM packages.
## Releases
- **[Release notes](./changelogs/index.md):** Release notes for all versions.
- **[Stable release](./changelogs/latest.md):** The latest stable release.
- **[Preview release](./changelogs/preview.md):** The latest preview release.
We're excited for you to experience a new level of terminal productivity with
Gemini CLI!
+3 -1
View File
@@ -14,7 +14,9 @@ feature), while the PR is the "how" (the implementation). This separation helps
us track work, prioritize features, and maintain clear historical context. Our
automation is built around this principle.
> **Note:** Issues tagged as "🔒Maintainers only" are reserved for project
<!-- prettier-ignore -->
> [!NOTE]
> Issues tagged as "🔒Maintainers only" are reserved for project
> maintainers. We will not accept pull requests related to these issues.
---
+3 -1
View File
@@ -79,7 +79,9 @@ You can view traces in the Jaeger UI for local development.
You can use an OpenTelemetry collector to forward telemetry data to Google Cloud
Trace for custom processing or routing.
> **Warning:** Ensure you complete the
<!-- prettier-ignore -->
> [!WARNING]
> Ensure you complete the
> [Google Cloud telemetry prerequisites](./cli/telemetry.md#prerequisites)
> (Project ID, authentication, IAM roles, and APIs) before using this method.
+2 -2
View File
@@ -60,8 +60,8 @@ Slash commands provide meta-level control over the CLI itself.
- `list` (selecting this opens the auto-saved session browser)
- `-- checkpoints --`
- `list`, `save`, `resume`, `delete`, `share` (manual tagged checkpoints)
- **Note:** Unique prefixes (for example `/cha` or `/resum`) resolve to the
same grouped menu.
- Unique prefixes (for example `/cha` or `/resu`) resolve to the same grouped
menu.
- **Sub-commands:**
- **`debug`**
- **Description:** Export the most recent API request as a JSON payload.
+203 -8
View File
@@ -25,7 +25,9 @@ overridden by higher numbers):
Gemini CLI uses JSON settings files for persistent configuration. There are four
locations for these files:
> **Tip:** JSON-aware editors can use autocomplete and validation by pointing to
<!-- prettier-ignore -->
> [!TIP]
> JSON-aware editors can use autocomplete and validation by pointing to
> the generated schema at `schemas/settings.schema.json` in this repository.
> When working outside the repo, reference the hosted schema at
> `https://raw.githubusercontent.com/google-gemini/gemini-cli/main/schemas/settings.schema.json`.
@@ -66,9 +68,9 @@ an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like
this: `"apiKey": "$MY_API_TOKEN"`. Additionally, each extension can have its own
`.env` file in its directory, which will be loaded automatically.
> **Note for Enterprise Users:** For guidance on deploying and managing Gemini
> CLI in a corporate environment, please see the
> [Enterprise Configuration](../cli/enterprise.md) documentation.
**Note for Enterprise Users:** For guidance on deploying and managing Gemini CLI
in a corporate environment, please see the
[Enterprise Configuration](../cli/enterprise.md) documentation.
### The `.gemini` directory in your project
@@ -684,6 +686,16 @@ their corresponding top-level category object in your `settings.json` file.
```json
{
"gemini-3.1-flash-lite-preview": {
"tier": "flash-lite",
"family": "gemini-3",
"isPreview": true,
"isVisible": true,
"features": {
"thinking": false,
"multimodalToolUse": true
}
},
"gemini-3.1-pro-preview": {
"tier": "pro",
"family": "gemini-3",
@@ -795,7 +807,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "auto",
"isPreview": true,
"isVisible": true,
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash",
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash",
"features": {
"thinking": true,
"multimodalToolUse": false
@@ -824,6 +836,39 @@ their corresponding top-level category object in your `settings.json` file.
```json
{
"gemini-3.1-pro-preview": {
"default": "gemini-3.1-pro-preview",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-pro"
}
]
},
"gemini-3.1-pro-preview-customtools": {
"default": "gemini-3.1-pro-preview-customtools",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-pro"
}
]
},
"gemini-3-flash-preview": {
"default": "gemini-3-flash-preview",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-flash"
}
]
},
"gemini-3-pro-preview": {
"default": "gemini-3-pro-preview",
"contexts": [
@@ -995,6 +1040,132 @@ their corresponding top-level category object in your `settings.json` file.
- **Requires restart:** Yes
- **`modelConfigs.modelChains`** (object):
- **Description:** Availability policy chains defining fallback behavior for
models.
- **Default:**
```json
{
"preview": [
{
"model": "gemini-3-pro-preview",
"actions": {
"terminal": "prompt",
"transient": "prompt",
"not_found": "prompt",
"unknown": "prompt"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
},
{
"model": "gemini-3-flash-preview",
"isLastResort": true,
"actions": {
"terminal": "prompt",
"transient": "prompt",
"not_found": "prompt",
"unknown": "prompt"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
}
],
"default": [
{
"model": "gemini-2.5-pro",
"actions": {
"terminal": "prompt",
"transient": "prompt",
"not_found": "prompt",
"unknown": "prompt"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
},
{
"model": "gemini-2.5-flash",
"isLastResort": true,
"actions": {
"terminal": "prompt",
"transient": "prompt",
"not_found": "prompt",
"unknown": "prompt"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
}
],
"lite": [
{
"model": "gemini-2.5-flash-lite",
"actions": {
"terminal": "silent",
"transient": "silent",
"not_found": "silent",
"unknown": "silent"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
},
{
"model": "gemini-2.5-flash",
"actions": {
"terminal": "silent",
"transient": "silent",
"not_found": "silent",
"unknown": "silent"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
},
{
"model": "gemini-2.5-pro",
"isLastResort": true,
"actions": {
"terminal": "silent",
"transient": "silent",
"not_found": "silent",
"unknown": "silent"
},
"stateTransitions": {
"terminal": "terminal",
"transient": "terminal",
"not_found": "terminal",
"unknown": "terminal"
}
}
]
}
```
- **Requires restart:** Yes
#### `agents`
- **`agents.overrides`** (object):
@@ -1105,10 +1276,21 @@ their corresponding top-level category object in your `settings.json` file.
- **Description:** Legacy full-process sandbox execution environment. Set to a
boolean to enable or disable the sandbox, provide a string path to a sandbox
profile, or specify an explicit sandbox command (e.g., "docker", "podman",
"lxc").
"lxc", "windows-native").
- **Default:** `undefined`
- **Requires restart:** Yes
- **`tools.sandboxAllowedPaths`** (array):
- **Description:** List of additional paths that the sandbox is allowed to
access.
- **Default:** `[]`
- **Requires restart:** Yes
- **`tools.sandboxNetworkAccess`** (boolean):
- **Description:** Whether the sandbox is allowed to access the network.
- **Default:** `false`
- **Requires restart:** Yes
- **`tools.shell.enableInteractiveShell`** (boolean):
- **Description:** Use node-pty for an interactive shell experience. Fallback
to child_process still applies.
@@ -1431,6 +1613,13 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `"gemma3-1b-gpu-custom"`
- **Requires restart:** Yes
- **`experimental.memoryManager`** (boolean):
- **Description:** Replace the built-in save_memory tool with a memory manager
subagent that supports adding, removing, de-duplicating, and organizing
memories.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.topicUpdateNarration`** (boolean):
- **Description:** Enable the experimental Topic & Update communication model
for reduced chattiness and structured progress reporting.
@@ -1539,7 +1728,11 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `true`
- **`admin.mcp.config`** (object):
- **Description:** Admin-configured MCP servers.
- **Description:** Admin-configured MCP servers (allowlist).
- **Default:** `{}`
- **`admin.mcp.requiredConfig`** (object):
- **Description:** Admin-required MCP servers that are always injected.
- **Default:** `{}`
- **`admin.skills.enabled`** (boolean):
@@ -1559,7 +1752,9 @@ for compatibility. At least one of `command`, `url`, or `httpUrl` must be
provided. If multiple are specified, the order of precedence is `httpUrl`, then
`url`, then `command`.
> **Warning:** Avoid using underscores (`_`) in your server aliases (e.g., use
<!-- prettier-ignore -->
> [!WARNING]
> Avoid using underscores (`_`) in your server aliases (e.g., use
> `my-server` instead of `my_server`). The underlying policy engine parses Fully
> Qualified Names (`mcp_server_tool`) using the first underscore after the
> `mcp_` prefix. An underscore in your server alias will cause the parser to
+16 -10
View File
@@ -113,7 +113,9 @@ There are three possible decisions a rule can enforce:
- `ask_user`: The user is prompted to approve or deny the tool call. (In
non-interactive mode, this is treated as `deny`.)
> **Note:** The `deny` decision is the recommended way to exclude tools. The
<!-- prettier-ignore -->
> [!NOTE]
> The `deny` decision is the recommended way to exclude tools. The
> legacy `tools.exclude` setting in `settings.json` is deprecated in favor of
> policy rules with a `deny` decision.
@@ -239,15 +241,17 @@ directory are **ignored**.
- **Linux / macOS:** Must be owned by `root` (UID 0) and NOT writable by group
or others (e.g., `chmod 755`).
- **Windows:** Must be in `C:\ProgramData`. Standard users (`Users`, `Everyone`)
must NOT have `Write`, `Modify`, or `Full Control` permissions. _Tip: If you
see a security warning, use the folder properties to remove write permissions
for non-admin groups. You may need to "Disable inheritance" in Advanced
Security Settings._
must NOT have `Write`, `Modify`, or `Full Control` permissions. If you see a
security warning, use the folder properties to remove write permissions for
non-admin groups. You may need to "Disable inheritance" in Advanced Security
Settings.
**Note:** Supplemental admin policies (provided via `--admin-policy` or
`adminPolicyPaths` settings) are **NOT** subject to these strict ownership
checks, as they are explicitly provided by the user or administrator in their
current execution context.
<!-- prettier-ignore -->
> [!NOTE]
> Supplemental admin policies (provided via `--admin-policy` or
> `adminPolicyPaths` settings) are **NOT** subject to these strict ownership
> checks, as they are explicitly provided by the user or administrator in their
> current execution context.
### TOML rule schema
@@ -348,7 +352,9 @@ using the `mcpName` field. **This is the recommended approach** for defining MCP
policies, as it is much more robust than manually writing Fully Qualified Names
(FQNs) or string wildcards.
> **Warning:** Do not use underscores (`_`) in your MCP server names (e.g., use
<!-- prettier-ignore -->
> [!WARNING]
> Do not use underscores (`_`) in your MCP server names (e.g., use
> `my-server` rather than `my_server`). The policy parser splits Fully Qualified
> Names (`mcp_server_tool`) on the _first_ underscore following the `mcp_`
> prefix. If your server name contains an underscore, the parser will
+3 -1
View File
@@ -95,7 +95,9 @@ For developers, the tool system is designed to be extensible and robust. The
You can extend Gemini CLI with custom tools by configuring
`tools.discoveryCommand` in your settings or by connecting to MCP servers.
> **Note:** For a deep dive into the internal Tool API and how to implement your
<!-- prettier-ignore -->
> [!NOTE]
> For a deep dive into the internal Tool API and how to implement your
> own tools in the codebase, see the `packages/core/src/tools/` directory in
> GitHub.
+7 -3
View File
@@ -21,9 +21,13 @@ All workflows in `.github/workflows/ci.yml` must pass on the `main` branch (for
nightly) or the release branch (for preview/stable).
- **Platforms:** Tests must pass on **Linux and macOS**.
- _Note:_ Windows tests currently run with `continue-on-error: true`. While a
failure here doesn't block the release technically, it should be
investigated.
<!-- prettier-ignore -->
> [!NOTE]
> Windows tests currently run with `continue-on-error: true`. While a
> failure here doesn't block the release technically, it should be
> investigated.
- **Checks:**
- **Linting:** No linting errors (ESLint, Prettier, etc.).
- **Typechecking:** No TypeScript errors.
+11 -7
View File
@@ -234,10 +234,12 @@ This workflow will automatically:
Review the automatically created pull request(s) to ensure the cherry-pick was
successful and the changes are correct. Once approved, merge the pull request.
**Security note:** The `release/*` branches are protected by branch protection
rules. A pull request to one of these branches requires at least one review from
a code owner before it can be merged. This ensures that no unauthorized code is
released.
<!-- prettier-ignore -->
> [!WARNING]
> The `release/*` branches are protected by branch protection
> rules. A pull request to one of these branches requires at least one review from
> a code owner before it can be merged. This ensures that no unauthorized code is
> released.
#### 2.5. Adding multiple commits to a hotfix (advanced)
@@ -524,9 +526,11 @@ Notifications use
[GitHub for Google Chat](https://workspace.google.com/marketplace/app/github_for_google_chat/536184076190).
To modify the notifications, use `/github-settings` within the chat space.
> [!WARNING] The following instructions describe a fragile workaround that
> depends on the internal structure of the chat application's UI. It is likely
> to break with future updates.
<!-- prettier-ignore -->
> [!WARNING]
> The following instructions describe a fragile workaround that depends on the
> internal structure of the chat application's UI. It is likely to break with
> future updates.
The list of available labels is not currently populated correctly. If you want
to add a label that does not appear alphabetically in the first 30 labels in the
+4 -2
View File
@@ -16,8 +16,10 @@ account.
Your Gemini CLI Usage Statistics are handled in accordance with Google's Privacy
Policy.
**Note:** See [quotas and pricing](quota-and-pricing.md) for the quota and
pricing details that apply to your usage of the Gemini CLI.
<!-- prettier-ignore -->
> [!NOTE]
> See [quotas and pricing](quota-and-pricing.md) for the quota and
> pricing details that apply to your usage of the Gemini CLI.
## Supported authentication methods
+3 -1
View File
@@ -187,5 +187,7 @@ guide_, consider searching the Gemini CLI
If you can't find an issue similar to yours, consider creating a new GitHub
Issue with a detailed description. Pull requests are also welcome!
> **Note:** Issues tagged as "🔒Maintainers only" are reserved for project
<!-- prettier-ignore -->
> [!NOTE]
> Issues tagged as "🔒Maintainers only" are reserved for project
> maintainers. We will not accept pull requests related to these issues.
+17 -9
View File
@@ -176,8 +176,8 @@ Each server configuration supports the following properties:
enabled by default.
- **`excludeTools`** (string[]): List of tool names to exclude from this MCP
server. Tools listed here will not be available to the model, even if they are
exposed by the server. **Note:** `excludeTools` takes precedence over
`includeTools` - if a tool is in both lists, it will be excluded.
exposed by the server. `excludeTools` takes precedence over `includeTools`. If
a tool is in both lists, it will be excluded.
- **`targetAudience`** (string): The OAuth Client ID allowlisted on the
IAP-protected application you are trying to access. Used with
`authProviderType: 'service_account_impersonation'`.
@@ -238,7 +238,9 @@ This follows the security principle that if a variable is explicitly configured
by the user for a specific server, it constitutes informed consent to share that
specific data with that server.
> **Note:** Even when explicitly defined, you should avoid hardcoding secrets.
<!-- prettier-ignore -->
> [!NOTE]
> Even when explicitly defined, you should avoid hardcoding secrets.
> Instead, use environment variable expansion (e.g., `"MY_KEY": "$MY_KEY"`) to
> securely pull the value from your host environment at runtime.
@@ -283,10 +285,12 @@ When connecting to an OAuth-enabled server:
#### Browser redirect requirements
**Important:** OAuth authentication requires that your local machine can:
- Open a web browser for authentication
- Receive redirects on `http://localhost:7777/oauth/callback`
<!-- prettier-ignore -->
> [!IMPORTANT]
> OAuth authentication requires that your local machine can:
>
> - Open a web browser for authentication
> - Receive redirects on `http://localhost:7777/oauth/callback`
This feature will not work in:
@@ -577,7 +581,9 @@ every discovered MCP tool is assigned a strict namespace.
[Special syntax for MCP tools](../reference/policy-engine.md#special-syntax-for-mcp-tools)
in the Policy Engine documentation.
> **Warning:** Do not use underscores (`_`) in your MCP server names (e.g., use
<!-- prettier-ignore -->
> [!WARNING]
> Do not use underscores (`_`) in your MCP server names (e.g., use
> `my-server` rather than `my_server`). The policy parser splits Fully Qualified
> Names (`mcp_server_tool`) on the _first_ underscore following the `mcp_`
> prefix. If your server name contains an underscore, the parser will
@@ -1116,7 +1122,9 @@ command has no flags.
gemini mcp list
```
> **Note on Trust:** For security, `stdio` MCP servers (those using the
<!-- prettier-ignore -->
> [!NOTE]
> For security, `stdio` MCP servers (those using the
> `command` property) are only tested and displayed as "Connected" if the
> current folder is trusted. If the folder is untrusted, they will show as
> "Disconnected". Use `gemini trust` to trust the current folder.
+3 -1
View File
@@ -11,7 +11,9 @@ by the agent when you ask it to "start a plan" using natural language. In this
mode, the agent is restricted to read-only tools to allow for safe exploration
and planning.
> **Note:** This tool is not available when the CLI is in YOLO mode.
<!-- prettier-ignore -->
> [!NOTE]
> This tool is not available when the CLI is in YOLO mode.
- **Tool name:** `enter_plan_mode`
- **Display name:** Enter Plan Mode
+4 -4
View File
@@ -57,8 +57,8 @@ implementation, which does not support interactive commands.
### Showing color in output
To show color in the shell output, you need to set the `tools.shell.showColor`
setting to `true`. **Note: This setting only applies when
`tools.shell.enableInteractiveShell` is enabled.**
setting to `true`. This setting only applies when
`tools.shell.enableInteractiveShell` is enabled.
**Example `settings.json`:**
@@ -75,8 +75,8 @@ setting to `true`. **Note: This setting only applies when
### Setting the pager
You can set a custom pager for the shell output by setting the
`tools.shell.pager` setting. The default pager is `cat`. **Note: This setting
only applies when `tools.shell.enableInteractiveShell` is enabled.**
`tools.shell.pager` setting. The default pager is `cat`. This setting only
applies when `tools.shell.enableInteractiveShell` is enabled.
**Example `settings.json`:**
+6 -1
View File
@@ -319,7 +319,12 @@ export default tseslint.config(
},
},
{
files: ['./scripts/**/*.js', 'esbuild.config.js', 'packages/core/scripts/**/*.{js,mjs}'],
files: [
'./scripts/**/*.js',
'packages/*/scripts/**/*.js',
'esbuild.config.js',
'packages/core/scripts/**/*.{js,mjs}',
],
languageOptions: {
globals: {
...globals.node,
@@ -0,0 +1,5 @@
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll help you with that."},{"functionCall":{"name":"browser_agent","args":{"task":"Open https://example.com and check if there is a heading"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"new_page","args":{"url":"https://example.com"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"complete_task","args":{"success":true,"summary":"SUCCESS_POLICY_TEST_COMPLETED"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Task completed successfully. The page has the heading \"Example Domain\"."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":50,"totalTokenCount":250}}]}
+178
View File
@@ -0,0 +1,178 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { TestRig, poll } from './test-helper.js';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';
import { existsSync, writeFileSync, readFileSync, mkdirSync } from 'node:fs';
import stripAnsi from 'strip-ansi';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const chromeAvailable = (() => {
try {
if (process.platform === 'darwin') {
execSync(
'test -d "/Applications/Google Chrome.app" || test -d "/Applications/Chromium.app"',
{
stdio: 'ignore',
},
);
} else if (process.platform === 'linux') {
execSync(
'which google-chrome || which chromium-browser || which chromium',
{ stdio: 'ignore' },
);
} else if (process.platform === 'win32') {
const chromePaths = [
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
`${process.env['LOCALAPPDATA'] ?? ''}\\Google\\Chrome\\Application\\chrome.exe`,
];
const found = chromePaths.some((p) => existsSync(p));
if (!found) {
execSync('where chrome || where chromium', { stdio: 'ignore' });
}
} else {
return false;
}
return true;
} catch {
return false;
}
})();
describe.skipIf(!chromeAvailable)('browser-policy', () => {
let rig: TestRig;
beforeEach(() => {
rig = new TestRig();
});
afterEach(async () => {
await rig.cleanup();
});
it('should skip confirmation when "Allow all server tools for this session" is chosen', async () => {
rig.setup('browser-policy-skip-confirmation', {
fakeResponsesPath: join(__dirname, 'browser-policy.responses'),
settings: {
agents: {
overrides: {
browser_agent: {
enabled: true,
},
},
browser: {
headless: true,
sessionMode: 'isolated',
allowedDomains: ['example.com'],
},
},
},
});
// Manually trust the folder to avoid the dialog and enable option 3
const geminiDir = join(rig.homeDir!, '.gemini');
mkdirSync(geminiDir, { recursive: true });
// Write to trustedFolders.json
const trustedFoldersPath = join(geminiDir, 'trustedFolders.json');
const trustedFolders = {
[rig.testDir!]: 'TRUST_FOLDER',
};
writeFileSync(trustedFoldersPath, JSON.stringify(trustedFolders, null, 2));
// Force confirmation for browser agent.
// NOTE: We don't force confirm browser tools here because "Allow all server tools"
// adds a rule with ALWAYS_ALLOW_PRIORITY (3.9x) which would be overshadowed by
// a rule in the user tier (4.x) like the one from this TOML.
// By removing the explicit mcp rule, the first MCP tool will still prompt
// due to default approvalMode = 'default', and then "Allow all" will correctly
// bypass subsequent tools.
const policyFile = join(rig.testDir!, 'force-confirm.toml');
writeFileSync(
policyFile,
`
[[rule]]
name = "Force confirm browser_agent"
toolName = "browser_agent"
decision = "ask_user"
priority = 200
`,
);
// Update settings.json in both project and home directories to point to the policy file
for (const baseDir of [rig.testDir!, rig.homeDir!]) {
const settingsPath = join(baseDir, '.gemini', 'settings.json');
if (existsSync(settingsPath)) {
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
settings.policyPaths = [policyFile];
// Ensure folder trust is enabled
settings.security = settings.security || {};
settings.security.folderTrust = settings.security.folderTrust || {};
settings.security.folderTrust.enabled = true;
writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
}
}
const run = await rig.runInteractive({
approvalMode: 'default',
env: {
GEMINI_CLI_INTEGRATION_TEST: 'true',
},
});
await run.sendKeys(
'Open https://example.com and check if there is a heading\r',
);
await run.sendKeys('\r');
// Handle confirmations.
// 1. Initial browser_agent delegation (likely only 3 options, so use option 1: Allow once)
await poll(
() => stripAnsi(run.output).toLowerCase().includes('action required'),
60000,
1000,
);
await run.sendKeys('1\r');
await new Promise((r) => setTimeout(r, 2000));
// Handle privacy notice
await poll(
() => stripAnsi(run.output).toLowerCase().includes('privacy notice'),
5000,
100,
);
await run.sendKeys('1\r');
await new Promise((r) => setTimeout(r, 5000));
// new_page (MCP tool, should have 4 options, use option 3: Allow all server tools)
await poll(
() => {
const stripped = stripAnsi(run.output).toLowerCase();
return (
stripped.includes('new_page') &&
stripped.includes('allow all server tools for this session')
);
},
60000,
1000,
);
// Select "Allow all server tools for this session" (option 3)
await run.sendKeys('3\r');
await new Promise((r) => setTimeout(r, 30000));
const output = stripAnsi(run.output).toLowerCase();
expect(output).toContain('browser_agent');
expect(output).toContain('completed successfully');
});
});
+5 -5
View File
@@ -22,7 +22,7 @@
"gemini": "bundle/gemini.js"
},
"devDependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
"@agentclientprotocol/sdk": "^0.16.1",
"@octokit/rest": "^22.0.0",
"@types/marked": "^5.0.2",
"@types/mime-types": "^3.0.1",
@@ -84,9 +84,9 @@
}
},
"node_modules/@agentclientprotocol/sdk": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-0.12.0.tgz",
"integrity": "sha512-V8uH/KK1t7utqyJmTA7y7DzKu6+jKFIXM+ZVouz8E55j8Ej2RV42rEvPKn3/PpBJlliI5crcGk1qQhZ7VwaepA==",
"version": "0.16.1",
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-0.16.1.tgz",
"integrity": "sha512-1ad+Sc/0sCtZGHthxxvgEUo5Wsbw16I+aF+YwdiLnPwkZG8KAGUEAPK6LM6Pf69lCyJPt1Aomk1d+8oE3C4ZEw==",
"license": "Apache-2.0",
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
@@ -17531,7 +17531,7 @@
"version": "0.36.0-nightly.20260317.2f90b4653",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
"@agentclientprotocol/sdk": "^0.16.1",
"@google/gemini-cli-core": "file:../core",
"@google/genai": "1.30.0",
"@iarna/toml": "^2.2.5",
+1 -1
View File
@@ -87,7 +87,7 @@
"LICENSE"
],
"devDependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
"@agentclientprotocol/sdk": "^0.16.1",
"@octokit/rest": "^22.0.0",
"@types/marked": "^5.0.2",
"@types/mime-types": "^3.0.1",
+1 -1
View File
@@ -30,7 +30,7 @@
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.36.0-nightly.20260317.2f90b4653"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
"@agentclientprotocol/sdk": "^0.16.1",
"@google/gemini-cli-core": "file:../core",
"@google/genai": "1.30.0",
"@iarna/toml": "^2.2.5",
+17 -8
View File
@@ -177,6 +177,9 @@ describe('GeminiAgent', () => {
getHasAccessToPreviewModel: vi.fn().mockReturnValue(false),
getCheckpointingEnabled: vi.fn().mockReturnValue(false),
getDisableAlwaysAllow: vi.fn().mockReturnValue(false),
get config() {
return this;
},
} as unknown as Mocked<Awaited<ReturnType<typeof loadCliConfig>>>;
mockSettings = {
merged: {
@@ -548,7 +551,7 @@ describe('GeminiAgent', () => {
});
expect(session.prompt).toHaveBeenCalled();
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
});
it('should delegate setMode to session', async () => {
@@ -656,6 +659,12 @@ describe('Session', () => {
getGitService: vi.fn().mockResolvedValue({} as GitService),
waitForMcpInit: vi.fn(),
getDisableAlwaysAllow: vi.fn().mockReturnValue(false),
get config() {
return this;
},
get toolRegistry() {
return mockToolRegistry;
},
} as unknown as Mocked<Config>;
mockConnection = {
sessionUpdate: vi.fn(),
@@ -741,7 +750,7 @@ describe('Session', () => {
content: { type: 'text', text: 'Hello' },
},
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
});
it('should handle /memory command', async () => {
@@ -758,7 +767,7 @@ describe('Session', () => {
prompt: [{ type: 'text', text: '/memory view' }],
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
expect(handleCommandSpy).toHaveBeenCalledWith(
'/memory view',
expect.any(Object),
@@ -780,7 +789,7 @@ describe('Session', () => {
prompt: [{ type: 'text', text: '/extensions list' }],
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
expect(handleCommandSpy).toHaveBeenCalledWith(
'/extensions list',
expect.any(Object),
@@ -802,7 +811,7 @@ describe('Session', () => {
prompt: [{ type: 'text', text: '/extensions explore' }],
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
expect(handleCommandSpy).toHaveBeenCalledWith(
'/extensions explore',
expect.any(Object),
@@ -824,7 +833,7 @@ describe('Session', () => {
prompt: [{ type: 'text', text: '/restore' }],
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
expect(handleCommandSpy).toHaveBeenCalledWith(
'/restore',
expect.any(Object),
@@ -846,7 +855,7 @@ describe('Session', () => {
prompt: [{ type: 'text', text: '/init' }],
});
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
expect(handleCommandSpy).toHaveBeenCalledWith('/init', expect.any(Object));
expect(mockChat.sendMessageStream).not.toHaveBeenCalled();
});
@@ -900,7 +909,7 @@ describe('Session', () => {
}),
}),
);
expect(result).toEqual({ stopReason: 'end_turn' });
expect(result).toMatchObject({ stopReason: 'end_turn' });
});
it('should handle tool call permission request', async () => {
+105 -36
View File
@@ -47,6 +47,7 @@ import {
DEFAULT_GEMINI_MODEL_AUTO,
PREVIEW_GEMINI_MODEL_AUTO,
getDisplayString,
type AgentLoopContext,
} from '@google/gemini-cli-core';
import * as acp from '@agentclientprotocol/sdk';
import { AcpFileSystemService } from './fileSystemService.js';
@@ -104,7 +105,7 @@ export class GeminiAgent {
private customHeaders: Record<string, string> | undefined;
constructor(
private config: Config,
private context: AgentLoopContext,
private settings: LoadedSettings,
private argv: CliArgs,
private connection: acp.AgentSideConnection,
@@ -148,7 +149,7 @@ export class GeminiAgent {
},
];
await this.config.initialize();
await this.context.config.initialize();
const version = await getVersion();
return {
protocolVersion: acp.PROTOCOL_VERSION,
@@ -220,7 +221,7 @@ export class GeminiAgent {
this.baseUrl = baseUrl;
this.customHeaders = headers;
await this.config.refreshAuth(
await this.context.config.refreshAuth(
method,
apiKey ?? this.apiKey,
baseUrl,
@@ -537,7 +538,7 @@ export class Session {
constructor(
private readonly id: string,
private readonly chat: GeminiChat,
private readonly config: Config,
private readonly context: AgentLoopContext,
private readonly connection: acp.AgentSideConnection,
private readonly settings: LoadedSettings,
) {}
@@ -552,13 +553,15 @@ export class Session {
}
setMode(modeId: acp.SessionModeId): acp.SetSessionModeResponse {
const availableModes = buildAvailableModes(this.config.isPlanEnabled());
const availableModes = buildAvailableModes(
this.context.config.isPlanEnabled(),
);
const mode = availableModes.find((m) => m.id === modeId);
if (!mode) {
throw new Error(`Invalid or unavailable mode: ${modeId}`);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
this.config.setApprovalMode(mode.id as ApprovalMode);
this.context.config.setApprovalMode(mode.id as ApprovalMode);
return {};
}
@@ -579,7 +582,7 @@ export class Session {
}
setModel(modelId: acp.ModelId): acp.SetSessionModelResponse {
this.config.setModel(modelId);
this.context.config.setModel(modelId);
return {};
}
@@ -634,7 +637,7 @@ export class Session {
}
}
const tool = this.config.getToolRegistry().getTool(toolCall.name);
const tool = this.context.toolRegistry.getTool(toolCall.name);
await this.sendUpdate({
sessionUpdate: 'tool_call',
@@ -658,7 +661,7 @@ export class Session {
const pendingSend = new AbortController();
this.pendingPrompt = pendingSend;
await this.config.waitForMcpInit();
await this.context.config.waitForMcpInit();
const promptId = Math.random().toString(16).slice(2);
const chat = this.chat;
@@ -696,10 +699,22 @@ export class Session {
// It uses `parts` argument but effectively ignores it in current implementation
const handled = await this.handleCommand(commandText, parts);
if (handled) {
return { stopReason: 'end_turn' };
return {
stopReason: 'end_turn',
_meta: {
quota: {
token_count: { input_tokens: 0, output_tokens: 0 },
model_usage: [],
},
},
};
}
}
let totalInputTokens = 0;
let totalOutputTokens = 0;
const modelUsageMap = new Map<string, { input: number; output: number }>();
let nextMessage: Content | null = { role: 'user', parts };
while (nextMessage !== null) {
@@ -712,8 +727,8 @@ export class Session {
try {
const model = resolveModel(
this.config.getModel(),
(await this.config.getGemini31Launched?.()) ?? false,
this.context.config.getModel(),
(await this.context.config.getGemini31Launched?.()) ?? false,
);
const responseStream = await chat.sendMessageStream(
{ model },
@@ -724,11 +739,25 @@ export class Session {
);
nextMessage = null;
let turnInputTokens = 0;
let turnOutputTokens = 0;
let turnModelId = model;
for await (const resp of responseStream) {
if (pendingSend.signal.aborted) {
return { stopReason: CoreToolCallStatus.Cancelled };
}
if (resp.type === StreamEventType.CHUNK && resp.value.usageMetadata) {
turnInputTokens =
resp.value.usageMetadata.promptTokenCount ?? turnInputTokens;
turnOutputTokens =
resp.value.usageMetadata.candidatesTokenCount ?? turnOutputTokens;
if (resp.value.modelVersion) {
turnModelId = resp.value.modelVersion;
}
}
if (
resp.type === StreamEventType.CHUNK &&
resp.value.candidates &&
@@ -760,6 +789,19 @@ export class Session {
}
}
totalInputTokens += turnInputTokens;
totalOutputTokens += turnOutputTokens;
if (turnInputTokens > 0 || turnOutputTokens > 0) {
const existing = modelUsageMap.get(turnModelId) ?? {
input: 0,
output: 0,
};
existing.input += turnInputTokens;
existing.output += turnOutputTokens;
modelUsageMap.set(turnModelId, existing);
}
if (pendingSend.signal.aborted) {
return { stopReason: CoreToolCallStatus.Cancelled };
}
@@ -796,7 +838,28 @@ export class Session {
}
}
return { stopReason: 'end_turn' };
const modelUsageArray = Array.from(modelUsageMap.entries()).map(
([modelName, counts]) => ({
model: modelName,
token_count: {
input_tokens: counts.input,
output_tokens: counts.output,
},
}),
);
return {
stopReason: 'end_turn',
_meta: {
quota: {
token_count: {
input_tokens: totalInputTokens,
output_tokens: totalOutputTokens,
},
model_usage: modelUsageArray,
},
},
};
}
private async handleCommand(
@@ -804,9 +867,9 @@ export class Session {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
parts: Part[],
): Promise<boolean> {
const gitService = await this.config.getGitService();
const gitService = await this.context.config.getGitService();
const commandContext = {
config: this.config,
agentContext: this.context,
settings: this.settings,
git: gitService,
sendMessage: async (text: string) => {
@@ -842,7 +905,7 @@ export class Session {
const errorResponse = (error: Error) => {
const durationMs = Date.now() - startTime;
logToolCall(
this.config,
this.context.config,
new ToolCallEvent(
undefined,
fc.name ?? '',
@@ -872,7 +935,7 @@ export class Session {
return errorResponse(new Error('Missing function name'));
}
const toolRegistry = this.config.getToolRegistry();
const toolRegistry = this.context.toolRegistry;
const tool = toolRegistry.getTool(fc.name);
if (!tool) {
@@ -908,7 +971,10 @@ export class Session {
const params: acp.RequestPermissionRequest = {
sessionId: this.id,
options: toPermissionOptions(confirmationDetails, this.config),
options: toPermissionOptions(
confirmationDetails,
this.context.config,
),
toolCall: {
toolCallId: callId,
status: 'pending',
@@ -974,7 +1040,7 @@ export class Session {
const durationMs = Date.now() - startTime;
logToolCall(
this.config,
this.context.config,
new ToolCallEvent(
undefined,
fc.name ?? '',
@@ -988,7 +1054,7 @@ export class Session {
),
);
this.chat.recordCompletedToolCalls(this.config.getActiveModel(), [
this.chat.recordCompletedToolCalls(this.context.config.getActiveModel(), [
{
status: CoreToolCallStatus.Success,
request: {
@@ -1006,8 +1072,8 @@ export class Session {
fc.name,
callId,
toolResult.llmContent,
this.config.getActiveModel(),
this.config,
this.context.config.getActiveModel(),
this.context.config,
),
resultDisplay: toolResult.returnDisplay,
error: undefined,
@@ -1020,8 +1086,8 @@ export class Session {
fc.name,
callId,
toolResult.llmContent,
this.config.getActiveModel(),
this.config,
this.context.config.getActiveModel(),
this.context.config,
);
} catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
@@ -1036,7 +1102,7 @@ export class Session {
kind: toAcpToolKind(tool.kind),
});
this.chat.recordCompletedToolCalls(this.config.getActiveModel(), [
this.chat.recordCompletedToolCalls(this.context.config.getActiveModel(), [
{
status: CoreToolCallStatus.Error,
request: {
@@ -1122,18 +1188,18 @@ export class Session {
const atPathToResolvedSpecMap = new Map<string, string>();
// Get centralized file discovery service
const fileDiscovery = this.config.getFileService();
const fileDiscovery = this.context.config.getFileService();
const fileFilteringOptions: FilterFilesOptions =
this.config.getFileFilteringOptions();
this.context.config.getFileFilteringOptions();
const pathSpecsToRead: string[] = [];
const contentLabelsForDisplay: string[] = [];
const ignoredPaths: string[] = [];
const toolRegistry = this.config.getToolRegistry();
const toolRegistry = this.context.toolRegistry;
const readManyFilesTool = new ReadManyFilesTool(
this.config,
this.config.getMessageBus(),
this.context.config,
this.context.messageBus,
);
const globTool = toolRegistry.getTool('glob');
@@ -1152,8 +1218,11 @@ export class Session {
let currentPathSpec = pathName;
let resolvedSuccessfully = false;
try {
const absolutePath = path.resolve(this.config.getTargetDir(), pathName);
if (isWithinRoot(absolutePath, this.config.getTargetDir())) {
const absolutePath = path.resolve(
this.context.config.getTargetDir(),
pathName,
);
if (isWithinRoot(absolutePath, this.context.config.getTargetDir())) {
const stats = await fs.stat(absolutePath);
if (stats.isDirectory()) {
currentPathSpec = pathName.endsWith('/')
@@ -1173,7 +1242,7 @@ export class Session {
}
} catch (error) {
if (isNodeError(error) && error.code === 'ENOENT') {
if (this.config.getEnableRecursiveFileSearch() && globTool) {
if (this.context.config.getEnableRecursiveFileSearch() && globTool) {
this.debug(
`Path ${pathName} not found directly, attempting glob search.`,
);
@@ -1181,7 +1250,7 @@ export class Session {
const globResult = await globTool.buildAndExecute(
{
pattern: `**/*${pathName}*`,
path: this.config.getTargetDir(),
path: this.context.config.getTargetDir(),
},
abortSignal,
);
@@ -1195,7 +1264,7 @@ export class Session {
if (lines.length > 1 && lines[1]) {
const firstMatchAbsolute = lines[1].trim();
currentPathSpec = path.relative(
this.config.getTargetDir(),
this.context.config.getTargetDir(),
firstMatchAbsolute,
);
this.debug(
@@ -1410,7 +1479,7 @@ export class Session {
}
debug(msg: string) {
if (this.config.getDebugMode()) {
if (this.context.config.getDebugMode()) {
debugLogger.warn(msg);
}
}
+6 -2
View File
@@ -97,6 +97,9 @@ describe('GeminiAgent Session Resume', () => {
getHasAccessToPreviewModel: vi.fn().mockReturnValue(false),
getGemini31LaunchedSync: vi.fn().mockReturnValue(false),
getCheckpointingEnabled: vi.fn().mockReturnValue(false),
get config() {
return this;
},
} as unknown as Mocked<Config>;
mockSettings = {
merged: {
@@ -158,9 +161,10 @@ describe('GeminiAgent Session Resume', () => {
],
};
mockConfig.getToolRegistry = vi.fn().mockReturnValue({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mockConfig as any).toolRegistry = {
getTool: vi.fn().mockReturnValue({ kind: 'read' }),
});
};
(SessionSelector as unknown as Mock).mockImplementation(() => ({
resolveSession: vi.fn().mockResolvedValue({
+10 -9
View File
@@ -53,7 +53,7 @@ export class ListExtensionsCommand implements Command {
context: CommandContext,
_: string[],
): Promise<CommandExecutionResponse> {
const extensions = listExtensions(context.config);
const extensions = listExtensions(context.agentContext.config);
const data = extensions.length ? extensions : 'No extensions installed.';
return { name: this.name, data };
@@ -134,7 +134,7 @@ export class EnableExtensionCommand implements Command {
args: string[],
): Promise<CommandExecutionResponse> {
const enableContext = getEnableDisableContext(
context.config,
context.agentContext.config,
args,
'enable',
);
@@ -156,7 +156,8 @@ export class EnableExtensionCommand implements Command {
if (extension?.mcpServers) {
const mcpEnablementManager = McpServerEnablementManager.getInstance();
const mcpClientManager = context.config.getMcpClientManager();
const mcpClientManager =
context.agentContext.config.getMcpClientManager();
const enabledServers = await mcpEnablementManager.autoEnableServers(
Object.keys(extension.mcpServers),
);
@@ -191,7 +192,7 @@ export class DisableExtensionCommand implements Command {
args: string[],
): Promise<CommandExecutionResponse> {
const enableContext = getEnableDisableContext(
context.config,
context.agentContext.config,
args,
'disable',
);
@@ -223,7 +224,7 @@ export class InstallExtensionCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const extensionLoader = context.config.getExtensionLoader();
const extensionLoader = context.agentContext.config.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
return {
name: this.name,
@@ -268,7 +269,7 @@ export class LinkExtensionCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const extensionLoader = context.config.getExtensionLoader();
const extensionLoader = context.agentContext.config.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
return {
name: this.name,
@@ -313,7 +314,7 @@ export class UninstallExtensionCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const extensionLoader = context.config.getExtensionLoader();
const extensionLoader = context.agentContext.config.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
return {
name: this.name,
@@ -369,7 +370,7 @@ export class RestartExtensionCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const extensionLoader = context.config.getExtensionLoader();
const extensionLoader = context.agentContext.config.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
return { name: this.name, data: 'Cannot restart extensions.' };
}
@@ -424,7 +425,7 @@ export class UpdateExtensionCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const extensionLoader = context.config.getExtensionLoader();
const extensionLoader = context.agentContext.config.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
return { name: this.name, data: 'Cannot update extensions.' };
}
+1 -1
View File
@@ -22,7 +22,7 @@ export class InitCommand implements Command {
context: CommandContext,
_args: string[] = [],
): Promise<CommandExecutionResponse> {
const targetDir = context.config.getTargetDir();
const targetDir = context.agentContext.config.getTargetDir();
if (!targetDir) {
throw new Error('Command requires a workspace.');
}
+6 -6
View File
@@ -49,7 +49,7 @@ export class ShowMemoryCommand implements Command {
context: CommandContext,
_: string[],
): Promise<CommandExecutionResponse> {
const result = showMemory(context.config);
const result = showMemory(context.agentContext.config);
return { name: this.name, data: result.content };
}
}
@@ -63,7 +63,7 @@ export class RefreshMemoryCommand implements Command {
context: CommandContext,
_: string[],
): Promise<CommandExecutionResponse> {
const result = await refreshMemory(context.config);
const result = await refreshMemory(context.agentContext.config);
return { name: this.name, data: result.content };
}
}
@@ -76,7 +76,7 @@ export class ListMemoryCommand implements Command {
context: CommandContext,
_: string[],
): Promise<CommandExecutionResponse> {
const result = listMemoryFiles(context.config);
const result = listMemoryFiles(context.agentContext.config);
return { name: this.name, data: result.content };
}
}
@@ -95,7 +95,7 @@ export class AddMemoryCommand implements Command {
return { name: this.name, data: result.content };
}
const toolRegistry = context.config.getToolRegistry();
const toolRegistry = context.agentContext.toolRegistry;
const tool = toolRegistry.getTool(result.toolName);
if (tool) {
const abortController = new AbortController();
@@ -106,10 +106,10 @@ export class AddMemoryCommand implements Command {
await tool.buildAndExecute(result.toolArgs, signal, undefined, {
shellExecutionConfig: {
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
sandboxManager: context.config.sandboxManager,
sandboxManager: context.agentContext.sandboxManager,
},
});
await refreshMemory(context.config);
await refreshMemory(context.agentContext.config);
return {
name: this.name,
data: `Added memory: "${textToAdd}"`,
+3 -2
View File
@@ -29,7 +29,8 @@ export class RestoreCommand implements Command {
context: CommandContext,
args: string[],
): Promise<CommandExecutionResponse> {
const { config, git: gitService } = context;
const { agentContext: agentContext, git: gitService } = context;
const { config } = agentContext;
const argsStr = args.join(' ');
try {
@@ -116,7 +117,7 @@ export class ListCheckpointsCommand implements Command {
readonly description = 'Lists all available checkpoints.';
async execute(context: CommandContext): Promise<CommandExecutionResponse> {
const { config } = context;
const { config } = context.agentContext;
try {
if (!config.getCheckpointingEnabled()) {
+2 -2
View File
@@ -4,11 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/
import type { Config, GitService } from '@google/gemini-cli-core';
import type { AgentLoopContext, GitService } from '@google/gemini-cli-core';
import type { LoadedSettings } from '../../config/settings.js';
export interface CommandContext {
config: Config;
agentContext: AgentLoopContext;
settings: LoadedSettings;
git?: GitService;
sendMessage: (text: string) => Promise<void>;
+1 -1
View File
@@ -14,7 +14,7 @@ export class AcpFileSystemService implements FileSystemService {
constructor(
private readonly connection: acp.AgentSideConnection,
private readonly sessionId: string,
private readonly capabilities: acp.FileSystemCapability,
private readonly capabilities: acp.FileSystemCapabilities,
private readonly fallback: FileSystemService,
) {}
@@ -264,6 +264,7 @@ describe('mcp list command', () => {
config: {
'allowed-server': { url: 'http://allowed' },
},
requiredConfig: {},
},
};
+34
View File
@@ -36,6 +36,7 @@ import {
Config,
resolveToRealPath,
applyAdminAllowlist,
applyRequiredServers,
getAdminBlockedMcpServersMessage,
type HookDefinition,
type HookEventName,
@@ -702,6 +703,19 @@ export async function loadCliConfig(
? defaultModel
: specifiedModel || defaultModel;
const sandboxConfig = await loadSandboxConfig(settings, argv);
if (sandboxConfig) {
const existingPaths = sandboxConfig.allowedPaths || [];
if (settings.tools.sandboxAllowedPaths?.length) {
sandboxConfig.allowedPaths = [
...new Set([...existingPaths, ...settings.tools.sandboxAllowedPaths]),
];
}
if (settings.tools.sandboxNetworkAccess !== undefined) {
sandboxConfig.networkAccess =
sandboxConfig.networkAccess || settings.tools.sandboxNetworkAccess;
}
}
const screenReader =
argv.screenReader !== undefined
? argv.screenReader
@@ -737,6 +751,25 @@ export async function loadCliConfig(
}
}
// Apply admin-required MCP servers (injected regardless of allowlist)
if (mcpEnabled) {
const requiredMcpConfig = settings.admin?.mcp?.requiredConfig;
if (requiredMcpConfig && Object.keys(requiredMcpConfig).length > 0) {
const requiredResult = applyRequiredServers(
mcpServers ?? {},
requiredMcpConfig,
);
mcpServers = requiredResult.mcpServers;
if (requiredResult.requiredServerNames.length > 0) {
coreEvents.emitConsoleLog(
'info',
`Admin-required MCP servers injected: ${requiredResult.requiredServerNames.join(', ')}`,
);
}
}
}
const isAcpMode = !!argv.acp || !!argv.experimentalAcp;
let clientName: string | undefined = undefined;
if (isAcpMode) {
@@ -840,6 +873,7 @@ export async function loadCliConfig(
skillsSupport: settings.skills?.enabled ?? true,
disabledSkills: settings.skills?.disabled,
experimentalJitContext: settings.experimental?.jitContext,
experimentalMemoryManager: settings.experimental?.memoryManager,
modelSteering: settings.experimental?.modelSteering,
topicUpdateNarration: settings.experimental?.topicUpdateNarration,
toolOutputMasking: settings.experimental?.toolOutputMasking,
@@ -0,0 +1,133 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { copyExtension } from './extension-manager.js';
describe('copyExtension permissions', () => {
let tempDir: string;
let sourceDir: string;
let destDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-permission-test-'));
sourceDir = path.join(tempDir, 'source');
destDir = path.join(tempDir, 'dest');
fs.mkdirSync(sourceDir);
});
afterEach(() => {
// Ensure we can delete the temp directory by making everything writable again
const makeWritableSync = (p: string) => {
try {
const stats = fs.lstatSync(p);
fs.chmodSync(p, stats.mode | 0o700);
if (stats.isDirectory()) {
fs.readdirSync(p).forEach((child) =>
makeWritableSync(path.join(p, child)),
);
}
} catch (_e) {
// Ignore errors during cleanup
}
};
if (fs.existsSync(tempDir)) {
makeWritableSync(tempDir);
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
it('should make destination writable even if source is read-only', async () => {
const fileName = 'test.txt';
const filePath = path.join(sourceDir, fileName);
fs.writeFileSync(filePath, 'hello');
// Make source read-only: 0o555 for directory, 0o444 for file
fs.chmodSync(filePath, 0o444);
fs.chmodSync(sourceDir, 0o555);
// Verify source is read-only
expect(() => fs.writeFileSync(filePath, 'fail')).toThrow();
// Perform copy
await copyExtension(sourceDir, destDir);
// Verify destination is writable
const destFilePath = path.join(destDir, fileName);
const destFileStats = fs.statSync(destFilePath);
const destDirStats = fs.statSync(destDir);
// Check that owner write bits are set (0o200)
expect(destFileStats.mode & 0o200).toBe(0o200);
expect(destDirStats.mode & 0o200).toBe(0o200);
// Verify we can actually write to the destination file
fs.writeFileSync(destFilePath, 'writable');
expect(fs.readFileSync(destFilePath, 'utf-8')).toBe('writable');
// Verify we can delete the destination (which requires write bit on destDir)
fs.rmSync(destFilePath);
expect(fs.existsSync(destFilePath)).toBe(false);
});
it('should handle nested directories with restrictive permissions', async () => {
const subDir = path.join(sourceDir, 'subdir');
fs.mkdirSync(subDir);
const fileName = 'nested.txt';
const filePath = path.join(subDir, fileName);
fs.writeFileSync(filePath, 'nested content');
// Make nested structure read-only
fs.chmodSync(filePath, 0o444);
fs.chmodSync(subDir, 0o555);
fs.chmodSync(sourceDir, 0o555);
// Perform copy
await copyExtension(sourceDir, destDir);
// Verify nested destination is writable
const destSubDir = path.join(destDir, 'subdir');
const destFilePath = path.join(destSubDir, fileName);
expect(fs.statSync(destSubDir).mode & 0o200).toBe(0o200);
expect(fs.statSync(destFilePath).mode & 0o200).toBe(0o200);
// Verify we can delete the whole destination tree
await fs.promises.rm(destDir, { recursive: true, force: true });
expect(fs.existsSync(destDir)).toBe(false);
});
it('should not follow symlinks or modify symlink targets', async () => {
const symlinkTarget = path.join(tempDir, 'external-target');
fs.writeFileSync(symlinkTarget, 'external content');
// Target is read-only
fs.chmodSync(symlinkTarget, 0o444);
const symlinkPath = path.join(sourceDir, 'symlink-file');
fs.symlinkSync(symlinkTarget, symlinkPath);
// Perform copy
await copyExtension(sourceDir, destDir);
const destSymlinkPath = path.join(destDir, 'symlink-file');
const destSymlinkStats = fs.lstatSync(destSymlinkPath);
// Verify it is still a symlink in the destination
expect(destSymlinkStats.isSymbolicLink()).toBe(true);
// Verify the target (external to the extension) was NOT modified
const targetStats = fs.statSync(symlinkTarget);
// Owner write bit should still NOT be set (0o200)
expect(targetStats.mode & 0o200).toBe(0o000);
// Clean up
fs.chmodSync(symlinkTarget, 0o644);
});
});
@@ -15,6 +15,10 @@ import { createExtension } from '../test-utils/createExtension.js';
import { EXTENSIONS_DIRECTORY_NAME } from './extensions/variables.js';
const mockHomedir = vi.hoisted(() => vi.fn(() => '/tmp/mock-home'));
const mockIntegrityManager = vi.hoisted(() => ({
verify: vi.fn().mockResolvedValue('verified'),
store: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('node:os', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:os')>();
@@ -31,6 +35,9 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
return {
...actual,
homedir: mockHomedir,
ExtensionIntegrityManager: vi
.fn()
.mockImplementation(() => mockIntegrityManager),
loadAgentsFromDirectory: vi
.fn()
.mockImplementation(async () => ({ agents: [], errors: [] })),
@@ -64,6 +71,7 @@ describe('ExtensionManager skills validation', () => {
requestConsent: vi.fn().mockResolvedValue(true),
requestSetting: vi.fn(),
workspaceDir: tempDir,
integrityManager: mockIntegrityManager,
});
});
@@ -139,6 +147,7 @@ describe('ExtensionManager skills validation', () => {
requestConsent: vi.fn().mockResolvedValue(true),
requestSetting: vi.fn(),
workspaceDir: tempDir,
integrityManager: mockIntegrityManager,
});
// 4. Load extensions
@@ -1248,11 +1248,32 @@ function filterMcpConfig(original: MCPServerConfig): MCPServerConfig {
return Object.freeze(rest);
}
/**
* Recursively ensures that the owner has write permissions for all files
* and directories within the target path.
*/
async function makeWritableRecursive(targetPath: string): Promise<void> {
const stats = await fs.promises.lstat(targetPath);
if (stats.isDirectory()) {
// Ensure directory is rwx for the owner (0o700)
await fs.promises.chmod(targetPath, stats.mode | 0o700);
const children = await fs.promises.readdir(targetPath);
for (const child of children) {
await makeWritableRecursive(path.join(targetPath, child));
}
} else if (stats.isFile()) {
// Ensure file is rw for the owner (0o600)
await fs.promises.chmod(targetPath, stats.mode | 0o600);
}
}
export async function copyExtension(
source: string,
destination: string,
): Promise<void> {
await fs.promises.cp(source, destination, { recursive: true });
await makeWritableRecursive(destination);
}
function getContextFileNames(config: ExtensionConfig): string[] {
@@ -36,6 +36,8 @@ vi.mock('node:fs', async (importOriginal) => {
rm: vi.fn(),
cp: vi.fn(),
readFile: vi.fn(),
lstat: vi.fn(),
chmod: vi.fn(),
},
};
});
@@ -143,6 +145,11 @@ describe('extensionUpdates', () => {
vi.mocked(fs.promises.rm).mockResolvedValue(undefined);
vi.mocked(fs.promises.cp).mockResolvedValue(undefined);
vi.mocked(fs.promises.readdir).mockResolvedValue([]);
vi.mocked(fs.promises.lstat).mockResolvedValue({
isDirectory: () => true,
mode: 0o755,
} as unknown as fs.Stats);
vi.mocked(fs.promises.chmod).mockResolvedValue(undefined);
vi.mocked(isWorkspaceTrusted).mockReturnValue({
isTrusted: true,
source: 'file',
@@ -516,7 +516,9 @@ describe('Policy Engine Integration Tests', () => {
);
expect(mcpServerRule?.priority).toBe(4.1); // MCP allowed server
const readOnlyToolRule = rules.find((r) => r.toolName === 'glob');
const readOnlyToolRule = rules.find(
(r) => r.toolName === 'glob' && !r.subagent,
);
// Priority 70 in default tier → 1.07 (Overriding Plan Mode Deny)
expect(readOnlyToolRule?.priority).toBeCloseTo(1.07, 5);
@@ -673,7 +675,7 @@ describe('Policy Engine Integration Tests', () => {
const server1Rule = rules.find((r) => r.toolName === 'mcp_server1_*');
expect(server1Rule?.priority).toBe(4.1); // Allowed servers (user tier)
const globRule = rules.find((r) => r.toolName === 'glob');
const globRule = rules.find((r) => r.toolName === 'glob' && !r.subagent);
// Priority 70 in default tier → 1.07
expect(globRule?.priority).toBeCloseTo(1.07, 5); // Auto-accept read-only
@@ -338,6 +338,8 @@ describe('loadSandboxConfig', () => {
sandbox: {
enabled: true,
command: 'podman',
allowedPaths: [],
networkAccess: false,
},
},
},
@@ -353,6 +355,8 @@ describe('loadSandboxConfig', () => {
sandbox: {
enabled: true,
image: 'custom/image',
allowedPaths: [],
networkAccess: false,
},
},
},
@@ -367,6 +371,8 @@ describe('loadSandboxConfig', () => {
tools: {
sandbox: {
enabled: false,
allowedPaths: [],
networkAccess: false,
},
},
},
@@ -382,6 +388,7 @@ describe('loadSandboxConfig', () => {
sandbox: {
enabled: true,
allowedPaths: ['/settings-path'],
networkAccess: false,
},
},
},
+16 -3
View File
@@ -29,6 +29,7 @@ const VALID_SANDBOX_COMMANDS = [
'sandbox-exec',
'runsc',
'lxc',
'windows-native',
];
function isSandboxCommand(
@@ -75,8 +76,15 @@ function getSandboxCommand(
'gVisor (runsc) sandboxing is only supported on Linux',
);
}
// confirm that specified command exists
if (!commandExists.sync(sandbox)) {
// windows-native is only supported on Windows
if (sandbox === 'windows-native' && os.platform() !== 'win32') {
throw new FatalSandboxError(
'Windows native sandboxing is only supported on Windows',
);
}
// confirm that specified command exists (unless it's built-in)
if (sandbox !== 'windows-native' && !commandExists.sync(sandbox)) {
throw new FatalSandboxError(
`Missing sandbox command '${sandbox}' (from GEMINI_SANDBOX)`,
);
@@ -149,7 +157,12 @@ export async function loadSandboxConfig(
customImage ??
packageJson?.config?.sandboxImageUri;
return command && image
const isNative =
command === 'windows-native' ||
command === 'sandbox-exec' ||
command === 'lxc';
return command && (image || isNative)
? { enabled: true, allowedPaths, networkAccess, command, image }
: undefined;
}
+22
View File
@@ -2751,6 +2751,28 @@ describe('Settings Loading and Merging', () => {
expect(loadedSettings.merged.admin?.mcp?.config).toEqual(mcpServers);
});
it('should map requiredMcpConfig from remote settings', () => {
const loadedSettings = loadSettings(MOCK_WORKSPACE_DIR);
const requiredMcpConfig = {
'corp-tool': {
url: 'https://mcp.corp/tool',
type: 'http' as const,
trust: true,
},
};
loadedSettings.setRemoteAdminSettings({
mcpSetting: {
mcpEnabled: true,
requiredMcpConfig,
},
});
expect(loadedSettings.merged.admin?.mcp?.requiredConfig).toEqual(
requiredMcpConfig,
);
});
it('should set skills based on unmanagedCapabilitiesEnabled', () => {
const loadedSettings = loadSettings();
loadedSettings.setRemoteAdminSettings({
+1
View File
@@ -480,6 +480,7 @@ export class LoadedSettings {
admin.mcp = {
enabled: mcpSetting?.mcpEnabled,
config: mcpSetting?.mcpConfig?.mcpServers,
requiredConfig: mcpSetting?.requiredMcpConfig,
};
admin.extensions = {
enabled: cliFeatureSetting?.extensionsSetting?.extensionsEnabled,
+156 -7
View File
@@ -12,7 +12,9 @@
import {
DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
DEFAULT_MODEL_CONFIGS,
AuthProviderType,
type MCPServerConfig,
type RequiredMcpServerConfig,
type BugCommandSettings,
type TelemetrySettings,
type AuthType,
@@ -1081,6 +1083,20 @@ const SETTINGS_SCHEMA = {
ref: 'ModelResolution',
},
},
modelChains: {
type: 'object',
label: 'Model Chains',
category: 'Model',
requiresRestart: true,
default: DEFAULT_MODEL_CONFIGS.modelChains,
description:
'Availability policy chains defining fallback behavior for models.',
showInDialog: false,
additionalProperties: {
type: 'array',
ref: 'ModelPolicy',
},
},
},
},
@@ -1344,10 +1360,30 @@ const SETTINGS_SCHEMA = {
description: oneLine`
Legacy full-process sandbox execution environment.
Set to a boolean to enable or disable the sandbox, provide a string path to a sandbox profile,
or specify an explicit sandbox command (e.g., "docker", "podman", "lxc").
or specify an explicit sandbox command (e.g., "docker", "podman", "lxc", "windows-native").
`,
showInDialog: false,
},
sandboxAllowedPaths: {
type: 'array',
label: 'Sandbox Allowed Paths',
category: 'Tools',
requiresRestart: true,
default: [] as string[],
description:
'List of additional paths that the sandbox is allowed to access.',
showInDialog: true,
items: { type: 'string' },
},
sandboxNetworkAccess: {
type: 'boolean',
label: 'Sandbox Network Access',
category: 'Tools',
requiresRestart: true,
default: false,
description: 'Whether the sandbox is allowed to access the network.',
showInDialog: true,
},
shell: {
type: 'object',
label: 'Shell',
@@ -2045,6 +2081,16 @@ const SETTINGS_SCHEMA = {
},
},
},
memoryManager: {
type: 'boolean',
label: 'Memory Manager Agent',
category: 'Experimental',
requiresRestart: true,
default: false,
description:
'Replace the built-in save_memory tool with a memory manager subagent that supports adding, removing, de-duplicating, and organizing memories.',
showInDialog: true,
},
topicUpdateNarration: {
type: 'boolean',
label: 'Topic & Update Narration',
@@ -2391,7 +2437,7 @@ const SETTINGS_SCHEMA = {
category: 'Admin',
requiresRestart: false,
default: {} as Record<string, MCPServerConfig>,
description: 'Admin-configured MCP servers.',
description: 'Admin-configured MCP servers (allowlist).',
showInDialog: false,
mergeStrategy: MergeStrategy.REPLACE,
additionalProperties: {
@@ -2399,6 +2445,20 @@ const SETTINGS_SCHEMA = {
ref: 'MCPServerConfig',
},
},
requiredConfig: {
type: 'object',
label: 'Required MCP Config',
category: 'Admin',
requiresRestart: false,
default: {} as Record<string, RequiredMcpServerConfig>,
description: 'Admin-required MCP servers that are always injected.',
showInDialog: false,
mergeStrategy: MergeStrategy.REPLACE,
additionalProperties: {
type: 'object',
ref: 'RequiredMcpServerConfig',
},
},
},
},
skills: {
@@ -2523,11 +2583,72 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
type: 'string',
description:
'Authentication provider used for acquiring credentials (for example `dynamic_discovery`).',
enum: [
'dynamic_discovery',
'google_credentials',
'service_account_impersonation',
],
enum: Object.values(AuthProviderType),
},
targetAudience: {
type: 'string',
description:
'OAuth target audience (CLIENT_ID.apps.googleusercontent.com).',
},
targetServiceAccount: {
type: 'string',
description:
'Service account email to impersonate (name@project.iam.gserviceaccount.com).',
},
},
},
RequiredMcpServerConfig: {
type: 'object',
description:
'Admin-required MCP server configuration (remote transports only).',
additionalProperties: false,
properties: {
url: {
type: 'string',
description: 'URL for the required MCP server.',
},
type: {
type: 'string',
description: 'Transport type for the required server.',
enum: ['sse', 'http'],
},
headers: {
type: 'object',
description: 'Additional HTTP headers sent to the server.',
additionalProperties: { type: 'string' },
},
timeout: {
type: 'number',
description: 'Timeout in milliseconds for MCP requests.',
},
trust: {
type: 'boolean',
description:
'Marks the server as trusted. Defaults to true for admin-required servers.',
},
description: {
type: 'string',
description: 'Human-readable description of the server.',
},
includeTools: {
type: 'array',
description: 'Subset of tools enabled for this server.',
items: { type: 'string' },
},
excludeTools: {
type: 'array',
description: 'Tools disabled for this server.',
items: { type: 'string' },
},
oauth: {
type: 'object',
description: 'OAuth configuration for authenticating with the server.',
additionalProperties: true,
},
authProviderType: {
type: 'string',
description: 'Authentication provider used for acquiring credentials.',
enum: Object.values(AuthProviderType),
},
targetAudience: {
type: 'string',
@@ -2867,6 +2988,34 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
},
},
},
ModelPolicy: {
type: 'object',
description:
'Defines the policy for a single model in the availability chain.',
properties: {
model: { type: 'string' },
isLastResort: { type: 'boolean' },
actions: {
type: 'object',
properties: {
terminal: { type: 'string', enum: ['silent', 'prompt'] },
transient: { type: 'string', enum: ['silent', 'prompt'] },
not_found: { type: 'string', enum: ['silent', 'prompt'] },
unknown: { type: 'string', enum: ['silent', 'prompt'] },
},
},
stateTransitions: {
type: 'object',
properties: {
terminal: { type: 'string', enum: ['terminal', 'sticky_retry'] },
transient: { type: 'string', enum: ['terminal', 'sticky_retry'] },
not_found: { type: 'string', enum: ['terminal', 'sticky_retry'] },
unknown: { type: 'string', enum: ['terminal', 'sticky_retry'] },
},
},
},
required: ['model'],
},
};
export function getSettingsSchema(): SettingsSchemaType {
@@ -29,7 +29,7 @@ describe('Model Steering Integration', () => {
configOverrides: { modelSteering: true },
});
await rig.initialize();
rig.render();
await rig.render();
await rig.waitForIdle();
rig.setToolPolicy('list_directory', PolicyDecision.ASK_USER);
@@ -65,9 +65,9 @@ export const handleSlashCommand = async (
const logger = new Logger(config?.getSessionId() || '', config?.storage);
const context: CommandContext = {
const commandContext: CommandContext = {
services: {
config,
agentContext: config,
settings,
git: undefined,
logger,
@@ -84,7 +84,7 @@ export const handleSlashCommand = async (
},
};
const result = await commandToExecute.action(context, args);
const result = await commandToExecute.action(commandContext, args);
if (result) {
switch (result.type) {
@@ -31,11 +31,14 @@ describe('AtFileProcessor', () => {
mockConfig = {
// The processor only passes the config through, so we don't need a full mock.
get config() {
return this;
},
} as unknown as Config;
context = createMockCommandContext({
services: {
config: mockConfig,
agentContext: mockConfig,
},
});
@@ -60,7 +63,7 @@ describe('AtFileProcessor', () => {
const prompt: PartUnion[] = [{ text: 'Analyze @{file.txt}' }];
const contextWithoutConfig = createMockCommandContext({
services: {
config: null,
agentContext: null,
},
});
const result = await processor.process(prompt, contextWithoutConfig);
@@ -25,7 +25,7 @@ export class AtFileProcessor implements IPromptProcessor {
input: PromptPipelineContent,
context: CommandContext,
): Promise<PromptPipelineContent> {
const config = context.services.config;
const config = context.services.agentContext?.config;
if (!config) {
return input;
}
@@ -89,6 +89,9 @@ describe('ShellProcessor', () => {
getPolicyEngine: vi.fn().mockReturnValue({
check: mockPolicyEngineCheck,
}),
get config() {
return this as unknown as Config;
},
};
context = createMockCommandContext({
@@ -98,7 +101,7 @@ describe('ShellProcessor', () => {
args: 'default args',
},
services: {
config: mockConfig as Config,
agentContext: mockConfig as Config,
},
session: {
sessionShellAllowlist: new Set(),
@@ -120,7 +123,7 @@ describe('ShellProcessor', () => {
const prompt: PromptPipelineContent = createPromptPipelineContent('!{ls}');
const contextWithoutConfig = createMockCommandContext({
services: {
config: null,
agentContext: null,
},
});
@@ -74,7 +74,7 @@ export class ShellProcessor implements IPromptProcessor {
];
}
const config = context.services.config;
const config = context.services.agentContext?.config;
if (!config) {
throw new Error(
`Security configuration not loaded. Cannot verify shell command permissions for '${this.commandName}'. Aborting.`,
+2 -8
View File
@@ -5,7 +5,6 @@
*/
import { describe, it, afterEach, expect } from 'vitest';
import { act } from 'react';
import { AppRig } from './AppRig.js';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -31,7 +30,7 @@ describe('AppRig', () => {
configOverrides: { modelSteering: true },
});
await rig.initialize();
rig.render();
await rig.render();
await rig.waitForIdle();
// Set breakpoints on the canonical tool names
@@ -69,12 +68,7 @@ describe('AppRig', () => {
);
rig = new AppRig({ fakeResponsesPath });
await rig.initialize();
await act(async () => {
rig!.render();
// Allow async initializations (like banners) to settle within the act boundary
await new Promise((resolve) => setTimeout(resolve, 0));
});
await rig.render();
// Wait for initial render
await rig.waitForIdle();
+5 -5
View File
@@ -11,7 +11,7 @@ import os from 'node:os';
import path from 'node:path';
import fs from 'node:fs';
import { AppContainer } from '../ui/AppContainer.js';
import { renderWithProviders } from './render.js';
import { renderWithProviders, type RenderInstance } from './render.js';
import {
makeFakeConfig,
type Config,
@@ -155,7 +155,7 @@ export interface PendingConfirmation {
}
export class AppRig {
private renderResult: ReturnType<typeof renderWithProviders> | undefined;
private renderResult: RenderInstance | undefined;
private config: Config | undefined;
private settings: LoadedSettings | undefined;
private testDir: string;
@@ -393,12 +393,12 @@ export class AppRig {
return isAnyToolActive || isAwaitingConfirmation;
}
render() {
async render() {
if (!this.config || !this.settings)
throw new Error('AppRig not initialized');
act(() => {
this.renderResult = renderWithProviders(
await act(async () => {
this.renderResult = await renderWithProviders(
<AppContainer
config={this.config!}
version="test-version"
@@ -46,15 +46,19 @@ describe('createMockCommandContext', () => {
const overrides = {
services: {
config: mockConfig,
agentContext: { config: mockConfig },
},
};
const context = createMockCommandContext(overrides);
expect(context.services.config).toBeDefined();
expect(context.services.config?.getModel()).toBe('gemini-pro');
expect(context.services.config?.getProjectRoot()).toBe('/test/project');
expect(context.services.agentContext).toBeDefined();
expect(context.services.agentContext?.config?.getModel()).toBe(
'gemini-pro',
);
expect(context.services.agentContext?.config?.getProjectRoot()).toBe(
'/test/project',
);
// Verify a default property on the same nested object is still there
expect(context.services.logger).toBeDefined();
@@ -36,7 +36,7 @@ export const createMockCommandContext = (
args: '',
},
services: {
config: null,
agentContext: null,
settings: {
merged: defaultMergedSettings,
+33 -68
View File
@@ -16,8 +16,6 @@ import { vi } from 'vitest';
import stripAnsi from 'strip-ansi';
import type React from 'react';
import { act, useState } from 'react';
import os from 'node:os';
import path from 'node:path';
import type { LoadedSettings } from '../config/settings.js';
import { KeypressProvider } from '../ui/contexts/KeypressContext.js';
import { SettingsContext } from '../ui/contexts/SettingsContext.js';
@@ -44,7 +42,7 @@ import {
type OverflowState,
} from '../ui/contexts/OverflowContext.js';
import { makeFakeConfig, type Config } from '@google/gemini-cli-core';
import { type Config } from '@google/gemini-cli-core';
import { FakePersistentState } from './persistentStateFake.js';
import { AppContext, type AppState } from '../ui/contexts/AppContext.js';
import { createMockSettings } from './settings.js';
@@ -53,6 +51,7 @@ import { themeManager, DEFAULT_THEME } from '../ui/themes/theme-manager.js';
import { DefaultLight } from '../ui/themes/builtin/light/default-light.js';
import { pickDefaultThemeName } from '../ui/themes/theme.js';
import { generateSvgForTerminal } from './svg.js';
import { loadCliConfig, type CliArgs } from '../config/config.js';
export const persistentStateMock = new FakePersistentState();
@@ -66,7 +65,9 @@ if (process.env['NODE_ENV'] === 'test') {
}
vi.mock('../utils/persistentState.js', () => ({
persistentState: persistentStateMock,
get persistentState() {
return persistentStateMock;
},
}));
vi.mock('../ui/utils/terminalUtils.js', () => ({
@@ -486,50 +487,6 @@ export const simulateClick = async (
});
};
let mockConfigInternal: Config | undefined;
const getMockConfigInternal = (): Config => {
if (!mockConfigInternal) {
mockConfigInternal = makeFakeConfig({
targetDir: os.tmpdir(),
enableEventDrivenScheduler: true,
});
}
return mockConfigInternal;
};
const configProxy = new Proxy({} as Config, {
get(_target, prop) {
if (prop === 'getTargetDir') {
return () =>
path.join(
path.parse(process.cwd()).root,
'Users',
'test',
'project',
'foo',
'bar',
'and',
'some',
'more',
'directories',
'to',
'make',
'it',
'long',
);
}
if (prop === 'getUseBackgroundColor') {
return () => true;
}
const internal = getMockConfigInternal();
if (prop in internal) {
return internal[prop as keyof typeof internal];
}
throw new Error(`mockConfig does not have property ${String(prop)}`);
},
});
export const mockSettings = createMockSettings();
// A minimal mock UIState to satisfy the context provider.
@@ -639,7 +596,7 @@ const ContextCapture: React.FC<{ children: React.ReactNode }> = ({
return <>{children}</>;
};
export const renderWithProviders = (
export const renderWithProviders = async (
component: React.ReactElement,
{
shellFocus = true,
@@ -647,8 +604,7 @@ export const renderWithProviders = (
uiState: providedUiState,
width,
mouseEventsEnabled = false,
config = configProxy as unknown as Config,
config,
uiActions,
persistentState,
appState = mockAppState,
@@ -666,13 +622,15 @@ export const renderWithProviders = (
};
appState?: AppState;
} = {},
): RenderInstance & {
simulateClick: (
col: number,
row: number,
button?: 0 | 1 | 2,
) => Promise<void>;
} => {
): Promise<
RenderInstance & {
simulateClick: (
col: number,
row: number,
button?: 0 | 1 | 2,
) => Promise<void>;
}
> => {
const baseState: UIState = new Proxy(
{ ...baseMockUiState, ...providedUiState },
{
@@ -701,8 +659,15 @@ export const renderWithProviders = (
persistentStateMock.mockClear();
const terminalWidth = width ?? baseState.terminalWidth;
const finalSettings = settings;
const finalConfig = config;
if (!config) {
config = await loadCliConfig(
settings.merged,
'random-session-id',
{} as unknown as CliArgs,
{ cwd: '/' },
);
}
const mainAreaWidth = terminalWidth;
@@ -732,8 +697,8 @@ export const renderWithProviders = (
const wrapWithProviders = (comp: React.ReactElement) => (
<AppContext.Provider value={appState}>
<ConfigContext.Provider value={finalConfig}>
<SettingsContext.Provider value={finalSettings}>
<ConfigContext.Provider value={config}>
<SettingsContext.Provider value={settings}>
<UIStateContext.Provider value={finalUiState}>
<VimModeProvider>
<ShellFocusContext.Provider value={shellFocus}>
@@ -744,7 +709,7 @@ export const renderWithProviders = (
<UIActionsContext.Provider value={finalUIActions}>
<OverflowProvider>
<ToolActionsProvider
config={finalConfig}
config={config}
toolCalls={allToolCalls}
>
<AskUserActionsProvider
@@ -863,7 +828,7 @@ export function renderHook<Result, Props>(
return { result, rerender, unmount, waitUntilReady, generateSvg };
}
export function renderHookWithProviders<Result, Props>(
export async function renderHookWithProviders<Result, Props>(
renderCallback: (props: Props) => Result,
options: {
initialProps?: Props;
@@ -876,13 +841,13 @@ export function renderHookWithProviders<Result, Props>(
mouseEventsEnabled?: boolean;
config?: Config;
} = {},
): {
): Promise<{
result: { current: Result };
rerender: (props?: Props) => void;
unmount: () => void;
waitUntilReady: () => Promise<void>;
generateSvg: () => string;
} {
}> {
const result = { current: undefined as unknown as Result };
let setPropsFn: ((props: Props) => void) | undefined;
@@ -901,8 +866,8 @@ export function renderHookWithProviders<Result, Props>(
let renderResult: ReturnType<typeof render>;
act(() => {
renderResult = renderWithProviders(
await act(async () => {
renderResult = await renderWithProviders(
<Wrapper>
{}
<TestComponent initialProps={options.initialProps as Props} />
+11 -21
View File
@@ -94,11 +94,10 @@ describe('App', () => {
};
it('should render main content and composer when not quitting', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: mockUIState,
config: makeFakeConfig({ useAlternateBuffer: false }),
settings: createMockSettings({ ui: { useAlternateBuffer: false } }),
},
);
@@ -116,11 +115,10 @@ describe('App', () => {
quittingMessages: [{ id: 1, type: 'user', text: 'test' }],
} as UIState;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: quittingUIState,
config: makeFakeConfig({ useAlternateBuffer: false }),
settings: createMockSettings({ ui: { useAlternateBuffer: false } }),
},
);
@@ -138,11 +136,10 @@ describe('App', () => {
pendingHistoryItems: [{ type: 'user', text: 'pending item' }],
} as UIState;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: quittingUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -159,11 +156,10 @@ describe('App', () => {
dialogsVisible: true,
} as UIState;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: dialogUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -187,11 +183,10 @@ describe('App', () => {
[stateKey]: true,
} as UIState;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -205,11 +200,10 @@ describe('App', () => {
it('should render ScreenReaderAppLayout when screen reader is enabled', async () => {
(useIsScreenReaderEnabled as Mock).mockReturnValue(true);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: mockUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -225,11 +219,10 @@ describe('App', () => {
it('should render DefaultAppLayout when screen reader is not enabled', async () => {
(useIsScreenReaderEnabled as Mock).mockReturnValue(false);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: mockUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -281,7 +274,7 @@ describe('App', () => {
vi.spyOn(configWithExperiment, 'isTrustedFolder').mockReturnValue(true);
vi.spyOn(configWithExperiment, 'getIdeMode').mockReturnValue(false);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: stateWithConfirmingTool,
@@ -302,11 +295,10 @@ describe('App', () => {
describe('Snapshots', () => {
it('renders default layout correctly', async () => {
(useIsScreenReaderEnabled as Mock).mockReturnValue(false);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: mockUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -317,11 +309,10 @@ describe('App', () => {
it('renders screen reader layout correctly', async () => {
(useIsScreenReaderEnabled as Mock).mockReturnValue(true);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: mockUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
@@ -335,11 +326,10 @@ describe('App', () => {
...mockUIState,
dialogsVisible: true,
} as UIState;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<App />,
{
uiState: dialogUIState,
config: makeFakeConfig({ useAlternateBuffer: true }),
settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
},
);
+4 -4
View File
@@ -212,7 +212,7 @@ import { useEditorSettings } from './hooks/useEditorSettings.js';
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
import { useModelCommand } from './hooks/useModelCommand.js';
import { useSlashCommandProcessor } from './hooks/slashCommandProcessor.js';
import { useConsoleMessages } from './hooks/useConsoleMessages.js';
import { useErrorCount } from './hooks/useConsoleMessages.js';
import { useGeminiStream } from './hooks/useGeminiStream.js';
import { useVim } from './hooks/vim.js';
import { useFolderTrust } from './hooks/useFolderTrust.js';
@@ -294,7 +294,7 @@ describe('AppContainer State Management', () => {
const mockedUseSettingsCommand = useSettingsCommand as Mock;
const mockedUseModelCommand = useModelCommand as Mock;
const mockedUseSlashCommandProcessor = useSlashCommandProcessor as Mock;
const mockedUseConsoleMessages = useConsoleMessages as Mock;
const mockedUseConsoleMessages = useErrorCount as Mock;
const mockedUseGeminiStream = useGeminiStream as Mock;
const mockedUseVim = useVim as Mock;
const mockedUseFolderTrust = useFolderTrust as Mock;
@@ -396,9 +396,9 @@ describe('AppContainer State Management', () => {
confirmationRequest: null,
});
mockedUseConsoleMessages.mockReturnValue({
consoleMessages: [],
errorCount: 0,
handleNewMessage: vi.fn(),
clearConsoleMessages: vi.fn(),
clearErrorCount: vi.fn(),
});
mockedUseGeminiStream.mockReturnValue(DEFAULT_GEMINI_STREAM_MOCK);
mockedUseVim.mockReturnValue({ handleInput: vi.fn() });
+15 -26
View File
@@ -103,7 +103,7 @@ import {
useOverflowActions,
useOverflowState,
} from './contexts/OverflowContext.js';
import { useConsoleMessages } from './hooks/useConsoleMessages.js';
import { useErrorCount } from './hooks/useConsoleMessages.js';
import { useTerminalSize } from './hooks/useTerminalSize.js';
import { calculatePromptWidths } from './components/InputPrompt.js';
import { calculateMainAreaWidth } from './utils/ui-sizing.js';
@@ -552,8 +552,7 @@ export const AppContainer = (props: AppContainerProps) => {
};
}, [settings]);
const { consoleMessages, clearConsoleMessages: clearConsoleMessagesState } =
useConsoleMessages();
const { errorCount, clearErrorCount } = useErrorCount();
const mainAreaWidth = calculateMainAreaWidth(terminalWidth, config);
// Derive widths for InputPrompt using shared helper
@@ -1008,10 +1007,18 @@ Logging in with Google... Restarting Gemini CLI to continue.
Date.now(),
);
try {
const { memoryContent, fileCount } =
await refreshServerHierarchicalMemory(config);
let flattenedMemory: string;
let fileCount: number;
const flattenedMemory = flattenMemory(memoryContent);
if (config.isJitContextEnabled()) {
await config.getContextManager()?.refresh();
flattenedMemory = flattenMemory(config.getUserMemory());
fileCount = config.getGeminiMdFileCount();
} else {
const result = await refreshServerHierarchicalMemory(config);
flattenedMemory = flattenMemory(result.memoryContent);
fileCount = result.fileCount;
}
historyManager.addItem(
{
@@ -1372,11 +1379,11 @@ Logging in with Google... Restarting Gemini CLI to continue.
// Explicitly hide the expansion hint and clear its x-second timer when clearing the screen.
triggerExpandHint(null);
historyManager.clearItems();
clearConsoleMessagesState();
clearErrorCount();
refreshStatic();
}, [
historyManager,
clearConsoleMessagesState,
clearErrorCount,
refreshStatic,
reset,
triggerExpandHint,
@@ -1983,22 +1990,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
};
}, [historyManager]);
const filteredConsoleMessages = useMemo(() => {
if (config.getDebugMode()) {
return consoleMessages;
}
return consoleMessages.filter((msg) => msg.type !== 'debug');
}, [consoleMessages, config]);
// Computed values
const errorCount = useMemo(
() =>
filteredConsoleMessages
.filter((msg) => msg.type === 'error')
.reduce((total, msg) => total + msg.count, 0),
[filteredConsoleMessages],
);
const nightly = props.version.includes('nightly');
const dialogsVisible =
@@ -2233,7 +2224,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
constrainHeight,
showErrorDetails,
showFullTodos,
filteredConsoleMessages,
ideContextState,
renderMarkdown,
ctrlCPressedOnce: ctrlCPressCount >= 1,
@@ -2361,7 +2351,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
constrainHeight,
showErrorDetails,
showFullTodos,
filteredConsoleMessages,
ideContextState,
renderMarkdown,
ctrlCPressCount,
@@ -53,7 +53,7 @@ describe('IdeIntegrationNudge', () => {
});
it('renders correctly with default options', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} />,
);
await waitUntilReady();
@@ -68,7 +68,7 @@ describe('IdeIntegrationNudge', () => {
it('handles "Yes" selection', async () => {
const onComplete = vi.fn();
const { stdin, waitUntilReady, unmount } = renderWithProviders(
const { stdin, waitUntilReady, unmount } = await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
@@ -89,7 +89,7 @@ describe('IdeIntegrationNudge', () => {
it('handles "No" selection', async () => {
const onComplete = vi.fn();
const { stdin, waitUntilReady, unmount } = renderWithProviders(
const { stdin, waitUntilReady, unmount } = await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
@@ -115,7 +115,7 @@ describe('IdeIntegrationNudge', () => {
it('handles "Dismiss" selection', async () => {
const onComplete = vi.fn();
const { stdin, waitUntilReady, unmount } = renderWithProviders(
const { stdin, waitUntilReady, unmount } = await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
@@ -146,7 +146,7 @@ describe('IdeIntegrationNudge', () => {
it('handles Escape key press', async () => {
const onComplete = vi.fn();
const { stdin, waitUntilReady, unmount } = renderWithProviders(
const { stdin, waitUntilReady, unmount } = await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
@@ -173,9 +173,10 @@ describe('IdeIntegrationNudge', () => {
vi.stubEnv('GEMINI_CLI_IDE_WORKSPACE_PATH', '/tmp');
const onComplete = vi.fn();
const { lastFrame, stdin, waitUntilReady, unmount } = renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
const { lastFrame, stdin, waitUntilReady, unmount } =
await renderWithProviders(
<IdeIntegrationNudge {...defaultProps} onComplete={onComplete} />,
);
await waitUntilReady();
+17 -17
View File
@@ -143,7 +143,7 @@ describe('AuthDialog', () => {
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value as string);
}
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -161,7 +161,7 @@ describe('AuthDialog', () => {
it('filters auth types when enforcedType is set', async () => {
props.settings.merged.security.auth.enforcedType = AuthType.USE_GEMINI;
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -173,7 +173,7 @@ describe('AuthDialog', () => {
it('sets initial index to 0 when enforcedType is set', async () => {
props.settings.merged.security.auth.enforcedType = AuthType.USE_GEMINI;
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -213,7 +213,7 @@ describe('AuthDialog', () => {
},
])('selects initial auth type $desc', async ({ setup, expected }) => {
setup();
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -226,7 +226,7 @@ describe('AuthDialog', () => {
describe('handleAuthSelect', () => {
it('calls onAuthError if validation fails', async () => {
mockedValidateAuthMethod.mockReturnValue('Invalid method');
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -245,7 +245,7 @@ describe('AuthDialog', () => {
it('sets auth context with requiresRestart: true for LOGIN_WITH_GOOGLE', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -261,7 +261,7 @@ describe('AuthDialog', () => {
it('sets auth context with empty object for other auth types', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -278,7 +278,7 @@ describe('AuthDialog', () => {
vi.stubEnv('GEMINI_API_KEY', 'test-key-from-env');
// props.settings.merged.security.auth.selectedType is undefined here, simulating initial setup
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -297,7 +297,7 @@ describe('AuthDialog', () => {
vi.stubEnv('GEMINI_API_KEY', ''); // Empty string
// props.settings.merged.security.auth.selectedType is undefined here
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -316,7 +316,7 @@ describe('AuthDialog', () => {
// process.env['GEMINI_API_KEY'] is not set
// props.settings.merged.security.auth.selectedType is undefined here, simulating initial setup
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -337,7 +337,7 @@ describe('AuthDialog', () => {
props.settings.merged.security.auth.selectedType =
AuthType.LOGIN_WITH_GOOGLE;
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -360,7 +360,7 @@ describe('AuthDialog', () => {
vi.mocked(props.config.isBrowserLaunchSuppressed).mockReturnValue(true);
mockedValidateAuthMethod.mockReturnValue(null);
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -383,7 +383,7 @@ describe('AuthDialog', () => {
it('displays authError when provided', async () => {
props.authError = 'Something went wrong';
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -429,7 +429,7 @@ describe('AuthDialog', () => {
},
])('$desc', async ({ setup, expectations }) => {
setup();
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -442,7 +442,7 @@ describe('AuthDialog', () => {
describe('Snapshots', () => {
it('renders correctly with default props', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -452,7 +452,7 @@ describe('AuthDialog', () => {
it('renders correctly with auth error', async () => {
props.authError = 'Something went wrong';
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -462,7 +462,7 @@ describe('AuthDialog', () => {
it('renders correctly with enforced auth type', async () => {
props.settings.merged.security.auth.enforcedType = AuthType.USE_GEMINI;
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<AuthDialog {...props} />,
);
await waitUntilReady();
@@ -73,7 +73,7 @@ describe('BannedAccountDialog', () => {
});
it('renders the suspension message from accountSuspensionInfo', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -89,7 +89,7 @@ describe('BannedAccountDialog', () => {
});
it('renders menu options with appeal link text from response', async () => {
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -109,7 +109,7 @@ describe('BannedAccountDialog', () => {
const infoWithoutUrl: AccountSuspensionInfo = {
message: 'Account suspended.',
};
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={infoWithoutUrl}
onExit={onExit}
@@ -129,7 +129,7 @@ describe('BannedAccountDialog', () => {
message: 'Account suspended.',
appealUrl: 'https://example.com/appeal',
};
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={infoWithoutLinkText}
onExit={onExit}
@@ -143,7 +143,7 @@ describe('BannedAccountDialog', () => {
});
it('opens browser when appeal option is selected', async () => {
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -162,7 +162,7 @@ describe('BannedAccountDialog', () => {
it('shows URL when browser cannot be launched', async () => {
mockedShouldLaunchBrowser.mockReturnValue(false);
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -180,7 +180,7 @@ describe('BannedAccountDialog', () => {
});
it('calls onExit when "Exit" is selected', async () => {
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -196,7 +196,7 @@ describe('BannedAccountDialog', () => {
});
it('calls onChangeAuth when "Change authentication" is selected', async () => {
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -212,7 +212,7 @@ describe('BannedAccountDialog', () => {
});
it('exits on escape key', async () => {
const { waitUntilReady, unmount } = renderWithProviders(
const { waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -227,7 +227,7 @@ describe('BannedAccountDialog', () => {
});
it('renders snapshot correctly', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
const { lastFrame, waitUntilReady, unmount } = await renderWithProviders(
<BannedAccountDialog
accountSuspensionInfo={DEFAULT_SUSPENSION_INFO}
onExit={onExit}
@@ -36,10 +36,12 @@ describe('aboutCommand', () => {
beforeEach(() => {
mockContext = createMockCommandContext({
services: {
config: {
getModel: vi.fn(),
getIdeMode: vi.fn().mockReturnValue(true),
getUserTierName: vi.fn().mockReturnValue(undefined),
agentContext: {
config: {
getModel: vi.fn(),
getIdeMode: vi.fn().mockReturnValue(true),
getUserTierName: vi.fn().mockReturnValue(undefined),
},
},
settings: {
merged: {
@@ -57,9 +59,10 @@ describe('aboutCommand', () => {
} as unknown as CommandContext);
vi.mocked(getVersion).mockResolvedValue('test-version');
vi.spyOn(mockContext.services.config!, 'getModel').mockReturnValue(
'test-model',
);
vi.spyOn(
mockContext.services.agentContext!.config,
'getModel',
).mockReturnValue('test-model');
process.env['GOOGLE_CLOUD_PROJECT'] = 'test-gcp-project';
Object.defineProperty(process, 'platform', {
value: 'test-os',
@@ -160,9 +163,9 @@ describe('aboutCommand', () => {
});
it('should display the tier when getUserTierName returns a value', async () => {
vi.mocked(mockContext.services.config!.getUserTierName).mockReturnValue(
'Enterprise Tier',
);
vi.mocked(
mockContext.services.agentContext!.config.getUserTierName,
).mockReturnValue('Enterprise Tier');
if (!aboutCommand.action) {
throw new Error('The about command must have an action.');
}
+4 -3
View File
@@ -34,7 +34,8 @@ export const aboutCommand: SlashCommand = {
process.env['SEATBELT_PROFILE'] || 'unknown'
})`;
}
const modelVersion = context.services.config?.getModel() || 'Unknown';
const modelVersion =
context.services.agentContext?.config.getModel() || 'Unknown';
const cliVersion = await getVersion();
const selectedAuthType =
context.services.settings.merged.security.auth.selectedType || '';
@@ -48,7 +49,7 @@ export const aboutCommand: SlashCommand = {
});
const userEmail = cachedAccount ?? undefined;
const tier = context.services.config?.getUserTierName();
const tier = context.services.agentContext?.config.getUserTierName();
const aboutItem: Omit<HistoryItemAbout, 'id'> = {
type: MessageType.ABOUT,
@@ -68,7 +69,7 @@ export const aboutCommand: SlashCommand = {
};
async function getIdeClientName(context: CommandContext) {
if (!context.services.config?.getIdeMode()) {
if (!context.services.agentContext?.config.getIdeMode()) {
return '';
}
const ideClient = await IdeClient.getInstance();
@@ -26,6 +26,7 @@ describe('agentsCommand', () => {
let mockContext: ReturnType<typeof createMockCommandContext>;
let mockConfig: {
getAgentRegistry: ReturnType<typeof vi.fn>;
config: Config;
};
beforeEach(() => {
@@ -37,11 +38,14 @@ describe('agentsCommand', () => {
getAllAgentNames: vi.fn().mockReturnValue([]),
reload: vi.fn(),
}),
get config() {
return this as unknown as Config;
},
};
mockContext = createMockCommandContext({
services: {
config: mockConfig as unknown as Config,
agentContext: mockConfig as unknown as Config,
settings: {
workspace: { path: '/mock/path' },
merged: { agents: { overrides: {} } },
@@ -53,7 +57,7 @@ describe('agentsCommand', () => {
it('should show an error if config is not available', async () => {
const contextWithoutConfig = createMockCommandContext({
services: {
config: null,
agentContext: null,
},
});
@@ -226,7 +230,7 @@ describe('agentsCommand', () => {
it('should show an error if config is not available for enable', async () => {
const contextWithoutConfig = createMockCommandContext({
services: { config: null },
services: { agentContext: null },
});
const enableCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'enable',
@@ -332,7 +336,7 @@ describe('agentsCommand', () => {
it('should show an error if config is not available for disable', async () => {
const contextWithoutConfig = createMockCommandContext({
services: { config: null },
services: { agentContext: null },
});
const disableCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'disable',
@@ -433,7 +437,7 @@ describe('agentsCommand', () => {
it('should show an error if config is not available', async () => {
const contextWithoutConfig = createMockCommandContext({
services: { config: null },
services: { agentContext: null },
});
const configCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'config',
+11 -8
View File
@@ -21,7 +21,7 @@ const agentsListCommand: SlashCommand = {
kind: CommandKind.BUILT_IN,
autoExecute: true,
action: async (context: CommandContext) => {
const { config } = context.services;
const config = context.services.agentContext?.config;
if (!config) {
return {
type: 'message',
@@ -61,7 +61,8 @@ async function enableAction(
context: CommandContext,
args: string,
): Promise<SlashCommandActionReturn | void> {
const { config, settings } = context.services;
const config = context.services.agentContext?.config;
const { settings } = context.services;
if (!config) {
return {
type: 'message',
@@ -137,7 +138,8 @@ async function disableAction(
context: CommandContext,
args: string,
): Promise<SlashCommandActionReturn | void> {
const { config, settings } = context.services;
const config = context.services.agentContext?.config;
const { settings } = context.services;
if (!config) {
return {
type: 'message',
@@ -216,7 +218,7 @@ async function configAction(
context: CommandContext,
args: string,
): Promise<SlashCommandActionReturn | void> {
const { config } = context.services;
const config = context.services.agentContext?.config;
if (!config) {
return {
type: 'message',
@@ -266,7 +268,8 @@ async function configAction(
}
function completeAgentsToEnable(context: CommandContext, partialArg: string) {
const { config, settings } = context.services;
const config = context.services.agentContext?.config;
const { settings } = context.services;
if (!config) return [];
const overrides = settings.merged.agents.overrides;
@@ -278,7 +281,7 @@ function completeAgentsToEnable(context: CommandContext, partialArg: string) {
}
function completeAgentsToDisable(context: CommandContext, partialArg: string) {
const { config } = context.services;
const config = context.services.agentContext?.config;
if (!config) return [];
const agentRegistry = config.getAgentRegistry();
@@ -287,7 +290,7 @@ function completeAgentsToDisable(context: CommandContext, partialArg: string) {
}
function completeAllAgents(context: CommandContext, partialArg: string) {
const { config } = context.services;
const config = context.services.agentContext?.config;
if (!config) return [];
const agentRegistry = config.getAgentRegistry();
@@ -328,7 +331,7 @@ const agentsReloadCommand: SlashCommand = {
description: 'Reload the agent registry',
kind: CommandKind.BUILT_IN,
action: async (context: CommandContext) => {
const { config } = context.services;
const config = context.services.agentContext?.config;
const agentRegistry = config?.getAgentRegistry();
if (!agentRegistry) {
return {
@@ -9,6 +9,7 @@ import { authCommand } from './authCommand.js';
import { type CommandContext } from './types.js';
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
import { SettingScope } from '../../config/settings.js';
import type { GeminiClient } from '@google/gemini-cli-core';
vi.mock('@google/gemini-cli-core', async () => {
const actual = await vi.importActual('@google/gemini-cli-core');
@@ -24,8 +25,10 @@ describe('authCommand', () => {
beforeEach(() => {
mockContext = createMockCommandContext({
services: {
config: {
getGeminiClient: vi.fn(),
agentContext: {
geminiClient: {
stripThoughtsFromHistory: vi.fn(),
},
},
},
});
@@ -101,17 +104,19 @@ describe('authCommand', () => {
const mockStripThoughts = vi.fn();
const mockClient = {
stripThoughtsFromHistory: mockStripThoughts,
} as unknown as ReturnType<
NonNullable<typeof mockContext.services.config>['getGeminiClient']
>;
if (mockContext.services.config) {
mockContext.services.config.getGeminiClient = vi.fn(() => mockClient);
} as unknown as GeminiClient;
if (mockContext.services.agentContext?.config) {
mockContext.services.agentContext.config.getGeminiClient = vi.fn(
() => mockClient,
);
}
await logoutCommand!.action!(mockContext, '');
expect(mockStripThoughts).toHaveBeenCalled();
expect(
mockContext.services.agentContext?.geminiClient
.stripThoughtsFromHistory,
).toHaveBeenCalled();
});
it('should return logout action to signal explicit state change', async () => {
@@ -123,7 +128,7 @@ describe('authCommand', () => {
it('should handle missing config gracefully', async () => {
const logoutCommand = authCommand.subCommands?.[1];
mockContext.services.config = null;
mockContext.services.agentContext = null;
const result = await logoutCommand!.action!(mockContext, '');
+1 -1
View File
@@ -39,7 +39,7 @@ const authLogoutCommand: SlashCommand = {
undefined,
);
// Strip thoughts from history instead of clearing completely
context.services.config?.getGeminiClient()?.stripThoughtsFromHistory();
context.services.agentContext?.geminiClient.stripThoughtsFromHistory();
// Return logout action to signal explicit state change
return {
type: 'logout',
+29 -23
View File
@@ -83,16 +83,18 @@ describe('bugCommand', () => {
it('should generate the default GitHub issue URL', async () => {
const mockContext = createMockCommandContext({
services: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => undefined,
getIdeMode: () => true,
getGeminiClient: () => ({
agentContext: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => undefined,
getIdeMode: () => true,
getContentGeneratorConfig: () => ({ authType: 'oauth-personal' }),
},
geminiClient: {
getChat: () => ({
getHistory: () => [],
}),
}),
getContentGeneratorConfig: () => ({ authType: 'oauth-personal' }),
},
},
},
});
@@ -126,18 +128,20 @@ describe('bugCommand', () => {
];
const mockContext = createMockCommandContext({
services: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => undefined,
getIdeMode: () => true,
getGeminiClient: () => ({
agentContext: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => undefined,
getIdeMode: () => true,
getContentGeneratorConfig: () => ({ authType: 'vertex-ai' }),
storage: {
getProjectTempDir: () => '/tmp/gemini',
},
},
geminiClient: {
getChat: () => ({
getHistory: () => history,
}),
}),
getContentGeneratorConfig: () => ({ authType: 'vertex-ai' }),
storage: {
getProjectTempDir: () => '/tmp/gemini',
},
},
},
@@ -172,16 +176,18 @@ describe('bugCommand', () => {
'https://internal.bug-tracker.com/new?desc={title}&details={info}';
const mockContext = createMockCommandContext({
services: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => ({ urlTemplate: customTemplate }),
getIdeMode: () => true,
getGeminiClient: () => ({
agentContext: {
config: {
getModel: () => 'gemini-pro',
getBugCommand: () => ({ urlTemplate: customTemplate }),
getIdeMode: () => true,
getContentGeneratorConfig: () => ({ authType: 'vertex-ai' }),
},
geminiClient: {
getChat: () => ({
getHistory: () => [],
}),
}),
getContentGeneratorConfig: () => ({ authType: 'vertex-ai' }),
},
},
},
});
+4 -4
View File
@@ -32,8 +32,8 @@ export const bugCommand: SlashCommand = {
autoExecute: false,
action: async (context: CommandContext, args?: string): Promise<void> => {
const bugDescription = (args || '').trim();
const { config } = context.services;
const agentContext = context.services.agentContext;
const config = agentContext?.config;
const osVersion = `${process.platform} ${process.version}`;
let sandboxEnv = 'no sandbox';
if (process.env['SANDBOX'] && process.env['SANDBOX'] !== 'sandbox-exec') {
@@ -73,7 +73,7 @@ export const bugCommand: SlashCommand = {
info += `* **IDE Client:** ${ideClient}\n`;
}
const chat = config?.getGeminiClient()?.getChat();
const chat = agentContext?.geminiClient?.getChat();
const history = chat?.getHistory() || [];
let historyFileMessage = '';
let problemValue = bugDescription;
@@ -134,7 +134,7 @@ export const bugCommand: SlashCommand = {
};
async function getIdeClientName(context: CommandContext) {
if (!context.services.config?.getIdeMode()) {
if (!context.services.agentContext?.config.getIdeMode()) {
return '';
}
const ideClient = await IdeClient.getInstance();
@@ -70,18 +70,19 @@ describe('chatCommand', () => {
mockContext = createMockCommandContext({
services: {
config: {
getProjectRoot: () => '/project/root',
getGeminiClient: () =>
({
getChat: mockGetChat,
}) as unknown as GeminiClient,
storage: {
getProjectTempDir: () => '/project/root/.gemini/tmp/mockhash',
agentContext: {
config: {
getProjectRoot: () => '/project/root',
getContentGeneratorConfig: () => ({
authType: AuthType.LOGIN_WITH_GOOGLE,
}),
storage: {
getProjectTempDir: () => '/project/root/.gemini/tmp/mockhash',
},
},
getContentGeneratorConfig: () => ({
authType: AuthType.LOGIN_WITH_GOOGLE,
}),
geminiClient: {
getChat: mockGetChat,
} as unknown as GeminiClient,
},
logger: {
saveCheckpoint: mockSaveCheckpoint,
@@ -698,7 +699,11 @@ Hi there!`;
beforeEach(() => {
mockGetLatestApiRequest = vi.fn();
mockContext.services.config!.getLatestApiRequest =
if (!mockContext.services.agentContext!.config) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mockContext.services.agentContext!.config as any) = {};
}
mockContext.services.agentContext!.config.getLatestApiRequest =
mockGetLatestApiRequest;
vi.spyOn(process, 'cwd').mockReturnValue('/project/root');
vi.spyOn(Date, 'now').mockReturnValue(1234567890);

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