Compare commits

...

30 Commits

Author SHA1 Message Date
Adam Weidman 14fe9815d0 fix(core): align wrapper replay semantics 2026-03-23 11:42:46 -04:00
Adam Weidman 2582669d62 fix(core): align legacy session tests with loop warnings 2026-03-23 10:58:41 -04:00
Adam Weidman 7abec8e3c7 !feat(core): tighten legacy agent session stream lifecycle 2026-03-23 10:57:55 -04:00
Adam Weidman f038ba417f !feat(core): adapt legacy session to merged agent session 2026-03-23 10:57:40 -04:00
Adam Weidman 1ee198cc2c !feat(core): clarify agent session resume boundaries 2026-03-23 10:57:21 -04:00
Adam Weidman 18544cc994 !feat(core): clarify mock stream event typing 2026-03-23 10:57:20 -04:00
Adam Weidman 139a5f3202 !feat(core): correlate all protocol events to streams 2026-03-23 10:56:52 -04:00
Adam Weidman db0624c6cd !feat(core): harden agent session stream semantics 2026-03-23 10:56:52 -04:00
Adam Weidman 1947629a38 !feat(core): harden agent session stream semantics 2026-03-23 10:56:52 -04:00
Adam Weidman 3878599772 !feat(core): surface loop detection as a warning 2026-03-23 09:57:45 -04:00
Adam Weidman db35ecd705 fix: resolve inherited strict typing violations 2026-03-20 11:59:02 -04:00
Adam Weidman 1b6c609165 refactor(core): end sessions after finished turns 2026-03-20 10:58:58 -04:00
Adam Weidman 6c9f644417 refactor(core): treat max session turns as stream end 2026-03-20 10:58:58 -04:00
Adam Weidman cc2058296c fix: address easy code review comments for event-translator 2026-03-20 10:58:58 -04:00
Adam Weidman fb1b814ff8 feat(core): add event-translator and update agent types 2026-03-20 10:58:58 -04:00
Michael Bleigh b9c87c14a2 feat(core): introduce AgentSession and rename stream events to agent events (#23159) 2026-03-20 13:40:10 +00:00
nmcnamara-eng 52250c162d feat(cli): conditionally exclude ask_user tool in ACP mode (#23045)
Co-authored-by: Sri Pasumarthi <sripas@google.com>
Co-authored-by: Sri Pasumarthi <111310667+sripasg@users.noreply.github.com>
2026-03-20 06:18:55 +00:00
matt korwel b52641de0d chore(lint): ignore .gemini directory and recursive node_modules (#23211) 2026-03-20 05:57:59 +00: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
122 changed files with 8424 additions and 785 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
+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`:**
+8 -3
View File
@@ -41,7 +41,7 @@ export default tseslint.config(
{
// Global ignores
ignores: [
'node_modules/*',
'**/node_modules/**',
'eslint.config.js',
'packages/**/dist/**',
'bundle/**',
@@ -50,7 +50,7 @@ export default tseslint.config(
'dist/**',
'evals/**',
'packages/test-utils/**',
'.gemini/skills/**',
'.gemini/**',
'**/*.d.ts',
],
},
@@ -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,
+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",
+8 -8
View File
@@ -551,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 () => {
@@ -750,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 () => {
@@ -767,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),
@@ -789,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),
@@ -811,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),
@@ -833,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),
@@ -855,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();
});
@@ -909,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 () => {
+62 -2
View File
@@ -699,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) {
@@ -727,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 &&
@@ -763,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 };
}
@@ -799,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(
+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: {},
},
};
+24
View File
@@ -2225,6 +2225,30 @@ describe('loadCliConfig tool exclusions', () => {
expect(config.getExcludeTools()).toContain('ask_user');
});
it('should exclude ask_user in interactive mode when --acp is provided', async () => {
process.stdin.isTTY = true;
process.argv = ['node', 'script.js', '--acp'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings(),
'test-session',
argv,
);
expect(config.getExcludeTools()).toContain('ask_user');
});
it('should exclude ask_user in interactive mode when --experimental-acp is provided', async () => {
process.stdin.isTTY = true;
process.argv = ['node', 'script.js', '--experimental-acp'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings(),
'test-session',
argv,
);
expect(config.getExcludeTools()).toContain('ask_user');
});
it('should not exclude shell tool in non-interactive mode when --allowed-tools="ShellTool" is set', async () => {
process.stdin.isTTY = false;
process.argv = [
+39 -2
View File
@@ -36,6 +36,7 @@ import {
Config,
resolveToRealPath,
applyAdminAllowlist,
applyRequiredServers,
getAdminBlockedMcpServersMessage,
type HookDefinition,
type HookEventName,
@@ -648,12 +649,16 @@ export async function loadCliConfig(
const allowedTools = argv.allowedTools || settings.tools?.allowed || [];
const isAcpMode = !!argv.acp || !!argv.experimentalAcp;
// In non-interactive mode, exclude tools that require a prompt.
const extraExcludes: string[] = [];
if (!interactive) {
if (!interactive || isAcpMode) {
// The Policy Engine natively handles headless safety by translating ASK_USER
// decisions to DENY. However, we explicitly block ask_user here to guarantee
// it can never be allowed via a high-priority policy rule when no human is present.
// We also exclude it in ACP mode as IDEs intercept tool calls and ask for permission,
// breaking conversational flows.
extraExcludes.push(ASK_USER_TOOL_NAME);
}
@@ -702,6 +707,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,7 +755,25 @@ export async function loadCliConfig(
}
}
const isAcpMode = !!argv.acp || !!argv.experimentalAcp;
// 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(', ')}`,
);
}
}
}
let clientName: string | undefined = undefined;
if (isAcpMode) {
const ide = detectIdeFromEnv();
@@ -840,6 +876,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 {
+11 -3
View File
@@ -1007,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(
{
@@ -116,7 +116,9 @@ describe('policiesCommand', () => {
expect(content).toContain(
'### Yolo Mode Policies (combined with normal mode policies)',
);
expect(content).toContain('### Plan Mode Policies');
expect(content).toContain(
'### Plan Mode Policies (combined with normal mode policies)',
);
expect(content).toContain(
'**DENY** tool: `dangerousTool` [Priority: 10]',
);
@@ -162,7 +164,9 @@ describe('policiesCommand', () => {
const content = (call[0] as { text: string }).text;
// Plan-only rules appear under Plan Mode section
expect(content).toContain('### Plan Mode Policies');
expect(content).toContain(
'### Plan Mode Policies (combined with normal mode policies)',
);
// glob ALLOW is plan-only, should appear in plan section
expect(content).toContain('**ALLOW** tool: `glob` [Priority: 70]');
// shell ALLOW has no modes (applies to all), appears in normal section
@@ -100,7 +100,10 @@ const listPoliciesCommand: SlashCommand = {
'Yolo Mode Policies (combined with normal mode policies)',
uniqueYolo,
);
content += formatSection('Plan Mode Policies', uniquePlan);
content += formatSection(
'Plan Mode Policies (combined with normal mode policies)',
uniquePlan,
);
context.ui.addItem(
{
+109 -2
View File
@@ -68,6 +68,17 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
useGemini31 && selectedAuthType === AuthType.USE_GEMINI;
const manualModelSelected = useMemo(() => {
if (
config?.getExperimentalDynamicModelConfiguration?.() === true &&
config.modelConfigService
) {
const def = config.modelConfigService.getModelDefinition(preferredModel);
// Only treat as manual selection if it's a visible, non-auto model.
return def && def.tier !== 'auto' && def.isVisible === true
? preferredModel
: '';
}
const manualModels = [
DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_FLASH_MODEL,
@@ -81,7 +92,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
return preferredModel;
}
return '';
}, [preferredModel]);
}, [preferredModel, config]);
useKeypress(
(key) => {
@@ -103,6 +114,47 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
);
const mainOptions = useMemo(() => {
// --- DYNAMIC PATH ---
if (
config?.getExperimentalDynamicModelConfiguration?.() === true &&
config.modelConfigService
) {
const list = Object.entries(
config.modelConfigService.getModelDefinitions?.() ?? {},
)
.filter(([_, m]) => {
// Basic visibility and Preview access
if (m.isVisible !== true) return false;
if (m.isPreview && !shouldShowPreviewModels) return false;
// Only auto models are shown on the main menu
if (m.tier !== 'auto') return false;
return true;
})
.map(([id, m]) => ({
value: id,
title: m.displayName ?? getDisplayString(id, config ?? undefined),
description:
id === 'auto-gemini-3' && useGemini31
? (m.dialogDescription ?? '').replace(
'gemini-3-pro',
'gemini-3.1-pro',
)
: (m.dialogDescription ?? ''),
key: id,
}));
list.push({
value: 'Manual',
title: manualModelSelected
? `Manual (${getDisplayString(manualModelSelected, config ?? undefined)})`
: 'Manual',
description: 'Manually select a model',
key: 'Manual',
});
return list;
}
// --- LEGACY PATH ---
const list = [
{
value: DEFAULT_GEMINI_MODEL_AUTO,
@@ -132,10 +184,65 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
});
}
return list;
}, [shouldShowPreviewModels, manualModelSelected, useGemini31]);
}, [config, shouldShowPreviewModels, manualModelSelected, useGemini31]);
const manualOptions = useMemo(() => {
const isFreeTier = config?.getUserTier() === UserTierId.FREE;
// --- DYNAMIC PATH ---
if (
config?.getExperimentalDynamicModelConfiguration?.() === true &&
config.modelConfigService
) {
const list = Object.entries(
config.modelConfigService.getModelDefinitions?.() ?? {},
)
.filter(([id, m]) => {
// Basic visibility and Preview access
if (m.isVisible !== true) return false;
if (m.isPreview && !shouldShowPreviewModels) return false;
// Auto models are for main menu only
if (m.tier === 'auto') return false;
// Pro models are shown for users with pro access
if (!hasAccessToProModel && m.tier === 'pro') return false;
// 3.1 Preview Flash-lite is only available on free tier
if (m.tier === 'flash-lite' && m.isPreview && !isFreeTier)
return false;
// Flag Guard: Versioned models only show if their flag is active.
if (id === PREVIEW_GEMINI_3_1_MODEL && !useGemini31) return false;
if (id === PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL && !useGemini31)
return false;
return true;
})
.map(([id, m]) => {
const resolvedId = config.modelConfigService.resolveModelId(id, {
useGemini3_1: useGemini31,
useCustomTools: useCustomToolModel,
});
// Title ID is the resolved ID without custom tools flag
const titleId = config.modelConfigService.resolveModelId(id, {
useGemini3_1: useGemini31,
});
return {
value: resolvedId,
title:
m.displayName ?? getDisplayString(titleId, config ?? undefined),
key: id,
};
});
// Deduplicate: only show one entry per unique resolved model value.
// This is needed because 3 pro and 3.1 pro models can resolve to the same value.
const seen = new Set<string>();
return list.filter((option) => {
if (seen.has(option.value)) return false;
seen.add(option.value);
return true;
});
}
// --- LEGACY PATH ---
const list = [
{
value: DEFAULT_GEMINI_MODEL,
@@ -0,0 +1,121 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-env node */
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Compiles the GeminiSandbox C# helper on Windows.
* This is used to provide native restricted token sandboxing.
*/
function compileWindowsSandbox() {
if (os.platform() !== 'win32') {
return;
}
const srcHelperPath = path.resolve(
__dirname,
'../src/services/scripts/GeminiSandbox.exe',
);
const distHelperPath = path.resolve(
__dirname,
'../dist/src/services/scripts/GeminiSandbox.exe',
);
const sourcePath = path.resolve(
__dirname,
'../src/services/scripts/GeminiSandbox.cs',
);
if (!fs.existsSync(sourcePath)) {
console.error(`Sandbox source not found at ${sourcePath}`);
return;
}
// Ensure directories exist
[srcHelperPath, distHelperPath].forEach((p) => {
const dir = path.dirname(p);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
});
// Find csc.exe (C# Compiler) which is built into Windows .NET Framework
const systemRoot = process.env['SystemRoot'] || 'C:\\Windows';
const cscPaths = [
'csc.exe', // Try in PATH first
path.join(
systemRoot,
'Microsoft.NET',
'Framework64',
'v4.0.30319',
'csc.exe',
),
path.join(
systemRoot,
'Microsoft.NET',
'Framework',
'v4.0.30319',
'csc.exe',
),
];
let csc = undefined;
for (const p of cscPaths) {
if (p === 'csc.exe') {
const result = spawnSync('where', ['csc.exe'], { stdio: 'ignore' });
if (result.status === 0) {
csc = 'csc.exe';
break;
}
} else if (fs.existsSync(p)) {
csc = p;
break;
}
}
if (!csc) {
console.warn(
'Windows C# compiler (csc.exe) not found. Native sandboxing will attempt to compile on first run.',
);
return;
}
console.log(`Compiling native Windows sandbox helper...`);
// Compile to src
let result = spawnSync(
csc,
[`/out:${srcHelperPath}`, '/optimize', sourcePath],
{
stdio: 'inherit',
},
);
if (result.status === 0) {
console.log('Successfully compiled GeminiSandbox.exe to src');
// Copy to dist if dist exists
const distDir = path.resolve(__dirname, '../dist');
if (fs.existsSync(distDir)) {
const distScriptsDir = path.dirname(distHelperPath);
if (!fs.existsSync(distScriptsDir)) {
fs.mkdirSync(distScriptsDir, { recursive: true });
}
fs.copyFileSync(srcHelperPath, distHelperPath);
console.log('Successfully copied GeminiSandbox.exe to dist');
}
} else {
console.error('Failed to compile Windows sandbox helper.');
}
}
compileWindowsSandbox();
@@ -0,0 +1,480 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it } from 'vitest';
import { AgentSession } from './agent-session.js';
import { MockAgentProtocol } from './mock.js';
import type { AgentEvent } from './types.js';
describe('AgentSession', () => {
it('should passthrough simple methods', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }]);
await session.send({ update: { title: 't' } });
// update, agent_start, message, agent_end = 4 events
expect(session.events).toHaveLength(4);
let emitted = false;
session.subscribe(() => {
emitted = true;
});
protocol.pushResponse([]);
await session.send({ update: { title: 't' } });
expect(emitted).toBe(true);
protocol.pushResponse([], { keepOpen: true });
await session.send({ update: { title: 't' } });
await session.abort();
expect(
session.events.some(
(e) => e.type === 'agent_end' && e.reason === 'aborted',
),
).toBe(true);
});
it('should yield events via sendStream', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'hello' }],
},
]);
const events: AgentEvent[] = [];
for await (const event of session.sendStream({
message: [{ type: 'text', text: 'hi' }],
})) {
events.push(event);
}
// agent_start, agent message, agent_end = 3 events (user message skipped)
expect(events).toHaveLength(3);
expect(events[0].type).toBe('agent_start');
expect(events[1].type).toBe('message');
expect((events[1] as AgentEvent<'message'>).role).toBe('agent');
expect(events[2].type).toBe('agent_end');
});
it('should filter events by streamId in sendStream', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }]);
const events: AgentEvent[] = [];
const stream = session.sendStream({ update: { title: 'foo' } });
for await (const event of stream) {
events.push(event);
}
expect(events).toHaveLength(3); // agent_start, message, agent_end (update skipped)
const streamId = events[0].streamId;
expect(streamId).not.toBeNull();
expect(events.every((e) => e.streamId === streamId)).toBe(true);
});
it('should handle events arriving before send() resolves', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }]);
const events: AgentEvent[] = [];
for await (const event of session.sendStream({
update: { title: 'foo' },
})) {
events.push(event);
}
expect(events).toHaveLength(3); // agent_start, message, agent_end (update skipped)
expect(events[0].type).toBe('agent_start');
expect(events[1].type).toBe('message');
expect(events[2].type).toBe('agent_end');
});
it('should return immediately from sendStream if streamId is null', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
// No response queued, so send() returns streamId: null
const events: AgentEvent[] = [];
for await (const event of session.sendStream({
update: { title: 'foo' },
})) {
events.push(event);
}
expect(events).toHaveLength(0);
expect(protocol.events).toHaveLength(1);
expect(protocol.events[0].type).toBe('session_update');
expect(protocol.events[0].streamId).toEqual(expect.any(String));
});
it('should skip events that occur before agent_start', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
// Custom emission to ensure events happen before agent_start
protocol.pushResponse([
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'hello' }],
},
]);
// We can't easily inject events before agent_start with MockAgentProtocol.pushResponse
// because it emits them all together.
// But we know session_update is emitted first.
const events: AgentEvent[] = [];
for await (const event of session.sendStream({
message: [{ type: 'text', text: 'hi' }],
})) {
events.push(event);
}
// The session_update (from the 'hi' message) should be skipped.
expect(events.some((e) => e.type === 'session_update')).toBe(false);
expect(events[0].type).toBe('agent_start');
});
describe('stream()', () => {
it('should replay events after eventId', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
// Create some events
protocol.pushResponse([{ type: 'message' }]);
await session.send({ update: { title: 't1' } });
// Wait for events to be emitted
await new Promise((resolve) => setTimeout(resolve, 10));
const allEvents = session.events;
expect(allEvents.length).toBeGreaterThan(2);
const eventId = allEvents[1].id;
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream({ eventId })) {
streamedEvents.push(event);
}
expect(streamedEvents).toEqual(allEvents.slice(2));
});
it('should complete immediately when resuming from agent_end', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }]);
const { streamId } = await session.send({
message: [{ type: 'text', text: 'request' }],
});
await new Promise((resolve) => setTimeout(resolve, 10));
const endEvent = session.events.findLast(
(event): event is AgentEvent<'agent_end'> =>
event.type === 'agent_end' && event.streamId === streamId,
);
expect(endEvent).toBeDefined();
const iterator = session
.stream({ eventId: endEvent!.id })
[Symbol.asyncIterator]();
await expect(iterator.next()).resolves.toEqual({
value: undefined,
done: true,
});
});
it('should throw for an unknown eventId', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
const iterator = session
.stream({ eventId: 'missing-event' })
[Symbol.asyncIterator]();
await expect(iterator.next()).rejects.toThrow(
'Unknown eventId: missing-event',
);
});
it('should throw when resuming from an event before agent_start on a stream with no agent activity', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
const { streamId } = await session.send({ update: { title: 'draft' } });
expect(streamId).toBeNull();
const updateEvent = session.events.find(
(event): event is AgentEvent<'session_update'> =>
event.type === 'session_update',
);
expect(updateEvent).toBeDefined();
const iterator = session
.stream({ eventId: updateEvent!.id })
[Symbol.asyncIterator]();
await expect(iterator.next()).rejects.toThrow(
`Cannot resume from eventId ${updateEvent!.id} before agent_start for stream ${updateEvent!.streamId}`,
);
});
it('should replay from agent_start when resuming from a pre-agent_start event after activity is in history', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'hello' }],
},
]);
await session.send({
message: [{ type: 'text', text: 'request' }],
});
await new Promise((resolve) => setTimeout(resolve, 10));
const userMessage = session.events.find(
(event): event is AgentEvent<'message'> =>
event.type === 'message' && event.role === 'user',
);
expect(userMessage).toBeDefined();
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream({ eventId: userMessage!.id })) {
streamedEvents.push(event);
}
expect(streamedEvents.map((event) => event.type)).toEqual([
'agent_start',
'message',
'agent_end',
]);
expect(streamedEvents[0]?.streamId).toBe(userMessage!.streamId);
});
it('should throw when resuming from a pre-agent_start event before activity is in history', async () => {
const protocol = new MockAgentProtocol([
{
id: 'e-1',
timestamp: '2026-01-01T00:00:00.000Z',
streamId: 'stream-1',
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'request' }],
},
]);
const session = new AgentSession(protocol);
const iterator = session
.stream({ eventId: 'e-1' })
[Symbol.asyncIterator]();
await expect(iterator.next()).rejects.toThrow(
'Cannot resume from eventId e-1 before agent_start for stream stream-1',
);
});
it('should resume from an in-stream event within the same stream only', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'first answer 1' }],
},
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'first answer 2' }],
},
]);
const { streamId: streamId1 } = await session.send({
message: [{ type: 'text', text: 'first request' }],
});
await new Promise((resolve) => setTimeout(resolve, 10));
protocol.pushResponse([
{
type: 'message',
role: 'agent',
content: [{ type: 'text', text: 'second answer' }],
},
]);
await session.send({
message: [{ type: 'text', text: 'second request' }],
});
await new Promise((resolve) => setTimeout(resolve, 10));
const resumeEvent = session.events.find(
(event): event is AgentEvent<'message'> =>
event.type === 'message' &&
event.streamId === streamId1 &&
event.role === 'agent' &&
event.content[0]?.type === 'text' &&
event.content[0].text === 'first answer 1',
);
expect(resumeEvent).toBeDefined();
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream({ eventId: resumeEvent!.id })) {
streamedEvents.push(event);
}
expect(
streamedEvents.every((event) => event.streamId === streamId1),
).toBe(true);
expect(streamedEvents.map((event) => event.type)).toEqual([
'message',
'agent_end',
]);
const resumedMessage = streamedEvents[0] as AgentEvent<'message'>;
expect(resumedMessage.content).toEqual([
{ type: 'text', text: 'first answer 2' },
]);
});
it('should replay events for streamId starting with agent_start', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }]);
const { streamId } = await session.send({ update: { title: 't1' } });
await new Promise((resolve) => setTimeout(resolve, 10));
const allEvents = session.events;
const startEventIndex = allEvents.findIndex(
(e) => e.type === 'agent_start' && e.streamId === streamId,
);
expect(startEventIndex).toBeGreaterThan(-1);
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream({ streamId: streamId! })) {
streamedEvents.push(event);
}
expect(streamedEvents).toEqual(allEvents.slice(startEventIndex));
});
it('should continue listening for active stream after replay', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
// Start a stream but keep it open
protocol.pushResponse([{ type: 'message' }], { keepOpen: true });
const { streamId } = await session.send({ update: { title: 't1' } });
await new Promise((resolve) => setTimeout(resolve, 10));
const streamedEvents: AgentEvent[] = [];
const streamPromise = (async () => {
for await (const event of session.stream({ streamId: streamId! })) {
streamedEvents.push(event);
}
})();
// Push more to the stream
await new Promise((resolve) => setTimeout(resolve, 20));
protocol.pushToStream(streamId!, [{ type: 'message' }], { close: true });
await streamPromise;
const allEvents = session.events;
const startEventIndex = allEvents.findIndex(
(e) => e.type === 'agent_start' && e.streamId === streamId,
);
expect(streamedEvents).toEqual(allEvents.slice(startEventIndex));
expect(streamedEvents.at(-1)?.type).toBe('agent_end');
});
it('should not drop agent_end that arrives while replay events are being yielded', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }], { keepOpen: true });
const { streamId } = await session.send({ update: { title: 't1' } });
await new Promise((resolve) => setTimeout(resolve, 10));
const iterator = session
.stream({ streamId: streamId! })
[Symbol.asyncIterator]();
const first = await iterator.next();
expect(first.value?.type).toBe('agent_start');
protocol.pushToStream(streamId!, [], { close: true });
const second = await iterator.next();
expect(second.value?.type).toBe('message');
const third = await iterator.next();
expect(third.value?.type).toBe('agent_end');
const fourth = await iterator.next();
expect(fourth.done).toBe(true);
});
it('should follow an active stream if no options provided', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
protocol.pushResponse([{ type: 'message' }], { keepOpen: true });
const { streamId } = await session.send({ update: { title: 't1' } });
await new Promise((resolve) => setTimeout(resolve, 10));
const streamedEvents: AgentEvent[] = [];
const streamPromise = (async () => {
for await (const event of session.stream()) {
streamedEvents.push(event);
}
})();
await new Promise((resolve) => setTimeout(resolve, 20));
protocol.pushToStream(streamId!, [{ type: 'message' }], { close: true });
await streamPromise;
expect(streamedEvents.length).toBeGreaterThan(0);
expect(streamedEvents.at(-1)?.type).toBe('agent_end');
});
it('should ONLY yield events for specific streamId even if newer streams exist', async () => {
const protocol = new MockAgentProtocol();
const session = new AgentSession(protocol);
// Stream 1
protocol.pushResponse([{ type: 'message' }]);
const { streamId: streamId1 } = await session.send({
update: { title: 's1' },
});
// Stream 2
protocol.pushResponse([{ type: 'message' }]);
const { streamId: streamId2 } = await session.send({
update: { title: 's2' },
});
await new Promise((resolve) => setTimeout(resolve, 20));
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream({ streamId: streamId1! })) {
streamedEvents.push(event);
}
expect(streamedEvents.every((e) => e.streamId === streamId1)).toBe(true);
expect(streamedEvents.some((e) => e.type === 'agent_end')).toBe(true);
expect(streamedEvents.some((e) => e.streamId === streamId2)).toBe(false);
});
});
});
+225
View File
@@ -0,0 +1,225 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {
AgentProtocol,
AgentSend,
AgentEvent,
Unsubscribe,
} from './types.js';
/**
* AgentSession is a wrapper around AgentProtocol that provides a more
* convenient API for consuming agent activity as an AsyncIterable.
*/
export class AgentSession implements AgentProtocol {
private _protocol: AgentProtocol;
constructor(protocol: AgentProtocol) {
this._protocol = protocol;
}
async send(payload: AgentSend): Promise<{ streamId: string | null }> {
return this._protocol.send(payload);
}
subscribe(callback: (event: AgentEvent) => void): Unsubscribe {
return this._protocol.subscribe(callback);
}
async abort(): Promise<void> {
return this._protocol.abort();
}
get events(): readonly AgentEvent[] {
return this._protocol.events;
}
/**
* Sends a payload to the agent and returns an AsyncIterable that yields
* events for the resulting stream.
*
* @param payload The payload to send to the agent.
*/
async *sendStream(payload: AgentSend): AsyncIterable<AgentEvent> {
const result = await this._protocol.send(payload);
const streamId = result.streamId;
if (streamId === null) {
return;
}
yield* this.stream({ streamId });
}
/**
* Returns an AsyncIterable that yields events from the agent session,
* optionally replaying events from history or reattaching to an existing stream.
*
* @param options Options for replaying or reattaching to the event stream.
*/
async *stream(
options: {
eventId?: string;
streamId?: string;
} = {},
): AsyncIterable<AgentEvent> {
let resolve: (() => void) | undefined;
let next = new Promise<void>((res) => {
resolve = res;
});
let eventQueue: AgentEvent[] = [];
const earlyEvents: AgentEvent[] = [];
let done = false;
let trackedStreamId = options.streamId;
let started = false;
let agentActivityStarted = false;
const queueVisibleEvent = (event: AgentEvent): void => {
if (trackedStreamId && event.streamId !== trackedStreamId) {
return;
}
if (!agentActivityStarted) {
if (event.type !== 'agent_start') {
return;
}
trackedStreamId = event.streamId;
agentActivityStarted = true;
}
if (!trackedStreamId) {
return;
}
eventQueue.push(event);
if (event.type === 'agent_end' && event.streamId === trackedStreamId) {
done = true;
}
};
// 1. Subscribe early to avoid missing any events that occur during replay setup
const unsubscribe = this._protocol.subscribe((event) => {
if (done) return;
if (!started) {
earlyEvents.push(event);
return;
}
queueVisibleEvent(event);
const currentResolve = resolve;
next = new Promise<void>((r) => {
resolve = r;
});
currentResolve?.();
});
try {
const currentEvents = this._protocol.events;
let replayStartIndex = -1;
if (options.eventId) {
const index = currentEvents.findIndex((e) => e.id === options.eventId);
if (index === -1) {
throw new Error(`Unknown eventId: ${options.eventId}`);
}
const resumeEvent = currentEvents[index];
trackedStreamId = resumeEvent.streamId;
const firstAgentStartIndex = currentEvents.findIndex(
(event) =>
event.type === 'agent_start' && event.streamId === trackedStreamId,
);
if (resumeEvent.type === 'agent_end') {
replayStartIndex = index + 1;
agentActivityStarted = true;
done = true;
} else if (
firstAgentStartIndex !== -1 &&
firstAgentStartIndex <= index
) {
replayStartIndex = index + 1;
agentActivityStarted = true;
} else if (firstAgentStartIndex !== -1) {
// A pre-agent_start cursor can be resumed once the corresponding
// agent activity is already present in history. Because stream()
// yields only agent_start -> agent_end, replay begins at agent_start
// rather than at the original pre-start event.
replayStartIndex = firstAgentStartIndex;
} else {
// Consumers can only resume by eventId once the corresponding stream
// has entered the agent_start -> agent_end lifecycle in history.
// Without a recorded agent_start, this wrapper cannot distinguish
// "agent activity may start later" from "this send was acknowledged
// without agent activity" without risking an infinite wait.
throw new Error(
`Cannot resume from eventId ${options.eventId} before agent_start for stream ${trackedStreamId}`,
);
}
} else if (options.streamId) {
const index = currentEvents.findIndex(
(e) => e.type === 'agent_start' && e.streamId === options.streamId,
);
if (index !== -1) {
replayStartIndex = index;
}
} else {
const activeStarts = currentEvents.filter(
(e) => e.type === 'agent_start',
);
for (let i = activeStarts.length - 1; i >= 0; i--) {
const start = activeStarts[i];
if (
!currentEvents.some(
(e) => e.type === 'agent_end' && e.streamId === start.streamId,
)
) {
trackedStreamId = start.streamId;
replayStartIndex = currentEvents.findIndex(
(e) => e.id === start.id,
);
break;
}
}
}
if (replayStartIndex !== -1) {
for (let i = replayStartIndex; i < currentEvents.length; i++) {
const event = currentEvents[i];
queueVisibleEvent(event);
if (done) break;
}
}
started = true;
// Process events that arrived while we were replaying
for (const event of earlyEvents) {
if (done) break;
queueVisibleEvent(event);
}
while (true) {
if (eventQueue.length > 0) {
const eventsToYield = eventQueue;
eventQueue = [];
for (const event of eventsToYield) {
yield event;
}
continue;
}
if (done) break;
await next;
}
} finally {
unsubscribe();
}
}
}
@@ -0,0 +1,733 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it, beforeEach } from 'vitest';
import { FinishReason } from '@google/genai';
import { ToolErrorType } from '../tools/tool-error.js';
import {
translateEvent,
createTranslationState,
mapFinishReason,
mapHttpToGrpcStatus,
mapError,
mapUsage,
type TranslationState,
} from './event-translator.js';
import { GeminiEventType } from '../core/turn.js';
import type { ServerGeminiStreamEvent } from '../core/turn.js';
import type { AgentEvent } from './types.js';
describe('createTranslationState', () => {
it('creates state with default streamId', () => {
const state = createTranslationState();
expect(state.streamId).toBeDefined();
expect(state.streamStartEmitted).toBe(false);
expect(state.model).toBeUndefined();
expect(state.eventCounter).toBe(0);
expect(state.pendingToolNames.size).toBe(0);
});
it('creates state with custom streamId', () => {
const state = createTranslationState('custom-stream');
expect(state.streamId).toBe('custom-stream');
});
});
describe('translateEvent', () => {
let state: TranslationState;
beforeEach(() => {
state = createTranslationState('test-stream');
});
describe('Content events', () => {
it('emits agent_start + message for first content event', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Content,
value: 'Hello world',
};
const result = translateEvent(event, state);
expect(result).toHaveLength(2);
expect(result[0]?.type).toBe('agent_start');
expect(result[1]?.type).toBe('message');
const msg = result[1] as AgentEvent<'message'>;
expect(msg.role).toBe('agent');
expect(msg.content).toEqual([{ type: 'text', text: 'Hello world' }]);
});
it('skips agent_start for subsequent content events', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Content,
value: 'more text',
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe('message');
});
});
describe('Thought events', () => {
it('emits thought content with metadata', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Thought,
value: { subject: 'Planning', description: 'I am thinking...' },
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const msg = result[0] as AgentEvent<'message'>;
expect(msg.content).toEqual([
{ type: 'thought', thought: 'I am thinking...' },
]);
expect(msg._meta?.['subject']).toBe('Planning');
});
});
describe('ToolCallRequest events', () => {
it('emits tool_request and tracks pending tool name', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'call-1',
name: 'read_file',
args: { path: '/tmp/test' },
isClientInitiated: false,
prompt_id: 'p1',
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const req = result[0] as AgentEvent<'tool_request'>;
expect(req.requestId).toBe('call-1');
expect(req.name).toBe('read_file');
expect(req.args).toEqual({ path: '/tmp/test' });
expect(state.pendingToolNames.get('call-1')).toBe('read_file');
});
});
describe('ToolCallResponse events', () => {
it('emits tool_response with content from responseParts', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-1', 'read_file');
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-1',
responseParts: [{ text: 'file contents' }],
resultDisplay: undefined,
error: undefined,
errorType: undefined,
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.requestId).toBe('call-1');
expect(resp.name).toBe('read_file');
expect(resp.content).toEqual([{ type: 'text', text: 'file contents' }]);
expect(resp.isError).toBe(false);
expect(state.pendingToolNames.has('call-1')).toBe(false);
});
it('uses error.message for content when tool errored', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-2', 'write_file');
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-2',
responseParts: [{ text: 'stale parts' }],
resultDisplay: 'Permission denied',
error: new Error('Permission denied to write'),
errorType: ToolErrorType.PERMISSION_DENIED,
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.isError).toBe(true);
// Should use error.message, not responseParts
expect(resp.content).toEqual([
{ type: 'text', text: 'Permission denied to write' },
]);
expect(resp.displayContent).toEqual([
{ type: 'text', text: 'Permission denied' },
]);
expect(resp.data).toEqual({ errorType: 'permission_denied' });
});
it('uses "unknown" name for untracked tool calls', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'untracked',
responseParts: [{ text: 'data' }],
resultDisplay: undefined,
error: undefined,
errorType: undefined,
},
};
const result = translateEvent(event, state);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.name).toBe('unknown');
});
it('stringifies object resultDisplay correctly', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-3', 'diff_tool');
const objectDisplay = {
fileDiff: '@@ -1 +1 @@\n-a\n+b',
fileName: 'test.txt',
filePath: '/tmp/test.txt',
originalContent: 'a',
newContent: 'b',
};
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-3',
responseParts: [{ text: 'diff result' }],
resultDisplay: objectDisplay,
error: undefined,
errorType: undefined,
},
};
const result = translateEvent(event, state);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.displayContent).toEqual([
{ type: 'text', text: JSON.stringify(objectDisplay) },
]);
});
it('passes through string resultDisplay as-is', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-4', 'shell');
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-4',
responseParts: [{ text: 'output' }],
resultDisplay: 'Command output text',
error: undefined,
errorType: undefined,
},
};
const result = translateEvent(event, state);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.displayContent).toEqual([
{ type: 'text', text: 'Command output text' },
]);
});
it('preserves outputFile and contentLength in data', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-5', 'write_file');
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-5',
responseParts: [{ text: 'written' }],
resultDisplay: undefined,
error: undefined,
errorType: undefined,
outputFile: '/tmp/out.txt',
contentLength: 42,
},
};
const result = translateEvent(event, state);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.data?.['outputFile']).toBe('/tmp/out.txt');
expect(resp.data?.['contentLength']).toBe(42);
});
it('handles multi-part responses (text + inlineData)', () => {
state.streamStartEmitted = true;
state.pendingToolNames.set('call-6', 'screenshot');
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallResponse,
value: {
callId: 'call-6',
responseParts: [
{ text: 'Here is the screenshot' },
{ inlineData: { data: 'base64img', mimeType: 'image/png' } },
],
resultDisplay: undefined,
error: undefined,
errorType: undefined,
},
};
const result = translateEvent(event, state);
const resp = result[0] as AgentEvent<'tool_response'>;
expect(resp.content).toEqual([
{ type: 'text', text: 'Here is the screenshot' },
{ type: 'media', data: 'base64img', mimeType: 'image/png' },
]);
expect(resp.isError).toBe(false);
});
});
describe('Error events', () => {
it('emits error event for structured errors', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Error,
value: { error: { message: 'Rate limited', status: 429 } },
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const err = result[0] as AgentEvent<'error'>;
expect(err.status).toBe('RESOURCE_EXHAUSTED');
expect(err.message).toBe('Rate limited');
expect(err.fatal).toBe(true);
});
it('emits error event for Error instances', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Error,
value: { error: new Error('Something broke') },
};
const result = translateEvent(event, state);
const err = result[0] as AgentEvent<'error'>;
expect(err.status).toBe('INTERNAL');
expect(err.message).toBe('Something broke');
});
});
describe('ModelInfo events', () => {
it('emits agent_start and session_update when no stream started yet', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ModelInfo,
value: 'gemini-2.5-pro',
};
const result = translateEvent(event, state);
expect(result).toHaveLength(2);
expect(result[0]?.type).toBe('agent_start');
expect(result[1]?.type).toBe('session_update');
const sessionUpdate = result[1] as AgentEvent<'session_update'>;
expect(sessionUpdate.model).toBe('gemini-2.5-pro');
expect(state.model).toBe('gemini-2.5-pro');
expect(state.streamStartEmitted).toBe(true);
});
it('emits session_update when stream already started', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ModelInfo,
value: 'gemini-2.5-flash',
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe('session_update');
});
});
describe('AgentExecutionStopped events', () => {
it('emits agent_end with the final stop message in data.message', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.AgentExecutionStopped,
value: {
reason: 'before_model',
systemMessage: 'Stopped by hook',
contextCleared: true,
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const streamEnd = result[0] as AgentEvent<'agent_end'>;
expect(streamEnd.type).toBe('agent_end');
expect(streamEnd.reason).toBe('completed');
expect(streamEnd.data).toEqual({ message: 'Stopped by hook' });
});
it('uses reason when systemMessage is not set', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.AgentExecutionStopped,
value: { reason: 'hook' },
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const streamEnd = result[0] as AgentEvent<'agent_end'>;
expect(streamEnd.data).toEqual({ message: 'hook' });
});
});
describe('AgentExecutionBlocked events', () => {
it('emits non-fatal error event (non-terminal, stream continues)', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.AgentExecutionBlocked,
value: { reason: 'Policy violation' },
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const err = result[0] as AgentEvent<'error'>;
expect(err.type).toBe('error');
expect(err.fatal).toBe(false);
expect(err._meta?.['code']).toBe('AGENT_EXECUTION_BLOCKED');
expect(err.message).toBe('Agent execution blocked: Policy violation');
});
it('uses systemMessage in the final error message when available', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.AgentExecutionBlocked,
value: {
reason: 'hook_blocked',
systemMessage: 'Blocked by policy hook',
contextCleared: true,
},
};
const result = translateEvent(event, state);
const err = result[0] as AgentEvent<'error'>;
expect(err.message).toBe(
'Agent execution blocked: Blocked by policy hook',
);
});
});
describe('LoopDetected events', () => {
it('emits a non-fatal warning error event', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.LoopDetected,
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe('error');
const loopWarning = result[0] as AgentEvent<'error'>;
expect(loopWarning.fatal).toBe(false);
expect(loopWarning.message).toBe('Loop detected, stopping execution');
expect(loopWarning._meta?.['code']).toBe('LOOP_DETECTED');
});
});
describe('MaxSessionTurns events', () => {
it('emits agent_end with max_turns', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.MaxSessionTurns,
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const streamEnd = result[0] as AgentEvent<'agent_end'>;
expect(streamEnd.type).toBe('agent_end');
expect(streamEnd.reason).toBe('max_turns');
expect(streamEnd.data).toEqual({ code: 'MAX_TURNS_EXCEEDED' });
});
});
describe('Finished events', () => {
it('emits usage for STOP', () => {
state.streamStartEmitted = true;
state.model = 'gemini-2.5-pro';
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Finished,
value: {
reason: FinishReason.STOP,
usageMetadata: {
promptTokenCount: 100,
candidatesTokenCount: 50,
cachedContentTokenCount: 10,
},
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const usage = result[0] as AgentEvent<'usage'>;
expect(usage.model).toBe('gemini-2.5-pro');
expect(usage.inputTokens).toBe(100);
expect(usage.outputTokens).toBe(50);
expect(usage.cachedTokens).toBe(10);
});
it('emits nothing when no usage metadata is present', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Finished,
value: { reason: undefined, usageMetadata: undefined },
};
const result = translateEvent(event, state);
expect(result).toHaveLength(0);
});
});
describe('Citation events', () => {
it('emits message with citation meta', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Citation,
value: 'Source: example.com',
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const msg = result[0] as AgentEvent<'message'>;
expect(msg.content).toEqual([
{ type: 'text', text: 'Source: example.com' },
]);
expect(msg._meta?.['citation']).toBe(true);
});
});
describe('UserCancelled events', () => {
it('emits agent_end with reason aborted', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.UserCancelled,
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const end = result[0] as AgentEvent<'agent_end'>;
expect(end.type).toBe('agent_end');
expect(end.reason).toBe('aborted');
});
});
describe('ContextWindowWillOverflow events', () => {
it('emits fatal error', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ContextWindowWillOverflow,
value: {
estimatedRequestTokenCount: 150000,
remainingTokenCount: 10000,
},
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const err = result[0] as AgentEvent<'error'>;
expect(err.status).toBe('RESOURCE_EXHAUSTED');
expect(err.fatal).toBe(true);
expect(err.message).toContain('150000');
expect(err.message).toContain('10000');
});
});
describe('InvalidStream events', () => {
it('emits fatal error', () => {
state.streamStartEmitted = true;
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.InvalidStream,
};
const result = translateEvent(event, state);
expect(result).toHaveLength(1);
const err = result[0] as AgentEvent<'error'>;
expect(err.status).toBe('INTERNAL');
expect(err.message).toBe('Invalid stream received from model');
expect(err.fatal).toBe(true);
});
});
describe('Events with no output', () => {
it('returns empty for Retry', () => {
const result = translateEvent({ type: GeminiEventType.Retry }, state);
expect(result).toEqual([]);
});
it('returns empty for ChatCompressed with null', () => {
const result = translateEvent(
{ type: GeminiEventType.ChatCompressed, value: null },
state,
);
expect(result).toEqual([]);
});
it('returns empty for ToolCallConfirmation', () => {
// ToolCallConfirmation is skipped in non-interactive mode (elicitations
// are deferred to the interactive runtime adaptation).
const event = {
type: GeminiEventType.ToolCallConfirmation,
value: {
request: {
callId: 'c1',
name: 'tool',
args: {},
isClientInitiated: false,
prompt_id: 'p1',
},
details: { type: 'info', title: 'Confirm', prompt: 'Confirm?' },
},
} as ServerGeminiStreamEvent;
const result = translateEvent(event, state);
expect(result).toEqual([]);
});
});
describe('Event IDs', () => {
it('generates sequential IDs', () => {
state.streamStartEmitted = true;
const e1 = translateEvent(
{ type: GeminiEventType.Content, value: 'a' },
state,
);
const e2 = translateEvent(
{ type: GeminiEventType.Content, value: 'b' },
state,
);
expect(e1[0]?.id).toBe('test-stream-0');
expect(e2[0]?.id).toBe('test-stream-1');
});
it('includes streamId in events', () => {
const events = translateEvent(
{ type: GeminiEventType.Content, value: 'hi' },
state,
);
for (const e of events) {
expect(e.streamId).toBe('test-stream');
}
});
});
});
describe('mapFinishReason', () => {
it('maps STOP to completed', () => {
expect(mapFinishReason(FinishReason.STOP)).toBe('completed');
});
it('maps undefined to completed', () => {
expect(mapFinishReason(undefined)).toBe('completed');
});
it('maps MAX_TOKENS to max_budget', () => {
expect(mapFinishReason(FinishReason.MAX_TOKENS)).toBe('max_budget');
});
it('maps SAFETY to refusal', () => {
expect(mapFinishReason(FinishReason.SAFETY)).toBe('refusal');
});
it('maps MALFORMED_FUNCTION_CALL to failed', () => {
expect(mapFinishReason(FinishReason.MALFORMED_FUNCTION_CALL)).toBe(
'failed',
);
});
it('maps RECITATION to refusal', () => {
expect(mapFinishReason(FinishReason.RECITATION)).toBe('refusal');
});
it('maps LANGUAGE to refusal', () => {
expect(mapFinishReason(FinishReason.LANGUAGE)).toBe('refusal');
});
it('maps BLOCKLIST to refusal', () => {
expect(mapFinishReason(FinishReason.BLOCKLIST)).toBe('refusal');
});
it('maps OTHER to failed', () => {
expect(mapFinishReason(FinishReason.OTHER)).toBe('failed');
});
it('maps PROHIBITED_CONTENT to refusal', () => {
expect(mapFinishReason(FinishReason.PROHIBITED_CONTENT)).toBe('refusal');
});
it('maps IMAGE_SAFETY to refusal', () => {
expect(mapFinishReason(FinishReason.IMAGE_SAFETY)).toBe('refusal');
});
it('maps IMAGE_PROHIBITED_CONTENT to refusal', () => {
expect(mapFinishReason(FinishReason.IMAGE_PROHIBITED_CONTENT)).toBe(
'refusal',
);
});
it('maps UNEXPECTED_TOOL_CALL to failed', () => {
expect(mapFinishReason(FinishReason.UNEXPECTED_TOOL_CALL)).toBe('failed');
});
it('maps NO_IMAGE to failed', () => {
expect(mapFinishReason(FinishReason.NO_IMAGE)).toBe('failed');
});
});
describe('mapHttpToGrpcStatus', () => {
it('maps 400 to INVALID_ARGUMENT', () => {
expect(mapHttpToGrpcStatus(400)).toBe('INVALID_ARGUMENT');
});
it('maps 401 to UNAUTHENTICATED', () => {
expect(mapHttpToGrpcStatus(401)).toBe('UNAUTHENTICATED');
});
it('maps 429 to RESOURCE_EXHAUSTED', () => {
expect(mapHttpToGrpcStatus(429)).toBe('RESOURCE_EXHAUSTED');
});
it('maps undefined to INTERNAL', () => {
expect(mapHttpToGrpcStatus(undefined)).toBe('INTERNAL');
});
it('maps unknown codes to INTERNAL', () => {
expect(mapHttpToGrpcStatus(418)).toBe('INTERNAL');
});
});
describe('mapError', () => {
it('maps structured errors with status', () => {
const result = mapError({ message: 'Rate limit', status: 429 });
expect(result.status).toBe('RESOURCE_EXHAUSTED');
expect(result.message).toBe('Rate limit');
expect(result.fatal).toBe(true);
expect(result._meta?.['rawError']).toEqual({
message: 'Rate limit',
status: 429,
});
});
it('maps Error instances', () => {
const result = mapError(new Error('Something failed'));
expect(result.status).toBe('INTERNAL');
expect(result.message).toBe('Something failed');
});
it('preserves error name in _meta', () => {
class CustomError extends Error {
constructor(msg: string) {
super(msg);
}
}
const result = mapError(new CustomError('test'));
expect(result._meta?.['errorName']).toBe('CustomError');
});
it('maps non-Error values to string', () => {
const result = mapError('raw string error');
expect(result.message).toBe('raw string error');
expect(result.status).toBe('INTERNAL');
});
});
describe('mapUsage', () => {
it('maps all fields', () => {
const result = mapUsage(
{
promptTokenCount: 100,
candidatesTokenCount: 50,
cachedContentTokenCount: 25,
},
'gemini-2.5-pro',
);
expect(result).toEqual({
model: 'gemini-2.5-pro',
inputTokens: 100,
outputTokens: 50,
cachedTokens: 25,
});
});
it('uses "unknown" for missing model', () => {
const result = mapUsage({});
expect(result.model).toBe('unknown');
});
});
+453
View File
@@ -0,0 +1,453 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Pure, stateless-per-call translation functions that convert
* ServerGeminiStreamEvent objects into AgentEvent objects.
*
* No side effects, no generators. Each call to `translateEvent` takes an event
* and mutable TranslationState, returning zero or more AgentEvents.
*/
import type { FinishReason } from '@google/genai';
import { GeminiEventType } from '../core/turn.js';
import type {
ServerGeminiStreamEvent,
StructuredError,
GeminiFinishedEventValue,
} from '../core/turn.js';
import type {
AgentEvent,
StreamEndReason,
ErrorData,
Usage,
AgentEventType,
} from './types.js';
import {
geminiPartsToContentParts,
toolResultDisplayToContentParts,
buildToolResponseData,
} from './content-utils.js';
// ---------------------------------------------------------------------------
// Translation State
// ---------------------------------------------------------------------------
export interface TranslationState {
streamId: string;
streamStartEmitted: boolean;
model: string | undefined;
eventCounter: number;
/** Tracks callId → tool name from requests so responses can reference the name. */
pendingToolNames: Map<string, string>;
}
export function createTranslationState(streamId?: string): TranslationState {
return {
streamId: streamId ?? crypto.randomUUID(),
streamStartEmitted: false,
model: undefined,
eventCounter: 0,
pendingToolNames: new Map(),
};
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeEvent<T extends AgentEventType>(
type: T,
state: TranslationState,
payload: Partial<AgentEvent<T>>,
): AgentEvent {
const id = `${state.streamId}-${state.eventCounter++}`;
return {
...payload,
id,
timestamp: new Date().toISOString(),
streamId: state.streamId,
type,
} as AgentEvent;
}
function ensureStreamStart(state: TranslationState, out: AgentEvent[]): void {
if (!state.streamStartEmitted) {
out.push(makeEvent('agent_start', state, {}));
state.streamStartEmitted = true;
}
}
// ---------------------------------------------------------------------------
// Core Translator
// ---------------------------------------------------------------------------
/**
* Translates a single ServerGeminiStreamEvent into zero or more AgentEvents.
* Mutates `state` (counter, flags) as a side effect.
*/
export function translateEvent(
event: ServerGeminiStreamEvent,
state: TranslationState,
): AgentEvent[] {
const out: AgentEvent[] = [];
switch (event.type) {
case GeminiEventType.ModelInfo:
state.model = event.value;
ensureStreamStart(state, out);
out.push(makeEvent('session_update', state, { model: event.value }));
break;
case GeminiEventType.Content:
ensureStreamStart(state, out);
out.push(
makeEvent('message', state, {
role: 'agent',
content: [{ type: 'text', text: event.value }],
}),
);
break;
case GeminiEventType.Thought:
ensureStreamStart(state, out);
out.push(
makeEvent('message', state, {
role: 'agent',
content: [{ type: 'thought', thought: event.value.description }],
_meta: event.value.subject
? { source: 'agent', subject: event.value.subject }
: { source: 'agent' },
}),
);
break;
case GeminiEventType.Citation:
ensureStreamStart(state, out);
out.push(
makeEvent('message', state, {
role: 'agent',
content: [{ type: 'text', text: event.value }],
_meta: { source: 'agent', citation: true },
}),
);
break;
case GeminiEventType.Finished:
handleFinished(event.value, state, out);
break;
case GeminiEventType.Error:
handleError(event.value.error, state, out);
break;
case GeminiEventType.UserCancelled:
ensureStreamStart(state, out);
out.push(
makeEvent('agent_end', state, {
reason: 'aborted',
}),
);
break;
case GeminiEventType.MaxSessionTurns:
ensureStreamStart(state, out);
out.push(
makeEvent('agent_end', state, {
reason: 'max_turns',
data: {
code: 'MAX_TURNS_EXCEEDED',
},
}),
);
break;
case GeminiEventType.LoopDetected:
ensureStreamStart(state, out);
out.push(
makeEvent('error', state, {
status: 'INTERNAL',
message: 'Loop detected, stopping execution',
fatal: false,
_meta: { code: 'LOOP_DETECTED' },
}),
);
break;
case GeminiEventType.ContextWindowWillOverflow:
ensureStreamStart(state, out);
out.push(
makeEvent('error', state, {
status: 'RESOURCE_EXHAUSTED',
message: `Context window will overflow (estimated: ${event.value.estimatedRequestTokenCount}, remaining: ${event.value.remainingTokenCount})`,
fatal: true,
}),
);
break;
case GeminiEventType.AgentExecutionStopped:
ensureStreamStart(state, out);
out.push(
makeEvent('agent_end', state, {
reason: 'completed',
data: {
message: event.value.systemMessage?.trim() || event.value.reason,
},
}),
);
break;
case GeminiEventType.AgentExecutionBlocked:
ensureStreamStart(state, out);
out.push(
makeEvent('error', state, {
status: 'PERMISSION_DENIED',
message: `Agent execution blocked: ${event.value.systemMessage?.trim() || event.value.reason}`,
fatal: false,
_meta: { code: 'AGENT_EXECUTION_BLOCKED' },
}),
);
break;
case GeminiEventType.InvalidStream:
ensureStreamStart(state, out);
out.push(
makeEvent('error', state, {
status: 'INTERNAL',
message: 'Invalid stream received from model',
fatal: true,
}),
);
break;
case GeminiEventType.ToolCallRequest:
ensureStreamStart(state, out);
state.pendingToolNames.set(event.value.callId, event.value.name);
out.push(
makeEvent('tool_request', state, {
requestId: event.value.callId,
name: event.value.name,
args: event.value.args,
}),
);
break;
case GeminiEventType.ToolCallResponse: {
ensureStreamStart(state, out);
const displayContent = toolResultDisplayToContentParts(
event.value.resultDisplay,
);
const data = buildToolResponseData(event.value);
out.push(
makeEvent('tool_response', state, {
requestId: event.value.callId,
name: state.pendingToolNames.get(event.value.callId) ?? 'unknown',
content: event.value.error
? [{ type: 'text', text: event.value.error.message }]
: geminiPartsToContentParts(event.value.responseParts),
isError: event.value.error !== undefined,
...(displayContent ? { displayContent } : {}),
...(data ? { data } : {}),
}),
);
state.pendingToolNames.delete(event.value.callId);
break;
}
case GeminiEventType.ToolCallConfirmation:
// Elicitations are handled separately by the session layer
break;
// Internal concerns — no AgentEvent emitted
case GeminiEventType.ChatCompressed:
case GeminiEventType.Retry:
break;
default:
((x: never) => {
throw new Error(`Unhandled event type: ${JSON.stringify(x)}`);
})(event);
break;
}
return out;
}
// ---------------------------------------------------------------------------
// Finished Event Handling
// ---------------------------------------------------------------------------
function handleFinished(
value: GeminiFinishedEventValue,
state: TranslationState,
out: AgentEvent[],
): void {
if (value.usageMetadata) {
ensureStreamStart(state, out);
const usage = mapUsage(value.usageMetadata, state.model);
out.push(makeEvent('usage', state, usage));
}
}
// ---------------------------------------------------------------------------
// Error Handling
// ---------------------------------------------------------------------------
function handleError(
error: unknown,
state: TranslationState,
out: AgentEvent[],
): void {
ensureStreamStart(state, out);
const mapped = mapError(error);
out.push(makeEvent('error', state, mapped));
}
// ---------------------------------------------------------------------------
// Public Mapping Functions
// ---------------------------------------------------------------------------
/**
* Maps a Gemini FinishReason to an AgentEnd reason.
*/
export function mapFinishReason(
reason: FinishReason | undefined,
): StreamEndReason {
if (!reason) return 'completed';
switch (reason) {
case 'STOP':
case 'FINISH_REASON_UNSPECIFIED':
return 'completed';
case 'MAX_TOKENS':
return 'max_budget';
case 'SAFETY':
case 'RECITATION':
case 'LANGUAGE':
case 'BLOCKLIST':
case 'PROHIBITED_CONTENT':
case 'SPII':
case 'IMAGE_SAFETY':
case 'IMAGE_PROHIBITED_CONTENT':
return 'refusal';
case 'MALFORMED_FUNCTION_CALL':
case 'OTHER':
case 'UNEXPECTED_TOOL_CALL':
case 'NO_IMAGE':
return 'failed';
default:
return 'failed';
}
}
/**
* Maps an HTTP status code to a gRPC-style status string.
*/
export function mapHttpToGrpcStatus(
httpStatus: number | undefined,
): ErrorData['status'] {
if (httpStatus === undefined) return 'INTERNAL';
switch (httpStatus) {
case 400:
return 'INVALID_ARGUMENT';
case 401:
return 'UNAUTHENTICATED';
case 403:
return 'PERMISSION_DENIED';
case 404:
return 'NOT_FOUND';
case 409:
return 'ALREADY_EXISTS';
case 429:
return 'RESOURCE_EXHAUSTED';
case 500:
return 'INTERNAL';
case 501:
return 'UNIMPLEMENTED';
case 503:
return 'UNAVAILABLE';
case 504:
return 'DEADLINE_EXCEEDED';
default:
return 'INTERNAL';
}
}
/**
* Maps a StructuredError (or unknown error value) to an ErrorData payload.
* Preserves selected error metadata in _meta and includes raw structured
* errors for lossless debugging.
*/
export function mapError(
error: unknown,
): ErrorData & { _meta?: Record<string, unknown> } {
const meta: Record<string, unknown> = {};
if (error instanceof Error) {
meta['errorName'] = error.constructor.name;
if ('exitCode' in error && typeof error.exitCode === 'number') {
meta['exitCode'] = error.exitCode;
}
if ('code' in error) {
meta['code'] = error.code;
}
}
if (isStructuredError(error)) {
const structuredMeta = { ...meta, rawError: error };
return {
status: mapHttpToGrpcStatus(error.status),
message: error.message,
fatal: true,
_meta: structuredMeta,
};
}
if (error instanceof Error) {
return {
status: 'INTERNAL',
message: error.message,
fatal: true,
...(Object.keys(meta).length > 0 ? { _meta: meta } : {}),
};
}
return {
status: 'INTERNAL',
message: String(error),
fatal: true,
};
}
function isStructuredError(error: unknown): error is StructuredError {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof error.message === 'string'
);
}
/**
* Maps Gemini usageMetadata to Usage.
*/
export function mapUsage(
metadata: {
promptTokenCount?: number;
candidatesTokenCount?: number;
cachedContentTokenCount?: number;
},
model?: string,
): Usage {
return {
model: model ?? 'unknown',
inputTokens: metadata.promptTokenCount,
outputTokens: metadata.candidatesTokenCount,
cachedTokens: metadata.cachedContentTokenCount,
};
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,459 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview LegacyAgentSession backed by the existing Gemini client +
* scheduler loop, adapted to the merged AgentProtocol / AgentSession surface.
*/
import { GeminiEventType } from '../core/turn.js';
import type { Part } from '@google/genai';
import type { GeminiClient } from '../core/client.js';
import type { Config } from '../config/config.js';
import type { ToolCallRequestInfo } from '../scheduler/types.js';
import type { Scheduler } from '../scheduler/scheduler.js';
import { recordToolCallInteractions } from '../code_assist/telemetry.js';
import { ToolErrorType, isFatalToolError } from '../tools/tool-error.js';
import { debugLogger } from '../utils/debugLogger.js';
import {
buildToolResponseData,
contentPartsToGeminiParts,
geminiPartsToContentParts,
toolResultDisplayToContentParts,
} from './content-utils.js';
import { AgentSession } from './agent-session.js';
import {
createTranslationState,
mapFinishReason,
translateEvent,
type TranslationState,
} from './event-translator.js';
import type {
AgentEvent,
AgentProtocol,
AgentSend,
ContentPart,
StreamEndReason,
Unsubscribe,
} from './types.js';
function isAbortLikeError(err: unknown): boolean {
return err instanceof Error && err.name === 'AbortError';
}
export interface LegacySessionDeps {
client: GeminiClient;
scheduler: Scheduler;
config: Config;
promptId: string;
streamId?: string;
}
class LegacyAgentProtocol implements AgentProtocol {
private _events: AgentEvent[] = [];
private _subscribers = new Set<(event: AgentEvent) => void>();
private _translationState: TranslationState;
private _agentEndEmitted = false;
private _activeStreamId?: string;
private _abortController = new AbortController();
private _nextStreamIdOverride?: string;
private readonly _client: GeminiClient;
private readonly _scheduler: Scheduler;
private readonly _config: Config;
private readonly _promptId: string;
constructor(deps: LegacySessionDeps) {
this._translationState = createTranslationState(deps.streamId);
this._nextStreamIdOverride = deps.streamId;
this._client = deps.client;
this._scheduler = deps.scheduler;
this._config = deps.config;
this._promptId = deps.promptId;
}
get events(): readonly AgentEvent[] {
return this._events;
}
subscribe(callback: (event: AgentEvent) => void): Unsubscribe {
this._subscribers.add(callback);
return () => {
this._subscribers.delete(callback);
};
}
async send(payload: AgentSend): Promise<{ streamId: string }> {
const message = 'message' in payload ? payload.message : undefined;
if (!message) {
throw new Error(
'LegacyAgentSession.send() only supports message sends for the moment.',
);
}
if (this._activeStreamId) {
// TODO: Interactive may eventually allow selected in-stream sends such as
// updates or elicitation responses. Keep rejecting all concurrent sends
// here until we define those correlation semantics.
throw new Error(
'LegacyAgentSession.send() cannot be called while a stream is active.',
);
}
this._beginNewStream();
const streamId = this._translationState.streamId;
const parts = contentPartsToGeminiParts(message);
const userMessage = this._makeUserMessageEvent(message, payload._meta);
this._emit([userMessage]);
this._scheduleRunLoop(parts);
return { streamId };
}
async abort(): Promise<void> {
this._abortController.abort();
}
private _scheduleRunLoop(initialParts: Part[]): void {
setTimeout(() => {
void this._runLoopInBackground(initialParts);
}, 0);
}
private async _runLoopInBackground(initialParts: Part[]): Promise<void> {
this._ensureAgentStart();
try {
await this._runLoop(initialParts);
} catch (err: unknown) {
if (this._abortController.signal.aborted || isAbortLikeError(err)) {
this._ensureAgentEnd('aborted');
} else {
this._emitErrorAndAgentEnd(err);
}
this._markStreamDone();
}
}
private async _runLoop(initialParts: Part[]): Promise<void> {
let currentParts: Part[] = initialParts;
let turnCount = 0;
const maxTurns = this._config.getMaxSessionTurns();
while (true) {
turnCount++;
if (maxTurns >= 0 && turnCount > maxTurns) {
this._finishStream('max_turns', {
code: 'MAX_TURNS_EXCEEDED',
maxTurns,
turnCount: turnCount - 1,
});
return;
}
const toolCallRequests: ToolCallRequestInfo[] = [];
const responseStream = this._client.sendMessageStream(
currentParts,
this._abortController.signal,
this._promptId,
);
for await (const event of responseStream) {
if (this._abortController.signal.aborted) {
this._finishStream('aborted');
return;
}
if (event.type === GeminiEventType.ToolCallRequest) {
toolCallRequests.push(event.value);
}
this._emit(translateEvent(event, this._translationState));
if (event.type === GeminiEventType.Error) {
this._finishStream('failed');
return;
}
if (
event.type === GeminiEventType.InvalidStream ||
event.type === GeminiEventType.ContextWindowWillOverflow
) {
this._finishStream('failed');
return;
}
if (event.type === GeminiEventType.Finished) {
if (toolCallRequests.length === 0) {
this._finishStream(mapFinishReason(event.value.reason));
return;
}
continue;
}
if (
event.type === GeminiEventType.AgentExecutionStopped ||
event.type === GeminiEventType.UserCancelled ||
event.type === GeminiEventType.MaxSessionTurns
) {
this._markStreamDone();
return;
}
}
if (this._abortController.signal.aborted) {
this._finishStream('aborted');
return;
}
if (toolCallRequests.length === 0) {
this._finishStream('completed');
return;
}
const completedToolCalls = await this._scheduler.schedule(
toolCallRequests,
this._abortController.signal,
);
if (this._abortController.signal.aborted) {
this._finishStream('aborted');
return;
}
const toolResponseParts: Part[] = [];
for (const tc of completedToolCalls) {
const response = tc.response;
const request = tc.request;
const content: ContentPart[] = response.error
? [{ type: 'text', text: response.error.message }]
: geminiPartsToContentParts(response.responseParts);
const displayContent = toolResultDisplayToContentParts(
response.resultDisplay,
);
const data = buildToolResponseData(response);
this._emit([
this._makeToolResponseEvent({
requestId: request.callId,
name: request.name,
content,
isError: response.error !== undefined,
...(displayContent ? { displayContent } : {}),
...(data ? { data } : {}),
}),
]);
if (response.responseParts) {
toolResponseParts.push(...response.responseParts);
}
}
try {
const currentModel =
this._client.getCurrentSequenceModel() ?? this._config.getModel();
this._client
.getChat()
.recordCompletedToolCalls(currentModel, completedToolCalls);
await recordToolCallInteractions(this._config, completedToolCalls);
} catch (error) {
debugLogger.error(
`Error recording completed tool call information: ${error}`,
);
}
const stopTool = completedToolCalls.find(
(tc) =>
tc.response.errorType === ToolErrorType.STOP_EXECUTION &&
tc.response.error !== undefined,
);
if (stopTool) {
this._finishStream('completed');
return;
}
const fatalTool = completedToolCalls.find((tc) =>
isFatalToolError(tc.response.errorType),
);
if (fatalTool) {
this._finishStream('failed');
return;
}
currentParts = toolResponseParts;
}
}
private _emit(events: AgentEvent[]): void {
if (events.length === 0) {
return;
}
const subscribers = [...this._subscribers];
for (const event of events) {
if (!this._events.some((existing) => existing.id === event.id)) {
this._events.push(event);
}
if (event.type === 'agent_end') {
this._agentEndEmitted = true;
}
for (const subscriber of subscribers) {
subscriber(event);
}
}
}
private _markStreamDone(): void {
this._activeStreamId = undefined;
}
private _beginNewStream(): void {
this._translationState = createTranslationState(this._nextStreamIdOverride);
this._nextStreamIdOverride = undefined;
this._abortController = new AbortController();
this._agentEndEmitted = false;
this._activeStreamId = this._translationState.streamId;
}
private _ensureAgentStart(): void {
if (!this._translationState.streamStartEmitted) {
this._translationState.streamStartEmitted = true;
this._emit([this._makeAgentStartEvent()]);
}
}
private _ensureAgentEnd(reason: StreamEndReason = 'completed'): void {
if (!this._agentEndEmitted && this._translationState.streamStartEmitted) {
this._agentEndEmitted = true;
this._emit([this._makeAgentEndEvent(reason)]);
}
}
private _finishStream(
reason: StreamEndReason,
data?: Record<string, unknown>,
): void {
if (data && !this._agentEndEmitted) {
this._emit([this._makeAgentEndEvent(reason, data)]);
} else {
this._ensureAgentEnd(reason);
}
this._markStreamDone();
}
/**
* Preserve error identity fields in _meta so downstream consumers can
* reconstruct fatal CLI errors.
*/
private _emitErrorAndAgentEnd(err: unknown): void {
const message = err instanceof Error ? err.message : String(err);
this._ensureAgentStart();
const meta: Record<string, unknown> = {};
if (err instanceof Error) {
meta['errorName'] = err.constructor.name;
if ('exitCode' in err && typeof err.exitCode === 'number') {
meta['exitCode'] = err.exitCode;
}
if ('code' in err) {
meta['code'] = err.code;
}
if ('status' in err) {
meta['status'] = err.status;
}
}
this._emit([
this._makeErrorEvent({
status: 'INTERNAL',
message,
fatal: true,
...(Object.keys(meta).length > 0 ? { _meta: meta } : {}),
}),
]);
this._ensureAgentEnd('failed');
}
private _nextEventFields() {
return {
id: `${this._translationState.streamId}-${this._translationState.eventCounter++}`,
timestamp: new Date().toISOString(),
streamId: this._translationState.streamId,
};
}
private _makeUserMessageEvent(
content: ContentPart[],
meta?: Record<string, unknown>,
): AgentEvent<'message'> {
const event = {
...this._nextEventFields(),
type: 'message',
role: 'user',
content,
...(meta ? { _meta: meta } : {}),
} satisfies AgentEvent<'message'>;
return event;
}
private _makeToolResponseEvent(
payload: Omit<
AgentEvent<'tool_response'>,
'id' | 'timestamp' | 'streamId' | 'type'
>,
): AgentEvent<'tool_response'> {
const event = {
...this._nextEventFields(),
type: 'tool_response',
...payload,
} satisfies AgentEvent<'tool_response'>;
return event;
}
private _makeAgentStartEvent(): AgentEvent<'agent_start'> {
const event = {
...this._nextEventFields(),
type: 'agent_start',
} satisfies AgentEvent<'agent_start'>;
return event;
}
private _makeAgentEndEvent(
reason: StreamEndReason,
data?: Record<string, unknown>,
): AgentEvent<'agent_end'> {
const event = {
...this._nextEventFields(),
type: 'agent_end',
reason,
...(data ? { data } : {}),
} satisfies AgentEvent<'agent_end'>;
return event;
}
private _makeErrorEvent(
payload: Omit<
AgentEvent<'error'>,
'id' | 'timestamp' | 'streamId' | 'type'
>,
): AgentEvent<'error'> {
const event = {
...this._nextEventFields(),
type: 'error',
...payload,
} satisfies AgentEvent<'error'>;
return event;
}
}
export class LegacyAgentSession extends AgentSession {
constructor(deps: LegacySessionDeps) {
super(new LegacyAgentProtocol(deps));
}
}
+124 -154
View File
@@ -5,12 +5,24 @@
*/
import { describe, expect, it } from 'vitest';
import { MockAgentSession } from './mock.js';
import type { AgentEvent } from './types.js';
import { MockAgentProtocol } from './mock.js';
import type { AgentEvent, AgentProtocol } from './types.js';
describe('MockAgentSession', () => {
it('should yield queued events on send and stream', async () => {
const session = new MockAgentSession();
const waitForStreamEnd = (session: AgentProtocol): Promise<AgentEvent[]> =>
new Promise((resolve) => {
const events: AgentEvent[] = [];
const unsubscribe = session.subscribe((e) => {
events.push(e);
if (e.type === 'agent_end') {
unsubscribe();
resolve(events);
}
});
});
describe('MockAgentProtocol', () => {
it('should emit queued events on send and subscribe', async () => {
const session = new MockAgentProtocol();
const event1 = {
type: 'message',
role: 'agent',
@@ -19,31 +31,30 @@ describe('MockAgentSession', () => {
session.pushResponse([event1]);
const streamPromise = waitForStreamEnd(session);
const { streamId } = await session.send({
message: [{ type: 'text', text: 'hi' }],
});
expect(streamId).toBeDefined();
const streamedEvents: AgentEvent[] = [];
for await (const event of session.stream()) {
streamedEvents.push(event);
}
const streamedEvents = await streamPromise;
// Auto stream_start, auto user message, agent message, auto stream_end = 4 events
// Ordered: user message, agent_start, agent message, agent_end = 4 events
expect(streamedEvents).toHaveLength(4);
expect(streamedEvents[0].type).toBe('stream_start');
expect(streamedEvents[1].type).toBe('message');
expect((streamedEvents[1] as AgentEvent<'message'>).role).toBe('user');
expect(streamedEvents[0].type).toBe('message');
expect((streamedEvents[0] as AgentEvent<'message'>).role).toBe('user');
expect(streamedEvents[1].type).toBe('agent_start');
expect(streamedEvents[2].type).toBe('message');
expect((streamedEvents[2] as AgentEvent<'message'>).role).toBe('agent');
expect(streamedEvents[3].type).toBe('stream_end');
expect(streamedEvents[3].type).toBe('agent_end');
expect(session.events).toHaveLength(4);
expect(session.events).toEqual(streamedEvents);
});
it('should handle multiple responses', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
// Test with empty payload (no message injected)
session.pushResponse([]);
@@ -57,204 +68,154 @@ describe('MockAgentSession', () => {
]);
// First send
const stream1Promise = waitForStreamEnd(session);
const { streamId: s1 } = await session.send({
update: {},
update: { title: 't1' },
});
const events1: AgentEvent[] = [];
for await (const e of session.stream()) events1.push(e);
expect(events1).toHaveLength(3); // stream_start, session_update, stream_end
expect(events1[0].type).toBe('stream_start');
expect(events1[1].type).toBe('session_update');
expect(events1[2].type).toBe('stream_end');
const events1 = await stream1Promise;
expect(events1).toHaveLength(3); // session_update, agent_start, agent_end
expect(events1[0].type).toBe('session_update');
expect(events1[1].type).toBe('agent_start');
expect(events1[2].type).toBe('agent_end');
// Second send
const stream2Promise = waitForStreamEnd(session);
const { streamId: s2 } = await session.send({
update: {},
update: { title: 't2' },
});
expect(s1).not.toBe(s2);
const events2: AgentEvent[] = [];
for await (const e of session.stream()) events2.push(e);
expect(events2).toHaveLength(4); // stream_start, session_update, error, stream_end
expect(events2[1].type).toBe('session_update');
const events2 = await stream2Promise;
expect(events2).toHaveLength(4); // session_update, agent_start, error, agent_end
expect(events2[0].type).toBe('session_update');
expect(events2[1].type).toBe('agent_start');
expect(events2[2].type).toBe('error');
expect(events2[3].type).toBe('agent_end');
expect(session.events).toHaveLength(7);
});
it('should allow streaming by streamId', async () => {
const session = new MockAgentSession();
session.pushResponse([{ type: 'message' }]);
const { streamId } = await session.send({
update: {},
});
it('should handle abort on a waiting stream', async () => {
const session = new MockAgentProtocol();
// Use keepOpen to prevent auto agent_end
session.pushResponse([{ type: 'message' }], { keepOpen: true });
const events: AgentEvent[] = [];
for await (const e of session.stream({ streamId })) {
let resolveStream: (evs: AgentEvent[]) => void;
const streamPromise = new Promise<AgentEvent[]>((res) => {
resolveStream = res;
});
session.subscribe((e) => {
events.push(e);
}
expect(events).toHaveLength(4); // start, update, message, end
});
if (e.type === 'agent_end') {
resolveStream(events);
}
});
it('should throw when streaming non-existent streamId', async () => {
const session = new MockAgentSession();
await expect(async () => {
const stream = session.stream({ streamId: 'invalid' });
await stream.next();
}).rejects.toThrow('Stream not found: invalid');
});
const { streamId: _streamId } = await session.send({
update: { title: 't' },
});
it('should throw when streaming non-existent eventId', async () => {
const session = new MockAgentSession();
session.pushResponse([{ type: 'message' }]);
await session.send({ update: {} });
await expect(async () => {
const stream = session.stream({ eventId: 'invalid' });
await stream.next();
}).rejects.toThrow('Event not found: invalid');
});
it('should handle abort on a waiting stream', async () => {
const session = new MockAgentSession();
// Use keepOpen to prevent auto stream_end
session.pushResponse([{ type: 'message' }], { keepOpen: true });
const { streamId } = await session.send({ update: {} });
const stream = session.stream({ streamId });
// Read initial events
const e1 = await stream.next();
expect(e1.value.type).toBe('stream_start');
const e2 = await stream.next();
expect(e2.value.type).toBe('session_update');
const e3 = await stream.next();
expect(e3.value.type).toBe('message');
// Initial events should have been emitted
expect(events.map((e) => e.type)).toEqual([
'session_update',
'agent_start',
'message',
]);
// At this point, the stream should be "waiting" for more events because it's still active
// and hasn't seen a stream_end.
const abortPromise = session.abort();
const e4 = await stream.next();
expect(e4.value.type).toBe('stream_end');
expect((e4.value as AgentEvent<'stream_end'>).reason).toBe('aborted');
// and hasn't seen an agent_end.
await session.abort();
await abortPromise;
expect(await stream.next()).toEqual({ done: true, value: undefined });
const finalEvents = await streamPromise;
expect(finalEvents[3].type).toBe('agent_end');
expect((finalEvents[3] as AgentEvent<'agent_end'>).reason).toBe('aborted');
});
it('should handle pushToStream on a waiting stream', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
session.pushResponse([], { keepOpen: true });
const { streamId } = await session.send({ update: {} });
const stream = session.stream({ streamId });
await stream.next(); // start
await stream.next(); // update
const events: AgentEvent[] = [];
session.subscribe((e) => events.push(e));
const { streamId } = await session.send({ update: { title: 't' } });
expect(events.map((e) => e.type)).toEqual([
'session_update',
'agent_start',
]);
// Push new event to active stream
session.pushToStream(streamId, [{ type: 'message' }]);
session.pushToStream(streamId!, [{ type: 'message' }]);
const e3 = await stream.next();
expect(e3.value.type).toBe('message');
expect(events).toHaveLength(3);
expect(events[2].type).toBe('message');
await session.abort();
const e4 = await stream.next();
expect(e4.value.type).toBe('stream_end');
expect(events).toHaveLength(4);
expect(events[3].type).toBe('agent_end');
});
it('should handle pushToStream with close option', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
session.pushResponse([], { keepOpen: true });
const { streamId } = await session.send({ update: {} });
const stream = session.stream({ streamId });
await stream.next(); // start
await stream.next(); // update
const streamPromise = waitForStreamEnd(session);
const { streamId } = await session.send({ update: { title: 't' } });
// Push new event and close
session.pushToStream(streamId, [{ type: 'message' }], { close: true });
session.pushToStream(streamId!, [{ type: 'message' }], { close: true });
const e3 = await stream.next();
expect(e3.value.type).toBe('message');
const e4 = await stream.next();
expect(e4.value.type).toBe('stream_end');
expect((e4.value as AgentEvent<'stream_end'>).reason).toBe('completed');
expect(await stream.next()).toEqual({ done: true, value: undefined });
const events = await streamPromise;
expect(events.map((e) => e.type)).toEqual([
'session_update',
'agent_start',
'message',
'agent_end',
]);
expect((events[3] as AgentEvent<'agent_end'>).reason).toBe('completed');
});
it('should not double up on stream_end if provided manually', async () => {
const session = new MockAgentSession();
it('should not double up on agent_end if provided manually', async () => {
const session = new MockAgentProtocol();
session.pushResponse([
{ type: 'message' },
{ type: 'stream_end', reason: 'completed' },
{ type: 'agent_end', reason: 'completed' },
]);
const { streamId } = await session.send({ update: {} });
const events: AgentEvent[] = [];
for await (const e of session.stream({ streamId })) {
events.push(e);
}
const streamPromise = waitForStreamEnd(session);
await session.send({ update: { title: 't' } });
const endEvents = events.filter((e) => e.type === 'stream_end');
const events = await streamPromise;
const endEvents = events.filter((e) => e.type === 'agent_end');
expect(endEvents).toHaveLength(1);
});
it('should stream after eventId', async () => {
const session = new MockAgentSession();
// Use manual IDs to test resumption
session.pushResponse([
{ type: 'stream_start', id: 'e1' },
{ type: 'message', id: 'e2' },
{ type: 'stream_end', id: 'e3' },
]);
await session.send({ update: {} });
// Stream first event only
const first: AgentEvent[] = [];
for await (const e of session.stream()) {
first.push(e);
if (e.id === 'e1') break;
}
expect(first).toHaveLength(1);
expect(first[0].id).toBe('e1');
// Resume from e1
const second: AgentEvent[] = [];
for await (const e of session.stream({ eventId: 'e1' })) {
second.push(e);
}
expect(second).toHaveLength(3); // update, message, end
expect(second[0].type).toBe('session_update');
expect(second[1].id).toBe('e2');
expect(second[2].id).toBe('e3');
});
it('should handle elicitations', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
session.pushResponse([]);
const streamPromise = waitForStreamEnd(session);
await session.send({
elicitations: [
{ requestId: 'r1', action: 'accept', content: { foo: 'bar' } },
],
});
const events: AgentEvent[] = [];
for await (const e of session.stream()) events.push(e);
expect(events[1].type).toBe('elicitation_response');
expect((events[1] as AgentEvent<'elicitation_response'>).requestId).toBe(
const events = await streamPromise;
expect(events[0].type).toBe('elicitation_response');
expect((events[0] as AgentEvent<'elicitation_response'>).requestId).toBe(
'r1',
);
expect(events[1].type).toBe('agent_start');
});
it('should handle updates and track state', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
session.pushResponse([]);
const streamPromise = waitForStreamEnd(session);
await session.send({
update: { title: 'New Title', model: 'gpt-4', config: { x: 1 } },
});
@@ -263,15 +224,24 @@ describe('MockAgentSession', () => {
expect(session.model).toBe('gpt-4');
expect(session.config).toEqual({ x: 1 });
const events: AgentEvent[] = [];
for await (const e of session.stream()) events.push(e);
expect(events[1].type).toBe('session_update');
const events = await streamPromise;
expect(events[0].type).toBe('session_update');
expect(events[1].type).toBe('agent_start');
});
it('should return streamId: null if no response queued', async () => {
const session = new MockAgentProtocol();
const { streamId } = await session.send({ update: { title: 'foo' } });
expect(streamId).toBeNull();
expect(session.events).toHaveLength(1);
expect(session.events[0].type).toBe('session_update');
expect(session.events[0].streamId).toEqual(expect.any(String));
});
it('should throw on action', async () => {
const session = new MockAgentSession();
const session = new MockAgentProtocol();
await expect(
session.send({ action: { type: 'foo', data: {} } }),
).rejects.toThrow('Actions not supported in MockAgentSession: foo');
).rejects.toThrow('Actions not supported in MockAgentProtocol: foo');
});
});
+140 -175
View File
@@ -8,32 +8,33 @@ import type {
AgentEvent,
AgentEventCommon,
AgentEventData,
AgentProtocol,
AgentSend,
AgentSession,
Unsubscribe,
} from './types.js';
export type MockAgentEvent = Partial<AgentEventCommon> & AgentEventData;
export interface PushResponseOptions {
/** If true, does not automatically add a stream_end event. */
/** If true, does not automatically add an agent_end event. */
keepOpen?: boolean;
}
/**
* A mock implementation of AgentSession for testing.
* A mock implementation of AgentProtocol for testing.
* Allows queuing responses that will be yielded when send() is called.
*/
export class MockAgentSession implements AgentSession {
export class MockAgentProtocol implements AgentProtocol {
private _events: AgentEvent[] = [];
private _responses: Array<{
events: MockAgentEvent[];
options?: PushResponseOptions;
}> = [];
private _streams = new Map<string, AgentEvent[]>();
private _subscribers = new Set<(event: AgentEvent) => void>();
private _activeStreamIds = new Set<string>();
private _lastStreamId?: string;
private _lastStreamId?: string | null;
private _nextEventId = 1;
private _streamResolvers = new Map<string, Array<() => void>>();
private _nextStreamId = 1;
title?: string;
model?: string;
@@ -50,12 +51,28 @@ export class MockAgentSession implements AgentSession {
return this._events;
}
subscribe(callback: (event: AgentEvent) => void): Unsubscribe {
this._subscribers.add(callback);
return () => this._subscribers.delete(callback);
}
private _emit(event: AgentEvent) {
if (!this._events.some((e) => e.id === event.id)) {
this._events.push(event);
}
for (const callback of this._subscribers) {
callback(event);
}
if (event.type === 'agent_end' && event.streamId) {
this._activeStreamIds.delete(event.streamId);
}
}
/**
* Queues a sequence of events to be "emitted" by the agent in response to the
* next send() call.
*/
pushResponse(events: MockAgentEvent[], options?: PushResponseOptions) {
// We store them as data and normalize them when send() is called
this._responses.push({ events, options });
}
@@ -67,218 +84,166 @@ export class MockAgentSession implements AgentSession {
events: MockAgentEvent[],
options?: { close?: boolean },
) {
const stream = this._streams.get(streamId);
if (!stream) {
throw new Error(`Stream not found: ${streamId}`);
}
const now = new Date().toISOString();
for (const eventData of events) {
const event: AgentEvent = {
...eventData,
id: eventData.id ?? `e-${this._nextEventId++}`,
timestamp: eventData.timestamp ?? now,
streamId: eventData.streamId ?? streamId,
} as AgentEvent;
stream.push(event);
const event = this._normalizeEvent(eventData, now, streamId);
this._emit(event);
}
if (
options?.close &&
!events.some((eventData) => eventData.type === 'stream_end')
!events.some((eventData) => eventData.type === 'agent_end')
) {
stream.push({
const endEvent = {
id: `e-${this._nextEventId++}`,
timestamp: now,
streamId,
type: 'stream_end',
type: 'agent_end',
reason: 'completed',
} as AgentEvent);
}
this._notify(streamId);
}
private _notify(streamId: string) {
const resolvers = this._streamResolvers.get(streamId);
if (resolvers) {
this._streamResolvers.delete(streamId);
for (const resolve of resolvers) resolve();
} satisfies AgentEvent<'agent_end'>;
this._emit(endEvent);
}
}
async send(payload: AgentSend): Promise<{ streamId: string }> {
const { events: response, options } = this._responses.shift() ?? {
async send(payload: AgentSend): Promise<{ streamId: string | null }> {
const responseData = this._responses.shift();
const { events: response, options } = responseData ?? {
events: [],
};
const streamId =
response[0]?.streamId ?? `mock-stream-${this._streams.size + 1}`;
// If there were queued responses (even if empty array), we trigger a stream.
const hasResponseEvents = responseData !== undefined;
let correlationStreamId: string | undefined;
const getCorrelationStreamId = (): string =>
(correlationStreamId ??=
response[0]?.streamId ?? `mock-stream-${this._nextStreamId++}`);
const streamId = hasResponseEvents ? getCorrelationStreamId() : null;
const now = new Date().toISOString();
const eventsToEmit: AgentEvent[] = [];
if (!response.some((eventData) => eventData.type === 'stream_start')) {
response.unshift({
type: 'stream_start',
streamId,
});
}
const startIndex = response.findIndex(
(eventData) => eventData.type === 'stream_start',
);
// All emitted events stay correlated to a stream even if this send does not
// start agent activity and therefore returns `streamId: null`.
const normalize = (eventData: MockAgentEvent): AgentEvent =>
this._normalizeEvent(eventData, now, getCorrelationStreamId());
// 1. User/Update event (BEFORE agent_start)
if ('message' in payload && payload.message) {
response.splice(startIndex + 1, 0, {
type: 'message',
role: 'user',
content: payload.message,
_meta: payload._meta,
});
} else if ('elicitations' in payload && payload.elicitations) {
payload.elicitations.forEach((elicitation, i) => {
response.splice(startIndex + 1 + i, 0, {
type: 'elicitation_response',
...elicitation,
eventsToEmit.push(
normalize({
type: 'message',
role: 'user',
content: payload.message,
_meta: payload._meta,
});
}),
);
} else if ('elicitations' in payload && payload.elicitations) {
payload.elicitations.forEach((elicitation) => {
eventsToEmit.push(
normalize({
type: 'elicitation_response',
...elicitation,
_meta: payload._meta,
}),
);
});
} else if ('update' in payload && payload.update) {
} else if (
'update' in payload &&
payload.update &&
Object.keys(payload.update).length > 0
) {
if (payload.update.title) this.title = payload.update.title;
if (payload.update.model) this.model = payload.update.model;
if (payload.update.config) {
this.config = payload.update.config;
}
response.splice(startIndex + 1, 0, {
type: 'session_update',
...payload.update,
_meta: payload._meta,
});
eventsToEmit.push(
normalize({
type: 'session_update',
...payload.update,
_meta: payload._meta,
}),
);
} else if ('action' in payload && payload.action) {
throw new Error(
`Actions not supported in MockAgentSession: ${payload.action.type}`,
`Actions not supported in MockAgentProtocol: ${payload.action.type}`,
);
}
if (
!options?.keepOpen &&
!response.some((eventData) => eventData.type === 'stream_end')
) {
response.push({
type: 'stream_end',
reason: 'completed',
streamId,
});
}
const normalizedResponse: AgentEvent[] = [];
for (const eventData of response) {
const event: AgentEvent = {
...eventData,
id: eventData.id ?? `e-${this._nextEventId++}`,
timestamp: eventData.timestamp ?? now,
streamId: eventData.streamId ?? streamId,
} as AgentEvent;
normalizedResponse.push(event);
}
this._streams.set(streamId, normalizedResponse);
this._activeStreamIds.add(streamId);
this._lastStreamId = streamId;
return { streamId };
}
async *stream(options?: {
streamId?: string;
eventId?: string;
}): AsyncIterableIterator<AgentEvent> {
let streamId = options?.streamId;
if (options?.eventId) {
const event = this._events.find(
(eventData) => eventData.id === options.eventId,
);
if (!event) {
throw new Error(`Event not found: ${options.eventId}`);
}
streamId = streamId ?? event.streamId;
}
streamId = streamId ?? this._lastStreamId;
if (!streamId) {
return;
}
const events = this._streams.get(streamId);
if (!events) {
throw new Error(`Stream not found: ${streamId}`);
}
let i = 0;
if (options?.eventId) {
const idx = events.findIndex(
(eventData) => eventData.id === options.eventId,
);
if (idx !== -1) {
i = idx + 1;
} else {
// This should theoretically not happen if the event was found in this._events
// but the trajectories match.
throw new Error(
`Event ${options.eventId} not found in stream ${streamId}`,
// 2. agent_start (if stream)
if (streamId) {
if (!response.some((eventData) => eventData.type === 'agent_start')) {
eventsToEmit.push(
normalize({
type: 'agent_start',
streamId,
}),
);
}
}
while (true) {
if (i < events.length) {
const event = events[i++];
// Add to session trajectory if not already present
if (!this._events.some((eventData) => eventData.id === event.id)) {
this._events.push(event);
}
yield event;
// 3. Response events
for (const eventData of response) {
eventsToEmit.push(normalize(eventData));
}
// If it's a stream_end, we're done with this stream
if (event.type === 'stream_end') {
this._activeStreamIds.delete(streamId);
return;
}
} else {
// No more events in the array currently. Check if we're still active.
if (!this._activeStreamIds.has(streamId)) {
// If we weren't terminated by a stream_end but we're no longer active,
// it was an abort.
const abortEvent: AgentEvent = {
id: `e-${this._nextEventId++}`,
timestamp: new Date().toISOString(),
// 4. agent_end (if stream and not manual)
if (streamId && !options?.keepOpen) {
if (!eventsToEmit.some((e) => e.type === 'agent_end')) {
eventsToEmit.push(
normalize({
type: 'agent_end',
reason: 'completed',
streamId,
type: 'stream_end',
reason: 'aborted',
} as AgentEvent;
if (!this._events.some((e) => e.id === abortEvent.id)) {
this._events.push(abortEvent);
}
yield abortEvent;
return;
}
// Wait for notification (new event or abort)
await new Promise<void>((resolve) => {
const resolvers = this._streamResolvers.get(streamId) ?? [];
resolvers.push(resolve);
this._streamResolvers.set(streamId, resolvers);
});
}),
);
}
}
if (streamId) {
this._activeStreamIds.add(streamId);
}
this._lastStreamId = streamId;
// Emit events asynchronously so the caller receives the streamId first.
if (eventsToEmit.length > 0) {
void Promise.resolve().then(() => {
for (const event of eventsToEmit) {
this._emit(event);
}
});
}
return { streamId };
}
private _normalizeEvent(
eventData: MockAgentEvent,
timestamp: string,
streamId: string,
): AgentEvent {
// TypeScript loses the specific union member when we add common event
// fields here, so keep the narrowing local to this mock-only helper.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return {
...eventData,
id: eventData.id ?? `e-${this._nextEventId++}`,
timestamp: eventData.timestamp ?? timestamp,
streamId: eventData.streamId ?? streamId,
} as AgentEvent;
}
async abort(): Promise<void> {
if (this._lastStreamId) {
if (this._lastStreamId && this._activeStreamIds.has(this._lastStreamId)) {
const streamId = this._lastStreamId;
this._activeStreamIds.delete(streamId);
this._notify(streamId);
const endEvent = {
id: `e-${this._nextEventId++}`,
timestamp: new Date().toISOString(),
streamId,
type: 'agent_end',
reason: 'aborted',
} satisfies AgentEvent<'agent_end'>;
this._emit(endEvent);
}
}
}
+40 -28
View File
@@ -6,25 +6,28 @@
export type WithMeta = { _meta?: Record<string, unknown> };
export interface AgentSession extends Trajectory {
export type Unsubscribe = () => void;
export interface AgentProtocol extends Trajectory {
/**
* Send data to the agent. Promise resolves when action is acknowledged.
* Returns the `streamId` of the stream the message was correlated to -- this may
* be a new stream if idle or an existing stream.
*/
send(payload: AgentSend): Promise<{ streamId: string }>;
/**
* Begin listening to actively streaming data. Stream must have the following
* properties:
* Returns the agent-activity `streamId` affected by the send. This may be a
* new stream if idle, an existing stream, or null if the send was
* acknowledged without starting agent activity. Emitted events should still
* remain correlated to a stream via their `streamId`.
*
* - If no arguments are provided, streams events from an active stream.
* - If a {streamId} is provided, streams ALL events from that stream.
* - If an {eventId} is provided, streams all events AFTER that event.
* When a new stream is created by a send, the streamId MUST be returned
* before the `agent_start` event is emitted for the stream.
*/
stream(options?: {
streamId?: string;
eventId?: string;
}): AsyncIterableIterator<AgentEvent>;
send(payload: AgentSend): Promise<{ streamId: string | null }>;
/**
* Subscribes the provided callback to all future events emitted by this
* session. Returns an unsubscribe function.
*
* @param callback The callback function to listen to events.
*/
subscribe(callback: (event: AgentEvent) => void): Unsubscribe;
/**
* Aborts an active stream of agent activity.
@@ -32,9 +35,9 @@ export interface AgentSession extends Trajectory {
abort(): Promise<void>;
/**
* AgentSession implements the Trajectory interface and can retrieve existing events.
* AgentProtocol implements the Trajectory interface and can retrieve existing events.
*/
readonly events: AgentEvent[];
readonly events: readonly AgentEvent[];
}
type RequireExactlyOne<T> = {
@@ -52,7 +55,7 @@ interface AgentSendPayloads {
export type AgentSend = RequireExactlyOne<AgentSendPayloads> & WithMeta;
export interface Trajectory {
readonly events: AgentEvent[];
readonly events: readonly AgentEvent[];
}
export interface AgentEventCommon {
@@ -60,8 +63,8 @@ export interface AgentEventCommon {
id: string;
/** Identifies the subagent thread, omitted for "main thread" events. */
threadId?: string;
/** Identifies a particular stream of a particular thread. */
streamId?: string;
/** Identifies the stream this event belongs to. */
streamId: string;
/** ISO Timestamp for the time at which the event occurred. */
timestamp: string;
/** The concrete type of the event. */
@@ -79,9 +82,18 @@ export type AgentEventData<
EventType extends keyof AgentEvents = keyof AgentEvents,
> = AgentEvents[EventType] & { type: EventType };
/**
* Mapped type that produces a proper discriminated union when `EventType` is
* the default (all keys), enabling `switch (event.type)` narrowing.
* When a specific EventType is provided, resolves to a single variant.
*/
export type AgentEvent<
EventType extends keyof AgentEvents = keyof AgentEvents,
> = AgentEventCommon & AgentEventData<EventType>;
> = {
[K in EventType]: AgentEventCommon & AgentEvents[K] & { type: K };
}[EventType];
export type AgentEventType = keyof AgentEvents;
export interface AgentEvents {
/** MUST be the first event emitted in a session. */
@@ -90,10 +102,10 @@ export interface AgentEvents {
session_update: SessionUpdate;
/** Message content provided by user, agent, or developer. */
message: Message;
/** Event indicating the start of a new stream. */
stream_start: StreamStart;
/** Event indicating the end of a running stream. */
stream_end: StreamEnd;
/** Event indicating the start of agent activity on a stream. */
agent_start: AgentStart;
/** Event indicating the end of agent activity on a stream. */
agent_end: AgentEnd;
/** Tool request issued by the agent. */
tool_request: ToolRequest;
/** Tool update issued by the agent. */
@@ -257,11 +269,11 @@ export interface Usage {
cost?: { amount: number; currency?: string };
}
export interface StreamStart {
export interface AgentStart {
streamId: string;
}
type StreamEndReason =
export type StreamEndReason =
| 'completed'
| 'failed'
| 'aborted'
@@ -272,7 +284,7 @@ type StreamEndReason =
| 'elicitation'
| (string & {});
export interface StreamEnd {
export interface AgentEnd {
streamId: string;
reason: StreamEndReason;
elicitationIds?: string[];
@@ -0,0 +1,153 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { MemoryManagerAgent } from './memory-manager-agent.js';
import {
ASK_USER_TOOL_NAME,
EDIT_TOOL_NAME,
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
LS_TOOL_NAME,
READ_FILE_TOOL_NAME,
WRITE_FILE_TOOL_NAME,
} from '../tools/tool-names.js';
import { Storage } from '../config/storage.js';
import type { Config } from '../config/config.js';
import type { HierarchicalMemory } from '../config/memory.js';
function createMockConfig(memory: string | HierarchicalMemory = ''): Config {
return {
getUserMemory: vi.fn().mockReturnValue(memory),
} as unknown as Config;
}
describe('MemoryManagerAgent', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should have the correct name "save_memory"', () => {
const agent = MemoryManagerAgent(createMockConfig());
expect(agent.name).toBe('save_memory');
});
it('should be a local agent', () => {
const agent = MemoryManagerAgent(createMockConfig());
expect(agent.kind).toBe('local');
});
it('should have a description', () => {
const agent = MemoryManagerAgent(createMockConfig());
expect(agent.description).toBeTruthy();
expect(agent.description).toContain('memory');
});
it('should have a system prompt with memory management instructions', () => {
const agent = MemoryManagerAgent(createMockConfig());
const prompt = agent.promptConfig.systemPrompt;
const globalGeminiDir = Storage.getGlobalGeminiDir();
expect(prompt).toContain(`Global (${globalGeminiDir}`);
expect(prompt).toContain('Project (./');
expect(prompt).toContain('Memory Hierarchy');
expect(prompt).toContain('De-duplicating');
expect(prompt).toContain('Adding');
expect(prompt).toContain('Removing stale entries');
expect(prompt).toContain('Organizing');
expect(prompt).toContain('Routing');
});
it('should have efficiency guidelines in the system prompt', () => {
const agent = MemoryManagerAgent(createMockConfig());
const prompt = agent.promptConfig.systemPrompt;
expect(prompt).toContain('Efficiency & Performance');
expect(prompt).toContain('Use as few turns as possible');
expect(prompt).toContain('Do not perform any exploration');
expect(prompt).toContain('Be strategic with your thinking');
expect(prompt).toContain('Context Awareness');
});
it('should inject hierarchical memory into initial context', () => {
const config = createMockConfig({
global:
'--- Context from: ../../.gemini/GEMINI.md ---\nglobal context\n--- End of Context from: ../../.gemini/GEMINI.md ---',
project:
'--- Context from: .gemini/GEMINI.md ---\nproject context\n--- End of Context from: .gemini/GEMINI.md ---',
});
const agent = MemoryManagerAgent(config);
const query = agent.promptConfig.query;
expect(query).toContain('# Initial Context');
expect(query).toContain('global context');
expect(query).toContain('project context');
});
it('should inject flat string memory into initial context', () => {
const config = createMockConfig('flat memory content');
const agent = MemoryManagerAgent(config);
const query = agent.promptConfig.query;
expect(query).toContain('# Initial Context');
expect(query).toContain('flat memory content');
});
it('should exclude extension memory from initial context', () => {
const config = createMockConfig({
global: 'global context',
extension: 'extension context that should be excluded',
project: 'project context',
});
const agent = MemoryManagerAgent(config);
const query = agent.promptConfig.query;
expect(query).toContain('global context');
expect(query).toContain('project context');
expect(query).not.toContain('extension context');
});
it('should not include initial context when memory is empty', () => {
const agent = MemoryManagerAgent(createMockConfig());
const query = agent.promptConfig.query;
expect(query).not.toContain('# Initial Context');
});
it('should have file-management and search tools', () => {
const agent = MemoryManagerAgent(createMockConfig());
expect(agent.toolConfig).toBeDefined();
expect(agent.toolConfig!.tools).toEqual(
expect.arrayContaining([
READ_FILE_TOOL_NAME,
EDIT_TOOL_NAME,
WRITE_FILE_TOOL_NAME,
LS_TOOL_NAME,
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
ASK_USER_TOOL_NAME,
]),
);
});
it('should require a "request" input parameter', () => {
const agent = MemoryManagerAgent(createMockConfig());
const schema = agent.inputConfig.inputSchema as Record<string, unknown>;
expect(schema).toBeDefined();
expect(schema['properties']).toHaveProperty('request');
expect(schema['required']).toContain('request');
});
it('should use a fast model', () => {
const agent = MemoryManagerAgent(createMockConfig());
expect(agent.modelConfig.model).toBe('flash');
});
});
@@ -0,0 +1,156 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { z } from 'zod';
import type { LocalAgentDefinition } from './types.js';
import {
ASK_USER_TOOL_NAME,
EDIT_TOOL_NAME,
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
LS_TOOL_NAME,
READ_FILE_TOOL_NAME,
WRITE_FILE_TOOL_NAME,
} from '../tools/tool-names.js';
import { Storage } from '../config/storage.js';
import { flattenMemory } from '../config/memory.js';
import { GEMINI_MODEL_ALIAS_FLASH } from '../config/models.js';
import type { Config } from '../config/config.js';
const MemoryManagerSchema = z.object({
response: z
.string()
.describe('A summary of the memory operations performed.'),
});
/**
* A memory management agent that replaces the built-in save_memory tool.
* It provides richer memory operations: adding, removing, de-duplicating,
* and organizing memories in the global GEMINI.md file.
*
* Users can override this agent by placing a custom save_memory.md
* in ~/.gemini/agents/ or .gemini/agents/.
*/
export const MemoryManagerAgent = (
config: Config,
): LocalAgentDefinition<typeof MemoryManagerSchema> => {
const globalGeminiDir = Storage.getGlobalGeminiDir();
const getInitialContext = (): string => {
const memory = config.getUserMemory();
// Only include global and project memory — extension memory is read-only
// and not relevant to the memory manager.
const content =
typeof memory === 'string'
? memory
: flattenMemory({ global: memory.global, project: memory.project });
if (!content.trim()) return '';
return `\n# Initial Context\n\n${content}\n`;
};
const buildSystemPrompt = (): string =>
`
You are a memory management agent maintaining user memories in GEMINI.md files.
# Memory Hierarchy
## Global (${globalGeminiDir})
- \`${globalGeminiDir}/GEMINI.md\` — Cross-project user preferences, key personal info,
and habits that apply everywhere.
## Project (./)
- \`./GEMINI.md\` — **Table of Contents** for project-specific context:
architecture decisions, conventions, key contacts, and references to
subdirectory GEMINI.md files for detailed context.
- Subdirectory GEMINI.md files (e.g. \`src/GEMINI.md\`, \`docs/GEMINI.md\`) —
detailed, domain-specific context for that part of the project. Reference
these from the root \`./GEMINI.md\`.
## Routing
When adding a memory, route it to the right store:
- **Global**: User preferences, personal info, tool aliases, cross-project habits **global**
- **Project Root**: Project architecture, conventions, workflows, team info **project root**
- **Subdirectory**: Detailed context about a specific module or directory **subdirectory
GEMINI.md**, with a reference added to the project root
- **Ambiguity**: If a memory (like a coding preference or workflow) could be interpreted as either a global habit or a project-specific convention, you **MUST** use \`${ASK_USER_TOOL_NAME}\` to clarify the user's intent. Do NOT make a unilateral decision when ambiguity exists between Global and Project stores.
# Operations
1. **Adding** Route to the correct store and file. Check for duplicates in your provided context first.
2. **Removing stale entries** Delete outdated or unwanted entries. Clean up
dangling references.
3. **De-duplicating** Semantically equivalent entries should be combined. Keep the most informative version.
4. **Organizing** Restructure for clarity. Update references between files.
# Restrictions
- Keep GEMINI.md files lean they are loaded into context every session.
- Keep entries concise.
- Edit surgically preserve existing structure and user-authored content.
- NEVER write or read any files other than GEMINI.md files.
# Efficiency & Performance
- **Use as few turns as possible.** Execute independent reads and writes to different files in parallel by calling multiple tools in a single turn.
- **Do not perform any exploration of the codebase.** Try to use the provided file context and only search additional GEMINI.md files as needed to accomplish your task.
- **Be strategic with your thinking.** carefully decide where to route memories and how to de-duplicate memories, but be decisive with simple memory writes.
- **Minimize file system operations.** You should typically only modify the GEMINI.md files that are already provided in your context. Only read or write to other files if explicitly directed or if you are following a specific reference from an existing memory file.
- **Context Awareness.** If a file's content is already provided in the "Initial Context" section, you do not need to call \`read_file\` for it.
# Insufficient context
If you find that you have insufficient context to read or modify the memories as described,
reply with what you need, and exit. Do not search the codebase for the missing context.
`.trim();
return {
kind: 'local',
name: 'save_memory',
displayName: 'Memory Manager',
description: `Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.`,
inputConfig: {
inputSchema: {
type: 'object',
properties: {
request: {
type: 'string',
description:
'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".',
},
},
required: ['request'],
},
},
outputConfig: {
outputName: 'result',
description: 'A summary of the memory operations performed.',
schema: MemoryManagerSchema,
},
modelConfig: {
model: GEMINI_MODEL_ALIAS_FLASH,
},
toolConfig: {
tools: [
READ_FILE_TOOL_NAME,
EDIT_TOOL_NAME,
WRITE_FILE_TOOL_NAME,
LS_TOOL_NAME,
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
ASK_USER_TOOL_NAME,
],
},
get promptConfig() {
return {
systemPrompt: buildSystemPrompt(),
query: `${getInitialContext()}\${request}`,
};
},
runConfig: {
maxTimeMinutes: 5,
maxTurns: 10,
},
};
};
+19
View File
@@ -13,6 +13,7 @@ import { CodebaseInvestigatorAgent } from './codebase-investigator.js';
import { CliHelpAgent } from './cli-help-agent.js';
import { GeneralistAgent } from './generalist-agent.js';
import { BrowserAgentDefinition } from './browser/browserAgentDefinition.js';
import { MemoryManagerAgent } from './memory-manager-agent.js';
import { A2AAuthProviderFactory } from './auth-provider/factory.js';
import type { AuthenticationHandler } from '@a2a-js/sdk/client';
import { type z } from 'zod';
@@ -249,6 +250,24 @@ export class AgentRegistry {
if (browserConfig.enabled) {
this.registerLocalAgent(BrowserAgentDefinition(this.config));
}
// Register the memory manager agent as a replacement for the save_memory tool.
if (this.config.isMemoryManagerEnabled()) {
this.registerLocalAgent(MemoryManagerAgent(this.config));
// Ensure the global .gemini directory is accessible to tools.
// This allows the save_memory agent to read and write to it.
// Access control is enforced by the Policy Engine (memory-manager.toml).
try {
const globalDir = Storage.getGlobalGeminiDir();
this.config.getWorkspaceContext().addDirectory(globalDir);
} catch (e) {
debugLogger.warn(
`[AgentRegistry] Could not add global .gemini directory to workspace:`,
e,
);
}
}
}
private async refreshAgents(): Promise<void> {
@@ -19,6 +19,8 @@ import {
PREVIEW_GEMINI_3_1_MODEL,
} from '../config/models.js';
import { AuthType } from '../core/contentGenerator.js';
import { ModelConfigService } from '../services/modelConfigService.js';
import { DEFAULT_MODEL_CONFIGS } from '../config/defaultModelConfigs.js';
const createMockConfig = (overrides: Partial<Config> = {}): Config => {
const config = {
@@ -163,6 +165,66 @@ describe('policyHelpers', () => {
});
});
describe('resolvePolicyChain behavior is identical between dynamic and legacy implementations', () => {
const testCases = [
{ name: 'Default Auto', model: DEFAULT_GEMINI_MODEL_AUTO },
{ name: 'Gemini 3 Auto', model: 'auto-gemini-3' },
{ name: 'Flash Lite', model: DEFAULT_GEMINI_FLASH_LITE_MODEL },
{
name: 'Gemini 3 Auto (3.1 Enabled)',
model: 'auto-gemini-3',
useGemini31: true,
},
{
name: 'Gemini 3 Auto (3.1 + Custom Tools)',
model: 'auto-gemini-3',
useGemini31: true,
authType: AuthType.USE_GEMINI,
},
{
name: 'Gemini 3 Auto (No Access)',
model: 'auto-gemini-3',
hasAccess: false,
},
{ name: 'Concrete Model (2.5 Pro)', model: 'gemini-2.5-pro' },
{ name: 'Custom Model', model: 'my-custom-model' },
{
name: 'Wrap Around',
model: DEFAULT_GEMINI_MODEL_AUTO,
wrapsAround: true,
},
];
testCases.forEach(
({ name, model, useGemini31, hasAccess, authType, wrapsAround }) => {
it(`achieves parity for: ${name}`, () => {
const createBaseConfig = (dynamic: boolean) =>
createMockConfig({
getExperimentalDynamicModelConfiguration: () => dynamic,
getModel: () => model,
getGemini31LaunchedSync: () => useGemini31 ?? false,
getHasAccessToPreviewModel: () => hasAccess ?? true,
getContentGeneratorConfig: () => ({ authType }),
modelConfigService: new ModelConfigService(DEFAULT_MODEL_CONFIGS),
});
const legacyChain = resolvePolicyChain(
createBaseConfig(false),
model,
wrapsAround,
);
const dynamicChain = resolvePolicyChain(
createBaseConfig(true),
model,
wrapsAround,
);
expect(dynamicChain).toEqual(legacyChain);
});
},
);
});
describe('buildFallbackPolicyContext', () => {
it('returns remaining candidates after the failed model', () => {
const chain = [
@@ -53,12 +53,57 @@ export function resolvePolicyChain(
useGemini31,
useCustomToolModel,
hasAccessToPreview,
config,
);
const isAutoPreferred = preferredModel
? isAutoModel(preferredModel, config)
: false;
const isAutoConfigured = isAutoModel(configuredModel, config);
// --- DYNAMIC PATH ---
if (config.getExperimentalDynamicModelConfiguration?.() === true) {
const context = {
useGemini3_1: useGemini31,
useCustomTools: useCustomToolModel,
};
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
chain = config.modelConfigService.resolveChain('lite', context);
} else if (
isGemini3Model(resolvedModel, config) ||
isAutoModel(preferredModel ?? '', config) ||
isAutoModel(configuredModel, config)
) {
// 1. Try to find a chain specifically for the current configured alias
if (
isAutoModel(configuredModel, config) &&
config.modelConfigService.getModelChain(configuredModel)
) {
chain = config.modelConfigService.resolveChain(
configuredModel,
context,
);
}
// 2. Fallback to family-based auto-routing
if (!chain) {
const previewEnabled =
hasAccessToPreview &&
(isGemini3Model(resolvedModel, config) ||
preferredModel === PREVIEW_GEMINI_MODEL_AUTO ||
configuredModel === PREVIEW_GEMINI_MODEL_AUTO);
const chainKey = previewEnabled ? 'preview' : 'default';
chain = config.modelConfigService.resolveChain(chainKey, context);
}
}
if (!chain) {
// No matching modelChains found, default to single model chain
chain = createSingleModelChain(modelFromConfig);
}
return applyDynamicSlicing(chain, resolvedModel, wrapsAround);
}
// --- LEGACY PATH ---
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
chain = getFlashLitePolicyChain();
} else if (
@@ -90,7 +135,17 @@ export function resolvePolicyChain(
} else {
chain = createSingleModelChain(modelFromConfig);
}
return applyDynamicSlicing(chain, resolvedModel, wrapsAround);
}
/**
* Applies active-index slicing and wrap-around logic to a chain template.
*/
function applyDynamicSlicing(
chain: ModelPolicy[],
resolvedModel: string,
wrapsAround: boolean,
): ModelPolicyChain {
const activeIndex = chain.findIndex(
(policy) => policy.model === resolvedModel,
);
@@ -224,6 +224,89 @@ describe('Admin Controls', () => {
const result = sanitizeAdminSettings(input);
expect(result.strictModeDisabled).toBe(true);
});
it('should parse requiredMcpServers from mcpConfigJson', () => {
const mcpConfig = {
mcpServers: {
'allowed-server': {
url: 'http://allowed.com',
type: 'sse' as const,
},
},
requiredMcpServers: {
'corp-tool': {
url: 'https://mcp.corp/tool',
type: 'http' as const,
trust: true,
description: 'Corp compliance tool',
},
},
};
const input: FetchAdminControlsResponse = {
mcpSetting: {
mcpEnabled: true,
mcpConfigJson: JSON.stringify(mcpConfig),
},
};
const result = sanitizeAdminSettings(input);
expect(result.mcpSetting?.mcpConfig?.mcpServers).toEqual(
mcpConfig.mcpServers,
);
expect(result.mcpSetting?.requiredMcpConfig).toEqual(
mcpConfig.requiredMcpServers,
);
});
it('should sort requiredMcpServers tool lists for stable comparison', () => {
const mcpConfig = {
requiredMcpServers: {
'corp-tool': {
url: 'https://mcp.corp/tool',
type: 'http' as const,
includeTools: ['toolC', 'toolA', 'toolB'],
excludeTools: ['toolZ', 'toolX'],
},
},
};
const input: FetchAdminControlsResponse = {
mcpSetting: {
mcpEnabled: true,
mcpConfigJson: JSON.stringify(mcpConfig),
},
};
const result = sanitizeAdminSettings(input);
const corpTool = result.mcpSetting?.requiredMcpConfig?.['corp-tool'];
expect(corpTool?.includeTools).toEqual(['toolA', 'toolB', 'toolC']);
expect(corpTool?.excludeTools).toEqual(['toolX', 'toolZ']);
});
it('should handle mcpConfigJson with only requiredMcpServers and no mcpServers', () => {
const mcpConfig = {
requiredMcpServers: {
'required-only': {
url: 'https://required.corp/tool',
type: 'http' as const,
},
},
};
const input: FetchAdminControlsResponse = {
mcpSetting: {
mcpEnabled: true,
mcpConfigJson: JSON.stringify(mcpConfig),
},
};
const result = sanitizeAdminSettings(input);
expect(result.mcpSetting?.mcpConfig?.mcpServers).toBeUndefined();
expect(result.mcpSetting?.requiredMcpConfig).toEqual(
mcpConfig.requiredMcpServers,
);
});
});
describe('isDeepStrictEqual verification', () => {
@@ -48,6 +48,16 @@ export function sanitizeAdminSettings(
}
}
}
if (mcpConfig.requiredMcpServers) {
for (const server of Object.values(mcpConfig.requiredMcpServers)) {
if (server.includeTools) {
server.includeTools.sort();
}
if (server.excludeTools) {
server.excludeTools.sort();
}
}
}
}
} catch (_e) {
// Ignore parsing errors
@@ -77,6 +87,7 @@ export function sanitizeAdminSettings(
mcpSetting: {
mcpEnabled: sanitized.mcpSetting?.mcpEnabled ?? false,
mcpConfig: mcpConfig ?? {},
requiredMcpConfig: mcpConfig?.requiredMcpServers,
},
};
}
@@ -5,8 +5,10 @@
*/
import { describe, it, expect } from 'vitest';
import { applyAdminAllowlist } from './mcpUtils.js';
import { applyAdminAllowlist, applyRequiredServers } from './mcpUtils.js';
import type { MCPServerConfig } from '../../config/config.js';
import { AuthProviderType } from '../../config/config.js';
import type { RequiredMcpServerConfig } from '../types.js';
describe('applyAdminAllowlist', () => {
it('should return original servers if no allowlist provided', () => {
@@ -111,3 +113,147 @@ describe('applyAdminAllowlist', () => {
expect(result.mcpServers['server1']?.includeTools).toEqual(['local-tool']);
});
});
describe('applyRequiredServers', () => {
it('should return original servers if no required servers provided', () => {
const mcpServers: Record<string, MCPServerConfig> = {
server1: { command: 'cmd1' },
};
const result = applyRequiredServers(mcpServers, undefined);
expect(result.mcpServers).toEqual(mcpServers);
expect(result.requiredServerNames).toEqual([]);
});
it('should return original servers if required servers is empty', () => {
const mcpServers: Record<string, MCPServerConfig> = {
server1: { command: 'cmd1' },
};
const result = applyRequiredServers(mcpServers, {});
expect(result.mcpServers).toEqual(mcpServers);
expect(result.requiredServerNames).toEqual([]);
});
it('should inject required servers when no local config exists', () => {
const mcpServers: Record<string, MCPServerConfig> = {
'local-server': { command: 'cmd1' },
};
const required: Record<string, RequiredMcpServerConfig> = {
'corp-tool': {
url: 'https://mcp.corp.internal/tool',
type: 'http',
description: 'Corp compliance tool',
},
};
const result = applyRequiredServers(mcpServers, required);
expect(Object.keys(result.mcpServers)).toContain('local-server');
expect(Object.keys(result.mcpServers)).toContain('corp-tool');
expect(result.requiredServerNames).toEqual(['corp-tool']);
const corpTool = result.mcpServers['corp-tool'];
expect(corpTool).toBeDefined();
expect(corpTool?.url).toBe('https://mcp.corp.internal/tool');
expect(corpTool?.type).toBe('http');
expect(corpTool?.description).toBe('Corp compliance tool');
// trust defaults to true for admin-forced servers
expect(corpTool?.trust).toBe(true);
// stdio fields should not be set
expect(corpTool?.command).toBeUndefined();
expect(corpTool?.args).toBeUndefined();
});
it('should override local server with same name', () => {
const mcpServers: Record<string, MCPServerConfig> = {
'shared-server': {
command: 'local-cmd',
args: ['local-arg'],
description: 'Local version',
},
};
const required: Record<string, RequiredMcpServerConfig> = {
'shared-server': {
url: 'https://admin.corp/shared',
type: 'sse',
trust: false,
description: 'Admin-mandated version',
},
};
const result = applyRequiredServers(mcpServers, required);
const server = result.mcpServers['shared-server'];
// Admin config should completely override local
expect(server?.url).toBe('https://admin.corp/shared');
expect(server?.type).toBe('sse');
expect(server?.trust).toBe(false);
expect(server?.description).toBe('Admin-mandated version');
// Local fields should NOT be preserved
expect(server?.command).toBeUndefined();
expect(server?.args).toBeUndefined();
});
it('should preserve auth configuration', () => {
const required: Record<string, RequiredMcpServerConfig> = {
'auth-server': {
url: 'https://auth.corp/tool',
type: 'http',
authProviderType: AuthProviderType.GOOGLE_CREDENTIALS,
oauth: {
scopes: ['https://www.googleapis.com/auth/scope1'],
},
targetAudience: 'client-id.apps.googleusercontent.com',
headers: { 'X-Custom': 'value' },
},
};
const result = applyRequiredServers({}, required);
const server = result.mcpServers['auth-server'];
expect(server?.authProviderType).toBe(AuthProviderType.GOOGLE_CREDENTIALS);
expect(server?.oauth).toEqual({
scopes: ['https://www.googleapis.com/auth/scope1'],
});
expect(server?.targetAudience).toBe('client-id.apps.googleusercontent.com');
expect(server?.headers).toEqual({ 'X-Custom': 'value' });
});
it('should preserve tool filtering', () => {
const required: Record<string, RequiredMcpServerConfig> = {
'filtered-server': {
url: 'https://corp/tool',
type: 'http',
includeTools: ['toolA', 'toolB'],
excludeTools: ['toolC'],
},
};
const result = applyRequiredServers({}, required);
const server = result.mcpServers['filtered-server'];
expect(server?.includeTools).toEqual(['toolA', 'toolB']);
expect(server?.excludeTools).toEqual(['toolC']);
});
it('should coexist with allowlisted servers', () => {
// Simulate post-allowlist filtering
const afterAllowlist: Record<string, MCPServerConfig> = {
'allowed-server': {
url: 'http://allowed',
type: 'sse',
trust: true,
},
};
const required: Record<string, RequiredMcpServerConfig> = {
'required-server': {
url: 'https://required.corp/tool',
type: 'http',
},
};
const result = applyRequiredServers(afterAllowlist, required);
expect(Object.keys(result.mcpServers)).toHaveLength(2);
expect(result.mcpServers['allowed-server']).toBeDefined();
expect(result.mcpServers['required-server']).toBeDefined();
expect(result.requiredServerNames).toEqual(['required-server']);
});
});
@@ -4,7 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import type { MCPServerConfig } from '../../config/config.js';
import { MCPServerConfig } from '../../config/config.js';
import type { RequiredMcpServerConfig } from '../types.js';
/**
* Applies the admin allowlist to the local MCP servers.
@@ -65,3 +66,58 @@ export function applyAdminAllowlist(
}
return { mcpServers: filteredMcpServers, blockedServerNames };
}
/**
* Applies admin-required MCP servers by injecting them into the MCP server
* list. Required servers always take precedence over locally configured servers
* with the same name and cannot be disabled by the user.
*
* @param mcpServers The current MCP servers (after allowlist filtering).
* @param requiredServers The admin-required MCP server configurations.
* @returns The MCP servers with required servers injected, and the list of
* required server names for informational purposes.
*/
export function applyRequiredServers(
mcpServers: Record<string, MCPServerConfig>,
requiredServers: Record<string, RequiredMcpServerConfig> | undefined,
): {
mcpServers: Record<string, MCPServerConfig>;
requiredServerNames: string[];
} {
if (!requiredServers || Object.keys(requiredServers).length === 0) {
return { mcpServers, requiredServerNames: [] };
}
const result: Record<string, MCPServerConfig> = { ...mcpServers };
const requiredServerNames: string[] = [];
for (const [serverId, requiredConfig] of Object.entries(requiredServers)) {
requiredServerNames.push(serverId);
// Convert RequiredMcpServerConfig to MCPServerConfig.
// Required servers completely override any local config with the same name.
result[serverId] = new MCPServerConfig(
undefined, // command (stdio not supported for required servers)
undefined, // args
undefined, // env
undefined, // cwd
requiredConfig.url, // url
undefined, // httpUrl (use url + type instead)
requiredConfig.headers, // headers
undefined, // tcp
requiredConfig.type, // type
requiredConfig.timeout, // timeout
requiredConfig.trust ?? true, // trust defaults to true for admin-forced
requiredConfig.description, // description
requiredConfig.includeTools, // includeTools
requiredConfig.excludeTools, // excludeTools
undefined, // extension
requiredConfig.oauth, // oauth
requiredConfig.authProviderType, // authProviderType
requiredConfig.targetAudience, // targetAudience
requiredConfig.targetServiceAccount, // targetServiceAccount
);
}
return { mcpServers: result, requiredServerNames };
}
+35
View File
@@ -5,6 +5,7 @@
*/
import { z } from 'zod';
import { AuthProviderType } from '../config/config.js';
export interface ClientMetadata {
ideType?: ClientMetadataIdeType;
@@ -359,8 +360,41 @@ const McpServerConfigSchema = z.object({
excludeTools: z.array(z.string()).optional(),
});
const RequiredMcpServerOAuthSchema = z.object({
scopes: z.array(z.string()).optional(),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
});
export const RequiredMcpServerConfigSchema = z.object({
// Connection (required for forced servers)
url: z.string(),
type: z.enum(['sse', 'http']),
// Auth
authProviderType: z.nativeEnum(AuthProviderType).optional(),
oauth: RequiredMcpServerOAuthSchema.optional(),
targetAudience: z.string().optional(),
targetServiceAccount: z.string().optional(),
headers: z.record(z.string()).optional(),
// Common
trust: z.boolean().optional(),
timeout: z.number().optional(),
description: z.string().optional(),
// Tool filtering
includeTools: z.array(z.string()).optional(),
excludeTools: z.array(z.string()).optional(),
});
export type RequiredMcpServerConfig = z.infer<
typeof RequiredMcpServerConfigSchema
>;
export const McpConfigDefinitionSchema = z.object({
mcpServers: z.record(McpServerConfigSchema).optional(),
requiredMcpServers: z.record(RequiredMcpServerConfigSchema).optional(),
});
export type McpConfigDefinition = z.infer<typeof McpConfigDefinitionSchema>;
@@ -377,6 +411,7 @@ export const AdminControlsSettingsSchema = z.object({
.object({
mcpEnabled: z.boolean().optional(),
mcpConfig: McpConfigDefinitionSchema.optional(),
requiredMcpConfig: z.record(RequiredMcpServerConfigSchema).optional(),
})
.optional(),
cliFeatureSetting: CliFeatureSettingSchema.optional(),
+29
View File
@@ -3104,6 +3104,35 @@ describe('Config JIT Initialization', () => {
expect(config.getUserMemory()).toBe('Initial Memory');
});
describe('isMemoryManagerEnabled', () => {
it('should default to false', () => {
const params: ConfigParameters = {
sessionId: 'test-session',
targetDir: '/tmp/test',
debugMode: false,
model: 'test-model',
cwd: '/tmp/test',
};
config = new Config(params);
expect(config.isMemoryManagerEnabled()).toBe(false);
});
it('should return true when experimentalMemoryManager is true', () => {
const params: ConfigParameters = {
sessionId: 'test-session',
targetDir: '/tmp/test',
debugMode: false,
model: 'test-model',
cwd: '/tmp/test',
experimentalMemoryManager: true,
};
config = new Config(params);
expect(config.isMemoryManagerEnabled()).toBe(true);
});
});
describe('reloadSkills', () => {
it('should refresh disabledSkills and re-register ActivateSkillTool when skills exist', async () => {
const mockOnReload = vi.fn().mockResolvedValue({
+52 -13
View File
@@ -42,9 +42,11 @@ import type { HookDefinition, HookEventName } from '../hooks/types.js';
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { GitService } from '../services/gitService.js';
import {
createSandboxManager,
type SandboxManager,
NoopSandboxManager,
} from '../services/sandboxManager.js';
import { createSandboxManager } from '../services/sandboxManagerFactory.js';
import { SandboxedFileSystemService } from '../services/sandboxedFileSystemService.js';
import {
initializeTelemetry,
DEFAULT_TELEMETRY_TARGET,
@@ -467,7 +469,13 @@ export interface SandboxConfig {
enabled: boolean;
allowedPaths?: string[];
networkAccess?: boolean;
command?: 'docker' | 'podman' | 'sandbox-exec' | 'runsc' | 'lxc';
command?:
| 'docker'
| 'podman'
| 'sandbox-exec'
| 'runsc'
| 'lxc'
| 'windows-native';
image?: string;
}
@@ -478,7 +486,14 @@ export const ConfigSchema = z.object({
allowedPaths: z.array(z.string()).default([]),
networkAccess: z.boolean().default(false),
command: z
.enum(['docker', 'podman', 'sandbox-exec', 'runsc', 'lxc'])
.enum([
'docker',
'podman',
'sandbox-exec',
'runsc',
'lxc',
'windows-native',
])
.optional(),
image: z.string().optional(),
})
@@ -629,6 +644,7 @@ export interface ConfigParameters {
disabledSkills?: string[];
adminSkillsEnabled?: boolean;
experimentalJitContext?: boolean;
experimentalMemoryManager?: boolean;
topicUpdateNarration?: boolean;
toolOutputMasking?: Partial<ToolOutputMaskingConfig>;
disableLLMCorrection?: boolean;
@@ -853,6 +869,7 @@ export class Config implements McpContext, AgentLoopContext {
private readonly adminSkillsEnabled: boolean;
private readonly experimentalJitContext: boolean;
private readonly experimentalMemoryManager: boolean;
private readonly topicUpdateNarration: boolean;
private readonly disableLLMCorrection: boolean;
private readonly planEnabled: boolean;
@@ -874,7 +891,6 @@ export class Config implements McpContext, AgentLoopContext {
this.approvedPlanPath = undefined;
this.embeddingModel =
params.embeddingModel ?? DEFAULT_GEMINI_EMBEDDING_MODEL;
this.fileSystemService = new StandardFileSystemService();
this.sandbox = params.sandbox
? {
enabled: params.sandbox.enabled ?? false,
@@ -888,6 +904,21 @@ export class Config implements McpContext, AgentLoopContext {
allowedPaths: [],
networkAccess: false,
};
this._sandboxManager = createSandboxManager(this.sandbox, params.targetDir);
if (
!(this._sandboxManager instanceof NoopSandboxManager) &&
this.sandbox.enabled
) {
this.fileSystemService = new SandboxedFileSystemService(
this._sandboxManager,
params.targetDir,
);
} else {
this.fileSystemService = new StandardFileSystemService();
}
this.targetDir = path.resolve(params.targetDir);
this.folderTrust = params.folderTrust ?? false;
this.workspaceContext = new WorkspaceContext(this.targetDir, []);
@@ -992,6 +1023,10 @@ export class Config implements McpContext, AgentLoopContext {
...DEFAULT_MODEL_CONFIGS.classifierIdResolutions,
...modelConfigServiceConfig.classifierIdResolutions,
};
const mergedModelChains = {
...DEFAULT_MODEL_CONFIGS.modelChains,
...modelConfigServiceConfig.modelChains,
};
modelConfigServiceConfig = {
// Preserve other user settings like customAliases
@@ -1005,6 +1040,7 @@ export class Config implements McpContext, AgentLoopContext {
modelDefinitions: mergedModelDefinitions,
modelIdResolutions: mergedModelIdResolutions,
classifierIdResolutions: mergedClassifierIdResolutions,
modelChains: mergedModelChains,
};
}
@@ -1013,6 +1049,7 @@ export class Config implements McpContext, AgentLoopContext {
);
this.experimentalJitContext = params.experimentalJitContext ?? true;
this.experimentalMemoryManager = params.experimentalMemoryManager ?? false;
this.topicUpdateNarration = params.topicUpdateNarration ?? false;
this.modelSteering = params.modelSteering ?? false;
this.injectionService = new InjectionService(() =>
@@ -1064,7 +1101,8 @@ export class Config implements McpContext, AgentLoopContext {
showColor: params.shellExecutionConfig?.showColor ?? false,
pager: params.shellExecutionConfig?.pager ?? 'cat',
sanitizationConfig: this.sanitizationConfig,
sandboxManager: this.sandboxManager,
sandboxManager: this._sandboxManager,
sandboxConfig: this.sandbox,
};
this.truncateToolOutputThreshold =
params.truncateToolOutputThreshold ??
@@ -1186,12 +1224,7 @@ export class Config implements McpContext, AgentLoopContext {
}
}
this._geminiClient = new GeminiClient(this);
this._sandboxManager = createSandboxManager(
params.toolSandboxing ?? false,
this.targetDir,
);
this.a2aClientManager = new A2AClientManager(this);
this.shellExecutionConfig.sandboxManager = this._sandboxManager;
this.modelRouterService = new ModelRouterService(this);
}
@@ -2157,6 +2190,10 @@ export class Config implements McpContext, AgentLoopContext {
return this.experimentalJitContext;
}
isMemoryManagerEnabled(): boolean {
return this.experimentalMemoryManager;
}
isTopicUpdateNarrationEnabled(): boolean {
return this.topicUpdateNarration;
}
@@ -3184,9 +3221,11 @@ export class Config implements McpContext, AgentLoopContext {
maybeRegister(ShellTool, () =>
registry.registerTool(new ShellTool(this, this.messageBus)),
);
maybeRegister(MemoryTool, () =>
registry.registerTool(new MemoryTool(this.messageBus)),
);
if (!this.isMemoryManagerEnabled()) {
maybeRegister(MemoryTool, () =>
registry.registerTool(new MemoryTool(this.messageBus)),
);
}
maybeRegister(WebSearchTool, () =>
registry.registerTool(new WebSearchTool(this, this.messageBus)),
);
+145 -1
View File
@@ -251,6 +251,13 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
],
modelDefinitions: {
// Concrete Models
'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',
@@ -331,7 +338,7 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
isPreview: true,
isVisible: true,
dialogDescription:
'Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash',
'Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash',
features: { thinking: true, multimodalToolUse: false },
},
'auto-gemini-2.5': {
@@ -345,6 +352,27 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
},
},
modelIdResolutions: {
'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: [
@@ -451,4 +479,120 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
],
},
},
modelChains: {
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',
},
},
],
},
};
-8
View File
@@ -190,14 +190,6 @@ describe('Dynamic Configuration Parity', () => {
}
});
it('supportsModernFeatures should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = supportsModernFeatures(model);
const dynamic = supportsModernFeatures(model);
expect(dynamic).toBe(legacy);
}
});
it('supportsMultimodalFunctionResponse should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = supportsMultimodalFunctionResponse(model, legacyConfig);
+14 -1
View File
@@ -102,11 +102,24 @@ export function resolveModel(
config?: ModelCapabilityContext,
): string {
if (config?.getExperimentalDynamicModelConfiguration?.() === true) {
return config.modelConfigService.resolveModelId(requestedModel, {
const resolved = config.modelConfigService.resolveModelId(requestedModel, {
useGemini3_1,
useCustomTools: useCustomToolModel,
hasAccessToPreview,
});
if (!hasAccessToPreview && isPreviewModel(resolved, config)) {
// Fallback for unknown preview models.
if (resolved.includes('flash-lite')) {
return DEFAULT_GEMINI_FLASH_LITE_MODEL;
}
if (resolved.includes('flash')) {
return DEFAULT_GEMINI_FLASH_MODEL;
}
return DEFAULT_GEMINI_MODEL;
}
return resolved;
}
let resolved: string;
@@ -0,0 +1,68 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Config } from './config.js';
import * as path from 'node:path';
import * as os from 'node:os';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return {
...actual,
existsSync: vi.fn().mockReturnValue(true),
statSync: vi.fn().mockReturnValue({
isDirectory: vi.fn().mockReturnValue(true),
}),
realpathSync: vi.fn((p) => p),
};
});
vi.mock('../utils/paths.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../utils/paths.js')>();
return {
...actual,
resolveToRealPath: vi.fn((p) => p),
isSubpath: (parent: string, child: string) => child.startsWith(parent),
};
});
describe('Config Path Validation', () => {
let config: Config;
const targetDir = '/mock/workspace';
const globalGeminiDir = path.join(os.homedir(), '.gemini');
beforeEach(() => {
config = new Config({
targetDir,
sessionId: 'test-session',
debugMode: false,
cwd: targetDir,
model: 'test-model',
});
});
it('should allow access to ~/.gemini if it is added to the workspace', () => {
const geminiMdPath = path.join(globalGeminiDir, 'GEMINI.md');
// Before adding, it should be denied
expect(config.isPathAllowed(geminiMdPath)).toBe(false);
// Add to workspace
config.getWorkspaceContext().addDirectory(globalGeminiDir);
// Now it should be allowed
expect(config.isPathAllowed(geminiMdPath)).toBe(true);
expect(config.validatePathAccess(geminiMdPath, 'read')).toBeNull();
expect(config.validatePathAccess(geminiMdPath, 'write')).toBeNull();
});
it('should still allow project workspace paths', () => {
const workspacePath = path.join(targetDir, 'src/index.ts');
expect(config.isPathAllowed(workspacePath)).toBe(true);
expect(config.validatePathAccess(workspacePath, 'read')).toBeNull();
});
});
@@ -447,7 +447,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -1148,7 +1148,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -1261,7 +1261,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -1382,7 +1382,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -1508,7 +1508,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -2876,7 +2876,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -3154,7 +3154,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -3268,7 +3268,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -3702,7 +3702,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim).
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information.
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
@@ -4123,7 +4123,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
## Interaction Details
+18 -1
View File
@@ -51,7 +51,7 @@ import { ClearcutLogger } from '../telemetry/clearcut-logger/clearcut-logger.js'
import * as policyCatalog from '../availability/policyCatalog.js';
import { LlmRole, LoopType } from '../telemetry/types.js';
import { partToString } from '../utils/partUtils.js';
import { coreEvents } from '../utils/events.js';
import { coreEvents, CoreEvent } from '../utils/events.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
// Mock fs module to prevent actual file system operations during tests
@@ -1997,6 +1997,23 @@ ${JSON.stringify(
);
});
it('should update system instruction when MemoryChanged event is emitted', async () => {
vi.mocked(mockConfig.getSystemInstructionMemory).mockReturnValue(
'Updated Memory',
);
const { getCoreSystemPrompt } = await import('./prompts.js');
const mockGetCoreSystemPrompt = vi.mocked(getCoreSystemPrompt);
mockGetCoreSystemPrompt.mockClear();
coreEvents.emit(CoreEvent.MemoryChanged, { fileCount: 2 });
expect(mockGetCoreSystemPrompt).toHaveBeenCalledWith(
mockConfig,
'Updated Memory',
);
});
it('should recursively call sendMessageStream with "Please continue." when InvalidStream event is received for Gemini 2 models', async () => {
vi.spyOn(client['config'], 'getContinueOnFailedApiCall').mockReturnValue(
true,
+6
View File
@@ -117,6 +117,7 @@ export class GeminiClient {
this.lastPromptId = this.config.getSessionId();
coreEvents.on(CoreEvent.ModelChanged, this.handleModelChanged);
coreEvents.on(CoreEvent.MemoryChanged, this.handleMemoryChanged);
}
private get config(): Config {
@@ -127,6 +128,10 @@ export class GeminiClient {
this.currentSequenceModel = null;
};
private handleMemoryChanged = () => {
this.updateSystemInstruction();
};
// Hook state to deduplicate BeforeAgent calls and track response for
// AfterAgent
private hookStateMap = new Map<
@@ -306,6 +311,7 @@ export class GeminiClient {
dispose() {
coreEvents.off(CoreEvent.ModelChanged, this.handleModelChanged);
coreEvents.off(CoreEvent.MemoryChanged, this.handleMemoryChanged);
}
async resumeChat(
+2
View File
@@ -96,6 +96,7 @@ describe('Core System Prompt (prompts.ts)', () => {
isInteractive: vi.fn().mockReturnValue(true),
isInteractiveShellEnabled: vi.fn().mockReturnValue(true),
isTopicUpdateNarrationEnabled: vi.fn().mockReturnValue(false),
isMemoryManagerEnabled: vi.fn().mockReturnValue(false),
isAgentsEnabled: vi.fn().mockReturnValue(false),
getPreviewFeatures: vi.fn().mockReturnValue(true),
getModel: vi.fn().mockReturnValue(DEFAULT_GEMINI_MODEL_AUTO),
@@ -423,6 +424,7 @@ describe('Core System Prompt (prompts.ts)', () => {
isInteractive: vi.fn().mockReturnValue(false),
isInteractiveShellEnabled: vi.fn().mockReturnValue(false),
isTopicUpdateNarrationEnabled: vi.fn().mockReturnValue(false),
isMemoryManagerEnabled: vi.fn().mockReturnValue(false),
isAgentsEnabled: vi.fn().mockReturnValue(false),
getModel: vi.fn().mockReturnValue('auto'),
getActiveModel: vi.fn().mockReturnValue(PREVIEW_GEMINI_MODEL),

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