Compare commits

..

3 Commits

Author SHA1 Message Date
Jack Wotherspoon 98682fc70c chore: merge main 2026-03-12 10:50:06 +01:00
Jack Wotherspoon b15b720c4e docs: regenerate settings documentation and schema for image generation 2026-03-02 10:03:19 -05:00
Jack Wotherspoon 989c7a9e60 feat: GenerateImage tool for built-in image generation 2026-03-02 09:54:31 -05:00
199 changed files with 3771 additions and 6754 deletions
+3 -6
View File
@@ -1,6 +1,6 @@
# Latest stable release: v0.33.1
# Latest stable release: v0.33.0
Released: March 12, 2026
Released: March 11, 2026
For most users, our latest stable release is the recommended release. Install
the latest stable version with:
@@ -29,9 +29,6 @@ npm install -g @google/gemini-cli
## What's Changed
- fix(patch): cherry-pick 8432bce to release/v0.33.0-pr-22069 to patch version
v0.33.0 and create version 0.33.1 by @gemini-cli-robot in
[#22206](https://github.com/google-gemini/gemini-cli/pull/22206)
- Docs: Update model docs to remove Preview Features. by @jkcinouye in
[#20084](https://github.com/google-gemini/gemini-cli/pull/20084)
- docs: fix typo in installation documentation by @AdityaSharma-Git3207 in
@@ -231,4 +228,4 @@ npm install -g @google/gemini-cli
[#21952](https://github.com/google-gemini/gemini-cli/pull/21952)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.32.1...v0.33.1
https://github.com/google-gemini/gemini-cli/compare/v0.32.1...v0.33.0
+3 -6
View File
@@ -1,6 +1,6 @@
# Preview release: v0.34.0-preview.1
# Preview release: v0.34.0-preview.0
Released: March 12, 2026
Released: March 11, 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).
@@ -28,9 +28,6 @@ npm install -g @google/gemini-cli@preview
## What's Changed
- fix(patch): cherry-pick 45faf4d to release/v0.34.0-preview.0-pr-22148
[CONFLICTS] by @gemini-cli-robot in
[#22174](https://github.com/google-gemini/gemini-cli/pull/22174)
- feat(cli): add chat resume footer on session quit by @lordshashank in
[#20667](https://github.com/google-gemini/gemini-cli/pull/20667)
- Support bold and other styles in svg snapshots by @jacob314 in
@@ -468,4 +465,4 @@ npm install -g @google/gemini-cli@preview
[#21938](https://github.com/google-gemini/gemini-cli/pull/21938)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.33.0-preview.15...v0.34.0-preview.1
https://github.com/google-gemini/gemini-cli/compare/v0.33.0-preview.15...v0.34.0-preview.0
+1 -18
View File
@@ -26,20 +26,6 @@ policies.
the CLI will use an available fallback model for the current turn or the
remainder of the session.
### Local Model Routing (Experimental)
Gemini CLI supports using a local model for routing decisions. When configured,
Gemini CLI will use a locally-running **Gemma** model to make routing decisions
(instead of sending routing decisions to a hosted model). This feature can help
reduce costs associated with hosted model usage while offering similar routing
decision latency and quality.
In order to use this feature, the local Gemma model **must** be served behind a
Gemini API and accessible via HTTP at an endpoint configured in `settings.json`.
For more details on how to configure local model routing, see
[Local Model Routing](../core/local-model-routing.md).
### Model selection precedence
The model used by Gemini CLI is determined by the following order of precedence:
@@ -52,8 +38,5 @@ The model used by Gemini CLI is determined by the following order of precedence:
3. **`model.name` in `settings.json`:** If neither of the above are set, the
model specified in the `model.name` property of your `settings.json` file
will be used.
4. **Local model (experimental):** If the Gemma local model router is enabled
in your `settings.json` file, the CLI will use the local Gemma model
(instead of Gemini models) to route the request to an appropriate model.
5. **Default model:** If none of the above are set, the default model will be
4. **Default model:** If none of the above are set, the default model will be
used. The default model is `auto`
+10 -71
View File
@@ -109,6 +109,16 @@ switch back to another mode.
- **Keyboard shortcut:** Press `Shift+Tab` to cycle to the desired mode.
- **Natural language:** Ask Gemini CLI to "exit plan mode" or "stop planning."
## Customization and best practices
Plan Mode is secure by default, but you can adapt it to fit your specific
workflows. You can customize how Gemini CLI plans by using skills, adjusting
safety policies, or changing where plans are stored.
## Commands
- **`/plan copy`**: Copy the currently approved plan to your clipboard.
## Tool Restrictions
Plan Mode enforces strict safety policies to prevent accidental changes.
@@ -136,12 +146,6 @@ These are the only allowed tools:
- **Skills:** [`activate_skill`](../cli/skills.md) (allows loading specialized
instructions and resources in a read-only manner)
## Customization and best practices
Plan Mode is secure by default, but you can adapt it to fit your specific
workflows. You can customize how Gemini CLI plans by using skills, adjusting
safety policies, changing where plans are stored, or adding hooks.
### Custom planning with skills
You can use [Agent Skills](../cli/skills.md) to customize how Gemini CLI
@@ -290,71 +294,6 @@ modes = ["plan"]
argsPattern = "\"file_path\":\"[^\"]+[\\\\/]+\\.gemini[\\\\/]+plans[\\\\/]+[\\w-]+\\.md\""
```
### Using hooks with Plan Mode
You can use the [hook system](../hooks/writing-hooks.md) to automate parts of
the planning workflow or enforce additional checks when Gemini CLI transitions
into or out of Plan Mode.
Hooks such as `BeforeTool` or `AfterTool` can be configured to intercept the
`enter_plan_mode` and `exit_plan_mode` tool calls.
> [!WARNING] When hooks are triggered by **tool executions**, they do **not**
> run when you manually toggle Plan Mode using the `/plan` command or the
> `Shift+Tab` keyboard shortcut. If you need hooks to execute on mode changes,
> ensure the transition is initiated by the agent (e.g., by asking "start a plan
> for...").
#### Example: Archive approved plans to GCS (`AfterTool`)
If your organizational policy requires a record of all execution plans, you can
use an `AfterTool` hook to securely copy the plan artifact to Google Cloud
Storage whenever Gemini CLI exits Plan Mode to start the implementation.
**`.gemini/hooks/archive-plan.sh`:**
```bash
#!/usr/bin/env bash
# Extract the plan path from the tool input JSON
plan_path=$(jq -r '.tool_input.plan_path // empty')
if [ -f "$plan_path" ]; then
# Generate a unique filename using a timestamp
filename="$(date +%s)_$(basename "$plan_path")"
# Upload the plan to GCS in the background so it doesn't block the CLI
gsutil cp "$plan_path" "gs://my-audit-bucket/gemini-plans/$filename" > /dev/null 2>&1 &
fi
# AfterTool hooks should generally allow the flow to continue
echo '{"decision": "allow"}'
```
To register this `AfterTool` hook, add it to your `settings.json`:
```json
{
"hooks": {
"AfterTool": [
{
"matcher": "exit_plan_mode",
"hooks": [
{
"name": "archive-plan",
"type": "command",
"command": "./.gemini/hooks/archive-plan.sh"
}
]
}
]
}
}
```
## Commands
- **`/plan copy`**: Copy the currently approved plan to your clipboard.
## Planning workflows
Plan Mode provides building blocks for structured research and design. These are
+1 -1
View File
@@ -55,7 +55,6 @@ they appear in the UI.
| Show Home Directory Warning | `ui.showHomeDirectoryWarning` | Show a warning when running Gemini CLI in the home directory. | `true` |
| Show Compatibility Warnings | `ui.showCompatibilityWarnings` | Show warnings about terminal or OS compatibility issues. | `true` |
| Hide Tips | `ui.hideTips` | Hide helpful tips in the UI | `false` |
| Escape Pasted @ Symbols | `ui.escapePastedAtSymbols` | When enabled, @ symbols in pasted text are escaped to prevent unintended @path expansion. | `false` |
| Show Shortcuts Hint | `ui.showShortcutsHint` | Show the "? for shortcuts" hint above the input. | `true` |
| Hide Banner | `ui.hideBanner` | Hide the application banner | `false` |
| Hide Context Summary | `ui.hideContextSummary` | Hide the context summary (GEMINI.md, MCP servers) above the input. | `false` |
@@ -148,6 +147,7 @@ they appear in the UI.
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 for pasting. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
| Use OSC 52 Copy | `experimental.useOSC52Copy` | Use OSC 52 for copying. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
| Plan | `experimental.plan` | Enable Plan Mode. | `true` |
| Image Generation | `experimental.imageGeneration` | Enable generating images with Nano Banana (experimental). | `false` |
| 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` |
-2
View File
@@ -15,8 +15,6 @@ requests sent from `packages/cli`. For a general overview of Gemini CLI, see the
modular GEMINI.md import feature using @file.md syntax.
- **[Policy Engine](../reference/policy-engine.md):** Use the Policy Engine for
fine-grained control over tool execution.
- **[Local Model Routing (experimental)](./local-model-routing.md):** Learn how
to enable use of a local Gemma model for model routing decisions.
## Role of the core
-193
View File
@@ -1,193 +0,0 @@
# Local Model Routing (experimental)
Gemini CLI supports using a local model for
[routing decisions](../cli/model-routing.md). When configured, Gemini CLI will
use a locally-running **Gemma** model to make routing decisions (instead of
sending routing decisions to a hosted model).
This feature can help reduce costs associated with hosted model usage while
offering similar routing decision latency and quality.
> **Note: Local model routing is currently an experimental feature.**
## Setup
Using a Gemma model for routing decisions requires that an implementation of a
Gemma model be running locally on your machine, served behind an HTTP endpoint
and accessed via the Gemini API.
To serve the Gemma model, follow these steps:
### Download the LiteRT-LM runtime
The [LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM) runtime offers
pre-built binaries for locally-serving models. Download the binary appropriate
for your system.
#### Windows
1. Download
[lit.windows_x86_64.exe](https://github.com/google-ai-edge/LiteRT-LM/releases/download/v0.9.0-alpha03/lit.windows_x86_64.exe).
2. Using GPU on Windows requires the DirectXShaderCompiler. Download the
[dxc zip from the latest release](https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.8.2505.1/dxc_2025_07_14.zip).
Unzip the archive and from the architecture-appropriate `bin\` directory, and
copy the `dxil.dll` and `dxcompiler.dll` into the same location as you saved
`lit.windows_x86_64.exe`.
3. (Optional) Test starting the runtime:
`.\lit.windows_x86_64.exe serve --verbose`
#### Linux
1. Download
[lit.linux_x86_64](https://github.com/google-ai-edge/LiteRT-LM/releases/download/v0.9.0-alpha03/lit.linux_x86_64).
2. Ensure the binary is executable: `chmod a+x lit.linux_x86_64`
3. (Optional) Test starting the runtime: `./lit.linux_x86_64 serve --verbose`
#### MacOS
1. Download
[lit-macos-arm64](https://github.com/google-ai-edge/LiteRT-LM/releases/download/v0.9.0-alpha03/lit.macos_arm64).
2. Ensure the binary is executable: `chmod a+x lit.macos_arm64`
3. (Optional) Test starting the runtime: `./lit.macos_arm64 serve --verbose`
> **Note**: MacOS can be configured to only allows binaries from "App Store &
> Known Developers". If you encounter an error message when attempting to run
> the binary, you will need to allow the application. One option is to visit
> `System Settings -> Privacy & Security`, scroll to `Security`, and click
> `"Allow Anyway"` for `"lit.macos_arm64"`. Another option is to run
> `xattr -d com.apple.quarantine lit.macos_arm64` from the commandline.
### Download the Gemma Model
Before using Gemma, you will need to download the model (and agree to the Terms
of Service).
This can be done via the LiteRT-LM runtime.
#### Windows
```bash
$ .\lit.windows_x86_64.exe pull gemma3-1b-gpu-custom
[Legal] The model you are about to download is governed by
the Gemma Terms of Use and Prohibited Use Policy. Please review these terms and ensure you agree before continuing.
Full Terms: https://ai.google.dev/gemma/terms
Prohibited Use Policy: https://ai.google.dev/gemma/prohibited_use_policy
Do you accept these terms? (Y/N): Y
Terms accepted.
Downloading model 'gemma3-1b-gpu-custom' ...
Downloading... 968.6 MB
Download complete.
```
#### Linux
```bash
$ ./lit.linux_x86_64 pull gemma3-1b-gpu-custom
[Legal] The model you are about to download is governed by
the Gemma Terms of Use and Prohibited Use Policy. Please review these terms and ensure you agree before continuing.
Full Terms: https://ai.google.dev/gemma/terms
Prohibited Use Policy: https://ai.google.dev/gemma/prohibited_use_policy
Do you accept these terms? (Y/N): Y
Terms accepted.
Downloading model 'gemma3-1b-gpu-custom' ...
Downloading... 968.6 MB
Download complete.
```
#### MacOS
```bash
$ ./lit.lit.macos_arm64 pull gemma3-1b-gpu-custom
[Legal] The model you are about to download is governed by
the Gemma Terms of Use and Prohibited Use Policy. Please review these terms and ensure you agree before continuing.
Full Terms: https://ai.google.dev/gemma/terms
Prohibited Use Policy: https://ai.google.dev/gemma/prohibited_use_policy
Do you accept these terms? (Y/N): Y
Terms accepted.
Downloading model 'gemma3-1b-gpu-custom' ...
Downloading... 968.6 MB
Download complete.
```
### Start LiteRT-LM Runtime
Using the command appropriate to your system, start the LiteRT-LM runtime.
Configure the port that you want to use for your Gemma model. For the purposes
of this document, we will use port `9379`.
Example command for MacOS: `./lit.macos_arm64 serve --port=9379 --verbose`
### (Optional) Verify Model Serving
Send a quick prompt to the model via HTTP to validate successful model serving.
This will cause the runtime to download the model and run it once.
You should see a short joke in the server output as an indicator of success.
#### Windows
```
# Run this in PowerShell to send a request to the server
$uri = "http://localhost:9379/v1beta/models/gemma3-1b-gpu-custom:generateContent"
$body = @{contents = @( @{
role = "user"
parts = @( @{ text = "Tell me a joke." } )
})} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri $uri -Method Post -Body $body -ContentType "application/json"
```
#### Linux/MacOS
```bash
$ curl "http://localhost:9379/v1beta/models/gemma3-1b-gpu-custom:generateContent" \
-H 'Content-Type: application/json' \
-X POST \
-d '{"contents":[{"role":"user","parts":[{"text":"Tell me a joke."}]}]}'
```
## Configuration
To use a local Gemma model for routing, you must explicitly enable it in your
`settings.json`:
```json
{
"experimental": {
"gemmaModelRouter": {
"enabled": true,
"classifier": {
"host": "http://localhost:9379",
"model": "gemma3-1b-gpu-custom"
}
}
}
}
```
> Use the port you started your LiteRT-LM runtime on in the setup steps.
### Configuration schema
| Field | Type | Required | Description |
| :----------------- | :------ | :------- | :----------------------------------------------------------------------------------------- |
| `enabled` | boolean | Yes | Must be `true` to enable the feature. |
| `classifier` | object | Yes | The configuration for the local model endpoint. It includes the host and model specifiers. |
| `classifier.host` | string | Yes | The URL to the local model server. Should be `http://localhost:<port>`. |
| `classifier.model` | string | Yes | The model name to use for decisions. Must be `"gemma3-1b-gpu-custom"`. |
> **Note: You will need to restart after configuration changes for local model
> routing to take effect.**
+5 -150
View File
@@ -245,11 +245,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Description:** Hide helpful tips in the UI
- **Default:** `false`
- **`ui.escapePastedAtSymbols`** (boolean):
- **Description:** When enabled, @ symbols in pasted text are escaped to
prevent unintended @path expansion.
- **Default:** `false`
- **`ui.showShortcutsHint`** (boolean):
- **Description:** Show the "? for shortcuts" hint above the input.
- **Default:** `true`
@@ -677,141 +672,6 @@ their corresponding top-level category object in your `settings.json` file.
used.
- **Default:** `[]`
- **`modelConfigs.modelDefinitions`** (object):
- **Description:** Registry of model metadata, including tier, family, and
features.
- **Default:**
```json
{
"gemini-3.1-pro-preview": {
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"dialogLocation": "manual",
"features": {
"thinking": true,
"multimodalToolUse": true
}
},
"gemini-3.1-pro-preview-customtools": {
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"features": {
"thinking": true,
"multimodalToolUse": true
}
},
"gemini-3-pro-preview": {
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"dialogLocation": "manual",
"features": {
"thinking": true,
"multimodalToolUse": true
}
},
"gemini-3-flash-preview": {
"tier": "flash",
"family": "gemini-3",
"isPreview": true,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": true
}
},
"gemini-2.5-pro": {
"tier": "pro",
"family": "gemini-2.5",
"isPreview": false,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
}
},
"gemini-2.5-flash": {
"tier": "flash",
"family": "gemini-2.5",
"isPreview": false,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
}
},
"gemini-2.5-flash-lite": {
"tier": "flash-lite",
"family": "gemini-2.5",
"isPreview": false,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
}
},
"auto": {
"tier": "auto",
"isPreview": true,
"features": {
"thinking": true,
"multimodalToolUse": false
}
},
"pro": {
"tier": "pro",
"isPreview": false,
"features": {
"thinking": true,
"multimodalToolUse": false
}
},
"flash": {
"tier": "flash",
"isPreview": false,
"features": {
"thinking": false,
"multimodalToolUse": false
}
},
"flash-lite": {
"tier": "flash-lite",
"isPreview": false,
"features": {
"thinking": false,
"multimodalToolUse": false
}
},
"auto-gemini-3": {
"displayName": "Auto (Gemini 3)",
"tier": "auto",
"isPreview": true,
"dialogLocation": "main",
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash",
"features": {
"thinking": true,
"multimodalToolUse": false
}
},
"auto-gemini-2.5": {
"displayName": "Auto (Gemini 2.5)",
"tier": "auto",
"isPreview": false,
"dialogLocation": "main",
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash",
"features": {
"thinking": false,
"multimodalToolUse": false
}
}
}
```
- **Requires restart:** Yes
#### `agents`
- **`agents.overrides`** (object):
@@ -841,10 +701,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `undefined`
- **Requires restart:** Yes
- **`agents.browser.disableUserInput`** (boolean):
- **Description:** Disable user input on browser window during automation.
- **Default:** `true`
#### `context`
- **`context.fileName`** (string | string[]):
@@ -1193,6 +1049,11 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.imageGeneration`** (boolean):
- **Description:** Enable generating images with Nano Banana (experimental).
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.modelSteering`** (boolean):
- **Description:** Enable model steering (user hints) to guide the model
during tool execution.
@@ -1203,12 +1064,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.dynamicModelConfiguration`** (boolean):
- **Description:** Enable dynamic model configuration (definitions,
resolutions, and chains) via settings.
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.gemmaModelRouter.enabled`** (boolean):
- **Description:** Enable the Gemma Model Router (experimental). Requires a
local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.
+1 -3
View File
@@ -342,9 +342,7 @@ policies, as it is much more robust than manually writing Fully Qualified Names
**1. Targeting a specific tool on a server**
Combine `mcpName` and `toolName` to target a single operation. When using
`mcpName`, the `toolName` field should strictly be the simple name of the tool
(e.g., `search`), **not** the Fully Qualified Name (e.g., `mcp_server_search`).
Combine `mcpName` and `toolName` to target a single operation.
```toml
# Allows the `search` tool on the `my-jira-server` MCP
-8
View File
@@ -120,14 +120,6 @@ tools to detect if they are being run from within the Gemini CLI.
## Command restrictions
<!-- prettier-ignore -->
> [!WARNING]
> The `tools.core` setting is an **allowlist for _all_ built-in
> tools**, not just shell commands. When you set `tools.core` to any value,
> _only_ the tools explicitly listed will be enabled. This includes all built-in
> tools like `read_file`, `write_file`, `glob`, `grep_search`, `list_directory`,
> `replace`, etc.
You can restrict the commands that can be executed by the `run_shell_command`
tool by using the `tools.core` and `tools.exclude` settings in your
configuration file.
+4 -9
View File
@@ -82,14 +82,11 @@ const commonAliases = {
const cliConfig = {
...baseConfig,
banner: {
js: `const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);`,
js: `const require = (await import('node:module')).createRequire(import.meta.url); globalThis.__filename = (await import('node:url')).fileURLToPath(import.meta.url); globalThis.__dirname = (await import('node:path')).dirname(globalThis.__filename);`,
},
entryPoints: { gemini: 'packages/cli/index.ts' },
outdir: 'bundle',
splitting: true,
entryPoints: ['packages/cli/index.ts'],
outfile: 'bundle/gemini.js',
define: {
__filename: '__chunk_filename',
__dirname: '__chunk_dirname',
'process.env.CLI_VERSION': JSON.stringify(pkg.version),
'process.env.GEMINI_SANDBOX_IMAGE_DEFAULT': JSON.stringify(
pkg.config?.sandboxImageUri,
@@ -106,13 +103,11 @@ const cliConfig = {
const a2aServerConfig = {
...baseConfig,
banner: {
js: `const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);`,
js: `const require = (await import('node:module')).createRequire(import.meta.url); globalThis.__filename = (await import('node:url')).fileURLToPath(import.meta.url); globalThis.__dirname = (await import('node:path')).dirname(globalThis.__filename);`,
},
entryPoints: ['packages/a2a-server/src/http/server.ts'],
outfile: 'packages/a2a-server/dist/a2a-server.mjs',
define: {
__filename: '__chunk_filename',
__dirname: '__chunk_dirname',
'process.env.CLI_VERSION': JSON.stringify(pkg.version),
},
plugins: createWasmPlugins(),
+5
View File
@@ -35,6 +35,11 @@ const commonRestrictedSyntaxRules = [
message:
'Do not throw string literals or non-Error objects. Throw new Error("...") instead.',
},
{
selector: 'CallExpression[callee.name="fetch"]',
message:
'Use safeFetch() from "@/utils/fetch" instead of the global fetch() to ensure SSRF protection. If you are implementing a custom security layer, use an eslint-disable comment and explain why.',
},
];
export default tseslint.config(
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

@@ -1,64 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, beforeEach, afterEach } from 'vitest';
import { TestRig } from './test-helper.js';
/**
* integration test to ensure no node.js deprecation warnings are emitted.
* must run for all supported node versions as warnings may vary by version.
*/
describe('deprecation-warnings', () => {
let rig: TestRig;
beforeEach(() => {
rig = new TestRig();
});
afterEach(async () => await rig.cleanup());
it.each([
{ command: '--version', description: 'running --version' },
{ command: '--help', description: 'running with --help' },
])(
'should not emit any deprecation warnings when $description',
async ({ command, description }) => {
await rig.setup(
`should not emit any deprecation warnings when ${description}`,
);
const { stderr, exitCode } = await rig.runWithStreams([command]);
// node.js deprecation warnings: (node:12345) [DEP0040] DeprecationWarning: ...
const deprecationWarningPattern = /\[DEP\d+\].*DeprecationWarning/i;
const hasDeprecationWarning = deprecationWarningPattern.test(stderr);
if (hasDeprecationWarning) {
const deprecationMatches = stderr.match(
/\[DEP\d+\].*DeprecationWarning:.*/gi,
);
const warnings = deprecationMatches
? deprecationMatches.map((m) => m.trim()).join('\n')
: 'Unknown deprecation warning format';
throw new Error(
`Deprecation warnings detected in CLI output:\n${warnings}\n\n` +
`Full stderr:\n${stderr}\n\n` +
`This test ensures no deprecated Node.js modules are used. ` +
`Please update dependencies to use non-deprecated alternatives.`,
);
}
// only check exit code if no deprecation warnings found
if (exitCode !== 0) {
throw new Error(
`CLI exited with code ${exitCode} (expected 0). This may indicate a setup issue.\n` +
`Stderr: ${stderr}`,
);
}
},
);
});
+167 -224
View File
@@ -1318,9 +1318,9 @@
}
},
"node_modules/@google-cloud/storage": {
"version": "7.19.0",
"resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.19.0.tgz",
"integrity": "sha512-n2FjE7NAOYyshogdc7KQOl/VZb4sneqPjWouSyia9CMDdMhRX5+RIbqalNmC7LOLzuLAN89VlF2HvG8na9G+zQ==",
"version": "7.17.0",
"resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.17.0.tgz",
"integrity": "sha512-5m9GoZqKh52a1UqkxDBu/+WVFDALNtHg5up5gNmNbXQWBcV813tzJKsyDtKjOPrlR1em1TxtD7NSPCrObH7koQ==",
"license": "Apache-2.0",
"dependencies": {
"@google-cloud/paginator": "^5.0.0",
@@ -1329,7 +1329,7 @@
"abort-controller": "^3.0.0",
"async-retry": "^1.3.3",
"duplexify": "^4.1.3",
"fast-xml-parser": "^5.3.4",
"fast-xml-parser": "^4.4.1",
"gaxios": "^6.0.2",
"google-auth-library": "^9.6.3",
"html-entities": "^2.5.2",
@@ -1516,9 +1516,9 @@
}
},
"node_modules/@hono/node-server": {
"version": "1.19.11",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.11.tgz",
"integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==",
"version": "1.19.9",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz",
"integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==",
"license": "MIT",
"engines": {
"node": ">=18.14.1"
@@ -2089,9 +2089,9 @@
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -2195,6 +2195,7 @@
"integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@octokit/auth-token": "^6.0.0",
"@octokit/graphql": "^9.0.2",
@@ -2375,6 +2376,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -2424,6 +2426,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.5.0.tgz",
"integrity": "sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
},
@@ -2798,6 +2801,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.5.0.tgz",
"integrity": "sha512-F8W52ApePshpoSrfsSk1H2yJn9aKjCrbpQF1M9Qii0GHzbfVeFUB+rc3X4aggyZD8x9Gu3Slua+s6krmq6Dt8g==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/semantic-conventions": "^1.29.0"
@@ -2831,6 +2835,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.5.0.tgz",
"integrity": "sha512-BeJLtU+f5Gf905cJX9vXFQorAr6TAfK3SPvTFqP+scfIpDQEJfRaGJWta7sJgP+m4dNtBf9y3yvBKVAZZtJQVA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0"
@@ -2885,6 +2890,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.5.0.tgz",
"integrity": "sha512-VzRf8LzotASEyNDUxTdaJ9IRJ1/h692WyArDBInf5puLCjxbICD6XkHgpuudis56EndyS7LYFmtTMny6UABNdQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0",
@@ -3039,9 +3045,9 @@
"license": "BSD-3-Clause"
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
"integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.2.tgz",
"integrity": "sha512-yDPzwsgiFO26RJA4nZo8I+xqzh7sJTZIWQOxn+/XOdPE31lAvLIYCKqjV+lNH/vxE2L2iH3plKxDCRK6i+CwhA==",
"cpu": [
"arm"
],
@@ -3052,9 +3058,9 @@
]
},
"node_modules/@rollup/rollup-android-arm64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz",
"integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.2.tgz",
"integrity": "sha512-k8FontTxIE7b0/OGKeSN5B6j25EuppBcWM33Z19JoVT7UTXFSo3D9CdU39wGTeb29NO3XxpMNauh09B+Ibw+9g==",
"cpu": [
"arm64"
],
@@ -3065,9 +3071,9 @@
]
},
"node_modules/@rollup/rollup-darwin-arm64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz",
"integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.2.tgz",
"integrity": "sha512-A6s4gJpomNBtJ2yioj8bflM2oogDwzUiMl2yNJ2v9E7++sHrSrsQ29fOfn5DM/iCzpWcebNYEdXpaK4tr2RhfQ==",
"cpu": [
"arm64"
],
@@ -3078,9 +3084,9 @@
]
},
"node_modules/@rollup/rollup-darwin-x64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz",
"integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.2.tgz",
"integrity": "sha512-e6XqVmXlHrBlG56obu9gDRPW3O3hLxpwHpLsBJvuI8qqnsrtSZ9ERoWUXtPOkY8c78WghyPHZdmPhHLWNdAGEw==",
"cpu": [
"x64"
],
@@ -3091,9 +3097,9 @@
]
},
"node_modules/@rollup/rollup-freebsd-arm64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz",
"integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.2.tgz",
"integrity": "sha512-v0E9lJW8VsrwPux5Qe5CwmH/CF/2mQs6xU1MF3nmUxmZUCHazCjLgYvToOk+YuuUqLQBio1qkkREhxhc656ViA==",
"cpu": [
"arm64"
],
@@ -3104,9 +3110,9 @@
]
},
"node_modules/@rollup/rollup-freebsd-x64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz",
"integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.2.tgz",
"integrity": "sha512-ClAmAPx3ZCHtp6ysl4XEhWU69GUB1D+s7G9YjHGhIGCSrsg00nEGRRZHmINYxkdoJehde8VIsDC5t9C0gb6yqA==",
"cpu": [
"x64"
],
@@ -3117,9 +3123,9 @@
]
},
"node_modules/@rollup/rollup-linux-arm-gnueabihf": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz",
"integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.2.tgz",
"integrity": "sha512-EPlb95nUsz6Dd9Qy13fI5kUPXNSljaG9FiJ4YUGU1O/Q77i5DYFW5KR8g1OzTcdZUqQQ1KdDqsTohdFVwCwjqg==",
"cpu": [
"arm"
],
@@ -3130,9 +3136,9 @@
]
},
"node_modules/@rollup/rollup-linux-arm-musleabihf": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz",
"integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.2.tgz",
"integrity": "sha512-BOmnVW+khAUX+YZvNfa0tGTEMVVEerOxN0pDk2E6N6DsEIa2Ctj48FOMfNDdrwinocKaC7YXUZ1pHlKpnkja/Q==",
"cpu": [
"arm"
],
@@ -3143,9 +3149,9 @@
]
},
"node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz",
"integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.2.tgz",
"integrity": "sha512-Xt2byDZ+6OVNuREgBXr4+CZDJtrVso5woFtpKdGPhpTPHcNG7D8YXeQzpNbFRxzTVqJf7kvPMCub/pcGUWgBjA==",
"cpu": [
"arm64"
],
@@ -3156,9 +3162,9 @@
]
},
"node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz",
"integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.53.2.tgz",
"integrity": "sha512-+LdZSldy/I9N8+klim/Y1HsKbJ3BbInHav5qE9Iy77dtHC/pibw1SR/fXlWyAk0ThnpRKoODwnAuSjqxFRDHUQ==",
"cpu": [
"arm64"
],
@@ -3169,22 +3175,9 @@
]
},
"node_modules/@rollup/rollup-linux-loong64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz",
"integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==",
"cpu": [
"loong64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@rollup/rollup-linux-loong64-musl": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz",
"integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.2.tgz",
"integrity": "sha512-8ms8sjmyc1jWJS6WdNSA23rEfdjWB30LH8Wqj0Cqvv7qSHnvw6kgMMXRdop6hkmGPlyYBdRPkjJnj3KCUHV/uQ==",
"cpu": [
"loong64"
],
@@ -3195,22 +3188,9 @@
]
},
"node_modules/@rollup/rollup-linux-ppc64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz",
"integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@rollup/rollup-linux-ppc64-musl": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz",
"integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.2.tgz",
"integrity": "sha512-3HRQLUQbpBDMmzoxPJYd3W6vrVHOo2cVW8RUo87Xz0JPJcBLBr5kZ1pGcQAhdZgX9VV7NbGNipah1omKKe23/g==",
"cpu": [
"ppc64"
],
@@ -3221,9 +3201,9 @@
]
},
"node_modules/@rollup/rollup-linux-riscv64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz",
"integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.2.tgz",
"integrity": "sha512-fMjKi+ojnmIvhk34gZP94vjogXNNUKMEYs+EDaB/5TG/wUkoeua7p7VCHnE6T2Tx+iaghAqQX8teQzcvrYpaQA==",
"cpu": [
"riscv64"
],
@@ -3234,9 +3214,9 @@
]
},
"node_modules/@rollup/rollup-linux-riscv64-musl": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz",
"integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.2.tgz",
"integrity": "sha512-XuGFGU+VwUUV5kLvoAdi0Wz5Xbh2SrjIxCtZj6Wq8MDp4bflb/+ThZsVxokM7n0pcbkEr2h5/pzqzDYI7cCgLQ==",
"cpu": [
"riscv64"
],
@@ -3247,9 +3227,9 @@
]
},
"node_modules/@rollup/rollup-linux-s390x-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz",
"integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.2.tgz",
"integrity": "sha512-w6yjZF0P+NGzWR3AXWX9zc0DNEGdtvykB03uhonSHMRa+oWA6novflo2WaJr6JZakG2ucsyb+rvhrKac6NIy+w==",
"cpu": [
"s390x"
],
@@ -3260,9 +3240,9 @@
]
},
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz",
"integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.2.tgz",
"integrity": "sha512-yo8d6tdfdeBArzC7T/PnHd7OypfI9cbuZzPnzLJIyKYFhAQ8SvlkKtKBMbXDxe1h03Rcr7u++nFS7tqXz87Gtw==",
"cpu": [
"x64"
],
@@ -3273,9 +3253,9 @@
]
},
"node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz",
"integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.2.tgz",
"integrity": "sha512-ah59c1YkCxKExPP8O9PwOvs+XRLKwh/mV+3YdKqQ5AMQ0r4M4ZDuOrpWkUaqO7fzAHdINzV9tEVu8vNw48z0lA==",
"cpu": [
"x64"
],
@@ -3285,23 +3265,10 @@
"linux"
]
},
"node_modules/@rollup/rollup-openbsd-x64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz",
"integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"openbsd"
]
},
"node_modules/@rollup/rollup-openharmony-arm64": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz",
"integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.2.tgz",
"integrity": "sha512-4VEd19Wmhr+Zy7hbUsFZ6YXEiP48hE//KPLCSVNY5RMGX2/7HZ+QkN55a3atM1C/BZCGIgqN+xrVgtdak2S9+A==",
"cpu": [
"arm64"
],
@@ -3312,9 +3279,9 @@
]
},
"node_modules/@rollup/rollup-win32-arm64-msvc": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz",
"integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.2.tgz",
"integrity": "sha512-IlbHFYc/pQCgew/d5fslcy1KEaYVCJ44G8pajugd8VoOEI8ODhtb/j8XMhLpwHCMB3yk2J07ctup10gpw2nyMA==",
"cpu": [
"arm64"
],
@@ -3325,9 +3292,9 @@
]
},
"node_modules/@rollup/rollup-win32-ia32-msvc": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz",
"integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.2.tgz",
"integrity": "sha512-lNlPEGgdUfSzdCWU176ku/dQRnA7W+Gp8d+cWv73jYrb8uT7HTVVxq62DUYxjbaByuf1Yk0RIIAbDzp+CnOTFg==",
"cpu": [
"ia32"
],
@@ -3338,9 +3305,9 @@
]
},
"node_modules/@rollup/rollup-win32-x64-gnu": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz",
"integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.2.tgz",
"integrity": "sha512-S6YojNVrHybQis2lYov1sd+uj7K0Q05NxHcGktuMMdIQ2VixGwAfbJ23NnlvvVV1bdpR2m5MsNBViHJKcA4ADw==",
"cpu": [
"x64"
],
@@ -3351,9 +3318,9 @@
]
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz",
"integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.2.tgz",
"integrity": "sha512-k+/Rkcyx//P6fetPoLMb8pBeqJBNGx81uuf7iljX9++yNBVRDQgD04L+SVXmXmh5ZP4/WOp4mWF0kmi06PW2tA==",
"cpu": [
"x64"
],
@@ -3408,9 +3375,9 @@
}
},
"node_modules/@secretlint/config-loader/node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4087,6 +4054,7 @@
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -4361,6 +4329,7 @@
"integrity": "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.35.0",
"@typescript-eslint/types": "8.35.0",
@@ -5234,6 +5203,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5270,9 +5240,9 @@
}
},
"node_modules/ajv": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -5304,9 +5274,9 @@
}
},
"node_modules/ajv-formats/node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -7765,6 +7735,7 @@
"integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -8275,6 +8246,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@@ -8314,12 +8286,12 @@
}
},
"node_modules/express-rate-limit": {
"version": "8.3.1",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.1.tgz",
"integrity": "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==",
"version": "8.2.1",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz",
"integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==",
"license": "MIT",
"dependencies": {
"ip-address": "10.1.0"
"ip-address": "10.0.1"
},
"engines": {
"node": ">= 16"
@@ -8461,25 +8433,10 @@
],
"license": "BSD-3-Clause"
},
"node_modules/fast-xml-builder": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.2.tgz",
"integrity": "sha512-NJAmiuVaJEjVa7TjLZKlYd7RqmzOC91EtPFXHvlTcqBVo50Qh7XV5IwvXi1c7NRz2Q/majGX9YLcwJtWgHjtkA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"dependencies": {
"path-expression-matcher": "^1.1.3"
}
},
"node_modules/fast-xml-parser": {
"version": "5.5.3",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.3.tgz",
"integrity": "sha512-Ymnuefk6VzAhT3SxLzVUw+nMio/wB1NGypHkgetwtXcK1JfryaHk4DWQFGVwQ9XgzyS5iRZ7C2ZGI4AMsdMZ6A==",
"version": "4.5.3",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz",
"integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==",
"funding": [
{
"type": "github",
@@ -8488,9 +8445,7 @@
],
"license": "MIT",
"dependencies": {
"fast-xml-builder": "^1.1.2",
"path-expression-matcher": "^1.1.3",
"strnum": "^2.1.2"
"strnum": "^1.1.1"
},
"bin": {
"fxparser": "src/cli/cli.js"
@@ -9555,10 +9510,11 @@
}
},
"node_modules/hono": {
"version": "4.12.7",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.7.tgz",
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
"version": "4.11.9",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.9.tgz",
"integrity": "sha512-Eaw2YTGM6WOxA6CXbckaEvslr2Ne4NFsKrvc0v97JD5awbmeBLO5w9Ho9L9kmKonrwF9RJlW6BxT1PVv/agBHQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=16.9.0"
}
@@ -9838,6 +9794,7 @@
"resolved": "https://registry.npmjs.org/@jrichman/ink/-/ink-6.4.11.tgz",
"integrity": "sha512-93LQlzT7vvZ1XJcmOMwN4s+6W334QegendeHOMnEJBlhnpIzr8bws6/aOEHG8ZCuVD/vNeeea5m1msHIdAY6ig==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alcalzone/ansi-tokenize": "^0.2.1",
"ansi-escapes": "^7.0.0",
@@ -10006,9 +9963,9 @@
}
},
"node_modules/ip-address": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
"integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz",
"integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==",
"license": "MIT",
"engines": {
"node": ">= 12"
@@ -10792,7 +10749,6 @@
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
"dev": true,
"license": "MIT"
},
"node_modules/json-schema-typed": {
@@ -12871,21 +12827,6 @@
"node": ">=8"
}
},
"node_modules/path-expression-matcher": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.1.3.tgz",
"integrity": "sha512-qdVgY8KXmVdJZRSS1JdEPOKPdTiEK/pi0RkcT2sw1RhXxohdujUlJFPuS1TSkevZ9vzd3ZlL7ULl1MHGTApKzQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -13440,6 +13381,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -13450,6 +13392,7 @@
"integrity": "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"shell-quote": "^1.6.1",
"ws": "^7"
@@ -13919,9 +13862,9 @@
}
},
"node_modules/rollup": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",
"integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",
"version": "4.53.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.2.tgz",
"integrity": "sha512-MHngMYwGJVi6Fmnk6ISmnk7JAHRNF0UkuucA0CUW3N3a4KnONPEZz+vUanQP/ZC/iY1Qkf3bwPWzyY84wEks1g==",
"license": "MIT",
"dependencies": {
"@types/estree": "1.0.8"
@@ -13934,31 +13877,28 @@
"npm": ">=8.0.0"
},
"optionalDependencies": {
"@rollup/rollup-android-arm-eabi": "4.59.0",
"@rollup/rollup-android-arm64": "4.59.0",
"@rollup/rollup-darwin-arm64": "4.59.0",
"@rollup/rollup-darwin-x64": "4.59.0",
"@rollup/rollup-freebsd-arm64": "4.59.0",
"@rollup/rollup-freebsd-x64": "4.59.0",
"@rollup/rollup-linux-arm-gnueabihf": "4.59.0",
"@rollup/rollup-linux-arm-musleabihf": "4.59.0",
"@rollup/rollup-linux-arm64-gnu": "4.59.0",
"@rollup/rollup-linux-arm64-musl": "4.59.0",
"@rollup/rollup-linux-loong64-gnu": "4.59.0",
"@rollup/rollup-linux-loong64-musl": "4.59.0",
"@rollup/rollup-linux-ppc64-gnu": "4.59.0",
"@rollup/rollup-linux-ppc64-musl": "4.59.0",
"@rollup/rollup-linux-riscv64-gnu": "4.59.0",
"@rollup/rollup-linux-riscv64-musl": "4.59.0",
"@rollup/rollup-linux-s390x-gnu": "4.59.0",
"@rollup/rollup-linux-x64-gnu": "4.59.0",
"@rollup/rollup-linux-x64-musl": "4.59.0",
"@rollup/rollup-openbsd-x64": "4.59.0",
"@rollup/rollup-openharmony-arm64": "4.59.0",
"@rollup/rollup-win32-arm64-msvc": "4.59.0",
"@rollup/rollup-win32-ia32-msvc": "4.59.0",
"@rollup/rollup-win32-x64-gnu": "4.59.0",
"@rollup/rollup-win32-x64-msvc": "4.59.0",
"@rollup/rollup-android-arm-eabi": "4.53.2",
"@rollup/rollup-android-arm64": "4.53.2",
"@rollup/rollup-darwin-arm64": "4.53.2",
"@rollup/rollup-darwin-x64": "4.53.2",
"@rollup/rollup-freebsd-arm64": "4.53.2",
"@rollup/rollup-freebsd-x64": "4.53.2",
"@rollup/rollup-linux-arm-gnueabihf": "4.53.2",
"@rollup/rollup-linux-arm-musleabihf": "4.53.2",
"@rollup/rollup-linux-arm64-gnu": "4.53.2",
"@rollup/rollup-linux-arm64-musl": "4.53.2",
"@rollup/rollup-linux-loong64-gnu": "4.53.2",
"@rollup/rollup-linux-ppc64-gnu": "4.53.2",
"@rollup/rollup-linux-riscv64-gnu": "4.53.2",
"@rollup/rollup-linux-riscv64-musl": "4.53.2",
"@rollup/rollup-linux-s390x-gnu": "4.53.2",
"@rollup/rollup-linux-x64-gnu": "4.53.2",
"@rollup/rollup-linux-x64-musl": "4.53.2",
"@rollup/rollup-openharmony-arm64": "4.53.2",
"@rollup/rollup-win32-arm64-msvc": "4.53.2",
"@rollup/rollup-win32-ia32-msvc": "4.53.2",
"@rollup/rollup-win32-x64-gnu": "4.53.2",
"@rollup/rollup-win32-x64-msvc": "4.53.2",
"fsevents": "~2.3.2"
}
},
@@ -14492,9 +14432,9 @@
}
},
"node_modules/simple-git": {
"version": "3.33.0",
"resolved": "https://registry.npmjs.org/simple-git/-/simple-git-3.33.0.tgz",
"integrity": "sha512-D4V/tGC2sjsoNhoMybKyGoE+v8A60hRawKQ1iFRA1zwuDgGZCBJ4ByOzZ5J8joBbi4Oam0qiPH+GhzmSBwbJng==",
"version": "3.28.0",
"resolved": "https://registry.npmjs.org/simple-git/-/simple-git-3.28.0.tgz",
"integrity": "sha512-Rs/vQRwsn1ILH1oBUy8NucJlXmnnLeLCfcvbSehkPzbv3wwoFWIdtfd6Ndo6ZPhlPsCZ60CPI4rxurnwAa+a2w==",
"license": "MIT",
"dependencies": {
"@kwsites/file-exists": "^1.1.1",
@@ -14997,9 +14937,9 @@
}
},
"node_modules/strnum": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.0.tgz",
"integrity": "sha512-Y7Bj8XyJxnPAORMZj/xltsfo55uOiyHcU2tnAVzHUnSJR/KsEX+9RoDeXEnsXtl/CX4fAcrt64gZ13aGaWPeBg==",
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",
"integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",
"funding": [
{
"type": "github",
@@ -15179,9 +15119,9 @@
}
},
"node_modules/systeminformation": {
"version": "5.31.4",
"resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.31.4.tgz",
"integrity": "sha512-lZppDyQx91VdS5zJvAyGkmwe+Mq6xY978BDUG2wRkWE+jkmUF5ti8cvOovFQoN5bvSFKCXVkyKEaU5ec3SJiRg==",
"version": "5.30.2",
"resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.30.2.tgz",
"integrity": "sha512-Rrt5oFTWluUVuPlbtn3o9ja+nvjdF3Um4DG0KxqfYvpzcx7Q9plZBTjJiJy9mAouua4+OI7IUGBaG9Zyt9NgxA==",
"license": "MIT",
"os": [
"darwin",
@@ -15222,9 +15162,9 @@
}
},
"node_modules/table/node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -15497,6 +15437,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15720,7 +15661,8 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
"license": "0BSD",
"peer": true
},
"node_modules/tsx": {
"version": "4.20.3",
@@ -15728,6 +15670,7 @@
"integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.25.0",
"get-tsconfig": "^4.7.5"
@@ -15887,6 +15830,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15945,9 +15889,9 @@
}
},
"node_modules/underscore": {
"version": "1.13.8",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz",
"integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==",
"version": "1.13.7",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz",
"integrity": "sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==",
"dev": true,
"license": "MIT"
},
@@ -16109,6 +16053,7 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.2.tgz",
"integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
@@ -16222,6 +16167,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -16234,6 +16180,7 @@
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4",
@@ -16875,6 +16822,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -17341,9 +17289,9 @@
}
},
"packages/core/node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -17391,12 +17339,6 @@
"node": ">= 4"
}
},
"packages/core/node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
"packages/core/node_modules/mime": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz",
@@ -17417,6 +17359,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -26,7 +26,7 @@ describe('Task Event-Driven Scheduler', () => {
mockConfig = createMockConfig({
isEventDrivenSchedulerEnabled: () => true,
}) as Config;
messageBus = mockConfig.messageBus;
messageBus = mockConfig.getMessageBus();
mockEventBus = {
publish: vi.fn(),
on: vi.fn(),
@@ -360,7 +360,7 @@ describe('Task Event-Driven Scheduler', () => {
isEventDrivenSchedulerEnabled: () => true,
getApprovalMode: () => ApprovalMode.YOLO,
}) as Config;
const yoloMessageBus = yoloConfig.messageBus;
const yoloMessageBus = yoloConfig.getMessageBus();
// @ts-expect-error - Calling private constructor
const task = new Task('task-id', 'context-id', yoloConfig, mockEventBus);
+7 -14
View File
@@ -5,7 +5,6 @@
*/
import {
type AgentLoopContext,
Scheduler,
type GeminiClient,
GeminiEventType,
@@ -115,8 +114,7 @@ export class Task {
this.scheduler = this.setupEventDrivenScheduler();
const loopContext: AgentLoopContext = this.config;
this.geminiClient = loopContext.geminiClient;
this.geminiClient = this.config.getGeminiClient();
this.pendingToolConfirmationDetails = new Map();
this.taskState = 'submitted';
this.eventBus = eventBus;
@@ -145,8 +143,7 @@ export class Task {
// process. This is not scoped to the individual task but reflects the global connection
// state managed within the @gemini-cli/core module.
async getMetadata(): Promise<TaskMetadata> {
const loopContext: AgentLoopContext = this.config;
const toolRegistry = loopContext.toolRegistry;
const toolRegistry = this.config.getToolRegistry();
const mcpServers = this.config.getMcpClientManager()?.getMcpServers() || {};
const serverStatuses = getAllMCPServerStatuses();
const servers = Object.keys(mcpServers).map((serverName) => ({
@@ -379,8 +376,7 @@ export class Task {
private messageBusListener?: (message: ToolCallsUpdateMessage) => void;
private setupEventDrivenScheduler(): Scheduler {
const loopContext: AgentLoopContext = this.config;
const messageBus = loopContext.messageBus;
const messageBus = this.config.getMessageBus();
const scheduler = new Scheduler({
schedulerId: this.id,
context: this.config,
@@ -399,11 +395,9 @@ export class Task {
dispose(): void {
if (this.messageBusListener) {
const loopContext: AgentLoopContext = this.config;
loopContext.messageBus.unsubscribe(
MessageBusType.TOOL_CALLS_UPDATE,
this.messageBusListener,
);
this.config
.getMessageBus()
.unsubscribe(MessageBusType.TOOL_CALLS_UPDATE, this.messageBusListener);
this.messageBusListener = undefined;
}
@@ -954,8 +948,7 @@ export class Task {
try {
if (correlationId) {
const loopContext: AgentLoopContext = this.config;
await loopContext.messageBus.publish({
await this.config.getMessageBus().publish({
type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
correlationId,
confirmed:
@@ -59,9 +59,6 @@ describe('a2a-server memory commands', () => {
} as unknown as ToolRegistry;
mockConfig = {
get toolRegistry() {
return mockToolRegistry;
},
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
} as unknown as Config;
@@ -171,6 +168,7 @@ describe('a2a-server memory commands', () => {
]);
expect(mockAddMemory).toHaveBeenCalledWith(fact);
expect(mockConfig.getToolRegistry).toHaveBeenCalled();
expect(mockToolRegistry.getTool).toHaveBeenCalledWith('save_memory');
expect(mockSaveMemoryTool.buildAndExecute).toHaveBeenCalledWith(
{ fact },
+1 -3
View File
@@ -15,7 +15,6 @@ import type {
CommandContext,
CommandExecutionResponse,
} from './types.js';
import type { AgentLoopContext } from '@google/gemini-cli-core';
const DEFAULT_SANITIZATION_CONFIG = {
allowedEnvironmentVariables: [],
@@ -96,8 +95,7 @@ export class AddMemoryCommand implements Command {
return { name: this.name, data: result.content };
}
const loopContext: AgentLoopContext = context.config;
const toolRegistry = loopContext.toolRegistry;
const toolRegistry = context.config.getToolRegistry();
const tool = toolRegistry.getTool(result.toolName);
if (tool) {
const abortController = new AbortController();
+5 -21
View File
@@ -16,7 +16,6 @@ import {
DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
GeminiClient,
HookSystem,
type MessageBus,
PolicyDecision,
tmpdir,
type Config,
@@ -32,27 +31,9 @@ export function createMockConfig(
const tmpDir = tmpdir();
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const mockConfig = {
get config() {
get toolRegistry(): ToolRegistry {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return this as unknown as Config;
},
get toolRegistry() {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const config = this as unknown as Config;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return config.getToolRegistry?.() as unknown as ToolRegistry;
},
get messageBus() {
return (
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
(this as unknown as Config).getMessageBus?.() as unknown as MessageBus
);
},
get geminiClient() {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const config = this as unknown as Config;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return config.getGeminiClient?.() as unknown as GeminiClient;
return (this as unknown as Config).getToolRegistry();
},
getToolRegistry: vi.fn().mockReturnValue({
getTool: vi.fn(),
@@ -100,6 +81,9 @@ export function createMockConfig(
...overrides,
} as unknown as Config;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
(mockConfig as unknown as { config: Config; promptId: string }).config =
mockConfig;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
(mockConfig as unknown as { config: Config; promptId: string }).promptId =
'test-prompt-id';
+4 -8
View File
@@ -1773,7 +1773,7 @@ describe('loadCliConfig model selection', () => {
});
it('always prefers model from argv', async () => {
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash'];
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash-preview'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings({
@@ -1785,11 +1785,11 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('gemini-2.5-flash');
expect(config.getModel()).toBe('gemini-2.5-flash-preview');
});
it('selects the model from argv if provided', async () => {
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash'];
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash-preview'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings({
@@ -1799,7 +1799,7 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('gemini-2.5-flash');
expect(config.getModel()).toBe('gemini-2.5-flash-preview');
});
it('selects the default auto model if provided via auto alias', async () => {
@@ -3632,8 +3632,6 @@ describe('loadCliConfig acpMode and clientName', () => {
it('should set acpMode to true and detect clientName when --acp flag is used', async () => {
process.argv = ['node', 'script.js', '--acp'];
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('VSCODE_GIT_ASKPASS_MAIN', '');
vi.stubEnv('ANTIGRAVITY_CLI_ALIAS', '');
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings(),
@@ -3647,8 +3645,6 @@ describe('loadCliConfig acpMode and clientName', () => {
it('should set acpMode to true but leave clientName undefined for generic terminals', async () => {
process.argv = ['node', 'script.js', '--acp'];
vi.stubEnv('TERM_PROGRAM', 'iTerm.app'); // Generic terminal
vi.stubEnv('VSCODE_GIT_ASKPASS_MAIN', '');
vi.stubEnv('ANTIGRAVITY_CLI_ALIAS', '');
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings(),
+1 -15
View File
@@ -31,8 +31,6 @@ import {
type HierarchicalMemory,
coreEvents,
GEMINI_MODEL_ALIAS_AUTO,
isValidModelOrAlias,
getValidModelsAndAliases,
getAdminErrorMessage,
isHeadlessMode,
Config,
@@ -673,18 +671,6 @@ export async function loadCliConfig(
const specifiedModel =
argv.model || process.env['GEMINI_MODEL'] || settings.model?.name;
// Validate the model if one was explicitly specified
if (specifiedModel && specifiedModel !== GEMINI_MODEL_ALIAS_AUTO) {
if (!isValidModelOrAlias(specifiedModel)) {
const validModels = getValidModelsAndAliases();
throw new FatalConfigError(
`Invalid model: "${specifiedModel}"\n\n` +
`Valid models and aliases:\n${validModels.map((m) => ` - ${m}`).join('\n')}\n\n` +
`Use /model to switch models interactively.`,
);
}
}
const resolvedModel =
specifiedModel === GEMINI_MODEL_ALIAS_AUTO
? defaultModel
@@ -822,6 +808,7 @@ export async function loadCliConfig(
skillsSupport: settings.skills?.enabled ?? true,
disabledSkills: settings.skills?.disabled,
experimentalJitContext: settings.experimental?.jitContext,
imageGeneration: settings.experimental?.imageGeneration,
modelSteering: settings.experimental?.modelSteering,
toolOutputMasking: settings.experimental?.toolOutputMasking,
noBrowser: !!process.env['NO_BROWSER'],
@@ -857,7 +844,6 @@ export async function loadCliConfig(
disableLLMCorrection: settings.tools?.disableLLMCorrection,
rawOutput: argv.rawOutput,
acceptRawOutputRisk: argv.acceptRawOutputRisk,
dynamicModelConfiguration: settings.experimental?.dynamicModelConfiguration,
modelConfigServiceConfig: settings.modelConfigs,
// TODO: loading of hooks based on workspace trust
enableHooks: settings.hooksConfig.enabled,
@@ -12,13 +12,12 @@ import { ExtensionManager } from './extension-manager.js';
import { createTestMergedSettings, type MergedSettings } from './settings.js';
import { createExtension } from '../test-utils/createExtension.js';
import { EXTENSIONS_DIRECTORY_NAME } from './extensions/variables.js';
import { themeManager } from '../ui/themes/theme-manager.js';
import {
TrustLevel,
loadTrustedFolders,
isWorkspaceTrusted,
} from './trustedFolders.js';
import { getRealPath, type CustomTheme } from '@google/gemini-cli-core';
import { getRealPath } from '@google/gemini-cli-core';
const mockHomedir = vi.hoisted(() => vi.fn(() => '/tmp/mock-home'));
@@ -39,26 +38,6 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
};
});
const testTheme: CustomTheme = {
type: 'custom',
name: 'MyTheme',
background: {
primary: '#282828',
diff: { added: '#2b3312', removed: '#341212' },
},
text: {
primary: '#ebdbb2',
secondary: '#a89984',
link: '#83a598',
accent: '#d3869b',
},
status: {
success: '#b8bb26',
warning: '#fabd2f',
error: '#fb4934',
},
};
describe('ExtensionManager', () => {
let tempHomeDir: string;
let tempWorkspaceDir: string;
@@ -86,7 +65,6 @@ describe('ExtensionManager', () => {
});
afterEach(() => {
themeManager.clearExtensionThemes();
try {
fs.rmSync(tempHomeDir, { recursive: true, force: true });
} catch (_e) {
@@ -506,45 +484,4 @@ describe('ExtensionManager', () => {
).rejects.toThrow(/already installed/);
});
});
describe('early theme registration', () => {
it('should register themes with ThemeManager during loadExtensions for active extensions', async () => {
createExtension({
extensionsDir: userExtensionsDir,
name: 'themed-ext',
version: '1.0.0',
themes: [testTheme],
});
await extensionManager.loadExtensions();
expect(themeManager.getCustomThemeNames()).toContain(
'MyTheme (themed-ext)',
);
});
it('should not register themes for inactive extensions', async () => {
createExtension({
extensionsDir: userExtensionsDir,
name: 'disabled-ext',
version: '1.0.0',
themes: [testTheme],
});
// Disable the extension by creating an enablement override
const manager = new ExtensionManager({
enabledExtensionOverrides: ['none'],
settings: createTestMergedSettings(),
workspaceDir: tempWorkspaceDir,
requestConsent: vi.fn().mockResolvedValue(true),
requestSetting: null,
});
await manager.loadExtensions();
expect(themeManager.getCustomThemeNames()).not.toContain(
'MyTheme (disabled-ext)',
);
});
});
});
+1 -8
View File
@@ -564,7 +564,7 @@ Would you like to attempt to install via "git clone" instead?`,
protected override async startExtension(extension: GeminiCLIExtension) {
await super.startExtension(extension);
if (extension.themes && !themeManager.hasExtensionThemes(extension.name)) {
if (extension.themes) {
themeManager.registerExtensionThemes(extension.name, extension.themes);
}
}
@@ -624,13 +624,6 @@ Would you like to attempt to install via "git clone" instead?`,
this.loadedExtensions = builtExtensions;
// Register extension themes early so they're available at startup.
for (const ext of this.loadedExtensions) {
if (ext.isActive && ext.themes) {
themeManager.registerExtensionThemes(ext.name, ext.themes);
}
}
await Promise.all(
this.loadedExtensions.map((ext) => this.maybeStartExtension(ext)),
);
+10 -63
View File
@@ -540,16 +540,6 @@ const SETTINGS_SCHEMA = {
description: 'Hide helpful tips in the UI',
showInDialog: true,
},
escapePastedAtSymbols: {
type: 'boolean',
label: 'Escape Pasted @ Symbols',
category: 'UI',
requiresRestart: false,
default: false,
description:
'When enabled, @ symbols in pasted text are escaped to prevent unintended @path expansion.',
showInDialog: true,
},
showShortcutsHint: {
type: 'boolean',
label: 'Show Shortcuts Hint',
@@ -1039,20 +1029,6 @@ const SETTINGS_SCHEMA = {
'Apply specific configuration overrides based on matches, with a primary key of model (or alias). The most specific match will be used.',
showInDialog: false,
},
modelDefinitions: {
type: 'object',
label: 'Model Definitions',
category: 'Model',
requiresRestart: true,
default: DEFAULT_MODEL_CONFIGS.modelDefinitions,
description:
'Registry of model metadata, including tier, family, and features.',
showInDialog: false,
additionalProperties: {
type: 'object',
ref: 'ModelDefinition',
},
},
},
},
@@ -1131,16 +1107,6 @@ const SETTINGS_SCHEMA = {
description: 'Model override for the visual agent.',
showInDialog: false,
},
disableUserInput: {
type: 'boolean',
label: 'Disable User Input',
category: 'Advanced',
requiresRestart: false,
default: true,
description:
'Disable user input on browser window during automation.',
showInDialog: false,
},
},
},
},
@@ -1895,6 +1861,16 @@ const SETTINGS_SCHEMA = {
description: 'Enable Plan Mode.',
showInDialog: true,
},
imageGeneration: {
type: 'boolean',
label: 'Image Generation',
category: 'Experimental',
requiresRestart: true,
default: false,
description:
'Enable generating images with Nano Banana (experimental).',
showInDialog: true,
},
taskTracker: {
type: 'boolean',
label: 'Task Tracker',
@@ -1924,16 +1900,6 @@ const SETTINGS_SCHEMA = {
'Enable web fetch behavior that bypasses LLM summarization.',
showInDialog: true,
},
dynamicModelConfiguration: {
type: 'boolean',
label: 'Dynamic Model Configuration',
category: 'Experimental',
requiresRestart: true,
default: false,
description:
'Enable dynamic model configuration (definitions, resolutions, and chains) via settings.',
showInDialog: false,
},
gemmaModelRouter: {
type: 'object',
label: 'Gemma Model Router',
@@ -2750,25 +2716,6 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
},
},
},
ModelDefinition: {
type: 'object',
description: 'Model metadata registry entry.',
properties: {
displayName: { type: 'string' },
tier: { enum: ['pro', 'flash', 'flash-lite', 'custom', 'auto'] },
family: { type: 'string' },
isPreview: { type: 'boolean' },
dialogLocation: { enum: ['main', 'manual'] },
dialogDescription: { type: 'string' },
features: {
type: 'object',
properties: {
thinking: { type: 'boolean' },
multimodalToolUse: { type: 'boolean' },
},
},
},
},
};
export function getSettingsSchema(): SettingsSchemaType {
+217 -38
View File
@@ -4,38 +4,13 @@
* SPDX-License-Identifier: Apache-2.0
*/
import {
type StartupWarning,
WarningPriority,
type Config,
type ResumedSessionData,
type OutputPayload,
type ConsoleLogPayload,
type UserFeedbackPayload,
sessionId,
logUserPrompt,
AuthType,
UserPromptEvent,
coreEvents,
CoreEvent,
getOauthClient,
patchStdio,
writeToStdout,
writeToStderr,
shouldEnterAlternateScreen,
startupProfiler,
ExitCodes,
SessionStartSource,
SessionEndReason,
ValidationCancelledError,
ValidationRequiredError,
type AdminControlsSettings,
debugLogger,
} from '@google/gemini-cli-core';
import React from 'react';
import { render } from 'ink';
import { AppContainer } from './ui/AppContainer.js';
import { loadCliConfig, parseArguments } from './config/config.js';
import * as cliConfig from './config/config.js';
import { readStdin } from './utils/readStdin.js';
import { basename } from 'node:path';
import { createHash } from 'node:crypto';
import v8 from 'node:v8';
import os from 'node:os';
@@ -62,11 +37,47 @@ import {
runExitCleanup,
registerTelemetryConfig,
setupSignalHandlers,
setupTtyCheck,
} from './utils/cleanup.js';
import {
cleanupToolOutputFiles,
cleanupExpiredSessions,
} from './utils/sessionCleanup.js';
import {
type StartupWarning,
WarningPriority,
type Config,
type ResumedSessionData,
type OutputPayload,
type ConsoleLogPayload,
type UserFeedbackPayload,
sessionId,
logUserPrompt,
AuthType,
getOauthClient,
UserPromptEvent,
debugLogger,
recordSlowRender,
coreEvents,
CoreEvent,
createWorkingStdio,
patchStdio,
writeToStdout,
writeToStderr,
disableMouseEvents,
enableMouseEvents,
disableLineWrapping,
enableLineWrapping,
shouldEnterAlternateScreen,
startupProfiler,
ExitCodes,
SessionStartSource,
SessionEndReason,
getVersion,
ValidationCancelledError,
ValidationRequiredError,
type AdminControlsSettings,
} from '@google/gemini-cli-core';
import {
initializeApp,
type InitializationResult,
@@ -74,9 +85,21 @@ import {
import { validateAuthMethod } from './config/auth.js';
import { runAcpClient } from './acp/acpClient.js';
import { validateNonInteractiveAuth } from './validateNonInterActiveAuth.js';
import { checkForUpdates } from './ui/utils/updateCheck.js';
import { handleAutoUpdate } from './utils/handleAutoUpdate.js';
import { appEvents, AppEvent } from './utils/events.js';
import { SessionError, SessionSelector } from './utils/sessionUtils.js';
import { SettingsContext } from './ui/contexts/SettingsContext.js';
import { MouseProvider } from './ui/contexts/MouseContext.js';
import { StreamingState } from './ui/types.js';
import { computeTerminalTitle } from './utils/windowTitle.js';
import { SessionStatsProvider } from './ui/contexts/SessionContext.js';
import { VimModeProvider } from './ui/contexts/VimModeContext.js';
import { KeyMatchersProvider } from './ui/hooks/useKeyMatchers.js';
import { loadKeyMatchers } from './ui/key/keyMatchers.js';
import { KeypressProvider } from './ui/contexts/KeypressContext.js';
import { useKittyKeyboardProtocol } from './ui/hooks/useKittyKeyboardProtocol.js';
import {
relaunchAppInChildProcess,
relaunchOnExitCode,
@@ -84,13 +107,19 @@ import {
import { loadSandboxConfig } from './config/sandboxConfig.js';
import { deleteSession, listSessions } from './utils/sessions.js';
import { createPolicyUpdater } from './config/policy.js';
import { ScrollProvider } from './ui/contexts/ScrollProvider.js';
import { TerminalProvider } from './ui/contexts/TerminalContext.js';
import { isAlternateBufferEnabled } from './ui/hooks/useAlternateBuffer.js';
import { OverflowProvider } from './ui/contexts/OverflowContext.js';
import { setupTerminalAndTheme } from './utils/terminalTheme.js';
import { profiler } from './ui/components/DebugProfiler.js';
import { runDeferredCommand } from './deferred.js';
import { cleanupBackgroundLogs } from './utils/logCleanup.js';
import { SlashCommandConflictHandler } from './services/SlashCommandConflictHandler.js';
const SLOW_RENDER_MS = 200;
export function validateDnsResolutionOrder(
order: string | undefined,
): DnsResolutionOrder {
@@ -169,16 +198,147 @@ export async function startInteractiveUI(
resumedSessionData: ResumedSessionData | undefined,
initializationResult: InitializationResult,
) {
// Dynamically import the heavy UI module so React/Ink are only parsed when needed
const { startInteractiveUI: doStartUI } = await import('./interactiveCli.js');
await doStartUI(
config,
settings,
startupWarnings,
workspaceRoot,
resumedSessionData,
initializationResult,
// Never enter Ink alternate buffer mode when screen reader mode is enabled
// as there is no benefit of alternate buffer mode when using a screen reader
// and the Ink alternate buffer mode requires line wrapping harmful to
// screen readers.
const useAlternateBuffer = shouldEnterAlternateScreen(
isAlternateBufferEnabled(config),
config.getScreenReader(),
);
const mouseEventsEnabled = useAlternateBuffer;
if (mouseEventsEnabled) {
enableMouseEvents();
registerCleanup(() => {
disableMouseEvents();
});
}
const { matchers, errors } = await loadKeyMatchers();
errors.forEach((error) => {
coreEvents.emitFeedback('warning', error);
});
const version = await getVersion();
setWindowTitle(basename(workspaceRoot), settings);
const consolePatcher = new ConsolePatcher({
onNewMessage: (msg) => {
coreEvents.emitConsoleLog(msg.type, msg.content);
},
debugMode: config.getDebugMode(),
});
consolePatcher.patch();
registerCleanup(consolePatcher.cleanup);
const { stdout: inkStdout, stderr: inkStderr } = createWorkingStdio();
const isShpool = !!process.env['SHPOOL_SESSION_NAME'];
// Create wrapper component to use hooks inside render
const AppWrapper = () => {
useKittyKeyboardProtocol();
return (
<SettingsContext.Provider value={settings}>
<KeyMatchersProvider value={matchers}>
<KeypressProvider
config={config}
debugKeystrokeLogging={
settings.merged.general.debugKeystrokeLogging
}
>
<MouseProvider
mouseEventsEnabled={mouseEventsEnabled}
debugKeystrokeLogging={
settings.merged.general.debugKeystrokeLogging
}
>
<TerminalProvider>
<ScrollProvider>
<OverflowProvider>
<SessionStatsProvider>
<VimModeProvider>
<AppContainer
config={config}
startupWarnings={startupWarnings}
version={version}
resumedSessionData={resumedSessionData}
initializationResult={initializationResult}
/>
</VimModeProvider>
</SessionStatsProvider>
</OverflowProvider>
</ScrollProvider>
</TerminalProvider>
</MouseProvider>
</KeypressProvider>
</KeyMatchersProvider>
</SettingsContext.Provider>
);
};
if (isShpool) {
// Wait a moment for shpool to stabilize terminal size and state.
// shpool is a persistence tool that restores terminal state by replaying it.
// This delay gives shpool time to finish its restoration replay and send
// the actual terminal size (often via an immediate SIGWINCH) before we
// render the first TUI frame. Without this, the first frame may be
// garbled or rendered at an incorrect size, which disabling incremental
// rendering alone cannot fix for the initial frame.
await new Promise((resolve) => setTimeout(resolve, 100));
}
const instance = render(
process.env['DEBUG'] ? (
<React.StrictMode>
<AppWrapper />
</React.StrictMode>
) : (
<AppWrapper />
),
{
stdout: inkStdout,
stderr: inkStderr,
stdin: process.stdin,
exitOnCtrlC: false,
isScreenReaderEnabled: config.getScreenReader(),
onRender: ({ renderTime }: { renderTime: number }) => {
if (renderTime > SLOW_RENDER_MS) {
recordSlowRender(config, renderTime);
}
profiler.reportFrameRendered();
},
patchConsole: false,
alternateBuffer: useAlternateBuffer,
incrementalRendering:
settings.merged.ui.incrementalRendering !== false &&
useAlternateBuffer &&
!isShpool,
},
);
if (useAlternateBuffer) {
disableLineWrapping();
registerCleanup(() => {
enableLineWrapping();
});
}
checkForUpdates(settings)
.then((info) => {
handleAutoUpdate(info, settings, config.getProjectRoot());
})
.catch((err) => {
// Silently ignore update check errors.
if (config.getDebugMode()) {
debugLogger.warn('Update check failed:', err);
}
});
registerCleanup(() => instance.unmount());
registerCleanup(setupTtyCheck());
}
export async function main() {
@@ -685,6 +845,25 @@ export async function main() {
}
}
function setWindowTitle(title: string, settings: LoadedSettings) {
if (!settings.merged.ui.hideWindowTitle) {
// Initial state before React loop starts
const windowTitle = computeTerminalTitle({
streamingState: StreamingState.Idle,
isConfirming: false,
isSilentWorking: false,
folderName: title,
showThoughts: !!settings.merged.ui.showStatusInTitle,
useDynamicTitle: settings.merged.ui.dynamicWindowTitle,
});
writeToStdout(`\x1b]0;${windowTitle}\x07`);
process.on('exit', () => {
writeToStdout(`\x1b]0;\x07`);
});
}
}
export function initializeOutputListenersAndFlush() {
// If there are no listeners for output, make sure we flush so output is not
// lost.
-214
View File
@@ -1,214 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import { render } from 'ink';
import { basename } from 'node:path';
import { AppContainer } from './ui/AppContainer.js';
import { ConsolePatcher } from './ui/utils/ConsolePatcher.js';
import { registerCleanup, setupTtyCheck } from './utils/cleanup.js';
import {
type StartupWarning,
type Config,
type ResumedSessionData,
coreEvents,
createWorkingStdio,
disableMouseEvents,
enableMouseEvents,
disableLineWrapping,
enableLineWrapping,
shouldEnterAlternateScreen,
recordSlowRender,
writeToStdout,
getVersion,
debugLogger,
} from '@google/gemini-cli-core';
import type { InitializationResult } from './core/initializer.js';
import type { LoadedSettings } from './config/settings.js';
import { checkForUpdates } from './ui/utils/updateCheck.js';
import { handleAutoUpdate } from './utils/handleAutoUpdate.js';
import { SettingsContext } from './ui/contexts/SettingsContext.js';
import { MouseProvider } from './ui/contexts/MouseContext.js';
import { StreamingState } from './ui/types.js';
import { computeTerminalTitle } from './utils/windowTitle.js';
import { SessionStatsProvider } from './ui/contexts/SessionContext.js';
import { VimModeProvider } from './ui/contexts/VimModeContext.js';
import { KeyMatchersProvider } from './ui/hooks/useKeyMatchers.js';
import { loadKeyMatchers } from './ui/key/keyMatchers.js';
import { KeypressProvider } from './ui/contexts/KeypressContext.js';
import { useKittyKeyboardProtocol } from './ui/hooks/useKittyKeyboardProtocol.js';
import { ScrollProvider } from './ui/contexts/ScrollProvider.js';
import { TerminalProvider } from './ui/contexts/TerminalContext.js';
import { isAlternateBufferEnabled } from './ui/hooks/useAlternateBuffer.js';
import { OverflowProvider } from './ui/contexts/OverflowContext.js';
import { profiler } from './ui/components/DebugProfiler.js';
const SLOW_RENDER_MS = 200;
export async function startInteractiveUI(
config: Config,
settings: LoadedSettings,
startupWarnings: StartupWarning[],
workspaceRoot: string = process.cwd(),
resumedSessionData: ResumedSessionData | undefined,
initializationResult: InitializationResult,
) {
// Never enter Ink alternate buffer mode when screen reader mode is enabled
// as there is no benefit of alternate buffer mode when using a screen reader
// and the Ink alternate buffer mode requires line wrapping harmful to
// screen readers.
const useAlternateBuffer = shouldEnterAlternateScreen(
isAlternateBufferEnabled(config),
config.getScreenReader(),
);
const mouseEventsEnabled = useAlternateBuffer;
if (mouseEventsEnabled) {
enableMouseEvents();
registerCleanup(() => {
disableMouseEvents();
});
}
const { matchers, errors } = await loadKeyMatchers();
errors.forEach((error) => {
coreEvents.emitFeedback('warning', error);
});
const version = await getVersion();
setWindowTitle(basename(workspaceRoot), settings);
const consolePatcher = new ConsolePatcher({
onNewMessage: (msg) => {
coreEvents.emitConsoleLog(msg.type, msg.content);
},
debugMode: config.getDebugMode(),
});
consolePatcher.patch();
registerCleanup(consolePatcher.cleanup);
const { stdout: inkStdout, stderr: inkStderr } = createWorkingStdio();
const isShpool = !!process.env['SHPOOL_SESSION_NAME'];
// Create wrapper component to use hooks inside render
const AppWrapper = () => {
useKittyKeyboardProtocol();
return (
<SettingsContext.Provider value={settings}>
<KeyMatchersProvider value={matchers}>
<KeypressProvider
config={config}
debugKeystrokeLogging={
settings.merged.general.debugKeystrokeLogging
}
>
<MouseProvider
mouseEventsEnabled={mouseEventsEnabled}
debugKeystrokeLogging={
settings.merged.general.debugKeystrokeLogging
}
>
<TerminalProvider>
<ScrollProvider>
<OverflowProvider>
<SessionStatsProvider>
<VimModeProvider>
<AppContainer
config={config}
startupWarnings={startupWarnings}
version={version}
resumedSessionData={resumedSessionData}
initializationResult={initializationResult}
/>
</VimModeProvider>
</SessionStatsProvider>
</OverflowProvider>
</ScrollProvider>
</TerminalProvider>
</MouseProvider>
</KeypressProvider>
</KeyMatchersProvider>
</SettingsContext.Provider>
);
};
if (isShpool) {
// Wait a moment for shpool to stabilize terminal size and state.
await new Promise((resolve) => setTimeout(resolve, 100));
}
const instance = render(
process.env['DEBUG'] ? (
<React.StrictMode>
<AppWrapper />
</React.StrictMode>
) : (
<AppWrapper />
),
{
stdout: inkStdout,
stderr: inkStderr,
stdin: process.stdin,
exitOnCtrlC: false,
isScreenReaderEnabled: config.getScreenReader(),
onRender: ({ renderTime }: { renderTime: number }) => {
if (renderTime > SLOW_RENDER_MS) {
recordSlowRender(config, renderTime);
}
profiler.reportFrameRendered();
},
patchConsole: false,
alternateBuffer: useAlternateBuffer,
incrementalRendering:
settings.merged.ui.incrementalRendering !== false &&
useAlternateBuffer &&
!isShpool,
},
);
if (useAlternateBuffer) {
disableLineWrapping();
registerCleanup(() => {
enableLineWrapping();
});
}
checkForUpdates(settings)
.then((info) => {
handleAutoUpdate(info, settings, config.getProjectRoot());
})
.catch((err) => {
// Silently ignore update check errors.
if (config.getDebugMode()) {
debugLogger.warn('Update check failed:', err);
}
});
registerCleanup(() => instance.unmount());
registerCleanup(setupTtyCheck());
}
function setWindowTitle(title: string, settings: LoadedSettings) {
if (!settings.merged.ui.hideWindowTitle) {
// Initial state before React loop starts
const windowTitle = computeTerminalTitle({
streamingState: StreamingState.Idle,
isConfirming: false,
isSilentWorking: false,
folderName: title,
showThoughts: !!settings.merged.ui.showStatusInTitle,
useDynamicTitle: settings.merged.ui.dynamicWindowTitle,
});
writeToStdout(`\x1b]0;${windowTitle}\x07`);
process.on('exit', () => {
writeToStdout(`\x1b]0;\x07`);
});
}
}
+1 -1
View File
@@ -263,8 +263,8 @@ export async function runNonInteractive({
onDebugMessage: () => {},
messageId: Date.now(),
signal: abortController.signal,
escapePastedAtSymbols: false,
});
if (error || !processedQuery) {
// An error occurred during @include processing (e.g., file not found).
// The error message is already logged by handleAtCommand.
@@ -60,6 +60,7 @@ import { shellsCommand } from '../ui/commands/shellsCommand.js';
import { vimCommand } from '../ui/commands/vimCommand.js';
import { setupGithubCommand } from '../ui/commands/setupGithubCommand.js';
import { terminalSetupCommand } from '../ui/commands/terminalSetupCommand.js';
import { imageCommand } from '../ui/commands/imageCommand.js';
import { upgradeCommand } from '../ui/commands/upgradeCommand.js';
/**
@@ -155,6 +156,7 @@ export class BuiltinCommandLoader implements ICommandLoader {
]
: [extensionsCommand(this.config?.getEnableExtensionReloading())]),
helpCommand,
imageCommand,
footerCommand,
shortcutsCommand,
...(this.config?.getEnableHooksUI() ? [hooksCommand] : []),
-15
View File
@@ -162,7 +162,6 @@ import {
import { LoginWithGoogleRestartDialog } from './auth/LoginWithGoogleRestartDialog.js';
import { NewAgentsChoice } from './components/NewAgentsNotification.js';
import { isSlashCommand } from './utils/commandUtils.js';
import { parseSlashCommand } from '../utils/commands.js';
import { useTerminalTheme } from './hooks/useTerminalTheme.js';
import { useTimedMessage } from './hooks/useTimedMessage.js';
import { useIsHelpDismissKey } from './utils/shortcutsHelp.js';
@@ -1290,18 +1289,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
...pendingGeminiHistoryItems,
]);
if (isSlash && isAgentRunning) {
const { commandToExecute } = parseSlashCommand(
submittedValue,
slashCommands ?? [],
);
if (commandToExecute?.isSafeConcurrent) {
void handleSlashCommand(submittedValue);
addInput(submittedValue);
return;
}
}
if (config.isModelSteeringEnabled() && isAgentRunning && !isSlash) {
handleHintSubmit(submittedValue);
addInput(submittedValue);
@@ -1345,8 +1332,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
addMessage,
addInput,
submitQuery,
handleSlashCommand,
slashCommands,
isMcpReady,
streamingState,
messageQueue.length,
@@ -23,7 +23,6 @@ export const aboutCommand: SlashCommand = {
description: 'Show version info',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: async (context) => {
const osVersion = process.platform;
let sandboxEnv = 'no sandbox';
@@ -0,0 +1,132 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { parseImageArgs, imageCommand } from './imageCommand.js';
describe('parseImageArgs', () => {
it('should parse a simple prompt with no flags', () => {
const result = parseImageArgs('a sunset over the ocean');
expect(result.prompt).toBe('a sunset over the ocean');
expect(result.flags).toEqual({});
});
it('should parse prompt with a space-separated flag value', () => {
const result = parseImageArgs('a sunset --ratio 16:9');
expect(result.prompt).toBe('a sunset');
expect(result.flags['ratio']).toBe('16:9');
});
it('should parse --return as boolean flag', () => {
const result = parseImageArgs('a cat --return');
expect(result.prompt).toBe('a cat');
expect(result.flags['return']).toBe(true);
});
it('should parse inline flag values with =', () => {
const result = parseImageArgs('a cat --ratio=16:9 --size=4K');
expect(result.prompt).toBe('a cat');
expect(result.flags['ratio']).toBe('16:9');
expect(result.flags['size']).toBe('4K');
});
it('should handle multiple flags', () => {
const result = parseImageArgs(
'abstract wallpaper --ratio 21:9 --size 4K --count 2 --return',
);
expect(result.prompt).toBe('abstract wallpaper');
expect(result.flags['ratio']).toBe('21:9');
expect(result.flags['size']).toBe('4K');
expect(result.flags['count']).toBe('2');
expect(result.flags['return']).toBe(true);
});
it('should return empty prompt when input starts with flags', () => {
const result = parseImageArgs('--ratio 16:9');
expect(result.prompt).toBe('');
expect(result.flags['ratio']).toBe('16:9');
});
it('should handle empty input', () => {
const result = parseImageArgs('');
expect(result.prompt).toBe('');
expect(result.flags).toEqual({});
});
});
describe('imageCommand', () => {
const mockContext = {} as Parameters<
NonNullable<typeof imageCommand.action>
>[0];
it('should return error for empty args', () => {
const result = imageCommand.action!(mockContext, '');
expect(result).toEqual(
expect.objectContaining({
type: 'message',
messageType: 'error',
}),
);
});
it('should return error when prompt is empty (only flags)', () => {
const result = imageCommand.action!(mockContext, '--ratio 16:9');
expect(result).toEqual(
expect.objectContaining({
type: 'message',
messageType: 'error',
content: expect.stringContaining('No prompt provided'),
}),
);
});
it('should return tool action for valid prompt', () => {
const result = imageCommand.action!(mockContext, 'a sunset over the ocean');
expect(result).toEqual({
type: 'tool',
toolName: 'generate_image',
toolArgs: { prompt: 'a sunset over the ocean' },
});
});
it('should map all flags to tool args correctly', () => {
const result = imageCommand.action!(
mockContext,
'a cat --ratio 16:9 --size 2K --count 3 --model gemini-3-pro-image-preview --edit ./img.png --output ./out --return',
);
expect(result).toEqual({
type: 'tool',
toolName: 'generate_image',
toolArgs: {
prompt: 'a cat',
aspect_ratio: '16:9',
size: '2K',
count: 3,
model: 'gemini-3-pro-image-preview',
input_image: './img.png',
output_path: './out',
return_to_context: true,
},
});
});
it('should have correct metadata', () => {
expect(imageCommand.name).toBe('image');
expect(imageCommand.altNames).toContain('img');
expect(imageCommand.kind).toBe('built-in');
expect(imageCommand.autoExecute).toBe(false);
});
it('should provide flag completions', () => {
const completions = imageCommand.completion!(mockContext, '--ra');
expect(completions).toContain('--ratio');
});
it('should return empty completions for non-flag input', () => {
const completions = imageCommand.completion!(mockContext, 'some');
expect(completions).toEqual([]);
});
});
@@ -0,0 +1,110 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { GENERATE_IMAGE_TOOL_NAME } from '@google/gemini-cli-core';
import type { SlashCommand, SlashCommandActionReturn } from './types.js';
import { CommandKind } from './types.js';
interface ParsedImageArgs {
prompt: string;
flags: Record<string, string | boolean>;
}
export function parseImageArgs(input: string): ParsedImageArgs {
const flags: Record<string, string | boolean> = {};
const parts = input.split(/\s+/);
const promptParts: string[] = [];
let i = 0;
// Collect prompt text (everything before first --flag)
while (i < parts.length && !parts[i].startsWith('--')) {
promptParts.push(parts[i]);
i++;
}
// Parse flags
while (i < parts.length) {
const part = parts[i];
if (part.startsWith('--')) {
const flagName = part.slice(2).split('=')[0];
const inlineValue = part.includes('=') ? part.split('=')[1] : undefined;
if (inlineValue !== undefined) {
flags[flagName] = inlineValue;
} else if (flagName === 'return') {
flags[flagName] = true;
} else if (i + 1 < parts.length && !parts[i + 1].startsWith('--')) {
flags[flagName] = parts[i + 1];
i++;
}
}
i++;
}
return { prompt: promptParts.join(' '), flags };
}
export const imageCommand: SlashCommand = {
name: 'image',
altNames: ['img'],
description: 'Generate or edit images using Nano Banana',
kind: CommandKind.BUILT_IN,
autoExecute: false,
action: (_context, args): SlashCommandActionReturn | void => {
if (!args.trim()) {
return {
type: 'message',
messageType: 'error',
content:
'Usage: /image <prompt> [--ratio 16:9] [--size 2K] [--count 3] [--edit path/to/image.png]',
};
}
const { prompt, flags } = parseImageArgs(args);
if (!prompt) {
return {
type: 'message',
messageType: 'error',
content:
'Error: No prompt provided. The prompt must come before any --flags.',
};
}
const toolArgs: Record<string, unknown> = { prompt };
if (flags['ratio']) toolArgs['aspect_ratio'] = flags['ratio'];
if (flags['size']) toolArgs['size'] = flags['size'];
if (flags['count'])
toolArgs['count'] = parseInt(String(flags['count']), 10);
if (flags['model']) toolArgs['model'] = flags['model'];
if (flags['edit']) toolArgs['input_image'] = flags['edit'];
if (flags['output']) toolArgs['output_path'] = flags['output'];
if (flags['return']) toolArgs['return_to_context'] = true;
return {
type: 'tool',
toolName: GENERATE_IMAGE_TOOL_NAME,
toolArgs,
};
},
completion: (_context, partialArg) => {
const flagOptions = [
'--ratio',
'--size',
'--count',
'--model',
'--edit',
'--output',
'--return',
];
if (partialArg.startsWith('--')) {
return flagOptions.filter((f) => f.startsWith(partialArg));
}
return [];
},
};
@@ -15,7 +15,6 @@ export const settingsCommand: SlashCommand = {
description: 'View and edit Gemini CLI settings',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: (_context, _args): OpenDialogActionReturn => ({
type: 'dialog',
dialog: 'settings',
@@ -123,6 +123,7 @@ async function downloadFiles({
downloads.push(
(async () => {
const endpoint = `${REPO_DOWNLOAD_URL}/refs/tags/${releaseTag}/${SOURCE_DIR}/${fileBasename}`;
// eslint-disable-next-line no-restricted-syntax -- TODO: Migrate to safeFetch for SSRF protection
const response = await fetch(endpoint, {
method: 'GET',
dispatcher: proxy ? new ProxyAgent(proxy) : undefined,
@@ -84,7 +84,6 @@ export const statsCommand: SlashCommand = {
description: 'Check session stats. Usage: /stats [session|model|tools]',
kind: CommandKind.BUILT_IN,
autoExecute: false,
isSafeConcurrent: true,
action: async (context: CommandContext) => {
await defaultSessionView(context);
},
@@ -94,7 +93,6 @@ export const statsCommand: SlashCommand = {
description: 'Show session-specific usage statistics',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: async (context: CommandContext) => {
await defaultSessionView(context);
},
@@ -104,7 +102,6 @@ export const statsCommand: SlashCommand = {
description: 'Show model-specific usage statistics',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: (context: CommandContext) => {
const { selectedAuthType, userEmail, tier } = getUserIdentity(context);
const currentModel = context.services.config?.getModel();
@@ -128,7 +125,6 @@ export const statsCommand: SlashCommand = {
description: 'Show tool-specific usage statistics',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: (context: CommandContext) => {
context.ui.addItem({
type: MessageType.TOOL_STATS,
-5
View File
@@ -207,11 +207,6 @@ export interface SlashCommand {
*/
autoExecute?: boolean;
/**
* Whether this command can be safely executed while the agent is busy (e.g. streaming a response).
*/
isSafeConcurrent?: boolean;
// Optional metadata for extension commands
extensionName?: string;
extensionId?: string;
@@ -37,7 +37,6 @@ describe('upgradeCommand', () => {
getContentGeneratorConfig: vi.fn().mockReturnValue({
authType: AuthType.LOGIN_WITH_GOOGLE,
}),
getUserTierName: vi.fn().mockReturnValue(undefined),
},
},
} as unknown as CommandContext);
@@ -116,23 +115,4 @@ describe('upgradeCommand', () => {
});
expect(openBrowserSecurely).not.toHaveBeenCalled();
});
it('should return info message for ultra tiers', async () => {
vi.mocked(mockContext.services.config!.getUserTierName).mockReturnValue(
'Advanced Ultra',
);
if (!upgradeCommand.action) {
throw new Error('The upgrade command must have an action.');
}
const result = await upgradeCommand.action(mockContext, '');
expect(result).toEqual({
type: 'message',
messageType: 'info',
content: 'You are already on the highest tier: Advanced Ultra.',
});
expect(openBrowserSecurely).not.toHaveBeenCalled();
});
});
@@ -10,7 +10,6 @@ import {
shouldLaunchBrowser,
UPGRADE_URL_PAGE,
} from '@google/gemini-cli-core';
import { isUltraTier } from '../../utils/tierUtils.js';
import { CommandKind, type SlashCommand } from './types.js';
/**
@@ -36,15 +35,6 @@ export const upgradeCommand: SlashCommand = {
};
}
const tierName = context.services.config?.getUserTierName();
if (isUltraTier(tierName)) {
return {
type: 'message',
messageType: 'info',
content: `You are already on the highest tier: ${tierName}.`,
};
}
if (!shouldLaunchBrowser()) {
return {
type: 'message',
@@ -11,7 +11,6 @@ export const vimCommand: SlashCommand = {
description: 'Toggle vim mode on/off',
kind: CommandKind.BUILT_IN,
autoExecute: true,
isSafeConcurrent: true,
action: async (context, _args) => {
const newVimState = await context.ui.toggleVimEnabled();
@@ -87,7 +87,6 @@ export const DialogManager = ({
!!uiState.quota.proQuotaRequest.isModelNotFoundError
}
authType={uiState.quota.proQuotaRequest.authType}
tierName={config?.getUserTierName()}
onChoice={uiActions.handleProQuotaChoice}
/>
);
@@ -94,12 +94,6 @@ afterEach(() => {
});
const mockSlashCommands: SlashCommand[] = [
{
name: 'stats',
description: 'Check stats',
kind: CommandKind.BUILT_IN,
isSafeConcurrent: true,
},
{
name: 'clear',
kind: CommandKind.BUILT_IN,
@@ -3882,13 +3876,6 @@ describe('InputPrompt', () => {
shouldSubmit: false,
errorMessage: 'Slash commands cannot be queued',
},
{
name: 'should allow concurrent-safe slash commands',
bufferText: '/stats',
shellMode: false,
shouldSubmit: true,
errorMessage: null,
},
{
name: 'should prevent shell commands',
bufferText: 'ls',
+4 -35
View File
@@ -11,7 +11,6 @@ import { Box, Text, useStdout, type DOMElement } from 'ink';
import { SuggestionsDisplay, MAX_WIDTH } from './SuggestionsDisplay.js';
import { theme } from '../semantic-colors.js';
import { useInputHistory } from '../hooks/useInputHistory.js';
import { escapeAtSymbols } from '../hooks/atCommandProcessor.js';
import { HalfLinePaddedBox } from './shared/HalfLinePaddedBox.js';
import {
type TextBuffer,
@@ -59,7 +58,6 @@ import {
isAutoExecutableCommand,
isSlashCommand,
} from '../utils/commandUtils.js';
import { parseSlashCommand } from '../../utils/commands.js';
import * as path from 'node:path';
import { SCREEN_READER_USER_PREFIX } from '../textConstants.js';
import { getSafeLowColorBackground } from '../themes/color-utils.js';
@@ -410,17 +408,6 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
(isSlash || isShell) &&
streamingState === StreamingState.Responding
) {
if (isSlash) {
const { commandToExecute } = parseSlashCommand(
trimmedMessage,
slashCommands,
);
if (commandToExecute?.isSafeConcurrent) {
inputHistory.handleSubmit(trimmedMessage);
return;
}
}
setQueueErrorMessage(
`${isShell ? 'Shell' : 'Slash'} commands cannot be queued`,
);
@@ -428,13 +415,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
}
inputHistory.handleSubmit(trimmedMessage);
},
[
inputHistory,
shellModeActive,
streamingState,
setQueueErrorMessage,
slashCommands,
],
[inputHistory, shellModeActive, streamingState, setQueueErrorMessage],
);
// Effect to reset completion if history navigation just occurred and set the text
@@ -516,11 +497,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
stdout.write('\x1b]52;c;?\x07');
} else {
const textToInsert = await clipboardy.read();
const escapedText = settings.ui?.escapePastedAtSymbols
? escapeAtSymbols(textToInsert)
: textToInsert;
buffer.insert(escapedText, { paste: true });
buffer.insert(textToInsert, { paste: true });
if (isLargePaste(textToInsert)) {
appEvents.emit(AppEvent.TransientMessage, {
message: `Press ${formatCommand(Command.EXPAND_PASTE)} to expand pasted text`,
@@ -755,15 +732,8 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
pasteTimeoutRef.current = null;
}, 40);
}
if (settings.ui?.escapePastedAtSymbols) {
buffer.handleInput({
...key,
sequence: escapeAtSymbols(key.sequence || ''),
});
} else {
buffer.handleInput(key);
}
// Ensure we never accidentally interpret paste as regular input.
buffer.handleInput(key);
if (key.sequence && isLargePaste(key.sequence)) {
appEvents.emit(AppEvent.TransientMessage, {
message: `Press ${formatCommand(Command.EXPAND_PASTE)} to expand pasted text`,
@@ -1303,7 +1273,6 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
forceShowShellSuggestions,
keyMatchers,
isHelpDismissKey,
settings,
],
);
@@ -202,40 +202,6 @@ describe('ProQuotaDialog', () => {
);
unmount();
});
it('should NOT render upgrade option for LOGIN_WITH_GOOGLE if tier is Ultra', () => {
const { unmount } = render(
<ProQuotaDialog
failedModel="gemini-2.5-pro"
fallbackModel="gemini-2.5-flash"
message="free tier quota error"
isTerminalQuotaError={true}
isModelNotFoundError={false}
authType={AuthType.LOGIN_WITH_GOOGLE}
tierName="Gemini Advanced Ultra"
onChoice={mockOnChoice}
/>,
);
expect(RadioButtonSelect).toHaveBeenCalledWith(
expect.objectContaining({
items: [
{
label: 'Switch to gemini-2.5-flash',
value: 'retry_always',
key: 'retry_always',
},
{
label: 'Stop',
value: 'retry_later',
key: 'retry_later',
},
],
}),
undefined,
);
unmount();
});
});
describe('when it is a capacity error', () => {
@@ -9,7 +9,6 @@ import { Box, Text } from 'ink';
import { RadioButtonSelect } from './shared/RadioButtonSelect.js';
import { theme } from '../semantic-colors.js';
import { AuthType } from '@google/gemini-cli-core';
import { isUltraTier } from '../../utils/tierUtils.js';
interface ProQuotaDialogProps {
failedModel: string;
@@ -18,7 +17,6 @@ interface ProQuotaDialogProps {
isTerminalQuotaError: boolean;
isModelNotFoundError?: boolean;
authType?: AuthType;
tierName?: string;
onChoice: (
choice: 'retry_later' | 'retry_once' | 'retry_always' | 'upgrade',
) => void;
@@ -31,7 +29,6 @@ export function ProQuotaDialog({
isTerminalQuotaError,
isModelNotFoundError,
authType,
tierName,
onChoice,
}: ProQuotaDialogProps): React.JSX.Element {
let items;
@@ -50,8 +47,6 @@ export function ProQuotaDialog({
},
];
} else if (isModelNotFoundError || isTerminalQuotaError) {
const isUltra = isUltraTier(tierName);
// free users and out of quota users on G1 pro and Cloud Console gets an option to upgrade
items = [
{
@@ -59,7 +54,7 @@ export function ProQuotaDialog({
value: 'retry_always' as const,
key: 'retry_always',
},
...(authType === AuthType.LOGIN_WITH_GOOGLE && !isUltra
...(authType === AuthType.LOGIN_WITH_GOOGLE
? [
{
label: 'Upgrade for higher limits',
@@ -13,8 +13,9 @@ import { useTerminalSize } from '../hooks/useTerminalSize.js';
import { useKeypress } from '../hooks/useKeypress.js';
import path from 'node:path';
import type { Config } from '@google/gemini-cli-core';
import type { SessionInfo } from '../../utils/sessionUtils.js';
import type { SessionInfo, TextMatch } from '../../utils/sessionUtils.js';
import {
cleanMessage,
formatRelativeTime,
getSessionFiles,
} from '../../utils/sessionUtils.js';
@@ -149,7 +150,124 @@ const SessionBrowserEmpty = (): React.JSX.Element => (
</Box>
);
import { sortSessions, filterSessions } from './SessionBrowser/utils.js';
/**
* Sorts an array of sessions by the specified criteria.
* @param sessions - Array of sessions to sort
* @param sortBy - Sort criteria: 'date' (lastUpdated), 'messages' (messageCount), or 'name' (displayName)
* @param reverse - Whether to reverse the sort order (ascending instead of descending)
* @returns New sorted array of sessions
*/
const sortSessions = (
sessions: SessionInfo[],
sortBy: 'date' | 'messages' | 'name',
reverse: boolean,
): SessionInfo[] => {
const sorted = [...sessions].sort((a, b) => {
switch (sortBy) {
case 'date':
return (
new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime()
);
case 'messages':
return b.messageCount - a.messageCount;
case 'name':
return a.displayName.localeCompare(b.displayName);
default:
return 0;
}
});
return reverse ? sorted.reverse() : sorted;
};
/**
* Finds all text matches for a search query within conversation messages.
* Creates TextMatch objects with context (10 chars before/after) and role information.
* @param messages - Array of messages to search through
* @param query - Search query string (case-insensitive)
* @returns Array of TextMatch objects containing match context and metadata
*/
const findTextMatches = (
messages: Array<{ role: 'user' | 'assistant'; content: string }>,
query: string,
): TextMatch[] => {
if (!query.trim()) return [];
const lowerQuery = query.toLowerCase();
const matches: TextMatch[] = [];
for (const message of messages) {
const m = cleanMessage(message.content);
const lowerContent = m.toLowerCase();
let startIndex = 0;
while (true) {
const matchIndex = lowerContent.indexOf(lowerQuery, startIndex);
if (matchIndex === -1) break;
const contextStart = Math.max(0, matchIndex - 10);
const contextEnd = Math.min(m.length, matchIndex + query.length + 10);
const snippet = m.slice(contextStart, contextEnd);
const relativeMatchStart = matchIndex - contextStart;
const relativeMatchEnd = relativeMatchStart + query.length;
let before = snippet.slice(0, relativeMatchStart);
const match = snippet.slice(relativeMatchStart, relativeMatchEnd);
let after = snippet.slice(relativeMatchEnd);
if (contextStart > 0) before = '…' + before;
if (contextEnd < m.length) after = after + '…';
matches.push({ before, match, after, role: message.role });
startIndex = matchIndex + 1;
}
}
return matches;
};
/**
* Filters sessions based on a search query, checking titles, IDs, and full content.
* Also populates matchSnippets and matchCount for sessions with content matches.
* @param sessions - Array of sessions to filter
* @param query - Search query string (case-insensitive)
* @returns Filtered array of sessions that match the query
*/
const filterSessions = (
sessions: SessionInfo[],
query: string,
): SessionInfo[] => {
if (!query.trim()) {
return sessions.map((session) => ({
...session,
matchSnippets: undefined,
matchCount: undefined,
}));
}
const lowerQuery = query.toLowerCase();
return sessions.filter((session) => {
const titleMatch =
session.displayName.toLowerCase().includes(lowerQuery) ||
session.id.toLowerCase().includes(lowerQuery) ||
session.firstUserMessage.toLowerCase().includes(lowerQuery);
const contentMatch = session.fullContent
?.toLowerCase()
.includes(lowerQuery);
if (titleMatch || contentMatch) {
if (session.messages) {
session.matchSnippets = findTextMatches(session.messages, query);
session.matchCount = session.matchSnippets.length;
}
return true;
}
return false;
});
};
/**
* Search input display component.
@@ -1,132 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { sortSessions, findTextMatches, filterSessions } from './utils.js';
import type { SessionInfo } from '../../../utils/sessionUtils.js';
describe('SessionBrowser utils', () => {
const createTestSession = (overrides: Partial<SessionInfo>): SessionInfo => ({
id: 'test-id',
file: 'test-file',
fileName: 'test-file.json',
startTime: '2025-01-01T10:00:00Z',
lastUpdated: '2025-01-01T10:00:00Z',
messageCount: 1,
displayName: 'Test Session',
firstUserMessage: 'Hello',
isCurrentSession: false,
index: 0,
...overrides,
});
describe('sortSessions', () => {
it('sorts by date ascending/descending', () => {
const older = createTestSession({
id: '1',
lastUpdated: '2025-01-01T10:00:00Z',
});
const newer = createTestSession({
id: '2',
lastUpdated: '2025-01-02T10:00:00Z',
});
const desc = sortSessions([older, newer], 'date', false);
expect(desc[0].id).toBe('2');
const asc = sortSessions([older, newer], 'date', true);
expect(asc[0].id).toBe('1');
});
it('sorts by message count ascending/descending', () => {
const more = createTestSession({ id: '1', messageCount: 10 });
const less = createTestSession({ id: '2', messageCount: 2 });
const desc = sortSessions([more, less], 'messages', false);
expect(desc[0].id).toBe('1');
const asc = sortSessions([more, less], 'messages', true);
expect(asc[0].id).toBe('2');
});
it('sorts by name ascending/descending', () => {
const apple = createTestSession({ id: '1', displayName: 'Apple' });
const banana = createTestSession({ id: '2', displayName: 'Banana' });
const asc = sortSessions([apple, banana], 'name', true);
expect(asc[0].id).toBe('2'); // Reversed alpha
const desc = sortSessions([apple, banana], 'name', false);
expect(desc[0].id).toBe('1');
});
});
describe('findTextMatches', () => {
it('returns empty array if query is practically empty', () => {
expect(
findTextMatches([{ role: 'user', content: 'hello world' }], ' '),
).toEqual([]);
});
it('finds simple matches with surrounding context', () => {
const messages: Array<{ role: 'user' | 'assistant'; content: string }> = [
{ role: 'user', content: 'What is the capital of France?' },
];
const matches = findTextMatches(messages, 'capital');
expect(matches.length).toBe(1);
expect(matches[0].match).toBe('capital');
expect(matches[0].before.endsWith('the ')).toBe(true);
expect(matches[0].after.startsWith(' of')).toBe(true);
expect(matches[0].role).toBe('user');
});
it('finds multiple matches in a single message', () => {
const messages: Array<{ role: 'user' | 'assistant'; content: string }> = [
{ role: 'user', content: 'test here test there' },
];
const matches = findTextMatches(messages, 'test');
expect(matches.length).toBe(2);
});
});
describe('filterSessions', () => {
it('returns all sessions when query is blank and clears existing snippets', () => {
const sessions = [createTestSession({ id: '1', matchCount: 5 })];
const result = filterSessions(sessions, ' ');
expect(result.length).toBe(1);
expect(result[0].matchCount).toBeUndefined();
});
it('filters by displayName', () => {
const session1 = createTestSession({
id: '1',
displayName: 'Cats and Dogs',
});
const session2 = createTestSession({ id: '2', displayName: 'Fish' });
const result = filterSessions([session1, session2], 'cat');
expect(result.length).toBe(1);
expect(result[0].id).toBe('1');
});
it('populates match snippets if it matches content inside messages array', () => {
const sessionWithMessages = createTestSession({
id: '1',
displayName: 'Unrelated Title',
fullContent: 'This mentions a giraffe',
messages: [{ role: 'user', content: 'This mentions a giraffe' }],
});
const result = filterSessions([sessionWithMessages], 'giraffe');
expect(result.length).toBe(1);
expect(result[0].matchCount).toBe(1);
expect(result[0].matchSnippets?.[0].match).toBe('giraffe');
});
});
});
@@ -1,130 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
cleanMessage,
type SessionInfo,
type TextMatch,
} from '../../../utils/sessionUtils.js';
/**
* Sorts an array of sessions by the specified criteria.
* @param sessions - Array of sessions to sort
* @param sortBy - Sort criteria: 'date' (lastUpdated), 'messages' (messageCount), or 'name' (displayName)
* @param reverse - Whether to reverse the sort order (ascending instead of descending)
* @returns New sorted array of sessions
*/
export const sortSessions = (
sessions: SessionInfo[],
sortBy: 'date' | 'messages' | 'name',
reverse: boolean,
): SessionInfo[] => {
const sorted = [...sessions].sort((a, b) => {
switch (sortBy) {
case 'date':
return (
new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime()
);
case 'messages':
return b.messageCount - a.messageCount;
case 'name':
return a.displayName.localeCompare(b.displayName);
default:
return 0;
}
});
return reverse ? sorted.reverse() : sorted;
};
/**
* Finds all text matches for a search query within conversation messages.
* Creates TextMatch objects with context (10 chars before/after) and role information.
* @param messages - Array of messages to search through
* @param query - Search query string (case-insensitive)
* @returns Array of TextMatch objects containing match context and metadata
*/
export const findTextMatches = (
messages: Array<{ role: 'user' | 'assistant'; content: string }>,
query: string,
): TextMatch[] => {
if (!query.trim()) return [];
const lowerQuery = query.toLowerCase();
const matches: TextMatch[] = [];
for (const message of messages) {
const m = cleanMessage(message.content);
const lowerContent = m.toLowerCase();
let startIndex = 0;
while (true) {
const matchIndex = lowerContent.indexOf(lowerQuery, startIndex);
if (matchIndex === -1) break;
const contextStart = Math.max(0, matchIndex - 10);
const contextEnd = Math.min(m.length, matchIndex + query.length + 10);
const snippet = m.slice(contextStart, contextEnd);
const relativeMatchStart = matchIndex - contextStart;
const relativeMatchEnd = relativeMatchStart + query.length;
let before = snippet.slice(0, relativeMatchStart);
const match = snippet.slice(relativeMatchStart, relativeMatchEnd);
let after = snippet.slice(relativeMatchEnd);
if (contextStart > 0) before = '…' + before;
if (contextEnd < m.length) after = after + '…';
matches.push({ before, match, after, role: message.role });
startIndex = matchIndex + 1;
}
}
return matches;
};
/**
* Filters sessions based on a search query, checking titles, IDs, and full content.
* Also populates matchSnippets and matchCount for sessions with content matches.
* @param sessions - Array of sessions to filter
* @param query - Search query string (case-insensitive)
* @returns Filtered array of sessions that match the query
*/
export const filterSessions = (
sessions: SessionInfo[],
query: string,
): SessionInfo[] => {
if (!query.trim()) {
return sessions.map((session) => ({
...session,
matchSnippets: undefined,
matchCount: undefined,
}));
}
const lowerQuery = query.toLowerCase();
return sessions.filter((session) => {
const titleMatch =
session.displayName.toLowerCase().includes(lowerQuery) ||
session.id.toLowerCase().includes(lowerQuery) ||
session.firstUserMessage.toLowerCase().includes(lowerQuery);
const contentMatch = session.fullContent
?.toLowerCase()
.includes(lowerQuery);
if (titleMatch || contentMatch) {
if (session.messages) {
session.matchSnippets = findTextMatches(session.messages, query);
session.matchCount = session.matchSnippets.length;
}
return true;
}
return false;
});
};
@@ -27,7 +27,6 @@ import {
} from '../utils/displayUtils.js';
import { computeSessionStats } from '../utils/computeStats.js';
import {
type Config,
type RetrieveUserQuotaResponse,
isActiveModel,
getDisplayString,
@@ -89,16 +88,13 @@ const Section: React.FC<SectionProps> = ({ title, children }) => (
// Logic for building the unified list of table rows
const buildModelRows = (
models: Record<string, ModelMetrics>,
config: Config,
quotas?: RetrieveUserQuotaResponse,
useGemini3_1 = false,
useCustomToolModel = false,
) => {
const getBaseModelName = (name: string) => name.replace('-001', '');
const usedModelNames = new Set(
Object.keys(models)
.map(getBaseModelName)
.map((name) => getDisplayString(name, config)),
Object.keys(models).map(getBaseModelName).map(getDisplayString),
);
// 1. Models with active usage
@@ -108,7 +104,7 @@ const buildModelRows = (
const inputTokens = metrics.tokens.input;
return {
key: name,
modelName: getDisplayString(modelName, config),
modelName: getDisplayString(modelName),
requests: metrics.api.totalRequests,
cachedTokens: cachedTokens.toLocaleString(),
inputTokens: inputTokens.toLocaleString(),
@@ -125,11 +121,11 @@ const buildModelRows = (
(b) =>
b.modelId &&
isActiveModel(b.modelId, useGemini3_1, useCustomToolModel) &&
!usedModelNames.has(getDisplayString(b.modelId, config)),
!usedModelNames.has(getDisplayString(b.modelId)),
)
.map((bucket) => ({
key: bucket.modelId!,
modelName: getDisplayString(bucket.modelId!, config),
modelName: getDisplayString(bucket.modelId!),
requests: '-',
cachedTokens: '-',
inputTokens: '-',
@@ -143,7 +139,6 @@ const buildModelRows = (
const ModelUsageTable: React.FC<{
models: Record<string, ModelMetrics>;
config: Config;
quotas?: RetrieveUserQuotaResponse;
cacheEfficiency: number;
totalCachedTokens: number;
@@ -155,7 +150,6 @@ const ModelUsageTable: React.FC<{
useCustomToolModel?: boolean;
}> = ({
models,
config,
quotas,
cacheEfficiency,
totalCachedTokens,
@@ -168,13 +162,7 @@ const ModelUsageTable: React.FC<{
}) => {
const { stdout } = useStdout();
const terminalWidth = stdout?.columns ?? 84;
const rows = buildModelRows(
models,
config,
quotas,
useGemini3_1,
useCustomToolModel,
);
const rows = buildModelRows(models, quotas, useGemini3_1, useCustomToolModel);
if (rows.length === 0) {
return null;
@@ -688,7 +676,6 @@ export const StatsDisplay: React.FC<StatsDisplayProps> = ({
</Section>
<ModelUsageTable
models={models}
config={config}
quotas={quotas}
cacheEfficiency={computed.cacheEfficiency}
totalCachedTokens={computed.totalCachedTokens}
@@ -182,23 +182,4 @@ describe('<UserIdentity />', () => {
expect(output).toContain('/upgrade');
unmount();
});
it('should not render /upgrade indicator for ultra tiers', async () => {
const mockConfig = makeFakeConfig();
vi.spyOn(mockConfig, 'getContentGeneratorConfig').mockReturnValue({
authType: AuthType.LOGIN_WITH_GOOGLE,
model: 'gemini-pro',
} as unknown as ContentGeneratorConfig);
vi.spyOn(mockConfig, 'getUserTierName').mockReturnValue('Advanced Ultra');
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
<UserIdentity config={mockConfig} />,
);
await waitUntilReady();
const output = lastFrame();
expect(output).toContain('Plan: Advanced Ultra');
expect(output).not.toContain('/upgrade');
unmount();
});
});
@@ -13,7 +13,6 @@ import {
UserAccountManager,
AuthType,
} from '@google/gemini-cli-core';
import { isUltraTier } from '../../utils/tierUtils.js';
interface UserIdentityProps {
config: Config;
@@ -34,8 +33,6 @@ export const UserIdentity: React.FC<UserIdentityProps> = ({ config }) => {
[config, authType],
);
const isUltra = useMemo(() => isUltraTier(tierName), [tierName]);
if (!authType) {
return null;
}
@@ -63,7 +60,7 @@ export const UserIdentity: React.FC<UserIdentityProps> = ({ config }) => {
<Text color={theme.text.primary} wrap="truncate-end">
<Text bold>Plan:</Text> {tierName}
</Text>
{!isUltra && <Text color={theme.text.secondary}> /upgrade</Text>}
<Text color={theme.text.secondary}> /upgrade</Text>
</Box>
)}
</Box>
@@ -13,11 +13,7 @@ import {
afterEach,
type Mock,
} from 'vitest';
import {
handleAtCommand,
escapeAtSymbols,
unescapeLiteralAt,
} from './atCommandProcessor.js';
import { handleAtCommand } from './atCommandProcessor.js';
import {
FileDiscoveryService,
GlobTool,
@@ -1485,56 +1481,3 @@ describe('handleAtCommand', () => {
);
});
});
describe('escapeAtSymbols', () => {
it('escapes a bare @ symbol', () => {
expect(escapeAtSymbols('test@domain.com')).toBe('test\\@domain.com');
});
it('escapes a leading @ symbol', () => {
expect(escapeAtSymbols('@scope/pkg')).toBe('\\@scope/pkg');
});
it('escapes multiple @ symbols', () => {
expect(escapeAtSymbols('a@b and c@d')).toBe('a\\@b and c\\@d');
});
it('does not double-escape an already escaped @', () => {
expect(escapeAtSymbols('test\\@domain.com')).toBe('test\\@domain.com');
});
it('returns text with no @ unchanged', () => {
expect(escapeAtSymbols('hello world')).toBe('hello world');
});
it('returns empty string unchanged', () => {
expect(escapeAtSymbols('')).toBe('');
});
});
describe('unescapeLiteralAt', () => {
it('unescapes \\@ to @', () => {
expect(unescapeLiteralAt('test\\@domain.com')).toBe('test@domain.com');
});
it('unescapes a leading \\@', () => {
expect(unescapeLiteralAt('\\@scope/pkg')).toBe('@scope/pkg');
});
it('unescapes multiple \\@ sequences', () => {
expect(unescapeLiteralAt('a\\@b and c\\@d')).toBe('a@b and c@d');
});
it('returns text with no \\@ unchanged', () => {
expect(unescapeLiteralAt('hello world')).toBe('hello world');
});
it('returns empty string unchanged', () => {
expect(unescapeLiteralAt('')).toBe('');
});
it('roundtrips correctly with escapeAtSymbols', () => {
const input = 'user@example.com and @scope/pkg';
expect(unescapeLiteralAt(escapeAtSymbols(input))).toBe(input);
});
});
@@ -30,26 +30,6 @@ import type { UseHistoryManagerReturn } from './useHistoryManager.js';
const REF_CONTENT_HEADER = `\n${REFERENCE_CONTENT_START}`;
const REF_CONTENT_FOOTER = `\n${REFERENCE_CONTENT_END}`;
/**
* Escapes unescaped @ symbols so they are not interpreted as @path commands.
*/
export function escapeAtSymbols(text: string): string {
return text.replace(/(?<!\\)@/g, '\\@');
}
/**
* Unescapes \@ back to @ correctly, preserving \\@ sequences.
*/
export function unescapeLiteralAt(text: string): string {
return text.replace(/\\@/g, (match, offset, full) => {
let backslashCount = 0;
for (let i = offset - 1; i >= 0 && full[i] === '\\'; i--) {
backslashCount++;
}
return backslashCount % 2 === 0 ? '@' : '\\@';
});
}
/**
* Regex source for the path/command part of an @ reference.
* It uses strict ASCII whitespace delimiters to allow Unicode characters like NNBSP in filenames.
@@ -69,7 +49,6 @@ interface HandleAtCommandParams {
onDebugMessage: (message: string) => void;
messageId: number;
signal: AbortSignal;
escapePastedAtSymbols?: boolean;
}
interface HandleAtCommandResult {
@@ -86,10 +65,7 @@ interface AtCommandPart {
* Parses a query string to find all '@<path>' commands and text segments.
* Handles \ escaped spaces within paths.
*/
function parseAllAtCommands(
query: string,
escapePastedAtSymbols = false,
): AtCommandPart[] {
function parseAllAtCommands(query: string): AtCommandPart[] {
const parts: AtCommandPart[] = [];
let lastIndex = 0;
@@ -109,9 +85,7 @@ function parseAllAtCommands(
if (matchIndex > lastIndex) {
parts.push({
type: 'text',
content: escapePastedAtSymbols
? unescapeLiteralAt(query.substring(lastIndex, matchIndex))
: query.substring(lastIndex, matchIndex),
content: query.substring(lastIndex, matchIndex),
});
}
@@ -124,12 +98,7 @@ function parseAllAtCommands(
// Add remaining text
if (lastIndex < query.length) {
parts.push({
type: 'text',
content: escapePastedAtSymbols
? unescapeLiteralAt(query.substring(lastIndex))
: query.substring(lastIndex),
});
parts.push({ type: 'text', content: query.substring(lastIndex) });
}
// Filter out empty text parts that might result from consecutive @paths or leading/trailing spaces
@@ -666,9 +635,8 @@ export async function handleAtCommand({
onDebugMessage,
messageId: userMessageTimestamp,
signal,
escapePastedAtSymbols = false,
}: HandleAtCommandParams): Promise<HandleAtCommandResult> {
const commandParts = parseAllAtCommands(query, escapePastedAtSymbols);
const commandParts = parseAllAtCommands(query);
const { agentParts, resourceParts, fileParts } = categorizeAtCommands(
commandParts,
+1 -2
View File
@@ -837,8 +837,8 @@ export const useGeminiStream = (
onDebugMessage,
messageId: userMessageTimestamp,
signal: abortSignal,
escapePastedAtSymbols: settings.merged.ui?.escapePastedAtSymbols,
});
if (atCommandResult.error) {
onDebugMessage(atCommandResult.error);
return { queryToSend: null, shouldProceed: false };
@@ -874,7 +874,6 @@ export const useGeminiStream = (
logger,
shellModeActive,
scheduleToolCalls,
settings,
],
);
+5 -11
View File
@@ -174,6 +174,11 @@ class ThemeManager {
return;
}
debugLogger.log(
`Registering extension themes for "${extensionName}":`,
customThemes,
);
for (const customThemeConfig of customThemes) {
const namespacedName = `${customThemeConfig.name} (${extensionName})`;
@@ -235,17 +240,6 @@ class ThemeManager {
}
}
/**
* Checks if themes for a given extension are already registered.
* @param extensionName The name of the extension.
* @returns True if any themes from the extension are registered.
*/
hasExtensionThemes(extensionName: string): boolean {
return Array.from(this.extensionThemes.keys()).some((name) =>
name.endsWith(`(${extensionName})`),
);
}
/**
* Clears all registered extension themes.
* This is primarily for testing purposes to reset state between tests.
+1 -1
View File
@@ -25,7 +25,7 @@ export type HighlightToken = {
// It matches any character except strict delimiters (ASCII whitespace, comma, etc.).
// This supports URIs like `@file:///example.txt` and filenames with Unicode spaces (like NNBSP).
const HIGHLIGHT_REGEX = new RegExp(
`(^/[a-zA-Z0-9_-]+|(?<!\\\\)@${AT_COMMAND_PATH_REGEX_SOURCE}|${PASTED_TEXT_PLACEHOLDER_REGEX.source})`,
`(^/[a-zA-Z0-9_-]+|@${AT_COMMAND_PATH_REGEX_SOURCE}|${PASTED_TEXT_PLACEHOLDER_REGEX.source})`,
'g',
);
+1
View File
@@ -61,6 +61,7 @@ export const getLatestGitHubRelease = async (
const endpoint = `https://api.github.com/repos/google-github-actions/run-gemini-cli/releases/latest`;
// eslint-disable-next-line no-restricted-syntax -- TODO: Migrate to safeFetch for SSRF protection
const response = await fetch(endpoint, {
method: 'GET',
headers: {
-28
View File
@@ -1,28 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it } from 'vitest';
import { isUltraTier } from './tierUtils.js';
describe('tierUtils', () => {
describe('isUltraTier', () => {
it('should return true if tier name contains "ultra" (case-insensitive)', () => {
expect(isUltraTier('Advanced Ultra')).toBe(true);
expect(isUltraTier('gemini ultra')).toBe(true);
expect(isUltraTier('ULTRA')).toBe(true);
});
it('should return false if tier name does not contain "ultra"', () => {
expect(isUltraTier('Free')).toBe(false);
expect(isUltraTier('Pro')).toBe(false);
expect(isUltraTier('Standard')).toBe(false);
});
it('should return false if tier name is undefined', () => {
expect(isUltraTier(undefined)).toBe(false);
});
});
});
-15
View File
@@ -1,15 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Checks if the given tier name corresponds to an "Ultra" tier.
*
* @param tierName The name of the user's tier.
* @returns True if the tier is an "Ultra" tier, false otherwise.
*/
export function isUltraTier(tierName?: string): boolean {
return !!tierName?.toLowerCase().includes('ultra');
}
@@ -5,8 +5,11 @@
*/
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { A2AClientManager } from './a2a-client-manager.js';
import type { AgentCard } from '@a2a-js/sdk';
import {
A2AClientManager,
type SendMessageResult,
} from './a2a-client-manager.js';
import type { AgentCard, Task } from '@a2a-js/sdk';
import {
ClientFactory,
DefaultAgentCardResolver,
@@ -15,99 +18,83 @@ import {
type AuthenticationHandler,
type Client,
} from '@a2a-js/sdk/client';
import type { Config } from '../config/config.js';
import { Agent as UndiciAgent, ProxyAgent } from 'undici';
import { debugLogger } from '../utils/debugLogger.js';
interface MockClient {
sendMessageStream: ReturnType<typeof vi.fn>;
getTask: ReturnType<typeof vi.fn>;
cancelTask: ReturnType<typeof vi.fn>;
}
vi.mock('@a2a-js/sdk/client', async (importOriginal) => {
const actual = await importOriginal();
return {
...(actual as Record<string, unknown>),
createAuthenticatingFetchWithRetry: vi.fn(),
ClientFactory: vi.fn(),
DefaultAgentCardResolver: vi.fn(),
ClientFactoryOptions: {
createFrom: vi.fn(),
default: {},
},
};
});
vi.mock('../utils/debugLogger.js', () => ({
debugLogger: {
debug: vi.fn(),
},
}));
vi.mock('@a2a-js/sdk/client', () => {
const ClientFactory = vi.fn();
const DefaultAgentCardResolver = vi.fn();
const RestTransportFactory = vi.fn();
const JsonRpcTransportFactory = vi.fn();
const ClientFactoryOptions = {
default: {},
createFrom: vi.fn(),
};
const createAuthenticatingFetchWithRetry = vi.fn();
DefaultAgentCardResolver.prototype.resolve = vi.fn();
ClientFactory.prototype.createFromUrl = vi.fn();
return {
ClientFactory,
ClientFactoryOptions,
DefaultAgentCardResolver,
RestTransportFactory,
JsonRpcTransportFactory,
createAuthenticatingFetchWithRetry,
};
});
describe('A2AClientManager', () => {
let manager: A2AClientManager;
const mockAgentCard: AgentCard = {
name: 'test-agent',
description: 'A test agent',
url: 'http://test.agent',
version: '1.0.0',
protocolVersion: '0.1.0',
capabilities: {},
skills: [],
defaultInputModes: [],
defaultOutputModes: [],
};
const mockClient: MockClient = {
sendMessageStream: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
};
// Stable mocks initialized once
const sendMessageStreamMock = vi.fn();
const getTaskMock = vi.fn();
const cancelTaskMock = vi.fn();
const getAgentCardMock = vi.fn();
const authFetchMock = vi.fn();
const mockClient = {
sendMessageStream: sendMessageStreamMock,
getTask: getTaskMock,
cancelTask: cancelTaskMock,
getAgentCard: getAgentCardMock,
} as unknown as Client;
const mockAgentCard: Partial<AgentCard> = { name: 'TestAgent' };
beforeEach(() => {
vi.clearAllMocks();
A2AClientManager.resetInstanceForTesting();
manager = A2AClientManager.getInstance();
// Re-create the instances as plain objects that can be spied on
const factoryInstance = {
createFromUrl: vi.fn(),
createFromAgentCard: vi.fn(),
};
const resolverInstance = {
resolve: vi.fn(),
};
vi.mocked(ClientFactory).mockReturnValue(
factoryInstance as unknown as ClientFactory,
);
vi.mocked(DefaultAgentCardResolver).mockReturnValue(
resolverInstance as unknown as DefaultAgentCardResolver,
);
vi.spyOn(factoryInstance, 'createFromUrl').mockResolvedValue(
mockClient as unknown as Client,
);
vi.spyOn(factoryInstance, 'createFromAgentCard').mockResolvedValue(
mockClient as unknown as Client,
);
vi.spyOn(resolverInstance, 'resolve').mockResolvedValue({
// Default mock implementations
getAgentCardMock.mockResolvedValue({
...mockAgentCard,
url: 'http://test.agent/real/endpoint',
} as AgentCard);
vi.spyOn(ClientFactoryOptions, 'createFrom').mockImplementation(
(_defaults, overrides) => overrides as unknown as ClientFactoryOptions,
vi.mocked(ClientFactory.prototype.createFromUrl).mockResolvedValue(
mockClient,
);
vi.mocked(createAuthenticatingFetchWithRetry).mockImplementation(() =>
authFetchMock.mockResolvedValue({
ok: true,
json: async () => ({}),
} as Response),
vi.mocked(DefaultAgentCardResolver.prototype.resolve).mockResolvedValue({
...mockAgentCard,
url: 'http://test.agent/real/endpoint',
} as AgentCard);
vi.mocked(ClientFactoryOptions.createFrom).mockImplementation(
(_defaults, overrides) => overrides as ClientFactoryOptions,
);
vi.mocked(createAuthenticatingFetchWithRetry).mockReturnValue(
authFetchMock,
);
vi.stubGlobal(
@@ -130,70 +117,21 @@ describe('A2AClientManager', () => {
expect(instance1).toBe(instance2);
});
describe('getInstance / dispatcher initialization', () => {
it('should use UndiciAgent when no proxy is configured', async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
const resolverOptions = vi.mocked(DefaultAgentCardResolver).mock
.calls[0][0];
const cardFetch = resolverOptions?.fetchImpl as typeof fetch;
await cardFetch('http://test.agent/card');
const fetchCall = vi
.mocked(fetch)
.mock.calls.find((call) => call[0] === 'http://test.agent/card');
expect(fetchCall).toBeDefined();
expect(
(fetchCall![1] as { dispatcher?: unknown })?.dispatcher,
).toBeInstanceOf(UndiciAgent);
expect(
(fetchCall![1] as { dispatcher?: unknown })?.dispatcher,
).not.toBeInstanceOf(ProxyAgent);
});
it('should use ProxyAgent when a proxy is configured via Config', async () => {
A2AClientManager.resetInstanceForTesting();
const mockConfig = {
getProxy: () => 'http://my-proxy:8080',
} as Config;
manager = A2AClientManager.getInstance(mockConfig);
await manager.loadAgent('TestProxyAgent', 'http://test.proxy.agent/card');
const resolverOptions = vi.mocked(DefaultAgentCardResolver).mock
.calls[0][0];
const cardFetch = resolverOptions?.fetchImpl as typeof fetch;
await cardFetch('http://test.proxy.agent/card');
const fetchCall = vi
.mocked(fetch)
.mock.calls.find((call) => call[0] === 'http://test.proxy.agent/card');
expect(fetchCall).toBeDefined();
expect(
(fetchCall![1] as { dispatcher?: unknown })?.dispatcher,
).toBeInstanceOf(ProxyAgent);
});
});
describe('loadAgent', () => {
it('should create and cache an A2AClient', async () => {
const agentCard = await manager.loadAgent(
'TestAgent',
'http://test.agent/card',
);
expect(agentCard).toMatchObject(mockAgentCard);
expect(manager.getAgentCard('TestAgent')).toBe(agentCard);
expect(manager.getClient('TestAgent')).toBeDefined();
});
it('should configure ClientFactory with REST, JSON-RPC, and gRPC transports', async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
expect(ClientFactoryOptions.createFrom).toHaveBeenCalled();
});
it('should throw an error if an agent with the same name is already loaded', async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
await expect(
manager.loadAgent('TestAgent', 'http://test.agent/card'),
manager.loadAgent('TestAgent', 'http://another.agent/card'),
).rejects.toThrow("Agent with name 'TestAgent' is already loaded.");
});
@@ -208,12 +146,20 @@ describe('A2AClientManager', () => {
shouldRetryWithHeaders: vi.fn(),
};
await manager.loadAgent(
'TestAgent',
'http://test.agent/card',
'CustomAuthAgent',
'http://custom.agent/card',
customAuthHandler as unknown as AuthenticationHandler,
);
expect(createAuthenticatingFetchWithRetry).toHaveBeenCalledWith(
expect.anything(),
customAuthHandler,
);
// Card resolver should NOT use the authenticated fetch by default.
const resolverInstance = vi.mocked(DefaultAgentCardResolver).mock
.instances[0];
expect(resolverInstance).toBeDefined();
const resolverOptions = vi.mocked(DefaultAgentCardResolver).mock
.calls[0][0];
expect(resolverOptions?.fetchImpl).not.toBe(authFetchMock);
@@ -274,163 +220,106 @@ describe('A2AClientManager', () => {
it('should log a debug message upon loading an agent', async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
expect(debugLogger.debug).toHaveBeenCalledWith(
expect.stringContaining("Loaded agent 'TestAgent'"),
"[A2AClientManager] Loaded agent 'TestAgent' from http://test.agent/card",
);
});
it('should clear the cache', async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
expect(manager.getAgentCard('TestAgent')).toBeDefined();
expect(manager.getClient('TestAgent')).toBeDefined();
manager.clearCache();
expect(manager.getAgentCard('TestAgent')).toBeUndefined();
expect(manager.getClient('TestAgent')).toBeUndefined();
});
it('should throw if resolveAgentCard fails', async () => {
const resolverInstance = {
resolve: vi.fn().mockRejectedValue(new Error('Resolution failed')),
};
vi.mocked(DefaultAgentCardResolver).mockReturnValue(
resolverInstance as unknown as DefaultAgentCardResolver,
expect(debugLogger.debug).toHaveBeenCalledWith(
'[A2AClientManager] Cache cleared.',
);
await expect(
manager.loadAgent('FailAgent', 'http://fail.agent'),
).rejects.toThrow('Resolution failed');
});
it('should throw if factory.createFromAgentCard fails', async () => {
const factoryInstance = {
createFromAgentCard: vi
.fn()
.mockRejectedValue(new Error('Factory failed')),
};
vi.mocked(ClientFactory).mockReturnValue(
factoryInstance as unknown as ClientFactory,
);
await expect(
manager.loadAgent('FailAgent', 'http://fail.agent'),
).rejects.toThrow('Factory failed');
});
});
describe('getAgentCard and getClient', () => {
it('should return undefined if agent is not found', () => {
expect(manager.getAgentCard('Unknown')).toBeUndefined();
expect(manager.getClient('Unknown')).toBeUndefined();
});
});
describe('sendMessageStream', () => {
beforeEach(async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
await manager.loadAgent('TestAgent', 'http://test.agent');
});
it('should send a message and return a stream', async () => {
mockClient.sendMessageStream.mockReturnValue(
const mockResult = {
kind: 'message',
messageId: 'a',
parts: [],
role: 'agent',
} as SendMessageResult;
sendMessageStreamMock.mockReturnValue(
(async function* () {
yield { kind: 'message' };
yield mockResult;
})(),
);
const stream = manager.sendMessageStream('TestAgent', 'Hello');
const results = [];
for await (const result of stream) {
results.push(result);
for await (const res of stream) {
results.push(res);
}
expect(results).toHaveLength(1);
expect(mockClient.sendMessageStream).toHaveBeenCalled();
});
it('should use contextId and taskId when provided', async () => {
mockClient.sendMessageStream.mockReturnValue(
(async function* () {
yield { kind: 'message' };
})(),
);
const stream = manager.sendMessageStream('TestAgent', 'Hello', {
contextId: 'ctx123',
taskId: 'task456',
});
// trigger execution
for await (const _ of stream) {
break;
}
expect(mockClient.sendMessageStream).toHaveBeenCalledWith(
expect(results).toEqual([mockResult]);
expect(sendMessageStreamMock).toHaveBeenCalledWith(
expect.objectContaining({
message: expect.objectContaining({
contextId: 'ctx123',
taskId: 'task456',
}),
message: expect.anything(),
}),
expect.any(Object),
);
});
it('should correctly propagate AbortSignal to the stream', async () => {
mockClient.sendMessageStream.mockReturnValue(
it('should use contextId and taskId when provided', async () => {
sendMessageStreamMock.mockReturnValue(
(async function* () {
yield { kind: 'message' };
yield {
kind: 'message',
messageId: 'a',
parts: [],
role: 'agent',
} as SendMessageResult;
})(),
);
const controller = new AbortController();
const expectedContextId = 'user-context-id';
const expectedTaskId = 'user-task-id';
const stream = manager.sendMessageStream('TestAgent', 'Hello', {
signal: controller.signal,
contextId: expectedContextId,
taskId: expectedTaskId,
});
// trigger execution
for await (const _ of stream) {
break;
// consume stream
}
expect(mockClient.sendMessageStream).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ signal: controller.signal }),
);
const call = sendMessageStreamMock.mock.calls[0][0];
expect(call.message.contextId).toBe(expectedContextId);
expect(call.message.taskId).toBe(expectedTaskId);
});
it('should handle a multi-chunk stream with different event types', async () => {
mockClient.sendMessageStream.mockReturnValue(
(async function* () {
yield { kind: 'message', messageId: 'm1' };
yield { kind: 'status-update', taskId: 't1' };
})(),
);
const stream = manager.sendMessageStream('TestAgent', 'Hello');
const results = [];
for await (const result of stream) {
results.push(result);
}
expect(results).toHaveLength(2);
expect(results[0].kind).toBe('message');
expect(results[1].kind).toBe('status-update');
});
it('should throw prefixed error on failure', async () => {
mockClient.sendMessageStream.mockImplementation(() => {
throw new Error('Network failure');
it('should propagate the original error on failure', async () => {
sendMessageStreamMock.mockImplementationOnce(() => {
throw new Error('Network error');
});
const stream = manager.sendMessageStream('TestAgent', 'Hello');
await expect(async () => {
for await (const _ of stream) {
// empty
// consume
}
}).rejects.toThrow(
'[A2AClientManager] sendMessageStream Error [TestAgent]: Network failure',
);
}).rejects.toThrow('Network error');
});
it('should throw an error if the agent is not found', async () => {
const stream = manager.sendMessageStream('NonExistentAgent', 'Hello');
await expect(async () => {
for await (const _ of stream) {
// empty
// consume
}
}).rejects.toThrow("Agent 'NonExistentAgent' not found.");
});
@@ -438,23 +327,28 @@ describe('A2AClientManager', () => {
describe('getTask', () => {
beforeEach(async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
await manager.loadAgent('TestAgent', 'http://test.agent');
});
it('should get a task from the correct agent', async () => {
const mockTask = { id: 'task123', kind: 'task' };
mockClient.getTask.mockResolvedValue(mockTask);
getTaskMock.mockResolvedValue({
id: 'task123',
contextId: 'a',
kind: 'task',
status: { state: 'completed' },
} as Task);
const result = await manager.getTask('TestAgent', 'task123');
expect(result).toBe(mockTask);
expect(mockClient.getTask).toHaveBeenCalledWith({ id: 'task123' });
await manager.getTask('TestAgent', 'task123');
expect(getTaskMock).toHaveBeenCalledWith({
id: 'task123',
});
});
it('should throw prefixed error on failure', async () => {
mockClient.getTask.mockRejectedValue(new Error('Not found'));
getTaskMock.mockRejectedValueOnce(new Error('Network error'));
await expect(manager.getTask('TestAgent', 'task123')).rejects.toThrow(
'A2AClient getTask Error [TestAgent]: Not found',
'A2AClient getTask Error [TestAgent]: Network error',
);
});
@@ -467,23 +361,28 @@ describe('A2AClientManager', () => {
describe('cancelTask', () => {
beforeEach(async () => {
await manager.loadAgent('TestAgent', 'http://test.agent/card');
await manager.loadAgent('TestAgent', 'http://test.agent');
});
it('should cancel a task on the correct agent', async () => {
const mockTask = { id: 'task123', kind: 'task' };
mockClient.cancelTask.mockResolvedValue(mockTask);
cancelTaskMock.mockResolvedValue({
id: 'task123',
contextId: 'a',
kind: 'task',
status: { state: 'canceled' },
} as Task);
const result = await manager.cancelTask('TestAgent', 'task123');
expect(result).toBe(mockTask);
expect(mockClient.cancelTask).toHaveBeenCalledWith({ id: 'task123' });
await manager.cancelTask('TestAgent', 'task123');
expect(cancelTaskMock).toHaveBeenCalledWith({
id: 'task123',
});
});
it('should throw prefixed error on failure', async () => {
mockClient.cancelTask.mockRejectedValue(new Error('Cannot cancel'));
cancelTaskMock.mockRejectedValueOnce(new Error('Network error'));
await expect(manager.cancelTask('TestAgent', 'task123')).rejects.toThrow(
'A2AClient cancelTask Error [TestAgent]: Cannot cancel',
'A2AClient cancelTask Error [TestAgent]: Network error',
);
});
+43 -80
View File
@@ -12,41 +12,45 @@ import type {
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
} from '@a2a-js/sdk';
import type { AuthenticationHandler, Client } from '@a2a-js/sdk/client';
import {
type Client,
ClientFactory,
ClientFactoryOptions,
DefaultAgentCardResolver,
JsonRpcTransportFactory,
RestTransportFactory,
JsonRpcTransportFactory,
type AuthenticationHandler,
createAuthenticatingFetchWithRetry,
} from '@a2a-js/sdk/client';
import { GrpcTransportFactory } from '@a2a-js/sdk/client/grpc';
import * as grpc from '@grpc/grpc-js';
import { v4 as uuidv4 } from 'uuid';
import { Agent as UndiciAgent, ProxyAgent } from 'undici';
import { normalizeAgentCard } from './a2aUtils.js';
import type { Config } from '../config/config.js';
import { Agent as UndiciAgent } from 'undici';
import { debugLogger } from '../utils/debugLogger.js';
import { safeLookup } from '../utils/fetch.js';
import { classifyAgentError } from './a2a-errors.js';
/**
* Result of sending a message, which can be a full message, a task,
* or an incremental status/artifact update.
*/
// Remote agents can take 10+ minutes (e.g. Deep Research).
// Use a dedicated dispatcher so the global 5-min timeout isn't affected.
const A2A_TIMEOUT = 1800000; // 30 minutes
const a2aDispatcher = new UndiciAgent({
headersTimeout: A2A_TIMEOUT,
bodyTimeout: A2A_TIMEOUT,
connect: {
lookup: safeLookup, // SSRF protection at connection level
},
});
const a2aFetch: typeof fetch = (input, init) =>
// eslint-disable-next-line no-restricted-syntax -- TODO: Migrate to safeFetch for SSRF protection
fetch(input, { ...init, dispatcher: a2aDispatcher } as RequestInit);
export type SendMessageResult =
| Message
| Task
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent;
// Remote agents can take 10+ minutes (e.g. Deep Research).
// Use a dedicated dispatcher so the global 5-min timeout isn't affected.
const A2A_TIMEOUT = 1800000; // 30 minutes
/**
* Orchestrates communication with remote A2A agents.
* Manages protocol negotiation, authentication, and transport selection.
* Manages A2A clients and caches loaded agent information.
* Follows a singleton pattern to ensure a single client instance.
*/
export class A2AClientManager {
private static instance: A2AClientManager;
@@ -55,35 +59,14 @@ export class A2AClientManager {
private clients = new Map<string, Client>();
private agentCards = new Map<string, AgentCard>();
private a2aDispatcher: UndiciAgent | ProxyAgent;
private a2aFetch: typeof fetch;
private constructor(config?: Config) {
const proxyUrl = config?.getProxy();
const agentOptions = {
headersTimeout: A2A_TIMEOUT,
bodyTimeout: A2A_TIMEOUT,
};
if (proxyUrl) {
this.a2aDispatcher = new ProxyAgent({
uri: proxyUrl,
...agentOptions,
});
} else {
this.a2aDispatcher = new UndiciAgent(agentOptions);
}
this.a2aFetch = (input, init) =>
fetch(input, { ...init, dispatcher: this.a2aDispatcher } as RequestInit);
}
private constructor() {}
/**
* Gets the singleton instance of the A2AClientManager.
*/
static getInstance(config?: Config): A2AClientManager {
static getInstance(): A2AClientManager {
if (!A2AClientManager.instance) {
A2AClientManager.instance = new A2AClientManager(config);
A2AClientManager.instance = new A2AClientManager();
}
return A2AClientManager.instance;
}
@@ -114,12 +97,9 @@ export class A2AClientManager {
}
// Authenticated fetch for API calls (transports).
let authFetch: typeof fetch = this.a2aFetch;
let authFetch: typeof fetch = a2aFetch;
if (authHandler) {
authFetch = createAuthenticatingFetchWithRetry(
this.a2aFetch,
authHandler,
);
authFetch = createAuthenticatingFetchWithRetry(a2aFetch, authHandler);
}
// Use unauthenticated fetch for the agent card unless explicitly required.
@@ -129,7 +109,7 @@ export class A2AClientManager {
init?: RequestInit,
): Promise<Response> => {
// Try without auth first
const response = await this.a2aFetch(input, init);
const response = await a2aFetch(input, init);
// Retry with auth if we hit a 401/403
if ((response.status === 401 || response.status === 403) && authFetch) {
@@ -140,35 +120,22 @@ export class A2AClientManager {
};
const resolver = new DefaultAgentCardResolver({ fetchImpl: cardFetch });
const rawCard = await resolver.resolve(agentCardUrl, '');
// TODO: Remove normalizeAgentCard once @a2a-js/sdk handles
// proto field name aliases (supportedInterfaces → additionalInterfaces,
// protocolBinding → transport).
const agentCard = normalizeAgentCard(rawCard);
const grpcUrl =
agentCard.additionalInterfaces?.find((i) => i.transport === 'GRPC')
?.url ?? agentCard.url;
const clientOptions = ClientFactoryOptions.createFrom(
const options = ClientFactoryOptions.createFrom(
ClientFactoryOptions.default,
{
transports: [
new RestTransportFactory({ fetchImpl: authFetch }),
new JsonRpcTransportFactory({ fetchImpl: authFetch }),
new GrpcTransportFactory({
grpcChannelCredentials: grpcUrl.startsWith('https://')
? grpc.credentials.createSsl()
: grpc.credentials.createInsecure(),
}),
],
cardResolver: resolver,
},
);
try {
const factory = new ClientFactory(clientOptions);
const client = await factory.createFromAgentCard(agentCard);
const factory = new ClientFactory(options);
const client = await factory.createFromUrl(agentCardUrl, '');
const agentCard = await client.getAgentCard();
this.clients.set(name, client);
this.agentCards.set(name, agentCard);
@@ -206,7 +173,9 @@ export class A2AClientManager {
options?: { contextId?: string; taskId?: string; signal?: AbortSignal },
): AsyncIterable<SendMessageResult> {
const client = this.clients.get(agentName);
if (!client) throw new Error(`Agent '${agentName}' not found.`);
if (!client) {
throw new Error(`Agent '${agentName}' not found.`);
}
const messageParams: MessageSendParams = {
message: {
@@ -219,19 +188,9 @@ export class A2AClientManager {
},
};
try {
yield* client.sendMessageStream(messageParams, {
signal: options?.signal,
});
} catch (error: unknown) {
const prefix = `[A2AClientManager] sendMessageStream Error [${agentName}]`;
if (error instanceof Error) {
throw new Error(`${prefix}: ${error.message}`, { cause: error });
}
throw new Error(
`${prefix}: Unexpected error during sendMessageStream: ${String(error)}`,
);
}
yield* client.sendMessageStream(messageParams, {
signal: options?.signal,
});
}
/**
@@ -260,7 +219,9 @@ export class A2AClientManager {
*/
async getTask(agentName: string, taskId: string): Promise<Task> {
const client = this.clients.get(agentName);
if (!client) throw new Error(`Agent '${agentName}' not found.`);
if (!client) {
throw new Error(`Agent '${agentName}' not found.`);
}
try {
return await client.getTask({ id: taskId });
} catch (error: unknown) {
@@ -280,7 +241,9 @@ export class A2AClientManager {
*/
async cancelTask(agentName: string, taskId: string): Promise<Task> {
const client = this.clients.get(agentName);
if (!client) throw new Error(`Agent '${agentName}' not found.`);
if (!client) {
throw new Error(`Agent '${agentName}' not found.`);
}
try {
return await client.cancelTask({ id: taskId });
} catch (error: unknown) {
+171 -20
View File
@@ -12,6 +12,9 @@ import {
A2AResultReassembler,
AUTH_REQUIRED_MSG,
normalizeAgentCard,
getGrpcCredentials,
pinUrlToIp,
splitAgentCardUrl,
} from './a2aUtils.js';
import type { SendMessageResult } from './a2a-client-manager.js';
import type {
@@ -23,6 +26,12 @@ import type {
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
} from '@a2a-js/sdk';
import * as dnsPromises from 'node:dns/promises';
import type { LookupAddress } from 'node:dns';
vi.mock('node:dns/promises', () => ({
lookup: vi.fn(),
}));
describe('a2aUtils', () => {
beforeEach(() => {
@@ -33,6 +42,89 @@ describe('a2aUtils', () => {
vi.restoreAllMocks();
});
describe('getGrpcCredentials', () => {
it('should return secure credentials for https', () => {
const credentials = getGrpcCredentials('https://test.agent');
expect(credentials).toBeDefined();
});
it('should return insecure credentials for http', () => {
const credentials = getGrpcCredentials('http://test.agent');
expect(credentials).toBeDefined();
});
});
describe('pinUrlToIp', () => {
it('should resolve and pin hostname to IP', async () => {
vi.mocked(
dnsPromises.lookup as unknown as (
hostname: string,
options: { all: true },
) => Promise<LookupAddress[]>,
).mockResolvedValue([{ address: '93.184.216.34', family: 4 }]);
const { pinnedUrl, hostname } = await pinUrlToIp(
'http://example.com:9000',
'test-agent',
);
expect(hostname).toBe('example.com');
expect(pinnedUrl).toBe('http://93.184.216.34:9000/');
});
it('should handle raw host:port strings (standard for gRPC)', async () => {
vi.mocked(
dnsPromises.lookup as unknown as (
hostname: string,
options: { all: true },
) => Promise<LookupAddress[]>,
).mockResolvedValue([{ address: '93.184.216.34', family: 4 }]);
const { pinnedUrl, hostname } = await pinUrlToIp(
'example.com:9000',
'test-agent',
);
expect(hostname).toBe('example.com');
expect(pinnedUrl).toBe('93.184.216.34:9000');
});
it('should throw error if resolution fails (fail closed)', async () => {
vi.mocked(dnsPromises.lookup).mockRejectedValue(new Error('DNS Error'));
await expect(
pinUrlToIp('http://unreachable.com', 'test-agent'),
).rejects.toThrow("Failed to resolve host for agent 'test-agent'");
});
it('should throw error if resolved to private IP', async () => {
vi.mocked(
dnsPromises.lookup as unknown as (
hostname: string,
options: { all: true },
) => Promise<LookupAddress[]>,
).mockResolvedValue([{ address: '10.0.0.1', family: 4 }]);
await expect(
pinUrlToIp('http://malicious.com', 'test-agent'),
).rejects.toThrow('resolves to private IP range');
});
it('should allow localhost/127.0.0.1/::1 exceptions', async () => {
vi.mocked(
dnsPromises.lookup as unknown as (
hostname: string,
options: { all: true },
) => Promise<LookupAddress[]>,
).mockResolvedValue([{ address: '127.0.0.1', family: 4 }]);
const { pinnedUrl, hostname } = await pinUrlToIp(
'http://localhost:9000',
'test-agent',
);
expect(hostname).toBe('localhost');
expect(pinnedUrl).toBe('http://127.0.0.1:9000/');
});
});
describe('isTerminalState', () => {
it('should return true for completed, failed, canceled, and rejected', () => {
expect(isTerminalState('completed')).toBe(true);
@@ -273,12 +365,12 @@ describe('a2aUtils', () => {
expect(normalized.name).toBe('my-agent');
// @ts-expect-error - testing dynamic preservation
expect(normalized.customField).toBe('keep-me');
expect(normalized.description).toBeUndefined();
expect(normalized.skills).toBeUndefined();
expect(normalized.defaultInputModes).toBeUndefined();
expect(normalized.description).toBe('');
expect(normalized.skills).toEqual([]);
expect(normalized.defaultInputModes).toEqual([]);
});
it('should map supportedInterfaces to additionalInterfaces with protocolBinding → transport', () => {
it('should normalize and synchronize interfaces while preserving other fields', () => {
const raw = {
name: 'test',
supportedInterfaces: [
@@ -292,7 +384,13 @@ describe('a2aUtils', () => {
const normalized = normalizeAgentCard(raw);
// Should exist in both fields
expect(normalized.additionalInterfaces).toHaveLength(1);
expect(
(normalized as unknown as Record<string, unknown>)[
'supportedInterfaces'
],
).toHaveLength(1);
const intf = normalized.additionalInterfaces?.[0] as unknown as Record<
string,
@@ -301,18 +399,43 @@ describe('a2aUtils', () => {
expect(intf['transport']).toBe('GRPC');
expect(intf['url']).toBe('grpc://test');
// Should fallback top-level url
expect(normalized.url).toBe('grpc://test');
});
it('should not overwrite additionalInterfaces if already present', () => {
it('should preserve existing top-level url if present', () => {
const raw = {
name: 'test',
additionalInterfaces: [{ url: 'http://grpc', transport: 'GRPC' }],
url: 'http://existing',
supportedInterfaces: [{ url: 'http://other', transport: 'REST' }],
};
const normalized = normalizeAgentCard(raw);
expect(normalized.additionalInterfaces).toHaveLength(1);
expect(normalized.additionalInterfaces?.[0].url).toBe('http://grpc');
expect(normalized.url).toBe('http://existing');
});
it('should NOT prepend http:// scheme to raw IP:port strings for gRPC interfaces', () => {
const raw = {
name: 'raw-ip-grpc',
supportedInterfaces: [{ url: '127.0.0.1:9000', transport: 'GRPC' }],
};
const normalized = normalizeAgentCard(raw);
expect(normalized.additionalInterfaces?.[0].url).toBe('127.0.0.1:9000');
expect(normalized.url).toBe('127.0.0.1:9000');
});
it('should prepend http:// scheme to raw IP:port strings for REST interfaces', () => {
const raw = {
name: 'raw-ip-rest',
supportedInterfaces: [{ url: '127.0.0.1:8080', transport: 'REST' }],
};
const normalized = normalizeAgentCard(raw);
expect(normalized.additionalInterfaces?.[0].url).toBe(
'http://127.0.0.1:8080',
);
});
it('should NOT override existing transport if protocolBinding is also present', () => {
@@ -325,20 +448,48 @@ describe('a2aUtils', () => {
const normalized = normalizeAgentCard(raw);
expect(normalized.additionalInterfaces?.[0].transport).toBe('GRPC');
});
});
it('should not mutate the original card object', () => {
const raw = {
name: 'test',
supportedInterfaces: [{ url: 'grpc://test', protocolBinding: 'GRPC' }],
};
describe('splitAgentCardUrl', () => {
const standard = '.well-known/agent-card.json';
const normalized = normalizeAgentCard(raw);
expect(normalized).not.toBe(raw);
expect(normalized.additionalInterfaces).toBeDefined();
// Original should not have additionalInterfaces added
expect(
(raw as Record<string, unknown>)['additionalInterfaces'],
).toBeUndefined();
it('should return baseUrl as-is if it does not end with standard path', () => {
const url = 'http://localhost:9001/custom/path';
expect(splitAgentCardUrl(url)).toEqual({ baseUrl: url });
});
it('should split correctly if URL ends with standard path', () => {
const url = `http://localhost:9001/${standard}`;
expect(splitAgentCardUrl(url)).toEqual({
baseUrl: 'http://localhost:9001/',
path: undefined,
});
});
it('should handle trailing slash in baseUrl when splitting', () => {
const url = `http://example.com/api/${standard}`;
expect(splitAgentCardUrl(url)).toEqual({
baseUrl: 'http://example.com/api/',
path: undefined,
});
});
it('should ignore hashes and query params when splitting', () => {
const url = `http://localhost:9001/${standard}?foo=bar#baz`;
expect(splitAgentCardUrl(url)).toEqual({
baseUrl: 'http://localhost:9001/',
path: undefined,
});
});
it('should return original URL if parsing fails', () => {
const url = 'not-a-url';
expect(splitAgentCardUrl(url)).toEqual({ baseUrl: url });
});
it('should handle standard path appearing earlier in the path', () => {
const url = `http://localhost:9001/${standard}/something-else`;
expect(splitAgentCardUrl(url)).toEqual({ baseUrl: url });
});
});
+234 -24
View File
@@ -4,6 +4,9 @@
* SPDX-License-Identifier: Apache-2.0
*/
import * as grpc from '@grpc/grpc-js';
import { lookup } from 'node:dns/promises';
import { z } from 'zod';
import type {
Message,
Part,
@@ -15,10 +18,37 @@ import type {
AgentCard,
AgentInterface,
} from '@a2a-js/sdk';
import { isAddressPrivate } from '../utils/fetch.js';
import type { SendMessageResult } from './a2a-client-manager.js';
export const AUTH_REQUIRED_MSG = `[Authorization Required] The agent has indicated it requires authorization to proceed. Please follow the agent's instructions.`;
const AgentInterfaceSchema = z
.object({
url: z.string().default(''),
transport: z.string().optional(),
protocolBinding: z.string().optional(),
})
.passthrough();
const AgentCardSchema = z
.object({
name: z.string().default('unknown'),
description: z.string().default(''),
url: z.string().default(''),
version: z.string().default(''),
protocolVersion: z.string().default(''),
capabilities: z.record(z.unknown()).default({}),
skills: z.array(z.union([z.string(), z.record(z.unknown())])).default([]),
defaultInputModes: z.array(z.string()).default([]),
defaultOutputModes: z.array(z.string()).default([]),
additionalInterfaces: z.array(AgentInterfaceSchema).optional(),
supportedInterfaces: z.array(AgentInterfaceSchema).optional(),
preferredTransport: z.string().optional(),
})
.passthrough();
/**
* Reassembles incremental A2A streaming updates into a coherent result.
* Shows sequential status/messages followed by all reassembled artifacts.
@@ -211,45 +241,166 @@ function extractPartText(part: Part): string {
}
/**
* Normalizes proto field name aliases that the SDK doesn't handle yet.
* The A2A proto spec uses `supported_interfaces` and `protocol_binding`,
* while the SDK expects `additionalInterfaces` and `transport`.
* TODO: Remove once @a2a-js/sdk handles these aliases natively.
* Normalizes an agent card by ensuring it has the required properties
* and resolving any inconsistencies between protocol versions.
*/
export function normalizeAgentCard(card: unknown): AgentCard {
if (!isObject(card)) {
throw new Error('Agent card is missing.');
}
// Shallow-copy to avoid mutating the SDK's cached object.
// Use Zod to validate and parse the card, ensuring safe defaults and narrowing types.
const parsed = AgentCardSchema.parse(card);
// Narrowing to AgentCard interface after runtime validation.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const result = { ...card } as unknown as AgentCard;
const result = parsed as unknown as AgentCard;
// Map supportedInterfaces → additionalInterfaces if needed
if (!result.additionalInterfaces) {
const raw = card;
if (Array.isArray(raw['supportedInterfaces'])) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
result.additionalInterfaces = raw[
'supportedInterfaces'
] as AgentInterface[];
}
// Normalize interfaces and synchronize both interface fields.
const normalizedInterfaces = extractNormalizedInterfaces(parsed);
result.additionalInterfaces = normalizedInterfaces;
// Sync supportedInterfaces for backward compatibility.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const legacyResult = result as unknown as Record<string, AgentInterface[]>;
legacyResult['supportedInterfaces'] = normalizedInterfaces;
// Fallback preferredTransport: If not specified, default to GRPC if available.
if (
!result.preferredTransport &&
normalizedInterfaces.some((i) => i.transport === 'GRPC')
) {
result.preferredTransport = 'GRPC';
}
// Map protocolBinding → transport on each interface
for (const intf of result.additionalInterfaces ?? []) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const raw = intf as unknown as Record<string, unknown>;
const binding = raw['protocolBinding'];
if (!intf.transport && typeof binding === 'string') {
intf.transport = binding;
}
// Fallback: If top-level URL is missing, use the first interface's URL.
if (result.url === '' && normalizedInterfaces.length > 0) {
result.url = normalizedInterfaces[0].url;
}
return result;
}
/**
* Returns gRPC channel credentials based on the URL scheme.
*/
export function getGrpcCredentials(url: string): grpc.ChannelCredentials {
return url.startsWith('https://')
? grpc.credentials.createSsl()
: grpc.credentials.createInsecure();
}
/**
* Returns gRPC channel options to ensure SSL/authority matches the original hostname
* when connecting via a pinned IP address.
*/
export function getGrpcChannelOptions(
hostname: string,
): Record<string, unknown> {
return {
'grpc.default_authority': hostname,
'grpc.ssl_target_name_override': hostname,
};
}
/**
* Resolves a hostname to its IP address and validates it against SSRF.
* Returns the pinned IP-based URL and the original hostname.
*/
export async function pinUrlToIp(
url: string,
agentName: string,
): Promise<{ pinnedUrl: string; hostname: string }> {
if (!url) return { pinnedUrl: url, hostname: '' };
// gRPC URLs in A2A can be 'host:port' or 'dns:///host:port' or have schemes.
// We normalize to host:port for resolution.
const hasScheme = url.includes('://');
const normalizedUrl = hasScheme ? url : `http://${url}`;
try {
const parsed = new URL(normalizedUrl);
const hostname = parsed.hostname;
const sanitizedHost =
hostname.startsWith('[') && hostname.endsWith(']')
? hostname.slice(1, -1)
: hostname;
// Resolve DNS to check the actual target IP and pin it
const addresses = await lookup(hostname, { all: true });
const publicAddresses = addresses.filter(
(addr) =>
!isAddressPrivate(addr.address) ||
sanitizedHost === 'localhost' ||
sanitizedHost === '127.0.0.1' ||
sanitizedHost === '::1',
);
if (publicAddresses.length === 0) {
if (addresses.length > 0) {
throw new Error(
`Refusing to load agent '${agentName}': transport URL '${url}' resolves to private IP range.`,
);
}
throw new Error(
`Failed to resolve any public IP addresses for host: ${hostname}`,
);
}
const pinnedIp = publicAddresses[0].address;
const pinnedHostname = pinnedIp.includes(':') ? `[${pinnedIp}]` : pinnedIp;
// Reconstruct URL with IP
parsed.hostname = pinnedHostname;
let pinnedUrl = parsed.toString();
// If original didn't have scheme, remove it (standard for gRPC targets)
if (!hasScheme) {
pinnedUrl = pinnedUrl.replace(/^http:\/\//, '');
// URL.toString() might append a trailing slash
if (pinnedUrl.endsWith('/') && !url.endsWith('/')) {
pinnedUrl = pinnedUrl.slice(0, -1);
}
}
return { pinnedUrl, hostname };
} catch (e) {
if (e instanceof Error && e.message.includes('Refusing')) throw e;
throw new Error(`Failed to resolve host for agent '${agentName}': ${url}`, {
cause: e,
});
}
}
/**
* Splts an agent card URL into a baseUrl and a standard path if it already
* contains '.well-known/agent-card.json'.
*/
export function splitAgentCardUrl(url: string): {
baseUrl: string;
path?: string;
} {
const standardPath = '.well-known/agent-card.json';
try {
const parsedUrl = new URL(url);
if (parsedUrl.pathname.endsWith(standardPath)) {
// Reconstruct baseUrl from parsed components to avoid issues with hashes or query params.
parsedUrl.pathname = parsedUrl.pathname.substring(
0,
parsedUrl.pathname.lastIndexOf(standardPath),
);
parsedUrl.search = '';
parsedUrl.hash = '';
// We return undefined for path if it's the standard one,
// because the SDK's DefaultAgentCardResolver appends it automatically.
return { baseUrl: parsedUrl.toString(), path: undefined };
}
} catch (_e) {
// Ignore URL parsing errors here, let the resolver handle them.
}
return { baseUrl: url };
}
/**
* Extracts contextId and taskId from a Message, Task, or Update response.
* Follows the pattern from the A2A CLI sample to maintain conversational continuity.
@@ -295,6 +446,65 @@ export function extractIdsFromResponse(result: SendMessageResult): {
return { contextId, taskId, clearTaskId };
}
/**
* Extracts and normalizes interfaces from the card, handling protocol version fallbacks.
* Preserves all original fields to maintain SDK compatibility.
*/
function extractNormalizedInterfaces(
card: Record<string, unknown>,
): AgentInterface[] {
const rawInterfaces =
getArray(card, 'additionalInterfaces') ||
getArray(card, 'supportedInterfaces');
if (!rawInterfaces) {
return [];
}
const mapped: AgentInterface[] = [];
for (const i of rawInterfaces) {
if (isObject(i)) {
// Use schema to validate interface object.
const parsed = AgentInterfaceSchema.parse(i);
// Narrowing to AgentInterface after runtime validation.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const normalized = parsed as unknown as AgentInterface & {
protocolBinding?: string;
};
// Normalize 'transport' from 'protocolBinding' if missing.
if (!normalized.transport && normalized.protocolBinding) {
normalized.transport = normalized.protocolBinding;
}
// Robust URL: Ensure the URL has a scheme (except for gRPC).
if (
normalized.url &&
!normalized.url.includes('://') &&
!normalized.url.startsWith('/') &&
normalized.transport !== 'GRPC'
) {
// Default to http:// for insecure REST/JSON-RPC if scheme is missing.
normalized.url = `http://${normalized.url}`;
}
mapped.push(normalized as AgentInterface);
}
}
return mapped;
}
/**
* Safely extracts an array property from an object.
*/
function getArray(
obj: Record<string, unknown>,
key: string,
): unknown[] | undefined {
const val = obj[key];
return Array.isArray(val) ? val : undefined;
}
// Type Guards
function isTextPart(part: Part): part is TextPart {
@@ -28,10 +28,10 @@ describe('agent-scheduler', () => {
mockMessageBus = {} as Mocked<MessageBus>;
mockToolRegistry = {
getTool: vi.fn(),
messageBus: mockMessageBus,
getMessageBus: vi.fn().mockReturnValue(mockMessageBus),
} as unknown as Mocked<ToolRegistry>;
mockConfig = {
messageBus: mockMessageBus,
getMessageBus: vi.fn().mockReturnValue(mockMessageBus),
toolRegistry: mockToolRegistry,
} as unknown as Mocked<Config>;
(mockConfig as unknown as { messageBus: MessageBus }).messageBus =
@@ -42,7 +42,7 @@ describe('agent-scheduler', () => {
it('should create a scheduler with agent-specific config', async () => {
const mockConfig = {
messageBus: mockMessageBus,
getMessageBus: vi.fn().mockReturnValue(mockMessageBus),
toolRegistry: mockToolRegistry,
} as unknown as Mocked<Config>;
@@ -87,11 +87,11 @@ describe('agent-scheduler', () => {
const mainRegistry = { _id: 'main' } as unknown as Mocked<ToolRegistry>;
const agentRegistry = {
_id: 'agent',
messageBus: mockMessageBus,
getMessageBus: vi.fn().mockReturnValue(mockMessageBus),
} as unknown as Mocked<ToolRegistry>;
const config = {
messageBus: mockMessageBus,
getMessageBus: vi.fn().mockReturnValue(mockMessageBus),
} as unknown as Mocked<Config>;
Object.defineProperty(config, 'toolRegistry', {
get: () => mainRegistry,
+2 -2
View File
@@ -60,7 +60,7 @@ export async function scheduleAgentTools(
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const agentConfig: Config = Object.create(config);
agentConfig.getToolRegistry = () => toolRegistry;
agentConfig.getMessageBus = () => toolRegistry.messageBus;
agentConfig.getMessageBus = () => toolRegistry.getMessageBus();
// Override toolRegistry property so AgentLoopContext reads the agent-specific registry.
Object.defineProperty(agentConfig, 'toolRegistry', {
get: () => toolRegistry,
@@ -69,7 +69,7 @@ export async function scheduleAgentTools(
const scheduler = new Scheduler({
context: agentConfig,
messageBus: toolRegistry.messageBus,
messageBus: toolRegistry.getMessageBus(),
getPreferredEditor: getPreferredEditor ?? (() => undefined),
schedulerId,
subagent,
+5 -25
View File
@@ -44,7 +44,7 @@ interface FrontmatterLocalAgentDefinition
* Authentication configuration for remote agents in frontmatter format.
*/
interface FrontmatterAuthConfig {
type: 'apiKey' | 'http' | 'google-credentials' | 'oauth2';
type: 'apiKey' | 'http' | 'oauth2';
// API Key
key?: string;
name?: string;
@@ -54,11 +54,10 @@ interface FrontmatterAuthConfig {
username?: string;
password?: string;
value?: string;
// Google Credentials
scopes?: string[];
// OAuth2
client_id?: string;
client_secret?: string;
scopes?: string[];
authorization_url?: string;
token_url?: string;
}
@@ -108,11 +107,9 @@ const localAgentSchema = z
display_name: z.string().optional(),
tools: z
.array(
z
.string()
.refine((val) => isValidToolName(val, { allowWildcards: true }), {
message: 'Invalid tool name',
}),
z.string().refine((val) => isValidToolName(val), {
message: 'Invalid tool name',
}),
)
.optional(),
model: z.string().optional(),
@@ -153,15 +150,6 @@ const httpAuthSchema = z.object({
value: z.string().min(1).optional(),
});
/**
* Google Credentials auth schema.
*/
const googleCredentialsAuthSchema = z.object({
...baseAuthFields,
type: z.literal('google-credentials'),
scopes: z.array(z.string()).optional(),
});
/**
* OAuth2 auth schema.
* authorization_url and token_url can be discovered from the agent card if omitted.
@@ -180,7 +168,6 @@ const authConfigSchema = z
.discriminatedUnion('type', [
apiKeyAuthSchema,
httpAuthSchema,
googleCredentialsAuthSchema,
oauth2AuthSchema,
])
.superRefine((data, ctx) => {
@@ -380,13 +367,6 @@ function convertFrontmatterAuthToConfig(
name: frontmatter.name,
};
case 'google-credentials':
return {
...base,
type: 'google-credentials',
scopes: frontmatter.scopes,
};
case 'http': {
if (!frontmatter.scheme) {
throw new Error(
@@ -12,15 +12,12 @@ import type {
} from './types.js';
import { ApiKeyAuthProvider } from './api-key-provider.js';
import { HttpAuthProvider } from './http-provider.js';
import { GoogleCredentialsAuthProvider } from './google-credentials-provider.js';
export interface CreateAuthProviderOptions {
/** Required for OAuth/OIDC token storage. */
agentName?: string;
authConfig?: A2AAuthConfig;
agentCard?: AgentCard;
/** Required by some providers (like google-credentials) to determine token audience. */
targetUrl?: string;
/** URL to fetch the agent card from, used for OAuth2 URL discovery. */
agentCardUrl?: string;
}
@@ -46,14 +43,9 @@ export class A2AAuthProviderFactory {
}
switch (authConfig.type) {
case 'google-credentials': {
const provider = new GoogleCredentialsAuthProvider(
authConfig,
options.targetUrl,
);
await provider.initialize();
return provider;
}
case 'google-credentials':
// TODO: Implement
throw new Error('google-credentials auth provider not yet implemented');
case 'apiKey': {
const provider = new ApiKeyAuthProvider(authConfig);
@@ -1,205 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import { GoogleCredentialsAuthProvider } from './google-credentials-provider.js';
import type { GoogleCredentialsAuthConfig } from './types.js';
import { GoogleAuth } from 'google-auth-library';
import { OAuthUtils } from '../../mcp/oauth-utils.js';
// Mock the external dependencies
vi.mock('google-auth-library', () => ({
GoogleAuth: vi.fn(),
}));
describe('GoogleCredentialsAuthProvider', () => {
const mockConfig: GoogleCredentialsAuthConfig = {
type: 'google-credentials',
};
let mockGetClient: Mock;
let mockGetAccessToken: Mock;
let mockGetIdTokenClient: Mock;
let mockFetchIdToken: Mock;
beforeEach(() => {
vi.clearAllMocks();
mockGetAccessToken = vi
.fn()
.mockResolvedValue({ token: 'mock-access-token' });
mockGetClient = vi.fn().mockResolvedValue({
getAccessToken: mockGetAccessToken,
credentials: { expiry_date: Date.now() + 3600 * 1000 },
});
mockFetchIdToken = vi.fn().mockResolvedValue('mock-id-token');
mockGetIdTokenClient = vi.fn().mockResolvedValue({
idTokenProvider: {
fetchIdToken: mockFetchIdToken,
},
});
(GoogleAuth as unknown as Mock).mockImplementation(() => ({
getClient: mockGetClient,
getIdTokenClient: mockGetIdTokenClient,
}));
});
describe('Initialization', () => {
it('throws if no targetUrl is provided', () => {
expect(() => new GoogleCredentialsAuthProvider(mockConfig)).toThrow(
/targetUrl must be provided/,
);
});
it('throws if targetHost is not allowed', () => {
expect(
() =>
new GoogleCredentialsAuthProvider(mockConfig, 'https://example.com'),
).toThrow(/is not an allowed host/);
});
it('initializes seamlessly with .googleapis.com', () => {
expect(
() =>
new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com/v1/models',
),
).not.toThrow();
});
it('initializes seamlessly with .run.app', () => {
expect(
() =>
new GoogleCredentialsAuthProvider(
mockConfig,
'https://my-cloud-run-service.run.app',
),
).not.toThrow();
});
});
describe('Token Fetching', () => {
it('fetches an access token for googleapis.com endpoint', async () => {
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com',
);
const headers = await provider.headers();
expect(headers).toEqual({ Authorization: 'Bearer mock-access-token' });
expect(mockGetClient).toHaveBeenCalled();
expect(mockGetAccessToken).toHaveBeenCalled();
expect(mockGetIdTokenClient).not.toHaveBeenCalled();
});
it('fetches an identity token for run.app endpoint', async () => {
// Mock OAuthUtils.parseTokenExpiry to avoid Base64 decoding issues in tests
vi.spyOn(OAuthUtils, 'parseTokenExpiry').mockReturnValue(
Date.now() + 1000000,
);
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://my-service.run.app/some-path',
);
const headers = await provider.headers();
expect(headers).toEqual({ Authorization: 'Bearer mock-id-token' });
expect(mockGetIdTokenClient).toHaveBeenCalledWith('my-service.run.app');
expect(mockFetchIdToken).toHaveBeenCalledWith('my-service.run.app');
expect(mockGetClient).not.toHaveBeenCalled();
});
it('returns cached access token on subsequent calls', async () => {
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com',
);
await provider.headers();
await provider.headers();
// Should only call getClient/getAccessToken once due to caching
expect(mockGetClient).toHaveBeenCalledTimes(1);
expect(mockGetAccessToken).toHaveBeenCalledTimes(1);
});
it('returns cached id token on subsequent calls', async () => {
vi.spyOn(OAuthUtils, 'parseTokenExpiry').mockReturnValue(
Date.now() + 1000000,
);
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://my-service.run.app',
);
await provider.headers();
await provider.headers();
expect(mockGetIdTokenClient).toHaveBeenCalledTimes(1);
expect(mockFetchIdToken).toHaveBeenCalledTimes(1);
});
it('re-fetches access token on 401 (shouldRetryWithHeaders)', async () => {
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com',
);
// Prime the cache
await provider.headers();
expect(mockGetAccessToken).toHaveBeenCalledTimes(1);
const req = {} as RequestInit;
const res = { status: 401 } as Response;
const retryHeaders = await provider.shouldRetryWithHeaders(req, res);
expect(retryHeaders).toEqual({
Authorization: 'Bearer mock-access-token',
});
// Cache was cleared, so getAccessToken was called again
expect(mockGetAccessToken).toHaveBeenCalledTimes(2);
});
it('re-fetches token on 403', async () => {
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com',
);
const req = {} as RequestInit;
const res = { status: 403 } as Response;
const retryHeaders = await provider.shouldRetryWithHeaders(req, res);
expect(retryHeaders).toEqual({
Authorization: 'Bearer mock-access-token',
});
});
it('stops retrying after MAX_AUTH_RETRIES', async () => {
const provider = new GoogleCredentialsAuthProvider(
mockConfig,
'https://language.googleapis.com',
);
const req = {} as RequestInit;
const res = { status: 401 } as Response;
// First two retries should succeed (MAX_AUTH_RETRIES = 2)
expect(await provider.shouldRetryWithHeaders(req, res)).toBeDefined();
expect(await provider.shouldRetryWithHeaders(req, res)).toBeDefined();
// Third should return undefined (exhausted)
expect(await provider.shouldRetryWithHeaders(req, res)).toBeUndefined();
});
});
});
@@ -1,161 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { HttpHeaders } from '@a2a-js/sdk/client';
import { BaseA2AAuthProvider } from './base-provider.js';
import type { GoogleCredentialsAuthConfig } from './types.js';
import { GoogleAuth } from 'google-auth-library';
import { debugLogger } from '../../utils/debugLogger.js';
import { OAuthUtils, FIVE_MIN_BUFFER_MS } from '../../mcp/oauth-utils.js';
const CLOUD_RUN_HOST_REGEX = /^(.*\.)?run\.app$/;
const ALLOWED_HOSTS = [/^.+\.googleapis\.com$/, CLOUD_RUN_HOST_REGEX];
/**
* Authentication provider for Google ADC (Application Default Credentials).
* Automatically decides whether to use identity tokens or access tokens
* based on the target endpoint URL.
*/
export class GoogleCredentialsAuthProvider extends BaseA2AAuthProvider {
readonly type = 'google-credentials' as const;
private readonly auth: GoogleAuth;
private readonly useIdToken: boolean = false;
private readonly audience?: string;
private cachedToken?: string;
private tokenExpiryTime?: number;
constructor(
private readonly config: GoogleCredentialsAuthConfig,
targetUrl?: string,
) {
super();
if (!targetUrl) {
throw new Error(
'targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.',
);
}
const hostname = new URL(targetUrl).hostname;
const isRunAppHost = CLOUD_RUN_HOST_REGEX.test(hostname);
if (isRunAppHost) {
this.useIdToken = true;
}
this.audience = hostname;
if (
!this.useIdToken &&
!ALLOWED_HOSTS.some((pattern) => pattern.test(hostname))
) {
throw new Error(
`Host "${hostname}" is not an allowed host for Google Credential provider.`,
);
}
// A2A spec requires scopes if configured, otherwise use default cloud-platform
const scopes =
this.config.scopes && this.config.scopes.length > 0
? this.config.scopes
: ['https://www.googleapis.com/auth/cloud-platform'];
this.auth = new GoogleAuth({
scopes,
});
}
override async initialize(): Promise<void> {
// We can pre-fetch or validate if necessary here,
// but deferred fetching is usually better for auth tokens.
}
async headers(): Promise<HttpHeaders> {
// Check cache
if (
this.cachedToken &&
this.tokenExpiryTime &&
Date.now() < this.tokenExpiryTime - FIVE_MIN_BUFFER_MS
) {
return { Authorization: `Bearer ${this.cachedToken}` };
}
// Clear expired cache
this.cachedToken = undefined;
this.tokenExpiryTime = undefined;
if (this.useIdToken) {
try {
const idClient = await this.auth.getIdTokenClient(this.audience!);
const idToken = await idClient.idTokenProvider.fetchIdToken(
this.audience!,
);
const expiryTime = OAuthUtils.parseTokenExpiry(idToken);
if (expiryTime) {
this.tokenExpiryTime = expiryTime;
this.cachedToken = idToken;
}
return { Authorization: `Bearer ${idToken}` };
} catch (e) {
const errorMessage = `Failed to get ADC ID token: ${
e instanceof Error ? e.message : String(e)
}`;
debugLogger.error(errorMessage, e);
throw new Error(errorMessage);
}
}
// Otherwise, access token
try {
const client = await this.auth.getClient();
const token = await client.getAccessToken();
if (token.token) {
this.cachedToken = token.token;
// Use expiry_date from the underlying credentials if available.
const creds = client.credentials;
if (creds.expiry_date) {
this.tokenExpiryTime = creds.expiry_date;
}
return { Authorization: `Bearer ${token.token}` };
}
throw new Error('Failed to retrieve ADC access token.');
} catch (e) {
const errorMessage = `Failed to get ADC access token: ${
e instanceof Error ? e.message : String(e)
}`;
debugLogger.error(errorMessage, e);
throw new Error(errorMessage);
}
}
override async shouldRetryWithHeaders(
_req: RequestInit,
res: Response,
): Promise<HttpHeaders | undefined> {
if (res.status !== 401 && res.status !== 403) {
this.authRetryCount = 0;
return undefined;
}
if (this.authRetryCount >= BaseA2AAuthProvider.MAX_AUTH_RETRIES) {
return undefined;
}
this.authRetryCount++;
debugLogger.debug(
'[GoogleCredentialsAuthProvider] Re-fetching token after auth failure',
);
// Clear cache to force a re-fetch
this.cachedToken = undefined;
this.tokenExpiryTime = undefined;
return this.headers();
}
}
@@ -109,7 +109,7 @@ export const BrowserAgentDefinition = (
): LocalAgentDefinition<typeof BrowserTaskResultSchema> => {
// Use Preview Flash model if the main model is any of the preview models.
// If the main model is not a preview model, use the default flash model.
const model = isPreviewModel(config.getModel(), config)
const model = isPreviewModel(config.getModel())
? PREVIEW_GEMINI_FLASH_MODEL
: DEFAULT_GEMINI_FLASH_MODEL;
@@ -28,7 +28,6 @@ import {
import { createMcpDeclarativeTools } from './mcpToolWrapper.js';
import { createAnalyzeScreenshotTool } from './analyzeScreenshot.js';
import { injectAutomationOverlay } from './automationOverlay.js';
import { injectInputBlocker } from './inputBlocker.js';
import { debugLogger } from '../../utils/debugLogger.js';
/**
@@ -63,30 +62,18 @@ export async function createBrowserAgentDefinition(
printOutput('Browser connected with isolated MCP client.');
}
// Determine if input blocker should be active (non-headless + enabled)
const shouldDisableInput = config.shouldDisableBrowserUserInput();
// Inject automation overlay and input blocker if not in headless mode
// Inject automation overlay if not in headless mode
const browserConfig = config.getBrowserAgentConfig();
if (!browserConfig?.customConfig?.headless) {
if (printOutput) {
printOutput('Injecting automation overlay...');
}
await injectAutomationOverlay(browserManager);
if (shouldDisableInput) {
if (printOutput) {
printOutput('Injecting input blocker...');
}
await injectInputBlocker(browserManager);
}
}
// Create declarative tools from dynamically discovered MCP tools
// These tools dispatch to browserManager's isolated client
const mcpTools = await createMcpDeclarativeTools(
browserManager,
messageBus,
shouldDisableInput,
);
const mcpTools = await createMcpDeclarativeTools(browserManager, messageBus);
const availableToolNames = mcpTools.map((t) => t.name);
// Validate required semantic tools are available
@@ -19,7 +19,6 @@ import {
vi.mock('../../utils/debugLogger.js', () => ({
debugLogger: {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
@@ -36,7 +36,6 @@ import {
createBrowserAgentDefinition,
cleanupBrowserAgent,
} from './browserAgentFactory.js';
import { removeInputBlocker } from './inputBlocker.js';
const INPUT_PREVIEW_MAX_LENGTH = 50;
const DESCRIPTION_MAX_LENGTH = 200;
@@ -491,7 +490,6 @@ ${displayResult}
} finally {
// Always cleanup browser resources
if (browserManager) {
await removeInputBlocker(browserManager);
await cleanupBrowserAgent(browserManager);
}
}
@@ -23,7 +23,6 @@ import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js';
import { debugLogger } from '../../utils/debugLogger.js';
import type { Config } from '../../config/config.js';
import { Storage } from '../../config/storage.js';
import { injectInputBlocker } from './inputBlocker.js';
import * as path from 'node:path';
import { injectAutomationOverlay } from './automationOverlay.js';
@@ -98,12 +97,10 @@ export class BrowserManager {
* Always false in headless mode (no visible window to decorate).
*/
private readonly shouldInjectOverlay: boolean;
private readonly shouldDisableInput: boolean;
constructor(private config: Config) {
const browserConfig = config.getBrowserAgentConfig();
this.shouldInjectOverlay = !browserConfig?.customConfig?.headless;
this.shouldDisableInput = config.shouldDisableBrowserUserInput();
}
/**
@@ -179,32 +176,20 @@ export class BrowserManager {
}
}
// Re-inject the automation overlay and input blocker after tools that
// can cause a full-page navigation. chrome-devtools-mcp emits no MCP
// notifications, so callTool() is the only interception point.
// Re-inject the automation overlay after any tool that can cause a
// full-page navigation (including implicit navigations from clicking links).
// chrome-devtools-mcp emits no MCP notifications, so callTool() is the
// only interception point we have — equivalent to a page-load listener.
if (
this.shouldInjectOverlay &&
!result.isError &&
POTENTIALLY_NAVIGATING_TOOLS.has(toolName) &&
!signal?.aborted
) {
try {
if (this.shouldInjectOverlay) {
await injectAutomationOverlay(this, signal);
}
// Only re-inject the input blocker for tools that *reliably*
// replace the page DOM (navigate_page, new_page, select_page).
// click/click_at are handled by pointer-events suspend/resume
// in mcpToolWrapper — no full re-inject roundtrip needed.
// press_key/handle_dialog only sometimes navigate.
const reliableNavigation =
toolName === 'navigate_page' ||
toolName === 'new_page' ||
toolName === 'select_page';
if (this.shouldDisableInput && reliableNavigation) {
await injectInputBlocker(this);
}
await injectAutomationOverlay(this, signal);
} catch {
// Never let overlay/blocker failures interrupt the tool result
// Never let overlay failures interrupt the tool result
}
}
@@ -390,7 +375,6 @@ export class BrowserManager {
await this.rawMcpClient!.connect(this.mcpTransport!);
debugLogger.log('MCP client connected to chrome-devtools-mcp');
await this.discoverTools();
this.registerInputBlockerHandler();
})(),
new Promise<never>((_, reject) => {
timeoutId = setTimeout(
@@ -501,45 +485,4 @@ export class BrowserManager {
this.discoveredTools.map((t) => t.name).join(', '),
);
}
/**
* Registers a fallback notification handler on the MCP client to
* automatically re-inject the input blocker after any server-side
* notification (e.g. page navigation, resource updates).
*
* This covers ALL navigation types (link clicks, form submissions,
* history navigation) not just explicit navigate_page tool calls.
*/
private registerInputBlockerHandler(): void {
if (!this.rawMcpClient) {
return;
}
if (!this.config.shouldDisableBrowserUserInput()) {
return;
}
const existingHandler = this.rawMcpClient.fallbackNotificationHandler;
this.rawMcpClient.fallbackNotificationHandler = async (notification: {
method: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params?: any;
}) => {
// Chain with any existing handler first.
if (existingHandler) {
await existingHandler(notification);
}
// Only re-inject on resource update notifications which indicate
// page content has changed (navigation, new page, etc.)
if (notification.method === 'notifications/resources/updated') {
debugLogger.log('Page content changed, re-injecting input blocker...');
void injectInputBlocker(this);
}
};
debugLogger.log(
'Registered global notification handler for input blocker re-injection',
);
}
}
@@ -1,113 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { injectInputBlocker, removeInputBlocker } from './inputBlocker.js';
import type { BrowserManager } from './browserManager.js';
describe('inputBlocker', () => {
let mockBrowserManager: BrowserManager;
beforeEach(() => {
mockBrowserManager = {
callTool: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Script ran on page and returned:' }],
}),
} as unknown as BrowserManager;
});
describe('injectInputBlocker', () => {
it('should call evaluate_script with correct function parameter', async () => {
await injectInputBlocker(mockBrowserManager);
expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
'evaluate_script',
{
function: expect.stringContaining('__gemini_input_blocker'),
},
);
});
it('should pass a function declaration, not an IIFE', async () => {
await injectInputBlocker(mockBrowserManager);
const call = vi.mocked(mockBrowserManager.callTool).mock.calls[0];
const args = call[1] as { function: string };
// Must start with "() =>" — chrome-devtools-mcp requires a function declaration
expect(args.function.trimStart()).toMatch(/^\(\)\s*=>/);
// Must NOT contain an IIFE invocation at the end
expect(args.function.trimEnd()).not.toMatch(/\}\)\(\)\s*;?\s*$/);
});
it('should use "function" parameter name, not "code"', async () => {
await injectInputBlocker(mockBrowserManager);
const call = vi.mocked(mockBrowserManager.callTool).mock.calls[0];
const args = call[1];
expect(args).toHaveProperty('function');
expect(args).not.toHaveProperty('code');
expect(args).not.toHaveProperty('expression');
});
it('should include the informational banner text', async () => {
await injectInputBlocker(mockBrowserManager);
const call = vi.mocked(mockBrowserManager.callTool).mock.calls[0];
const args = call[1] as { function: string };
expect(args.function).toContain('Gemini CLI is controlling this browser');
});
it('should set aria-hidden to prevent accessibility tree pollution', async () => {
await injectInputBlocker(mockBrowserManager);
const call = vi.mocked(mockBrowserManager.callTool).mock.calls[0];
const args = call[1] as { function: string };
expect(args.function).toContain('aria-hidden');
});
it('should not throw if script execution fails', async () => {
mockBrowserManager.callTool = vi
.fn()
.mockRejectedValue(new Error('Script failed'));
await expect(
injectInputBlocker(mockBrowserManager),
).resolves.toBeUndefined();
});
});
describe('removeInputBlocker', () => {
it('should call evaluate_script with function to remove blocker', async () => {
await removeInputBlocker(mockBrowserManager);
expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
'evaluate_script',
{
function: expect.stringContaining('__gemini_input_blocker'),
},
);
});
it('should use "function" parameter name for removal too', async () => {
await removeInputBlocker(mockBrowserManager);
const call = vi.mocked(mockBrowserManager.callTool).mock.calls[0];
const args = call[1];
expect(args).toHaveProperty('function');
expect(args).not.toHaveProperty('code');
});
it('should not throw if removal fails', async () => {
mockBrowserManager.callTool = vi
.fn()
.mockRejectedValue(new Error('Removal failed'));
await expect(
removeInputBlocker(mockBrowserManager),
).resolves.toBeUndefined();
});
});
});
@@ -1,271 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Input blocker utility for browser agent.
*
* Injects a transparent overlay that captures all user input events
* and displays an informational banner during automation.
*
* The overlay is PERSISTENT it stays in the DOM for the entire
* browser agent session. To allow CDP tool calls to interact with
* page elements, we temporarily set `pointer-events: none` on the
* overlay (via {@link suspendInputBlocker}) which makes it invisible
* to hit-testing / interactability checks without any DOM mutation
* or visual change. After the tool call, {@link resumeInputBlocker}
* restores `pointer-events: auto`.
*
* IMPORTANT: chrome-devtools-mcp's evaluate_script tool expects:
* { function: "() => { ... }" }
* It takes a function declaration string, NOT raw code.
* The parameter name is "function", not "code" or "expression".
*/
import type { BrowserManager } from './browserManager.js';
import { debugLogger } from '../../utils/debugLogger.js';
/**
* JavaScript function to inject the input blocker overlay.
* This blocks all user input events while allowing CDP commands to work normally.
*
* Must be a function declaration (NOT an IIFE) because evaluate_script
* evaluates it via Puppeteer's page.evaluate().
*/
const INPUT_BLOCKER_FUNCTION = `() => {
// If the blocker already exists, just ensure it's active and return.
// This makes re-injection after potentially-navigating tools near-free
// when the page didn't actually navigate (most clicks don't navigate).
var existing = document.getElementById('__gemini_input_blocker');
if (existing) {
existing.style.pointerEvents = 'auto';
return;
}
const blocker = document.createElement('div');
blocker.id = '__gemini_input_blocker';
blocker.setAttribute('aria-hidden', 'true');
blocker.setAttribute('role', 'presentation');
blocker.style.cssText = [
'position: fixed',
'inset: 0',
'z-index: 2147483646',
'cursor: not-allowed',
'background: transparent',
].join('; ');
// Block all input events on the overlay itself
var blockEvent = function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
};
var events = [
'click', 'mousedown', 'mouseup', 'keydown', 'keyup',
'keypress', 'touchstart', 'touchend', 'touchmove', 'wheel',
'contextmenu', 'dblclick', 'pointerdown', 'pointerup', 'pointermove',
];
for (var i = 0; i < events.length; i++) {
blocker.addEventListener(events[i], blockEvent, { capture: true });
}
// Capsule-shaped floating pill at bottom center
var pill = document.createElement('div');
pill.style.cssText = [
'position: fixed',
'bottom: 20px',
'left: 50%',
'transform: translateX(-50%) translateY(20px)',
'display: flex',
'align-items: center',
'gap: 10px',
'padding: 10px 20px',
'background: rgba(24, 24, 27, 0.88)',
'color: #fff',
'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
'font-size: 13px',
'line-height: 1',
'border-radius: 999px',
'z-index: 2147483647',
'backdrop-filter: blur(16px)',
'-webkit-backdrop-filter: blur(16px)',
'border: 1px solid rgba(255, 255, 255, 0.08)',
'box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.05)',
'opacity: 0',
'transition: opacity 0.4s ease, transform 0.4s ease',
'white-space: nowrap',
'user-select: none',
'pointer-events: none',
].join('; ');
// Pulsing red dot
var dot = document.createElement('span');
dot.style.cssText = [
'width: 10px',
'height: 10px',
'border-radius: 50%',
'background: #ef4444',
'display: inline-block',
'flex-shrink: 0',
'box-shadow: 0 0 6px rgba(239, 68, 68, 0.6)',
'animation: __gemini_pulse 2s ease-in-out infinite',
].join('; ');
// Labels
var label = document.createElement('span');
label.style.cssText = 'font-weight: 600; letter-spacing: 0.01em;';
label.textContent = 'Gemini CLI is controlling this browser';
var sep = document.createElement('span');
sep.style.cssText = 'width: 1px; height: 14px; background: rgba(255,255,255,0.2); flex-shrink: 0;';
var sub = document.createElement('span');
sub.style.cssText = 'color: rgba(255,255,255,0.55); font-size: 12px;';
sub.textContent = 'Input disabled during automation';
pill.appendChild(dot);
pill.appendChild(label);
pill.appendChild(sep);
pill.appendChild(sub);
// Inject @keyframes for the pulse animation
var styleEl = document.createElement('style');
styleEl.id = '__gemini_input_blocker_style';
styleEl.textContent = '@keyframes __gemini_pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(0.85); } }';
document.head.appendChild(styleEl);
blocker.appendChild(pill);
var target = document.body || document.documentElement;
if (target) {
target.appendChild(blocker);
// Trigger entrance animation
requestAnimationFrame(function() {
pill.style.opacity = '1';
pill.style.transform = 'translateX(-50%) translateY(0)';
});
}
}`;
/**
* JavaScript function to remove the input blocker overlay entirely.
* Used only during final cleanup.
*/
const REMOVE_BLOCKER_FUNCTION = `() => {
var blocker = document.getElementById('__gemini_input_blocker');
if (blocker) {
blocker.remove();
}
var style = document.getElementById('__gemini_input_blocker_style');
if (style) {
style.remove();
}
}`;
/**
* JavaScript to temporarily suspend the input blocker by setting
* pointer-events to 'none'. This makes the overlay invisible to
* hit-testing so chrome-devtools-mcp's interactability checks pass
* and CDP clicks fall through to page elements.
*
* The overlay DOM element stays in place no visual change, no flickering.
*/
const SUSPEND_BLOCKER_FUNCTION = `() => {
var blocker = document.getElementById('__gemini_input_blocker');
if (blocker) {
blocker.style.pointerEvents = 'none';
}
}`;
/**
* JavaScript to resume the input blocker by restoring pointer-events
* to 'auto'. User clicks are blocked again.
*/
const RESUME_BLOCKER_FUNCTION = `() => {
var blocker = document.getElementById('__gemini_input_blocker');
if (blocker) {
blocker.style.pointerEvents = 'auto';
}
}`;
/**
* Injects the input blocker overlay into the current page.
*
* @param browserManager The browser manager to use for script execution
* @returns Promise that resolves when the blocker is injected
*/
export async function injectInputBlocker(
browserManager: BrowserManager,
): Promise<void> {
try {
await browserManager.callTool('evaluate_script', {
function: INPUT_BLOCKER_FUNCTION,
});
debugLogger.log('Input blocker injected successfully');
} catch (error) {
// Log but don't throw - input blocker is a UX enhancement, not critical functionality
debugLogger.warn(
'Failed to inject input blocker: ' +
(error instanceof Error ? error.message : String(error)),
);
}
}
/**
* Removes the input blocker overlay from the current page entirely.
* Used only during final cleanup.
*
* @param browserManager The browser manager to use for script execution
* @returns Promise that resolves when the blocker is removed
*/
export async function removeInputBlocker(
browserManager: BrowserManager,
): Promise<void> {
try {
await browserManager.callTool('evaluate_script', {
function: REMOVE_BLOCKER_FUNCTION,
});
debugLogger.log('Input blocker removed successfully');
} catch (error) {
// Log but don't throw - removal failure is not critical
debugLogger.warn(
'Failed to remove input blocker: ' +
(error instanceof Error ? error.message : String(error)),
);
}
}
/**
* Temporarily suspends the input blocker so CDP tool calls can
* interact with page elements. The overlay stays in the DOM
* (no visual change) only pointer-events is toggled.
*/
export async function suspendInputBlocker(
browserManager: BrowserManager,
): Promise<void> {
try {
await browserManager.callTool('evaluate_script', {
function: SUSPEND_BLOCKER_FUNCTION,
});
} catch {
// Non-critical — tool call will still attempt to proceed
}
}
/**
* Resumes the input blocker after a tool call completes.
* Restores pointer-events so user clicks are blocked again.
*/
export async function resumeInputBlocker(
browserManager: BrowserManager,
): Promise<void> {
try {
await browserManager.callTool('evaluate_script', {
function: RESUME_BLOCKER_FUNCTION,
});
} catch {
// Non-critical
}
}
@@ -193,104 +193,4 @@ describe('mcpToolWrapper', () => {
expect(result.error?.message).toBe('Connection lost');
});
});
describe('Input blocker suspend/resume', () => {
it('should suspend and resume input blocker around click (interactive tool)', async () => {
const tools = await createMcpDeclarativeTools(
mockBrowserManager,
mockMessageBus,
true, // shouldDisableInput
);
const clickTool = tools.find((t) => t.name === 'click')!;
const invocation = clickTool.build({ uid: 'elem-42' });
await invocation.execute(new AbortController().signal);
// callTool: suspend blocker + click + resume blocker
expect(mockBrowserManager.callTool).toHaveBeenCalledTimes(3);
// First call: suspend blocker (pointer-events: none)
expect(mockBrowserManager.callTool).toHaveBeenNthCalledWith(
1,
'evaluate_script',
expect.objectContaining({
function: expect.stringContaining('__gemini_input_blocker'),
}),
);
// Second call: click
expect(mockBrowserManager.callTool).toHaveBeenNthCalledWith(
2,
'click',
{ uid: 'elem-42' },
expect.any(AbortSignal),
);
// Third call: resume blocker (pointer-events: auto)
expect(mockBrowserManager.callTool).toHaveBeenNthCalledWith(
3,
'evaluate_script',
expect.objectContaining({
function: expect.stringContaining('__gemini_input_blocker'),
}),
);
});
it('should NOT suspend/resume for take_snapshot (read-only tool)', async () => {
const tools = await createMcpDeclarativeTools(
mockBrowserManager,
mockMessageBus,
true, // shouldDisableInput
);
const snapshotTool = tools.find((t) => t.name === 'take_snapshot')!;
const invocation = snapshotTool.build({});
await invocation.execute(new AbortController().signal);
// callTool should only be called once for take_snapshot — no suspend/resume
expect(mockBrowserManager.callTool).toHaveBeenCalledTimes(1);
expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
'take_snapshot',
{},
expect.any(AbortSignal),
);
});
it('should NOT suspend/resume when shouldDisableInput is false', async () => {
const tools = await createMcpDeclarativeTools(
mockBrowserManager,
mockMessageBus,
false, // shouldDisableInput disabled
);
const clickTool = tools.find((t) => t.name === 'click')!;
const invocation = clickTool.build({ uid: 'elem-42' });
await invocation.execute(new AbortController().signal);
// callTool should only be called once for click — no suspend/resume
expect(mockBrowserManager.callTool).toHaveBeenCalledTimes(1);
});
it('should resume blocker even when interactive tool fails', async () => {
vi.mocked(mockBrowserManager.callTool)
.mockResolvedValueOnce({ content: [] }) // suspend blocker succeeds
.mockRejectedValueOnce(new Error('Click failed')) // tool fails
.mockResolvedValueOnce({ content: [] }); // resume succeeds
const tools = await createMcpDeclarativeTools(
mockBrowserManager,
mockMessageBus,
true, // shouldDisableInput
);
const clickTool = tools.find((t) => t.name === 'click')!;
const invocation = clickTool.build({ uid: 'bad-elem' });
const result = await invocation.execute(new AbortController().signal);
// Should return error, not throw
expect(result.error).toBeDefined();
// Should still try to resume
expect(mockBrowserManager.callTool).toHaveBeenCalledTimes(3);
});
});
});
@@ -30,23 +30,6 @@ import {
import type { MessageBus } from '../../confirmation-bus/message-bus.js';
import type { BrowserManager, McpToolCallResult } from './browserManager.js';
import { debugLogger } from '../../utils/debugLogger.js';
import { suspendInputBlocker, resumeInputBlocker } from './inputBlocker.js';
/**
* Tools that interact with page elements and require the input blocker
* overlay to be temporarily SUSPENDED (pointer-events: none) so
* chrome-devtools-mcp's interactability checks pass. The overlay
* stays in the DOM only the CSS property toggles, zero flickering.
*/
const INTERACTIVE_TOOLS = new Set([
'click',
'click_at',
'fill',
'fill_form',
'hover',
'drag',
'upload_file',
]);
/**
* Tool invocation that dispatches to BrowserManager's isolated MCP client.
@@ -60,7 +43,6 @@ class McpToolInvocation extends BaseToolInvocation<
protected readonly toolName: string,
params: Record<string, unknown>,
messageBus: MessageBus,
private readonly shouldDisableInput: boolean,
) {
super(params, messageBus, toolName, toolName);
}
@@ -96,29 +78,16 @@ class McpToolInvocation extends BaseToolInvocation<
};
}
/**
* Whether this specific tool needs the input blocker suspended
* (pointer-events toggled to 'none') before execution.
*/
private get needsBlockerSuspend(): boolean {
return this.shouldDisableInput && INTERACTIVE_TOOLS.has(this.toolName);
}
async execute(signal: AbortSignal): Promise<ToolResult> {
try {
// Suspend the input blocker for interactive tools so
// chrome-devtools-mcp's interactability checks pass.
// Only toggles pointer-events CSS — no DOM change, no flicker.
if (this.needsBlockerSuspend) {
await suspendInputBlocker(this.browserManager);
}
const result: McpToolCallResult = await this.browserManager.callTool(
const callToolPromise = this.browserManager.callTool(
this.toolName,
this.params,
signal,
);
const result: McpToolCallResult = await callToolPromise;
// Extract text content from MCP response
let textContent = '';
if (result.content && Array.isArray(result.content)) {
@@ -134,11 +103,6 @@ class McpToolInvocation extends BaseToolInvocation<
textContent,
);
// Resume input blocker after interactive tool completes.
if (this.needsBlockerSuspend) {
await resumeInputBlocker(this.browserManager);
}
if (result.isError) {
return {
llmContent: `Error: ${processedContent}`,
@@ -160,11 +124,6 @@ class McpToolInvocation extends BaseToolInvocation<
throw error;
}
// Resume on error path too so the blocker is always restored
if (this.needsBlockerSuspend) {
await resumeInputBlocker(this.browserManager).catch(() => {});
}
debugLogger.error(`MCP tool ${this.toolName} failed: ${errorMsg}`);
return {
llmContent: `Error: ${errorMsg}`,
@@ -326,7 +285,6 @@ class McpDeclarativeTool extends DeclarativeTool<
description: string,
parameterSchema: unknown,
messageBus: MessageBus,
private readonly shouldDisableInput: boolean,
) {
super(
name,
@@ -348,7 +306,6 @@ class McpDeclarativeTool extends DeclarativeTool<
this.name,
params,
this.messageBus,
this.shouldDisableInput,
);
}
}
@@ -428,14 +385,12 @@ class TypeTextDeclarativeTool extends DeclarativeTool<
export async function createMcpDeclarativeTools(
browserManager: BrowserManager,
messageBus: MessageBus,
shouldDisableInput: boolean = false,
): Promise<Array<McpDeclarativeTool | TypeTextDeclarativeTool>> {
// Get dynamically discovered tools from the MCP server
const mcpTools = await browserManager.getDiscoveredTools();
debugLogger.log(
`Creating ${mcpTools.length} declarative tools for browser agent` +
(shouldDisableInput ? ' (input blocker enabled)' : ''),
`Creating ${mcpTools.length} declarative tools for browser agent`,
);
const tools: Array<McpDeclarativeTool | TypeTextDeclarativeTool> =
@@ -452,7 +407,6 @@ export async function createMcpDeclarativeTools(
augmentedDescription,
schema.parametersJsonSchema,
messageBus,
shouldDisableInput,
);
});
+3 -3
View File
@@ -7,8 +7,8 @@
import type { AgentDefinition } from './types.js';
import { GEMINI_MODEL_ALIAS_FLASH } from '../config/models.js';
import { z } from 'zod';
import type { Config } from '../config/config.js';
import { GetInternalDocsTool } from '../tools/get-internal-docs.js';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
const CliHelpReportSchema = z.object({
answer: z
@@ -24,7 +24,7 @@ const CliHelpReportSchema = z.object({
* using its own documentation and runtime state.
*/
export const CliHelpAgent = (
context: AgentLoopContext,
config: Config,
): AgentDefinition<typeof CliHelpReportSchema> => ({
name: 'cli_help',
kind: 'local',
@@ -69,7 +69,7 @@ export const CliHelpAgent = (
},
toolConfig: {
tools: [new GetInternalDocsTool(context.messageBus)],
tools: [new GetInternalDocsTool(config.getMessageBus())],
},
promptConfig: {
@@ -22,19 +22,9 @@ describe('GeneralistAgent', () => {
it('should create a valid generalist agent definition', () => {
const config = makeFakeConfig();
const mockToolRegistry = {
vi.spyOn(config, 'getToolRegistry').mockReturnValue({
getAllToolNames: () => ['tool1', 'tool2', 'agent-tool'],
} as unknown as ToolRegistry;
vi.spyOn(config, 'getToolRegistry').mockReturnValue(mockToolRegistry);
Object.defineProperty(config, 'toolRegistry', {
get: () => mockToolRegistry,
});
Object.defineProperty(config, 'config', {
get() {
return this;
},
});
} as unknown as ToolRegistry);
vi.spyOn(config, 'getAgentRegistry').mockReturnValue({
getDirectoryContext: () => 'mock directory context',
getAllAgentNames: () => ['agent-tool'],
+4 -4
View File
@@ -5,7 +5,7 @@
*/
import { z } from 'zod';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import type { Config } from '../config/config.js';
import { getCoreSystemPrompt } from '../core/prompts.js';
import type { LocalAgentDefinition } from './types.js';
@@ -18,7 +18,7 @@ const GeneralistAgentSchema = z.object({
* It uses the same core system prompt as the main agent but in a non-interactive mode.
*/
export const GeneralistAgent = (
context: AgentLoopContext,
config: Config,
): LocalAgentDefinition<typeof GeneralistAgentSchema> => ({
kind: 'local',
name: 'generalist',
@@ -46,7 +46,7 @@ export const GeneralistAgent = (
model: 'inherit',
},
get toolConfig() {
const tools = context.toolRegistry.getAllToolNames();
const tools = config.getToolRegistry().getAllToolNames();
return {
tools,
};
@@ -54,7 +54,7 @@ export const GeneralistAgent = (
get promptConfig() {
return {
systemPrompt: getCoreSystemPrompt(
context.config,
config,
/*useMemory=*/ undefined,
/*interactiveOverride=*/ false,
),
+6 -365
View File
@@ -33,7 +33,6 @@ import {
type PartListUnion,
type Tool,
type CallableTool,
type FunctionDeclaration,
} from '@google/genai';
import type { Config } from '../config/config.js';
import { MockTool } from '../test-utils/mock-tool.js';
@@ -313,9 +312,12 @@ describe('LocalAgentExecutor', () => {
get: () => 'test-prompt-id',
configurable: true,
});
parentToolRegistry = new ToolRegistry(mockConfig, mockConfig.messageBus);
parentToolRegistry = new ToolRegistry(
mockConfig,
mockConfig.getMessageBus(),
);
parentToolRegistry.registerTool(
new LSTool(mockConfig, mockConfig.messageBus),
new LSTool(mockConfig, mockConfig.getMessageBus()),
);
parentToolRegistry.registerTool(
new MockTool({ name: READ_FILE_TOOL_NAME }),
@@ -521,7 +523,7 @@ describe('LocalAgentExecutor', () => {
toolName,
'description',
{},
mockConfig.messageBus,
mockConfig.getMessageBus(),
);
// Mock getTool to return our real DiscoveredMCPTool instance
@@ -558,34 +560,6 @@ describe('LocalAgentExecutor', () => {
getToolSpy.mockRestore();
});
it('should not duplicate schemas when instantiated tools are provided in toolConfig', async () => {
// Create an instantiated mock tool
const instantiatedTool = new MockTool({ name: 'instantiated_tool' });
// Create an agent definition containing the instantiated tool
const definition = createTestDefinition([instantiatedTool]);
// Create the executor
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
// Extract the prepared tools list using the private method
const toolsList = (
executor as unknown as { prepareToolsList: () => FunctionDeclaration[] }
).prepareToolsList();
// Filter for the specific tool schema
const foundSchemas = (
toolsList as unknown as FunctionDeclaration[]
).filter((t: FunctionDeclaration) => t.name === 'instantiated_tool');
// Assert that there is exactly ONE schema for this tool
expect(foundSchemas).toHaveLength(1);
});
});
describe('run (Execution Loop and Logic)', () => {
@@ -2492,337 +2466,4 @@ describe('LocalAgentExecutor', () => {
expect(mockSetHistory).toHaveBeenCalledWith(compressedHistory);
});
});
describe('DeclarativeTool instance tools (browser agent pattern)', () => {
/**
* The browser agent passes DeclarativeTool instances (not string names) in
* toolConfig.tools. These tests ensure that prepareToolsList() and
* create() handle that pattern correctly in particular, that each tool
* appears exactly once in the function declarations sent to the model.
*/
/**
* Helper that creates a definition using MockTool *instances* in
* toolConfig.tools the same pattern the browser agent uses.
*/
const createInstanceToolDefinition = (
instanceTools: MockTool[],
outputConfigMode: 'default' | 'none' = 'default',
): LocalAgentDefinition => {
const outputConfig =
outputConfigMode === 'default'
? {
outputName: 'finalResult',
description: 'The final result.',
schema: z.string(),
}
: undefined;
return {
kind: 'local',
name: 'BrowserLikeAgent',
description: 'An agent using instance tools.',
inputConfig: {
inputSchema: {
type: 'object',
properties: {
goal: { type: 'string', description: 'goal' },
},
required: ['goal'],
},
},
modelConfig: {
model: 'gemini-test-model',
generateContentConfig: { temperature: 0, topP: 1 },
},
runConfig: { maxTimeMinutes: 5, maxTurns: 5 },
promptConfig: { systemPrompt: 'Achieve: ${goal}.' },
toolConfig: {
// Cast required because the type expects AnyDeclarativeTool |
// string | FunctionDeclaration; MockTool satisfies the first.
tools: instanceTools as unknown as AnyDeclarativeTool[],
},
outputConfig,
} as unknown as LocalAgentDefinition;
};
/**
* Helper to extract the functionDeclarations sent to GeminiChat.
*/
const getSentFunctionDeclarations = () => {
const chatCtorArgs = MockedGeminiChat.mock.calls[0];
const toolsArg = chatCtorArgs[2] as Tool[];
return toolsArg[0].functionDeclarations ?? [];
};
it('should produce NO duplicate function declarations when tools are DeclarativeTool instances', async () => {
const clickTool = new MockTool({ name: 'click' });
const fillTool = new MockTool({ name: 'fill' });
const snapshotTool = new MockTool({ name: 'take_snapshot' });
const definition = createInstanceToolDefinition([
clickTool,
fillTool,
snapshotTool,
]);
mockModelResponse([
{
name: TASK_COMPLETE_TOOL_NAME,
args: { finalResult: 'done' },
id: 'c1',
},
]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
await executor.run({ goal: 'Test' }, signal);
const declarations = getSentFunctionDeclarations();
const names = declarations.map((d) => d.name);
// Each tool must appear exactly once
expect(names.filter((n) => n === 'click')).toHaveLength(1);
expect(names.filter((n) => n === 'fill')).toHaveLength(1);
expect(names.filter((n) => n === 'take_snapshot')).toHaveLength(1);
// Total = 3 tools + complete_task
expect(declarations).toHaveLength(4);
});
it('should register DeclarativeTool instances in the isolated tool registry', async () => {
const clickTool = new MockTool({ name: 'click' });
const navTool = new MockTool({ name: 'navigate_page' });
const definition = createInstanceToolDefinition([clickTool, navTool]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
const registry = executor['toolRegistry'];
expect(registry.getTool('click')).toBeDefined();
expect(registry.getTool('navigate_page')).toBeDefined();
// Should NOT have tools that were not passed
expect(registry.getTool(LS_TOOL_NAME)).toBeUndefined();
});
it('should handle mixed string + DeclarativeTool instances without duplicates', async () => {
const instanceTool = new MockTool({ name: 'fill' });
const definition: LocalAgentDefinition = {
kind: 'local',
name: 'MixedAgent',
description: 'Uses both patterns.',
inputConfig: {
inputSchema: {
type: 'object',
properties: { goal: { type: 'string', description: 'goal' } },
},
},
modelConfig: {
model: 'gemini-test-model',
generateContentConfig: { temperature: 0, topP: 1 },
},
runConfig: { maxTimeMinutes: 5, maxTurns: 5 },
promptConfig: { systemPrompt: 'Achieve: ${goal}.' },
toolConfig: {
tools: [
LS_TOOL_NAME, // string reference
instanceTool as unknown as AnyDeclarativeTool, // instance
],
},
outputConfig: {
outputName: 'finalResult',
description: 'result',
schema: z.string(),
},
} as unknown as LocalAgentDefinition;
mockModelResponse([
{
name: TASK_COMPLETE_TOOL_NAME,
args: { finalResult: 'ok' },
id: 'c1',
},
]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
await executor.run({ goal: 'Mixed' }, signal);
const declarations = getSentFunctionDeclarations();
const names = declarations.map((d) => d.name);
expect(names.filter((n) => n === LS_TOOL_NAME)).toHaveLength(1);
expect(names.filter((n) => n === 'fill')).toHaveLength(1);
expect(names.filter((n) => n === TASK_COMPLETE_TOOL_NAME)).toHaveLength(
1,
);
// Total = ls + fill + complete_task
expect(declarations).toHaveLength(3);
});
it('should correctly execute tools passed as DeclarativeTool instances', async () => {
const executeFn = vi.fn().mockResolvedValue({
llmContent: 'Clicked successfully.',
returnDisplay: 'Clicked successfully.',
});
const clickTool = new MockTool({ name: 'click', execute: executeFn });
const definition = createInstanceToolDefinition([clickTool]);
// Turn 1: Model calls click
mockModelResponse([
{ name: 'click', args: { uid: '42' }, id: 'call-click' },
]);
mockScheduleAgentTools.mockResolvedValueOnce([
{
status: 'success',
request: {
callId: 'call-click',
name: 'click',
args: { uid: '42' },
isClientInitiated: false,
prompt_id: 'test',
},
tool: {} as AnyDeclarativeTool,
invocation: {} as AnyToolInvocation,
response: {
callId: 'call-click',
resultDisplay: 'Clicked',
responseParts: [
{
functionResponse: {
name: 'click',
response: { result: 'Clicked' },
id: 'call-click',
},
},
],
error: undefined,
errorType: undefined,
contentLength: undefined,
},
},
]);
// Turn 2: Model completes
mockModelResponse([
{
name: TASK_COMPLETE_TOOL_NAME,
args: { finalResult: 'done' },
id: 'call-done',
},
]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
const output = await executor.run({ goal: 'Click test' }, signal);
// The scheduler should have received the click tool call
expect(mockScheduleAgentTools).toHaveBeenCalled();
const scheduledRequests = mockScheduleAgentTools.mock
.calls[0][1] as ToolCallRequestInfo[];
expect(scheduledRequests).toHaveLength(1);
expect(scheduledRequests[0].name).toBe('click');
expect(output.terminate_reason).toBe(AgentTerminateMode.GOAL);
});
it('should always include complete_task even when all tools are instances', async () => {
const definition = createInstanceToolDefinition(
[new MockTool({ name: 'take_snapshot' })],
'none',
);
mockModelResponse([
{
name: TASK_COMPLETE_TOOL_NAME,
args: { result: 'done' },
id: 'c1',
},
]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
await executor.run({ goal: 'Test' }, signal);
const declarations = getSentFunctionDeclarations();
const names = declarations.map((d) => d.name);
expect(names).toContain(TASK_COMPLETE_TOOL_NAME);
expect(names).toContain('take_snapshot');
expect(declarations).toHaveLength(2);
});
it('should produce unique declarations for many instance tools (browser agent scale)', async () => {
// Simulates the full set of tools the browser agent typically registers
const browserToolNames = [
'click',
'click_at',
'fill',
'fill_form',
'hover',
'drag',
'press_key',
'take_snapshot',
'navigate_page',
'new_page',
'close_page',
'select_page',
'evaluate_script',
'type_text',
];
const instanceTools = browserToolNames.map(
(name) => new MockTool({ name }),
);
const definition = createInstanceToolDefinition(instanceTools);
mockModelResponse([
{
name: TASK_COMPLETE_TOOL_NAME,
args: { finalResult: 'done' },
id: 'c1',
},
]);
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
);
await executor.run({ goal: 'Scale test' }, signal);
const declarations = getSentFunctionDeclarations();
const names = declarations.map((d) => d.name);
// Every tool name must appear exactly once
for (const toolName of browserToolNames) {
const count = names.filter((n) => n === toolName).length;
expect(count).toBe(1);
}
// Plus complete_task
expect(declarations).toHaveLength(browserToolNames.length + 1);
// Verify the complete set of names has no duplicates
const uniqueNames = new Set(names);
expect(uniqueNames.size).toBe(names.length);
});
});
});
+23 -48
View File
@@ -17,13 +17,7 @@ import {
type Schema,
} from '@google/genai';
import { ToolRegistry } from '../tools/tool-registry.js';
import { type AnyDeclarativeTool } from '../tools/tools.js';
import {
DiscoveredMCPTool,
isMcpToolName,
parseMcpToolName,
MCP_TOOL_PREFIX,
} from '../tools/mcp-tool.js';
import { DiscoveredMCPTool } from '../tools/mcp-tool.js';
import { CompressionStatus } from '../core/turn.js';
import { type ToolCallRequestInfo } from '../scheduler/types.js';
import { type Message } from '../confirmation-bus/types.js';
@@ -152,55 +146,28 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
context.config.getAgentRegistry().getAllAgentNames(),
);
const registerToolInstance = (tool: AnyDeclarativeTool) => {
const registerToolByName = (toolName: string) => {
// Check if the tool is a subagent to prevent recursion.
// We do not allow agents to call other agents.
if (allAgentNames.has(tool.name)) {
if (allAgentNames.has(toolName)) {
debugLogger.warn(
`[LocalAgentExecutor] Skipping subagent tool '${tool.name}' for agent '${definition.name}' to prevent recursion.`,
`[LocalAgentExecutor] Skipping subagent tool '${toolName}' for agent '${definition.name}' to prevent recursion.`,
);
return;
}
agentToolRegistry.registerTool(tool);
};
const registerToolByName = (toolName: string) => {
// Handle global wildcard
if (toolName === '*') {
for (const tool of parentToolRegistry.getAllTools()) {
registerToolInstance(tool);
}
return;
}
// Handle MCP wildcards
if (isMcpToolName(toolName)) {
if (toolName === `${MCP_TOOL_PREFIX}*`) {
for (const tool of parentToolRegistry.getAllTools()) {
if (tool instanceof DiscoveredMCPTool) {
registerToolInstance(tool);
}
}
return;
}
const parsed = parseMcpToolName(toolName);
if (parsed.serverName && parsed.toolName === '*') {
for (const tool of parentToolRegistry.getToolsByServer(
parsed.serverName,
)) {
registerToolInstance(tool);
}
return;
}
}
// If the tool is referenced by name, retrieve it from the parent
// registry and register it with the agent's isolated registry.
const tool = parentToolRegistry.getTool(toolName);
if (tool) {
registerToolInstance(tool);
if (tool instanceof DiscoveredMCPTool) {
// Subagents MUST use fully qualified names for MCP tools to ensure
// unambiguous tool calls and to comply with policy requirements.
// We automatically "upgrade" any MCP tool to its qualified version.
agentToolRegistry.registerTool(tool.asFullyQualifiedTool());
} else {
agentToolRegistry.registerTool(tool);
}
}
};
@@ -1208,14 +1175,22 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
const { toolConfig, outputConfig } = this.definition;
if (toolConfig) {
const toolNamesToLoad: string[] = [];
for (const toolRef of toolConfig.tools) {
if (typeof toolRef === 'object' && !('schema' in toolRef)) {
if (typeof toolRef === 'string') {
toolNamesToLoad.push(toolRef);
} else if (typeof toolRef === 'object' && 'schema' in toolRef) {
// Tool instance with an explicit schema property.
toolsList.push(toolRef.schema);
} else {
// Raw `FunctionDeclaration` object.
toolsList.push(toolRef);
}
}
// Add schemas from tools that were explicitly registered by name, wildcard, or instance.
toolsList.push(...this.toolRegistry.getFunctionDeclarations());
// Add schemas from tools that were registered by name.
toolsList.push(
...this.toolRegistry.getFunctionDeclarationsFiltered(toolNamesToLoad),
);
}
// Always inject complete_task.
@@ -593,7 +593,6 @@ describe('AgentRegistry', () => {
expect(A2AAuthProviderFactory.create).toHaveBeenCalledWith({
authConfig: mockAuth,
agentName: 'RemoteAgentWithAuth',
targetUrl: 'https://example.com/card',
agentCardUrl: 'https://example.com/card',
});
expect(loadAgentSpy).toHaveBeenCalledWith(
+2 -3
View File
@@ -69,7 +69,7 @@ export class AgentRegistry {
* Clears the current registry and re-scans for agents.
*/
async reload(): Promise<void> {
A2AClientManager.getInstance(this.config).clearCache();
A2AClientManager.getInstance().clearCache();
await this.config.reloadAgents();
this.agents.clear();
this.allDefinitions.clear();
@@ -414,13 +414,12 @@ export class AgentRegistry {
// Load the remote A2A agent card and register.
try {
const clientManager = A2AClientManager.getInstance(this.config);
const clientManager = A2AClientManager.getInstance();
let authHandler: AuthenticationHandler | undefined;
if (definition.auth) {
const provider = await A2AAuthProviderFactory.create({
authConfig: definition.auth,
agentName: definition.name,
targetUrl: definition.agentCardUrl,
agentCardUrl: remoteDef.agentCardUrl,
});
if (!provider) {
@@ -195,7 +195,6 @@ describe('RemoteAgentInvocation', () => {
expect(A2AAuthProviderFactory.create).toHaveBeenCalledWith({
authConfig: mockAuth,
agentName: 'test-agent',
targetUrl: 'http://test-agent/card',
agentCardUrl: 'http://test-agent/card',
});
expect(mockClientManager.loadAgent).toHaveBeenCalledWith(
+34 -1
View File
@@ -22,6 +22,7 @@ import {
type SendMessageResult,
} from './a2a-client-manager.js';
import { extractIdsFromResponse, A2AResultReassembler } from './a2aUtils.js';
import { GoogleAuth } from 'google-auth-library';
import type { AuthenticationHandler } from '@a2a-js/sdk/client';
import { debugLogger } from '../utils/debugLogger.js';
import { safeJsonToMarkdown } from '../utils/markdownUtils.js';
@@ -29,6 +30,39 @@ import type { AnsiOutput } from '../utils/terminalSerializer.js';
import { A2AAuthProviderFactory } from './auth-provider/factory.js';
import { A2AAgentError } from './a2a-errors.js';
/**
* Authentication handler implementation using Google Application Default Credentials (ADC).
*/
export class ADCHandler implements AuthenticationHandler {
private auth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
async headers(): Promise<Record<string, string>> {
try {
const client = await this.auth.getClient();
const token = await client.getAccessToken();
if (token.token) {
return { Authorization: `Bearer ${token.token}` };
}
throw new Error('Failed to retrieve ADC access token.');
} catch (e) {
const errorMessage = `Failed to get ADC token: ${
e instanceof Error ? e.message : String(e)
}`;
debugLogger.log('ERROR', errorMessage);
throw new Error(errorMessage);
}
}
async shouldRetryWithHeaders(
_response: unknown,
): Promise<Record<string, string> | undefined> {
// For ADC, we usually just re-fetch the token if needed.
return this.headers();
}
}
/**
* A tool invocation that proxies to a remote A2A agent.
*
@@ -87,7 +121,6 @@ export class RemoteAgentInvocation extends BaseToolInvocation<
const provider = await A2AAuthProviderFactory.create({
authConfig: this.definition.auth,
agentName: this.definition.name,
targetUrl: this.definition.agentCardUrl,
agentCardUrl: this.definition.agentCardUrl,
});
if (!provider) {
@@ -103,19 +103,9 @@ describe('SubagentToolWrapper', () => {
expect(schema.name).toBe(mockDefinition.name);
expect(schema.description).toBe(mockDefinition.description);
expect(schema.parametersJsonSchema).toEqual({
...(mockDefinition.inputConfig.inputSchema as Record<string, unknown>),
properties: {
...((
mockDefinition.inputConfig.inputSchema as Record<string, unknown>
)['properties'] as Record<string, unknown>),
wait_for_previous: {
type: 'boolean',
description:
'Set to true to wait for all previously requested tools in this turn to complete before starting. Set to false (or omit) to run in parallel. Use true when this tool depends on the output of previous tools.',
},
},
});
expect(schema.parametersJsonSchema).toEqual(
mockDefinition.inputConfig.inputSchema,
);
});
});
+4 -4
View File
@@ -43,12 +43,12 @@ export const DEFAULT_QUERY_STRING = 'Get Started!';
/**
* The default maximum number of conversational turns for an agent.
*/
export const DEFAULT_MAX_TURNS = 30;
export const DEFAULT_MAX_TURNS = 15;
/**
* The default maximum execution time for an agent in minutes.
*/
export const DEFAULT_MAX_TIME_MINUTES = 10;
export const DEFAULT_MAX_TIME_MINUTES = 5;
/**
* Represents the validated input parameters passed to an agent upon invocation.
@@ -223,12 +223,12 @@ export interface OutputConfig<T extends z.ZodTypeAny> {
export interface RunConfig {
/**
* The maximum execution time for the agent in minutes.
* If not specified, defaults to DEFAULT_MAX_TIME_MINUTES (10).
* If not specified, defaults to DEFAULT_MAX_TIME_MINUTES (5).
*/
maxTimeMinutes?: number;
/**
* The maximum number of conversational turns.
* If not specified, defaults to DEFAULT_MAX_TURNS (30).
* If not specified, defaults to DEFAULT_MAX_TURNS (15).
*/
maxTurns?: number;
}
@@ -54,21 +54,19 @@ export function resolvePolicyChain(
useCustomToolModel,
hasAccessToPreview,
);
const isAutoPreferred = preferredModel
? isAutoModel(preferredModel, config)
: false;
const isAutoConfigured = isAutoModel(configuredModel, config);
const isAutoPreferred = preferredModel ? isAutoModel(preferredModel) : false;
const isAutoConfigured = isAutoModel(configuredModel);
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
chain = getFlashLitePolicyChain();
} else if (
isGemini3Model(resolvedModel, config) ||
isGemini3Model(resolvedModel) ||
isAutoPreferred ||
isAutoConfigured
) {
if (hasAccessToPreview) {
const previewEnabled =
isGemini3Model(resolvedModel, config) ||
isGemini3Model(resolvedModel) ||
preferredModel === PREVIEW_GEMINI_MODEL_AUTO ||
configuredModel === PREVIEW_GEMINI_MODEL_AUTO;
chain = getModelPolicyChain({
+1
View File
@@ -700,6 +700,7 @@ async function fetchAndCacheUserInfo(client: OAuth2Client): Promise<void> {
return;
}
// eslint-disable-next-line no-restricted-syntax -- TODO: Migrate to safeFetch for SSRF protection
const response = await fetch(
'https://www.googleapis.com/oauth2/v2/userinfo',
{
@@ -208,7 +208,6 @@ describe('CodeAssistServer', () => {
traceId: 'test-trace-id',
status: ActionStatus.ACTION_STATUS_NO_ERROR,
initiationMethod: InitiationMethod.COMMAND,
trajectoryId: 'test-session',
streamingLatency: expect.objectContaining({
totalLatency: expect.stringMatching(/\d+s/),
firstMessageLatency: expect.stringMatching(/\d+s/),
@@ -278,7 +277,6 @@ describe('CodeAssistServer', () => {
conversationOffered: expect.objectContaining({
traceId: 'stream-trace-id',
initiationMethod: InitiationMethod.COMMAND,
trajectoryId: 'test-session',
}),
timestamp: expect.stringMatching(
/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/,
-2
View File
@@ -153,7 +153,6 @@ export class CodeAssistServer implements ContentGenerator {
translatedResponse,
streamingLatency,
req.config?.abortSignal,
server.sessionId, // Use sessionId as trajectoryId
);
if (response.consumedCredits) {
@@ -224,7 +223,6 @@ export class CodeAssistServer implements ContentGenerator {
translatedResponse,
streamingLatency,
req.config?.abortSignal,
this.sessionId, // Use sessionId as trajectoryId
);
if (response.remainingCredits) {
@@ -92,7 +92,6 @@ describe('telemetry', () => {
traceId,
undefined,
streamingLatency,
'trajectory-id',
);
expect(result).toEqual({
@@ -103,7 +102,6 @@ describe('telemetry', () => {
streamingLatency,
isAgentic: true,
initiationMethod: InitiationMethod.COMMAND,
trajectoryId: 'trajectory-id',
});
});
@@ -126,7 +124,6 @@ describe('telemetry', () => {
'trace-id',
undefined,
{},
'trajectory-id',
);
expect(result).toBeUndefined();
});
@@ -143,7 +140,6 @@ describe('telemetry', () => {
'trace-id',
signal,
{},
'trajectory-id',
);
expect(result?.status).toBe(ActionStatus.ACTION_STATUS_CANCELLED);
@@ -159,7 +155,6 @@ describe('telemetry', () => {
'trace-id',
undefined,
{},
'trajectory-id',
);
expect(result?.status).toBe(ActionStatus.ACTION_STATUS_ERROR_UNKNOWN);
@@ -182,7 +177,6 @@ describe('telemetry', () => {
'trace-id',
undefined,
{},
'trajectory-id',
);
expect(result?.status).toBe(ActionStatus.ACTION_STATUS_ERROR_UNKNOWN);
@@ -200,7 +194,6 @@ describe('telemetry', () => {
'trace-id',
undefined,
{},
undefined,
);
expect(result?.status).toBe(ActionStatus.ACTION_STATUS_EMPTY);
@@ -221,13 +214,7 @@ describe('telemetry', () => {
true,
[{ name: 'replace', args: {} }],
);
const result = createConversationOffered(
response,
'id',
undefined,
{},
undefined,
);
const result = createConversationOffered(response, 'id', undefined, {});
expect(result?.includedCode).toBe(true);
});
@@ -244,13 +231,7 @@ describe('telemetry', () => {
true,
[{ name: 'replace', args: {} }],
);
const result = createConversationOffered(
response,
'id',
undefined,
{},
undefined,
);
const result = createConversationOffered(response, 'id', undefined, {});
expect(result?.includedCode).toBe(false);
});
});
@@ -279,7 +260,6 @@ describe('telemetry', () => {
response,
streamingLatency,
undefined,
undefined,
);
expect(serverMock.recordConversationOffered).toHaveBeenCalledWith(
@@ -303,7 +283,6 @@ describe('telemetry', () => {
response,
{},
undefined,
undefined,
);
expect(serverMock.recordConversationOffered).not.toHaveBeenCalled();
@@ -36,7 +36,6 @@ export async function recordConversationOffered(
response: GenerateContentResponse,
streamingLatency: StreamingLatency,
abortSignal: AbortSignal | undefined,
trajectoryId: string | undefined,
): Promise<void> {
try {
if (traceId) {
@@ -45,7 +44,6 @@ export async function recordConversationOffered(
traceId,
abortSignal,
streamingLatency,
trajectoryId,
);
if (offered) {
await server.recordConversationOffered(offered);
@@ -89,7 +87,6 @@ export function createConversationOffered(
traceId: string,
signal: AbortSignal | undefined,
streamingLatency: StreamingLatency,
trajectoryId: string | undefined,
): ConversationOffered | undefined {
// Only send conversation offered events for responses that contain edit
// function calls. Non-edit function calls don't represent file modifications.
@@ -110,7 +107,6 @@ export function createConversationOffered(
streamingLatency,
isAgentic: true,
initiationMethod: InitiationMethod.COMMAND,
trajectoryId,
};
}
-1
View File
@@ -315,7 +315,6 @@ export interface ConversationOffered {
streamingLatency?: StreamingLatency;
isAgentic?: boolean;
initiationMethod?: InitiationMethod;
trajectoryId?: string;
}
export interface StreamingLatency {
+5 -11
View File
@@ -67,7 +67,6 @@ import {
DEFAULT_GEMINI_MODEL_AUTO,
} from './models.js';
import { Storage } from './storage.js';
import type { AgentLoopContext } from './agent-loop-context.js';
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>();
@@ -642,9 +641,8 @@ describe('Server Config (config.ts)', () => {
await config.refreshAuth(AuthType.LOGIN_WITH_GOOGLE);
const loopContext: AgentLoopContext = config;
expect(
loopContext.geminiClient.stripThoughtsFromHistory,
config.getGeminiClient().stripThoughtsFromHistory,
).toHaveBeenCalledWith();
});
@@ -662,9 +660,8 @@ describe('Server Config (config.ts)', () => {
await config.refreshAuth(AuthType.USE_VERTEX_AI);
const loopContext: AgentLoopContext = config;
expect(
loopContext.geminiClient.stripThoughtsFromHistory,
config.getGeminiClient().stripThoughtsFromHistory,
).toHaveBeenCalledWith();
});
@@ -682,9 +679,8 @@ describe('Server Config (config.ts)', () => {
await config.refreshAuth(AuthType.USE_GEMINI);
const loopContext: AgentLoopContext = config;
expect(
loopContext.geminiClient.stripThoughtsFromHistory,
config.getGeminiClient().stripThoughtsFromHistory,
).not.toHaveBeenCalledWith();
});
});
@@ -3063,8 +3059,7 @@ describe('Config JIT Initialization', () => {
await config.initialize();
const skillManager = config.getSkillManager();
const loopContext: AgentLoopContext = config;
const toolRegistry = loopContext.toolRegistry;
const toolRegistry = config.getToolRegistry();
vi.spyOn(skillManager, 'discoverSkills').mockResolvedValue(undefined);
vi.spyOn(skillManager, 'setDisabledSkills');
@@ -3100,8 +3095,7 @@ describe('Config JIT Initialization', () => {
await config.initialize();
const skillManager = config.getSkillManager();
const loopContext: AgentLoopContext = config;
const toolRegistry = loopContext.toolRegistry;
const toolRegistry = config.getToolRegistry();
vi.spyOn(skillManager, 'discoverSkills').mockResolvedValue(undefined);
vi.spyOn(toolRegistry, 'registerTool');
+79 -70
View File
@@ -32,6 +32,7 @@ import { WriteFileTool } from '../tools/write-file.js';
import { WebFetchTool } from '../tools/web-fetch.js';
import { MemoryTool, setGeminiMdFilename } from '../tools/memoryTool.js';
import { WebSearchTool } from '../tools/web-search.js';
import { GenerateImageTool } from '../tools/generate-image.js';
import { AskUserTool } from '../tools/ask-user.js';
import { ExitPlanModeTool } from '../tools/exit-plan-mode.js';
import { EnterPlanModeTool } from '../tools/enter-plan-mode.js';
@@ -316,8 +317,6 @@ export interface BrowserAgentCustomConfig {
profilePath?: string;
/** Model override for the visual agent. */
visualModel?: string;
/** Disable user input on the browser window during automation. Default: true in non-headless mode */
disableUserInput?: boolean;
}
/**
@@ -398,6 +397,7 @@ import { McpClientManager } from '../tools/mcp-client-manager.js';
import { type McpContext } from '../tools/mcp-client.js';
import type { EnvironmentSanitizationConfig } from '../services/environmentSanitization.js';
import { getErrorMessage } from '../utils/errors.js';
import { GENERATE_IMAGE_TOOL_NAME } from '../tools/tool-names.js';
export type { FileFilteringOptions };
export {
@@ -601,7 +601,6 @@ export interface ConfigParameters {
disableYoloMode?: boolean;
rawOutput?: boolean;
acceptRawOutputRisk?: boolean;
dynamicModelConfiguration?: boolean;
modelConfigServiceConfig?: ModelConfigServiceConfig;
enableHooks?: boolean;
enableHooksUI?: boolean;
@@ -615,6 +614,7 @@ export interface ConfigParameters {
disabledSkills?: string[];
adminSkillsEnabled?: boolean;
experimentalJitContext?: boolean;
imageGeneration?: boolean;
toolOutputMasking?: Partial<ToolOutputMaskingConfig>;
disableLLMCorrection?: boolean;
plan?: boolean;
@@ -800,7 +800,6 @@ export class Config implements McpContext, AgentLoopContext {
private readonly disableYoloMode: boolean;
private readonly rawOutput: boolean;
private readonly acceptRawOutputRisk: boolean;
private readonly dynamicModelConfiguration: boolean;
private pendingIncludeDirectories: string[];
private readonly enableHooks: boolean;
private readonly enableHooksUI: boolean;
@@ -834,6 +833,7 @@ export class Config implements McpContext, AgentLoopContext {
private readonly adminSkillsEnabled: boolean;
private readonly experimentalJitContext: boolean;
private readonly imageGeneration: boolean;
private readonly disableLLMCorrection: boolean;
private readonly planEnabled: boolean;
private readonly trackerEnabled: boolean;
@@ -936,6 +936,7 @@ export class Config implements McpContext, AgentLoopContext {
this.adminSkillsEnabled = params.adminSkillsEnabled ?? true;
this.modelAvailabilityService = new ModelAvailabilityService();
this.experimentalJitContext = params.experimentalJitContext ?? false;
this.imageGeneration = params.imageGeneration ?? false;
this.modelSteering = params.modelSteering ?? false;
this.userHintService = new UserHintService(() =>
this.isModelSteeringEnabled(),
@@ -989,7 +990,7 @@ export class Config implements McpContext, AgentLoopContext {
this.truncateToolOutputThreshold =
params.truncateToolOutputThreshold ??
DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;
this.useWriteTodos = isPreviewModel(this.model, this)
this.useWriteTodos = isPreviewModel(this.model)
? false
: (params.useWriteTodos ?? true);
this.workspacePoliciesDir = params.workspacePoliciesDir;
@@ -1038,7 +1039,7 @@ export class Config implements McpContext, AgentLoopContext {
// Register Conseca if enabled
if (this.enableConseca) {
debugLogger.log('[SAFETY] Registering Conseca Safety Checker');
ConsecaSafetyChecker.getInstance().setContext(this);
ConsecaSafetyChecker.getInstance().setConfig(this);
}
this._messageBus = new MessageBus(this.policyEngine, this.debugMode);
@@ -1064,7 +1065,6 @@ export class Config implements McpContext, AgentLoopContext {
this.disableYoloMode = params.disableYoloMode ?? false;
this.rawOutput = params.rawOutput ?? false;
this.acceptRawOutputRisk = params.acceptRawOutputRisk ?? false;
this.dynamicModelConfiguration = params.dynamicModelConfiguration ?? false;
if (params.hooks) {
this.hooks = params.hooks;
@@ -1114,23 +1114,18 @@ export class Config implements McpContext, AgentLoopContext {
// remove this hack.
let modelConfigServiceConfig = params.modelConfigServiceConfig;
if (modelConfigServiceConfig) {
// Ensure user-defined model definitions augment, not replace, the defaults.
const mergedModelDefinitions = {
...DEFAULT_MODEL_CONFIGS.modelDefinitions,
...modelConfigServiceConfig.modelDefinitions,
};
modelConfigServiceConfig = {
// Preserve other user settings like customAliases
...modelConfigServiceConfig,
// Apply defaults for aliases and overrides if they are not provided
aliases:
modelConfigServiceConfig.aliases ?? DEFAULT_MODEL_CONFIGS.aliases,
overrides:
modelConfigServiceConfig.overrides ?? DEFAULT_MODEL_CONFIGS.overrides,
// Use the merged model definitions
modelDefinitions: mergedModelDefinitions,
};
if (!modelConfigServiceConfig.aliases) {
modelConfigServiceConfig = {
...modelConfigServiceConfig,
aliases: DEFAULT_MODEL_CONFIGS.aliases,
};
}
if (!modelConfigServiceConfig.overrides) {
modelConfigServiceConfig = {
...modelConfigServiceConfig,
overrides: DEFAULT_MODEL_CONFIGS.overrides,
};
}
}
this.modelConfigService = new ModelConfigService(
@@ -1233,8 +1228,8 @@ export class Config implements McpContext, AgentLoopContext {
// Re-register ActivateSkillTool to update its schema with the discovered enabled skill enums
if (this.getSkillManager().getSkills().length > 0) {
this.toolRegistry.unregisterTool(ActivateSkillTool.Name);
this.toolRegistry.registerTool(
this.getToolRegistry().unregisterTool(ActivateSkillTool.Name);
this.getToolRegistry().registerTool(
new ActivateSkillTool(this, this.messageBus),
);
}
@@ -1333,10 +1328,7 @@ export class Config implements McpContext, AgentLoopContext {
// Only reset when we have explicit "no access" (hasAccessToPreviewModel === false).
// When null (quota not fetched) or true, we preserve the saved model.
if (
isPreviewModel(this.model, this) &&
this.hasAccessToPreviewModel === false
) {
if (isPreviewModel(this.model) && this.hasAccessToPreviewModel === false) {
this.setModel(DEFAULT_GEMINI_MODEL_AUTO);
}
@@ -1355,6 +1347,36 @@ export class Config implements McpContext, AgentLoopContext {
},
);
this.setRemoteAdminSettings(adminControls);
// Re-evaluate image generation tool registration after auth change
this.updateImageGenToolRegistration();
}
/**
* Registers or unregisters the GenerateImageTool based on current auth type.
* Called after auth completes or is refreshed.
*/
private updateImageGenToolRegistration(): void {
if (!this.imageGeneration) {
this.toolRegistry?.unregisterTool(GENERATE_IMAGE_TOOL_NAME);
return;
}
const currentAuthType = this.getContentGeneratorConfig()?.authType;
const supportsImageGen =
currentAuthType === AuthType.USE_GEMINI ||
currentAuthType === AuthType.USE_VERTEX_AI;
if (
supportsImageGen &&
!this.toolRegistry?.getTool(GENERATE_IMAGE_TOOL_NAME)
) {
this.toolRegistry?.registerTool(
new GenerateImageTool(this, this.messageBus),
);
} else if (!supportsImageGen) {
this.toolRegistry?.unregisterTool(GENERATE_IMAGE_TOOL_NAME);
}
}
async getExperimentsAsync(): Promise<Experiments | undefined> {
@@ -1408,26 +1430,14 @@ export class Config implements McpContext, AgentLoopContext {
return this._sessionId;
}
/**
* @deprecated Do not access directly on Config.
* Use the injected AgentLoopContext instead.
*/
get toolRegistry(): ToolRegistry {
return this._toolRegistry;
}
/**
* @deprecated Do not access directly on Config.
* Use the injected AgentLoopContext instead.
*/
get messageBus(): MessageBus {
return this._messageBus;
}
/**
* @deprecated Do not access directly on Config.
* Use the injected AgentLoopContext instead.
*/
get geminiClient(): GeminiClient {
return this._geminiClient;
}
@@ -1604,7 +1614,7 @@ export class Config implements McpContext, AgentLoopContext {
const isPreview =
model === PREVIEW_GEMINI_MODEL_AUTO ||
isPreviewModel(this.getActiveModel(), this);
isPreviewModel(this.getActiveModel());
const proModel = isPreview ? PREVIEW_GEMINI_MODEL : DEFAULT_GEMINI_MODEL;
const flashModel = isPreview
? PREVIEW_GEMINI_FLASH_MODEL
@@ -1802,9 +1812,8 @@ export class Config implements McpContext, AgentLoopContext {
}
const hasAccess =
quota.buckets?.some(
(b) => b.modelId && isPreviewModel(b.modelId, this),
) ?? false;
quota.buckets?.some((b) => b.modelId && isPreviewModel(b.modelId)) ??
false;
this.setHasAccessToPreviewModel(hasAccess);
return quota;
} catch (e) {
@@ -2196,10 +2205,6 @@ export class Config implements McpContext, AgentLoopContext {
return this.acceptRawOutputRisk;
}
getExperimentalDynamicModelConfiguration(): boolean {
return this.dynamicModelConfiguration;
}
getPendingIncludeDirectories(): string[] {
return this.pendingIncludeDirectories;
}
@@ -2271,7 +2276,7 @@ export class Config implements McpContext, AgentLoopContext {
* Whenever the user memory (GEMINI.md files) is updated.
*/
updateSystemInstructionIfInitialized(): void {
const geminiClient = this.geminiClient;
const geminiClient = this.getGeminiClient();
if (geminiClient?.isInitialized()) {
geminiClient.updateSystemInstruction();
}
@@ -2380,6 +2385,10 @@ export class Config implements McpContext, AgentLoopContext {
}
}
isImageGenerationEnabled(): boolean {
return this.imageGeneration;
}
getListExtensions(): boolean {
return this.listExtensions;
}
@@ -2737,16 +2746,16 @@ export class Config implements McpContext, AgentLoopContext {
// Re-register ActivateSkillTool to update its schema with the newly discovered skills
if (this.getSkillManager().getSkills().length > 0) {
this.toolRegistry.unregisterTool(ActivateSkillTool.Name);
this.toolRegistry.registerTool(
this.getToolRegistry().unregisterTool(ActivateSkillTool.Name);
this.getToolRegistry().registerTool(
new ActivateSkillTool(this, this.messageBus),
);
} else {
this.toolRegistry.unregisterTool(ActivateSkillTool.Name);
this.getToolRegistry().unregisterTool(ActivateSkillTool.Name);
}
} else {
this.getSkillManager().clearSkills();
this.toolRegistry.unregisterTool(ActivateSkillTool.Name);
this.getToolRegistry().unregisterTool(ActivateSkillTool.Name);
}
// Notify the client that system instructions might need updating
@@ -2918,23 +2927,10 @@ export class Config implements McpContext, AgentLoopContext {
headless: customConfig.headless ?? false,
profilePath: customConfig.profilePath,
visualModel: customConfig.visualModel,
disableUserInput: customConfig.disableUserInput,
},
};
}
/**
* Determines if user input should be disabled during browser automation.
* Based on the `disableUserInput` setting and `headless` mode.
*/
shouldDisableBrowserUserInput(): boolean {
const browserConfig = this.getBrowserAgentConfig();
return (
browserConfig.customConfig?.disableUserInput !== false &&
!browserConfig.customConfig?.headless
);
}
async createToolRegistry(): Promise<ToolRegistry> {
const registry = new ToolRegistry(this, this.messageBus);
@@ -3037,6 +3033,19 @@ export class Config implements McpContext, AgentLoopContext {
);
}
// Register image generation tool if enabled and auth supports it
if (this.imageGeneration) {
const authType = this.getContentGeneratorConfig()?.authType;
if (
authType === AuthType.USE_GEMINI ||
authType === AuthType.USE_VERTEX_AI
) {
maybeRegister(GenerateImageTool, () =>
registry.registerTool(new GenerateImageTool(this, this.messageBus)),
);
}
}
if (this.isTrackerEnabled()) {
maybeRegister(TrackerCreateTaskTool, () =>
registry.registerTool(new TrackerCreateTaskTool(this, this.messageBus)),
@@ -3082,7 +3091,7 @@ export class Config implements McpContext, AgentLoopContext {
for (const definition of definitions) {
try {
const tool = new SubagentTool(definition, this, this.messageBus);
const tool = new SubagentTool(definition, this, this.getMessageBus());
registry.registerTool(tool);
} catch (e: unknown) {
debugLogger.warn(
@@ -3187,7 +3196,7 @@ export class Config implements McpContext, AgentLoopContext {
this.registerSubAgentTools(this._toolRegistry);
}
// Propagate updates to the active chat session
const client = this.geminiClient;
const client = this.getGeminiClient();
if (client?.isInitialized()) {
await client.setTools();
client.updateSystemInstruction();
@@ -249,94 +249,4 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
},
},
],
modelDefinitions: {
// Concrete Models
'gemini-3.1-pro-preview': {
tier: 'pro',
family: 'gemini-3',
isPreview: true,
dialogLocation: 'manual',
features: { thinking: true, multimodalToolUse: true },
},
'gemini-3.1-pro-preview-customtools': {
tier: 'pro',
family: 'gemini-3',
isPreview: true,
features: { thinking: true, multimodalToolUse: true },
},
'gemini-3-pro-preview': {
tier: 'pro',
family: 'gemini-3',
isPreview: true,
dialogLocation: 'manual',
features: { thinking: true, multimodalToolUse: true },
},
'gemini-3-flash-preview': {
tier: 'flash',
family: 'gemini-3',
isPreview: true,
dialogLocation: 'manual',
features: { thinking: false, multimodalToolUse: true },
},
'gemini-2.5-pro': {
tier: 'pro',
family: 'gemini-2.5',
isPreview: false,
dialogLocation: 'manual',
features: { thinking: false, multimodalToolUse: false },
},
'gemini-2.5-flash': {
tier: 'flash',
family: 'gemini-2.5',
isPreview: false,
dialogLocation: 'manual',
features: { thinking: false, multimodalToolUse: false },
},
'gemini-2.5-flash-lite': {
tier: 'flash-lite',
family: 'gemini-2.5',
isPreview: false,
dialogLocation: 'manual',
features: { thinking: false, multimodalToolUse: false },
},
// Aliases
auto: {
tier: 'auto',
isPreview: true,
features: { thinking: true, multimodalToolUse: false },
},
pro: {
tier: 'pro',
isPreview: false,
features: { thinking: true, multimodalToolUse: false },
},
flash: {
tier: 'flash',
isPreview: false,
features: { thinking: false, multimodalToolUse: false },
},
'flash-lite': {
tier: 'flash-lite',
isPreview: false,
features: { thinking: false, multimodalToolUse: false },
},
'auto-gemini-3': {
displayName: 'Auto (Gemini 3)',
tier: 'auto',
isPreview: true,
dialogLocation: 'main',
dialogDescription:
'Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash',
features: { thinking: true, multimodalToolUse: false },
},
'auto-gemini-2.5': {
displayName: 'Auto (Gemini 2.5)',
tier: 'auto',
isPreview: false,
dialogLocation: 'main',
dialogDescription:
'Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash',
features: { thinking: false, multimodalToolUse: false },
},
},
};
-179
View File
@@ -22,7 +22,6 @@ import {
GEMINI_MODEL_ALIAS_PRO,
GEMINI_MODEL_ALIAS_FLASH,
GEMINI_MODEL_ALIAS_AUTO,
GEMINI_MODEL_ALIAS_FLASH_LITE,
PREVIEW_GEMINI_FLASH_MODEL,
PREVIEW_GEMINI_MODEL_AUTO,
DEFAULT_GEMINI_MODEL_AUTO,
@@ -31,126 +30,7 @@ import {
PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
isPreviewModel,
isProModel,
isValidModelOrAlias,
getValidModelsAndAliases,
VALID_GEMINI_MODELS,
VALID_ALIASES,
} from './models.js';
import type { Config } from './config.js';
import { ModelConfigService } from '../services/modelConfigService.js';
import { DEFAULT_MODEL_CONFIGS } from './defaultModelConfigs.js';
const modelConfigService = new ModelConfigService(DEFAULT_MODEL_CONFIGS);
const dynamicConfig = {
getExperimentalDynamicModelConfiguration: () => true,
modelConfigService,
} as unknown as Config;
const legacyConfig = {
getExperimentalDynamicModelConfiguration: () => false,
modelConfigService,
} as unknown as Config;
describe('Dynamic Configuration Parity', () => {
const modelsToTest = [
GEMINI_MODEL_ALIAS_AUTO,
GEMINI_MODEL_ALIAS_PRO,
GEMINI_MODEL_ALIAS_FLASH,
GEMINI_MODEL_ALIAS_FLASH_LITE,
PREVIEW_GEMINI_MODEL_AUTO,
DEFAULT_GEMINI_MODEL_AUTO,
PREVIEW_GEMINI_MODEL,
DEFAULT_GEMINI_MODEL,
'custom-model',
];
it('getDisplayString should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = getDisplayString(model, legacyConfig);
const dynamic = getDisplayString(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isPreviewModel should match legacy behavior', () => {
const allModels = [
...modelsToTest,
PREVIEW_GEMINI_3_1_MODEL,
PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
PREVIEW_GEMINI_FLASH_MODEL,
];
for (const model of allModels) {
const legacy = isPreviewModel(model, legacyConfig);
const dynamic = isPreviewModel(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isProModel should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isProModel(model, legacyConfig);
const dynamic = isProModel(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isGemini3Model should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isGemini3Model(model, legacyConfig);
const dynamic = isGemini3Model(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isGemini2Model should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isGemini2Model(model, legacyConfig);
const dynamic = isGemini2Model(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isCustomModel should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isCustomModel(model, legacyConfig);
const dynamic = isCustomModel(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('supportsModernFeatures should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = supportsModernFeatures(model, legacyConfig);
const dynamic = supportsModernFeatures(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isActiveModel should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isActiveModel(model, false, false, legacyConfig);
const dynamic = isActiveModel(model, false, false, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('isValidModelOrAlias should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = isValidModelOrAlias(model, legacyConfig);
const dynamic = isValidModelOrAlias(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
it('supportsMultimodalFunctionResponse should match legacy behavior', () => {
for (const model of modelsToTest) {
const legacy = supportsMultimodalFunctionResponse(model, legacyConfig);
const dynamic = supportsMultimodalFunctionResponse(model, dynamicConfig);
expect(dynamic).toBe(legacy);
}
});
});
describe('isPreviewModel', () => {
it('should return true for preview models', () => {
@@ -509,62 +389,3 @@ describe('isActiveModel', () => {
).toBe(false);
});
});
describe('isValidModelOrAlias', () => {
it('should return true for valid model names', () => {
expect(isValidModelOrAlias(DEFAULT_GEMINI_MODEL)).toBe(true);
expect(isValidModelOrAlias(PREVIEW_GEMINI_MODEL)).toBe(true);
expect(isValidModelOrAlias(DEFAULT_GEMINI_FLASH_MODEL)).toBe(true);
expect(isValidModelOrAlias(DEFAULT_GEMINI_FLASH_LITE_MODEL)).toBe(true);
expect(isValidModelOrAlias(PREVIEW_GEMINI_FLASH_MODEL)).toBe(true);
expect(isValidModelOrAlias(PREVIEW_GEMINI_3_1_MODEL)).toBe(true);
expect(isValidModelOrAlias(PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL)).toBe(
true,
);
});
it('should return true for valid aliases', () => {
expect(isValidModelOrAlias(GEMINI_MODEL_ALIAS_AUTO)).toBe(true);
expect(isValidModelOrAlias(GEMINI_MODEL_ALIAS_PRO)).toBe(true);
expect(isValidModelOrAlias(GEMINI_MODEL_ALIAS_FLASH)).toBe(true);
expect(isValidModelOrAlias(GEMINI_MODEL_ALIAS_FLASH_LITE)).toBe(true);
expect(isValidModelOrAlias(PREVIEW_GEMINI_MODEL_AUTO)).toBe(true);
expect(isValidModelOrAlias(DEFAULT_GEMINI_MODEL_AUTO)).toBe(true);
});
it('should return true for custom (non-gemini) models', () => {
expect(isValidModelOrAlias('gpt-4')).toBe(true);
expect(isValidModelOrAlias('claude-3')).toBe(true);
expect(isValidModelOrAlias('my-custom-model')).toBe(true);
});
it('should return false for invalid gemini model names', () => {
expect(isValidModelOrAlias('gemini-4-pro')).toBe(false);
expect(isValidModelOrAlias('gemini-99-flash')).toBe(false);
expect(isValidModelOrAlias('gemini-invalid')).toBe(false);
});
});
describe('getValidModelsAndAliases', () => {
it('should return a sorted array', () => {
const result = getValidModelsAndAliases();
const sorted = [...result].sort();
expect(result).toEqual(sorted);
});
it('should include all valid models and aliases', () => {
const result = getValidModelsAndAliases();
for (const model of VALID_GEMINI_MODELS) {
expect(result).toContain(model);
}
for (const alias of VALID_ALIASES) {
expect(result).toContain(alias);
}
});
it('should not contain duplicates', () => {
const result = getValidModelsAndAliases();
const unique = [...new Set(result)];
expect(result).toEqual(unique);
});
});

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