Compare commits

..

15 Commits

Author SHA1 Message Date
jacob314 e2981da430 refactor(cli): simplify command completion orchestration and fix shell cache race
- Simplified `useCommandCompletion.tsx` by moving shell-specific tokenization into `useShellCompletion.ts`.
- Reverted most changes to the `useCommandCompletion` `useMemo` block to keep it clean and consistent with other modes.
- Fixed a potential race condition in `useShellCompletion.ts` where `scanPathExecutables` could be called multiple times if it was slow. It now caches the Promise itself.
- Updated tests to match the refined hook interfaces.
2026-02-25 10:35:14 -08:00
jacob314 1dbb9af41c fix(cli): prioritize shorter command names in shell autocomplete results 2026-02-25 10:00:14 -08:00
jacob314 b4724a1eed test(cli): update snapshots for shell autocompletion refinements 2026-02-25 09:37:28 -08:00
jacob314 4eea909f28 fix(cli): add Windows shell built-in commands to autocomplete list
On Windows, many common commands like `dir`, `copy`, `del`, etc., are internal to `cmd.exe` and do not exist as separate executables on the disk. This updates `scanPathExecutables` to explicitly include these built-ins when running on Windows, ensuring a consistent autocomplete experience for Windows users.
2026-02-25 09:26:38 -08:00
jacob314 af8462f76d fix(cli): disable shell autocompletion on completely empty prompts
To reduce visual noise and distraction, autocompletion is now suppressed when the shell prompt is entirely empty (or only contains whitespace). It remains active as soon as the user starts typing or moves the cursor to a position that would suggest paths/commands.
2026-02-25 09:09:33 -08:00
jacob314 2f4242fb60 fix(cli): prevent autocomplete UI flicker by decoupling disabled state reset from completion refresh
When typing outside of shell mode (e.g., using `@` completion), the `useShellCompletion` hook was continuously re-rendering and executing its `useEffect` because `performCompletion` was recreated on every keystroke (since its `query` dependency changed).

Because `enabled` was false, the effect unconditionally called `setSuggestions([])`, rapidly overriding the suggestions populated by `useAtCompletion` and causing severe UI flickering.

This splits the effect to ensure `setSuggestions([])` is only called once when `enabled` becomes false, stabilizing the suggestions list.
2026-02-25 08:58:31 -08:00
jacob314 aeecf5a9e7 fix(cli): prevent auto-submit on Enter when navigating to first shell autocomplete suggestion
When using shell autocomplete, pressing Down then Up returns the activeSuggestionIndex to 0. If the first suggestion happened to be an exact match, the InputPrompt would bypass the normal autocomplete logic and eagerly submit the prompt on Enter because it ignored whether the user had actively navigated.

This fix updates the isPerfectMatch check to require that the user has not navigated the suggestions list, ensuring that explicitly selected items always autocomplete instead of submitting.
2026-02-25 08:23:53 -08:00
MD. MOHIBUR RAHMAN dfa5c79a47 refactor(cli): centralize token parsing in useCommandCompletion to optimize re-renders 2026-02-24 05:22:51 +06:00
MD. MOHIBUR RAHMAN d6770d2ae9 fix(cli): escape executables in shell autocompletion to prevent command injection 2026-02-24 05:06:10 +06:00
MD. MOHIBUR RAHMAN c1d7bc4c8c fix(cli): escape npm script names in shell autocompletion to prevent command injection 2026-02-24 05:04:27 +06:00
MD. MOHIBUR RAHMAN 39b393abfb fix(cli): prevent command injection by escaping git branch suggestions 2026-02-24 04:25:16 +06:00
MD. MOHIBUR RAHMAN 5b3819073f fix(cli): add missing shell metacharacters (\n, \r, \t, \\) to escape regex 2026-02-24 04:14:54 +06:00
MD. MOHIBUR RAHMAN 926afab788 fix(cli): improve shell completion for dotfiles, spaces, and quotes 2026-02-24 03:41:33 +06:00
MD. MOHIBUR RAHMAN 555b95eb09 feat(cli): add context-sensitive shell completions for git and npm (#2492) 2026-02-24 02:52:20 +06:00
MD. MOHIBUR RAHMAN 0c6ebbd1f5 feat(cli): implement interactive shell autocompletion (#2492) 2026-02-24 01:49:30 +06:00
75 changed files with 2586 additions and 2712 deletions
-8
View File
@@ -77,14 +77,6 @@ runs:
--image google/gemini-cli-sandbox:${{ steps.image_tag.outputs.FINAL_TAG }} \
--output-file final_image_uri.txt
echo "uri=$(cat final_image_uri.txt)" >> $GITHUB_OUTPUT
- name: 'verify'
shell: 'bash'
run: |-
docker run --rm --entrypoint sh "${{ steps.docker_build.outputs.uri }}" -lc '
set -e
node -e "const fs=require(\"node:fs\"); JSON.parse(fs.readFileSync(\"/usr/local/share/npm-global/lib/node_modules/@google/gemini-cli/package.json\",\"utf8\")); JSON.parse(fs.readFileSync(\"/usr/local/share/npm-global/lib/node_modules/@google/gemini-cli-core/package.json\",\"utf8\"));"
/usr/local/share/npm-global/bin/gemini --version >/dev/null
'
- name: 'publish'
shell: 'bash'
if: "${{ inputs.dry-run != 'true' }}"
+6 -5
View File
@@ -372,7 +372,8 @@ specific debug settings.
### React DevTools
To debug the CLI's React-based UI, you can use React DevTools.
To debug the CLI's React-based UI, you can use React DevTools. Ink, the library
used for the CLI's interface, is compatible with React DevTools version 4.x.
1. **Start the Gemini CLI in development mode:**
@@ -380,20 +381,20 @@ To debug the CLI's React-based UI, you can use React DevTools.
DEV=true npm start
```
2. **Install and run React DevTools version 6 (which matches the CLI's
`react-devtools-core`):**
2. **Install and run React DevTools version 4.28.5 (or the latest compatible
4.x version):**
You can either install it globally:
```bash
npm install -g react-devtools@6
npm install -g react-devtools@4.28.5
react-devtools
```
Or run it directly using npx:
```bash
npx react-devtools@6
npx react-devtools@4.28.5
```
Your running CLI application should then connect to React DevTools.
+1 -4
View File
@@ -42,10 +42,7 @@ USER node
# install gemini-cli and clean up
COPY packages/cli/dist/google-gemini-cli-*.tgz /tmp/gemini-cli.tgz
COPY packages/core/dist/google-gemini-cli-core-*.tgz /tmp/gemini-core.tgz
RUN npm install -g /tmp/gemini-core.tgz \
&& npm install -g /tmp/gemini-cli.tgz \
&& node -e "const fs=require('node:fs'); JSON.parse(fs.readFileSync('/usr/local/share/npm-global/lib/node_modules/@google/gemini-cli/package.json','utf8')); JSON.parse(fs.readFileSync('/usr/local/share/npm-global/lib/node_modules/@google/gemini-cli-core/package.json','utf8'));" \
&& gemini --version > /dev/null \
RUN npm install -g /tmp/gemini-cli.tgz /tmp/gemini-core.tgz \
&& npm cache clean --force \
&& rm -f /tmp/gemini-{cli,core}.tgz
-2
View File
@@ -29,7 +29,6 @@ they appear in the UI.
| Enable Auto Update | `general.enableAutoUpdate` | Enable automatic updates. | `true` |
| Enable Notifications | `general.enableNotifications` | Enable run-event notifications for action-required prompts and session completion. Currently macOS only. | `false` |
| Plan Directory | `general.plan.directory` | The directory where planning artifacts are stored. If not specified, defaults to the system temporary directory. | `undefined` |
| Max Chat Model Attempts | `general.maxAttempts` | Maximum number of attempts for requests to the main chat model. Cannot exceed 10. | `10` |
| Debug Keystroke Logging | `general.debugKeystrokeLogging` | Enable debug logging of keystrokes to the console. | `false` |
| Enable Session Cleanup | `general.sessionRetention.enabled` | Enable automatic session cleanup | `false` |
| Keep chat history | `general.sessionRetention.maxAge` | Automatically delete chats older than this time period (e.g., "30d", "7d", "24h", "1w") | `undefined` |
@@ -136,7 +135,6 @@ they appear in the UI.
| 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 planning features (Plan Mode and tools). | `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` |
### Skills
-10
View File
@@ -142,11 +142,6 @@ their corresponding top-level category object in your `settings.json` file.
request" errors.
- **Default:** `false`
- **`general.maxAttempts`** (number):
- **Description:** Maximum number of attempts for requests to the main chat
model. Cannot exceed 10.
- **Default:** `10`
- **`general.debugKeystrokeLogging`** (boolean):
- **Description:** Enable debug logging of keystrokes to the console.
- **Default:** `false`
@@ -974,11 +969,6 @@ their corresponding top-level category object in your `settings.json` file.
during tool execution.
- **Default:** `false`
- **`experimental.directWebFetch`** (boolean):
- **Description:** Enable web fetch behavior that bypasses LLM summarization.
- **Default:** `false`
- **Requires restart:** Yes
#### `skills`
- **`skills.enabled`** (boolean):
+14 -42
View File
@@ -64,11 +64,9 @@ primary conditions are the tool's name and its arguments.
The `toolName` in the rule must match the name of the tool being called.
- **Wildcards**: You can use wildcards to match multiple tools.
- `*`: Matches **any tool** (built-in or MCP).
- `server__*`: Matches any tool from a specific MCP server.
- `*__toolName`: Matches a specific tool name across **all** MCP servers.
- `*__*`: Matches **any tool from any MCP server**.
- **Wildcards**: For Model-hosting-protocol (MCP) servers, you can use a
wildcard. A `toolName` of `my-server__*` will match any tool from the
`my-server` MCP.
#### Arguments pattern
@@ -146,9 +144,9 @@ A rule matches a tool call if all of its conditions are met:
1. **Tool name**: The `toolName` in the rule must match the name of the tool
being called.
- **Wildcards**: You can use wildcards like `*`, `server__*`, or
`*__toolName` to match multiple tools. See [Tool Name](#tool-name) for
details.
- **Wildcards**: For Model-hosting-protocol (MCP) servers, you can use a
wildcard. A `toolName` of `my-server__*` will match any tool from the
`my-server` MCP.
2. **Arguments pattern**: If `argsPattern` is specified, the tool's arguments
are converted to a stable JSON string, which is then tested against the
provided regular expression. If the arguments don't match the pattern, the
@@ -274,12 +272,13 @@ priority = 100
### Special syntax for MCP tools
You can create rules that target tools from Model Context Protocol (MCP) servers
using the `mcpName` field or composite wildcard patterns.
You can create rules that target tools from Model-hosting-protocol (MCP) servers
using the `mcpName` field or a wildcard pattern.
**1. Targeting a specific tool on a server**
**1. Using `mcpName`**
Combine `mcpName` and `toolName` to target a single operation.
To target a specific tool from a specific server, combine `mcpName` and
`toolName`.
```toml
# Allows the `search` tool on the `my-jira-server` MCP
@@ -290,10 +289,10 @@ decision = "allow"
priority = 200
```
**2. Targeting all tools on a specific server**
**2. Using a wildcard**
Specify only the `mcpName` to apply a rule to every tool provided by that
server.
To create a rule that applies to _all_ tools on a specific MCP server, specify
only the `mcpName`.
```toml
# Denies all tools from the `untrusted-server` MCP
@@ -304,33 +303,6 @@ priority = 500
deny_message = "This server is not trusted by the admin."
```
**3. Targeting all MCP servers**
Use `mcpName = "*"` to create a rule that applies to **all** tools from **any**
registered MCP server. This is useful for setting category-wide defaults.
```toml
# Ask user for any tool call from any MCP server
[[rule]]
mcpName = "*"
decision = "ask_user"
priority = 10
```
**4. Targeting a tool name across all servers**
Use `mcpName = "*"` with a specific `toolName` to target that operation
regardless of which server provides it.
```toml
# Allow the `search` tool across all connected MCP servers
[[rule]]
mcpName = "*"
toolName = "search"
decision = "allow"
priority = 50
```
## Default policies
The Gemini CLI ships with a set of default policies to provide a safe
+4 -7
View File
@@ -105,11 +105,10 @@ lines containing matches, along with their file paths and line numbers.
## 6. `replace` (Edit)
`replace` replaces text within a file. By default, the tool expects to find and
replace exactly ONE occurrence of `old_string`. If you want to replace multiple
occurrences of the exact same string, set `allow_multiple` to `true`. This tool
is designed for precise, targeted changes and requires significant context
around the `old_string` to ensure it modifies the correct location.
`replace` replaces text within a file. By default, replaces a single occurrence,
but can replace multiple occurrences when `expected_replacements` is specified.
This tool is designed for precise, targeted changes and requires significant
context around the `old_string` to ensure it modifies the correct location.
- **Tool name:** `replace`
- **Arguments:**
@@ -117,8 +116,6 @@ around the `old_string` to ensure it modifies the correct location.
- `instruction` (string, required): Semantic description of the change.
- `old_string` (string, required): Exact literal text to find.
- `new_string` (string, required): Exact literal text to replace with.
- `allow_multiple` (boolean, optional): If `true`, replaces all occurrences.
If `false` (default), only succeeds if exactly one occurrence is found.
- **Confirmation:** Requires manual user approval.
## Next steps
+2 -62
View File
@@ -163,8 +163,7 @@ Each server configuration supports the following properties:
- **`args`** (string[]): Command-line arguments for Stdio transport
- **`headers`** (object): Custom HTTP headers when using `url` or `httpUrl`
- **`env`** (object): Environment variables for the server process. Values can
reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax (all
platforms), or `%VAR_NAME%` (Windows only).
reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax
- **`cwd`** (string): Working directory for Stdio transport
- **`timeout`** (number): Request timeout in milliseconds (default: 600,000ms =
10 minutes)
@@ -185,63 +184,6 @@ Each server configuration supports the following properties:
Service Account to impersonate. Used with
`authProviderType: 'service_account_impersonation'`.
### Environment variable expansion
Gemini CLI automatically expands environment variables in the `env` block of
your MCP server configuration. This allows you to securely reference variables
defined in your shell or environment without hardcoding sensitive information
directly in your `settings.json` file.
The expansion utility supports:
- **POSIX/Bash syntax:** `$VARIABLE_NAME` or `${VARIABLE_NAME}` (supported on
all platforms)
- **Windows syntax:** `%VARIABLE_NAME%` (supported only when running on Windows)
If a variable is not defined in the current environment, it resolves to an empty
string.
**Example:**
```json
"env": {
"API_KEY": "$MY_EXTERNAL_TOKEN",
"LOG_LEVEL": "$LOG_LEVEL",
"TEMP_DIR": "%TEMP%"
}
```
### Security and environment sanitization
To protect your credentials, Gemini CLI performs environment sanitization when
spawning MCP server processes.
#### Automatic redaction
By default, the CLI redacts sensitive environment variables from the base
environment (inherited from the host process) to prevent unintended exposure to
third-party MCP servers. This includes:
- Core project keys: `GEMINI_API_KEY`, `GOOGLE_API_KEY`, etc.
- Variables matching sensitive patterns: `*TOKEN*`, `*SECRET*`, `*PASSWORD*`,
`*KEY*`, `*AUTH*`, `*CREDENTIAL*`.
- Certificates and private key patterns.
#### Explicit overrides
If an environment variable must be passed to an MCP server, you must explicitly
state it in the `env` property of the server configuration in `settings.json`.
Explicitly defined variables (including those from extensions) are trusted and
are **not** subjected to the automatic redaction process.
This follows the security principle that if a variable is explicitly configured
by the user for a specific server, it constitutes informed consent to share that
specific data with that server.
> **Note:** Even when explicitly defined, you should avoid hardcoding secrets.
> Instead, use environment variable expansion (e.g., `"MY_KEY": "$MY_KEY"`) to
> securely pull the value from your host environment at runtime.
### OAuth support for remote MCP servers
The Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using
@@ -796,9 +738,7 @@ The MCP integration tracks several states:
- **Trust settings:** The `trust` option bypasses all confirmation dialogs. Use
cautiously and only for servers you completely control
- **Access tokens:** Be security-aware when configuring environment variables
containing API keys or tokens. See
[Security and environment sanitization](#security-and-environment-sanitization)
for details on how Gemini CLI protects your credentials.
containing API keys or tokens
- **Sandbox compatibility:** When using sandboxing, ensure MCP servers are
available within the sandbox environment
- **Private data:** Using broadly scoped personal access tokens can lead to
+426 -379
View File
File diff suppressed because it is too large Load Diff
+10 -9
View File
@@ -29,8 +29,6 @@ import {
CoderAgentEvent,
getPersistedState,
setPersistedState,
getContextIdFromMetadata,
getAgentSettingsFromMetadata,
} from '../types.js';
import { loadConfig, loadEnvironment, setTargetDir } from '../config/config.js';
import { loadSettings } from '../config/settings.js';
@@ -119,7 +117,8 @@ export class CoderAgentExecutor implements AgentExecutor {
const agentSettings = persistedState._agentSettings;
const config = await this.getConfig(agentSettings, sdkTask.id);
const contextId: string =
getContextIdFromMetadata(metadata) || sdkTask.contextId;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
(metadata['_contextId'] as string) || sdkTask.contextId;
const runtimeTask = await Task.create(
sdkTask.id,
contextId,
@@ -142,10 +141,8 @@ export class CoderAgentExecutor implements AgentExecutor {
agentSettingsInput?: AgentSettings,
eventBus?: ExecutionEventBus,
): Promise<TaskWrapper> {
const agentSettings: AgentSettings = agentSettingsInput || {
kind: CoderAgentEvent.StateAgentSettingsEvent,
workspacePath: process.cwd(),
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const agentSettings = agentSettingsInput || ({} as AgentSettings);
const config = await this.getConfig(agentSettings, taskId);
const runtimeTask = await Task.create(
taskId,
@@ -295,7 +292,8 @@ export class CoderAgentExecutor implements AgentExecutor {
const contextId: string =
userMessage.contextId ||
sdkTask?.contextId ||
getContextIdFromMetadata(sdkTask?.metadata) ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
(sdkTask?.metadata?.['_contextId'] as string) ||
uuidv4();
logger.info(
@@ -390,7 +388,10 @@ export class CoderAgentExecutor implements AgentExecutor {
}
} else {
logger.info(`[CoderAgentExecutor] Creating new task ${taskId}.`);
const agentSettings = getAgentSettingsFromMetadata(userMessage.metadata);
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const agentSettings = userMessage.metadata?.[
'coderAgent'
] as AgentSettings;
try {
wrapper = await this.createTask(
taskId,
+2 -8
View File
@@ -513,10 +513,7 @@ describe('Task', () => {
{
request: { callId: '1' },
status: 'awaiting_approval',
confirmationDetails: {
type: 'edit',
onConfirm: onConfirmSpy,
},
confirmationDetails: { onConfirm: onConfirmSpy },
},
] as unknown as ToolCall[];
@@ -536,10 +533,7 @@ describe('Task', () => {
{
request: { callId: '1' },
status: 'awaiting_approval',
confirmationDetails: {
type: 'edit',
onConfirm: onConfirmSpy,
},
confirmationDetails: { onConfirm: onConfirmSpy },
},
] as unknown as ToolCall[];
+41 -99
View File
@@ -59,33 +59,6 @@ import type { PartUnion, Part as genAiPart } from '@google/genai';
type UnionKeys<T> = T extends T ? keyof T : never;
type ConfirmationType = ToolCallConfirmationDetails['type'];
const VALID_CONFIRMATION_TYPES: readonly ConfirmationType[] = [
'edit',
'exec',
'mcp',
'info',
'ask_user',
'exit_plan_mode',
] as const;
function isToolCallConfirmationDetails(
value: unknown,
): value is ToolCallConfirmationDetails {
if (
typeof value !== 'object' ||
value === null ||
!('onConfirm' in value) ||
typeof value.onConfirm !== 'function' ||
!('type' in value) ||
typeof value.type !== 'string'
) {
return false;
}
return (VALID_CONFIRMATION_TYPES as readonly string[]).includes(value.type);
}
export class Task {
id: string;
contextId: string;
@@ -403,10 +376,11 @@ export class Task {
}
if (tc.status === 'awaiting_approval' && tc.confirmationDetails) {
const details = tc.confirmationDetails;
if (isToolCallConfirmationDetails(details)) {
this.pendingToolConfirmationDetails.set(tc.request.callId, details);
}
this.pendingToolConfirmationDetails.set(
tc.request.callId,
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
tc.confirmationDetails as ToolCallConfirmationDetails,
);
}
// Only send an update if the status has actually changed.
@@ -438,12 +412,11 @@ export class Task {
);
toolCalls.forEach((tc: ToolCall) => {
if (tc.status === 'awaiting_approval' && tc.confirmationDetails) {
const details = tc.confirmationDetails;
if (isToolCallConfirmationDetails(details)) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
details.onConfirm(ToolConfirmationOutcome.ProceedOnce);
this.pendingToolConfirmationDetails.delete(tc.request.callId);
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises, @typescript-eslint/no-unsafe-type-assertion
(tc.confirmationDetails as ToolCallConfirmationDetails).onConfirm(
ToolConfirmationOutcome.ProceedOnce,
);
this.pendingToolConfirmationDetails.delete(tc.request.callId);
}
});
return;
@@ -493,13 +466,15 @@ export class Task {
T extends ToolCall | AnyDeclarativeTool,
K extends UnionKeys<T>,
>(from: T, ...fields: K[]): Partial<T> {
const ret: Partial<T> = {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const ret = {} as Pick<T, K>;
for (const field of fields) {
if (field in from && from[field] !== undefined) {
if (field in from) {
ret[field] = from[field];
}
}
return ret;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return ret as Partial<T>;
}
private toolStatusMessage(
@@ -510,11 +485,8 @@ export class Task {
const messageParts: Part[] = [];
// Create a serializable version of the ToolCall (pick necessary
// properties/avoid methods causing circular reference errors).
// Type allows tool to be Partial<AnyDeclarativeTool> for serialization.
const serializableToolCall: Partial<Omit<ToolCall, 'tool'>> & {
tool?: Partial<AnyDeclarativeTool>;
} = this._pickFields(
// properties/avoid methods causing circular reference errors)
const serializableToolCall: Partial<ToolCall> = this._pickFields(
tc,
'request',
'status',
@@ -524,7 +496,8 @@ export class Task {
);
if (tc.tool) {
const toolFields = this._pickFields(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
serializableToolCall.tool = this._pickFields(
tc.tool,
'name',
'displayName',
@@ -534,8 +507,7 @@ export class Task {
'canUpdateOutput',
'schema',
'parameterSchema',
);
serializableToolCall.tool = toolFields;
) as AnyDeclarativeTool;
}
messageParts.push({
@@ -558,15 +530,8 @@ export class Task {
old_string: string,
new_string: string,
): Promise<string> {
// Validate path to prevent path traversal vulnerabilities
const resolvedPath = path.resolve(this.config.getTargetDir(), file_path);
const pathError = this.config.validatePathAccess(resolvedPath, 'read');
if (pathError) {
throw new Error(`Path validation failed: ${pathError}`);
}
try {
const currentContent = await fs.readFile(resolvedPath, 'utf8');
const currentContent = await fs.readFile(file_path, 'utf8');
return this._applyReplacement(
currentContent,
old_string,
@@ -660,32 +625,15 @@ export class Task {
request.args['old_string'] &&
request.args['new_string']
) {
const filePath = request.args['file_path'];
const oldString = request.args['old_string'];
const newString = request.args['new_string'];
if (
typeof filePath === 'string' &&
typeof oldString === 'string' &&
typeof newString === 'string'
) {
// Resolve and validate path to prevent path traversal (user-controlled file_path).
const resolvedPath = path.resolve(
this.config.getTargetDir(),
filePath,
);
const pathError = this.config.validatePathAccess(
resolvedPath,
'read',
);
if (!pathError) {
const newContent = await this.getProposedContent(
resolvedPath,
oldString,
newString,
);
return { ...request, args: { ...request.args, newContent } };
}
}
const newContent = await this.getProposedContent(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
request.args['file_path'] as string,
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
request.args['old_string'] as string,
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
request.args['new_string'] as string,
);
return { ...request, args: { ...request.args, newContent } };
}
return request;
}),
@@ -777,17 +725,10 @@ export class Task {
break;
case GeminiEventType.Error:
default: {
// Use type guard instead of unsafe type assertion
let errorEvent: ServerGeminiErrorEvent | undefined;
if (
event.type === GeminiEventType.Error &&
event.value &&
typeof event.value === 'object' &&
'error' in event.value
) {
errorEvent = event;
}
const errorMessage = errorEvent?.value?.error
// Block scope for lexical declaration
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const errorEvent = event as ServerGeminiErrorEvent; // Type assertion
const errorMessage = errorEvent.value?.error
? getErrorMessage(errorEvent.value.error)
: 'Unknown error from LLM stream';
logger.error(
@@ -796,7 +737,7 @@ export class Task {
);
let errMessage = `Unknown error from LLM stream: ${JSON.stringify(event)}`;
if (errorEvent?.value?.error) {
if (errorEvent.value?.error) {
errMessage = parseAndFormatApiError(errorEvent.value.error);
}
this.cancelPendingTools(`LLM stream error: ${errorMessage}`);
@@ -873,11 +814,12 @@ export class Task {
// If `edit` tool call, pass updated payload if presesent
if (confirmationDetails.type === 'edit') {
const newContent = part.data['newContent'];
const payload =
typeof newContent === 'string'
? ({ newContent } as ToolConfirmationPayload)
: undefined;
const payload = part.data['newContent']
? ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
newContent: part.data['newContent'] as string,
} as ToolConfirmationPayload)
: undefined;
this.skipFinalTrueAfterInlineEdit = !!payload;
try {
await confirmationDetails.onConfirm(confirmationOutcome, payload);
+2 -51
View File
@@ -122,60 +122,11 @@ export type PersistedTaskMetadata = { [k: string]: unknown };
export const METADATA_KEY = '__persistedState';
function isAgentSettings(value: unknown): value is AgentSettings {
return (
typeof value === 'object' &&
value !== null &&
'kind' in value &&
value.kind === CoderAgentEvent.StateAgentSettingsEvent &&
'workspacePath' in value &&
typeof value.workspacePath === 'string'
);
}
function isPersistedStateMetadata(
value: unknown,
): value is PersistedStateMetadata {
return (
typeof value === 'object' &&
value !== null &&
'_agentSettings' in value &&
'_taskState' in value &&
isAgentSettings(value._agentSettings)
);
}
export function getPersistedState(
metadata: PersistedTaskMetadata,
): PersistedStateMetadata | undefined {
const state = metadata?.[METADATA_KEY];
if (isPersistedStateMetadata(state)) {
return state;
}
return undefined;
}
export function getContextIdFromMetadata(
metadata: PersistedTaskMetadata | undefined,
): string | undefined {
if (!metadata) {
return undefined;
}
const contextId = metadata['_contextId'];
return typeof contextId === 'string' ? contextId : undefined;
}
export function getAgentSettingsFromMetadata(
metadata: PersistedTaskMetadata | undefined,
): AgentSettings | undefined {
if (!metadata) {
return undefined;
}
const coderAgent = metadata['coderAgent'];
if (isAgentSettings(coderAgent)) {
return coderAgent;
}
return undefined;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return metadata?.[METADATA_KEY] as PersistedStateMetadata | undefined;
}
export function setPersistedState(
@@ -71,7 +71,6 @@ export function createMockConfig(
getMcpServers: vi.fn().mockReturnValue({}),
}),
getGitService: vi.fn(),
validatePathAccess: vi.fn().mockReturnValue(undefined),
...overrides,
} as unknown as Config;
mockConfig.getMessageBus = vi.fn().mockReturnValue(createMockMessageBus());
-34
View File
@@ -2016,40 +2016,6 @@ describe('loadCliConfig useRipgrep', () => {
});
});
describe('loadCliConfig directWebFetch', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
vi.stubEnv('GEMINI_API_KEY', 'test-api-key');
vi.spyOn(ExtensionManager.prototype, 'getExtensions').mockReturnValue([]);
});
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it('should be false by default when directWebFetch is not set in settings', async () => {
process.argv = ['node', 'script.js'];
const argv = await parseArguments(createTestMergedSettings());
const settings = createTestMergedSettings();
const config = await loadCliConfig(settings, 'test-session', argv);
expect(config.getDirectWebFetch()).toBe(false);
});
it('should be true when directWebFetch is set to true in settings', async () => {
process.argv = ['node', 'script.js'];
const argv = await parseArguments(createTestMergedSettings());
const settings = createTestMergedSettings({
experimental: {
directWebFetch: true,
},
});
const config = await loadCliConfig(settings, 'test-session', argv);
expect(config.getDirectWebFetch()).toBe(true);
});
});
describe('screenReader configuration', () => {
beforeEach(() => {
vi.resetAllMocks();
+1 -2
View File
@@ -826,8 +826,7 @@ export async function loadCliConfig(
enableExtensionReloading: settings.experimental?.extensionReloading,
enableAgents: settings.experimental?.enableAgents,
plan: settings.experimental?.plan,
directWebFetch: settings.experimental?.directWebFetch,
planSettings: settings.general?.plan,
planSettings: settings.general.plan,
enableEventDrivenScheduler: true,
skillsSupport: settings.skills?.enabled ?? true,
disabledSkills: settings.skills?.disabled,
@@ -132,35 +132,6 @@ describe('Policy Engine Integration Tests', () => {
).toBe(PolicyDecision.ASK_USER);
});
it('should handle global MCP wildcard (*) in settings', async () => {
const settings: Settings = {
mcp: {
allowed: ['*'],
},
};
const config = await createPolicyEngineConfig(
settings,
ApprovalMode.DEFAULT,
);
const engine = new PolicyEngine(config);
// ANY tool with a server name should be allowed
expect(
(await engine.check({ name: 'mcp-server__tool' }, 'mcp-server'))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'another-server__tool' }, 'another-server'))
.decision,
).toBe(PolicyDecision.ALLOW);
// Built-in tools should NOT be allowed by the MCP wildcard
expect(
(await engine.check({ name: 'run_shell_command' }, undefined)).decision,
).toBe(PolicyDecision.ASK_USER);
});
it('should correctly prioritize specific tool excludes over MCP server wildcards', async () => {
const settings: Settings = {
mcp: {
@@ -352,38 +323,6 @@ describe('Policy Engine Integration Tests', () => {
).toBe(PolicyDecision.DENY);
});
it('should correctly match tool annotations', async () => {
const settings: Settings = {};
const config = await createPolicyEngineConfig(
settings,
ApprovalMode.DEFAULT,
);
// Add a manual rule with annotations to the config
config.rules = config.rules || [];
config.rules.push({
toolAnnotations: { readOnlyHint: true },
decision: PolicyDecision.ALLOW,
priority: 10,
});
const engine = new PolicyEngine(config);
// A tool with readOnlyHint=true should be ALLOWED
const roCall = { name: 'some_tool', args: {} };
const roMeta = { readOnlyHint: true };
expect((await engine.check(roCall, undefined, roMeta)).decision).toBe(
PolicyDecision.ALLOW,
);
// A tool without the hint (or with false) should follow default decision (ASK_USER)
const rwMeta = { readOnlyHint: false };
expect((await engine.check(roCall, undefined, rwMeta)).decision).toBe(
PolicyDecision.ASK_USER,
);
});
describe.each(['write_file', 'replace'])(
'Plan Mode policy for %s',
(toolName) => {
-44
View File
@@ -142,48 +142,4 @@ describe('resolveWorkspacePolicyState', () => {
expect.stringContaining('Automatically accepting and loading'),
);
});
it('should not return workspace policies if cwd is the home directory', async () => {
const policiesDir = path.join(tempDir, '.gemini', 'policies');
fs.mkdirSync(policiesDir, { recursive: true });
fs.writeFileSync(path.join(policiesDir, 'policy.toml'), 'rules = []');
// Run from HOME directory (tempDir is mocked as HOME in beforeEach)
const result = await resolveWorkspacePolicyState({
cwd: tempDir,
trustedFolder: true,
interactive: true,
});
expect(result.workspacePoliciesDir).toBeUndefined();
expect(result.policyUpdateConfirmationRequest).toBeUndefined();
});
it('should not return workspace policies if cwd is a symlink to the home directory', async () => {
const policiesDir = path.join(tempDir, '.gemini', 'policies');
fs.mkdirSync(policiesDir, { recursive: true });
fs.writeFileSync(path.join(policiesDir, 'policy.toml'), 'rules = []');
// Create a symlink to the home directory
const symlinkDir = path.join(
os.tmpdir(),
`gemini-cli-symlink-${Date.now()}`,
);
fs.symlinkSync(tempDir, symlinkDir, 'dir');
try {
// Run from symlink to HOME directory
const result = await resolveWorkspacePolicyState({
cwd: symlinkDir,
trustedFolder: true,
interactive: true,
});
expect(result.workspacePoliciesDir).toBeUndefined();
expect(result.policyUpdateConfirmationRequest).toBeUndefined();
} finally {
// Clean up symlink
fs.unlinkSync(symlinkDir);
}
});
});
+3 -9
View File
@@ -67,15 +67,9 @@ export async function resolveWorkspacePolicyState(options: {
| undefined;
if (trustedFolder) {
const storage = new Storage(cwd);
// If we are in the home directory (or rather, our target Gemini dir is the global one),
// don't treat it as a workspace to avoid loading global policies twice.
if (storage.isWorkspaceHomeDir()) {
return { workspacePoliciesDir: undefined };
}
const potentialWorkspacePoliciesDir = storage.getWorkspacePoliciesDir();
const potentialWorkspacePoliciesDir = new Storage(
cwd,
).getWorkspacePoliciesDir();
const integrityManager = new PolicyIntegrityManager();
const integrityResult = await integrityManager.checkIntegrity(
'workspace',
+7 -41
View File
@@ -79,7 +79,6 @@ import {
import {
FatalConfigError,
GEMINI_DIR,
Storage,
type MCPServerConfig,
} from '@google/gemini-cli-core';
import { updateSettingsFilePreservingFormat } from '../utils/commentJson.js';
@@ -127,30 +126,6 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
const os = await import('node:os');
const pathMod = await import('node:path');
const fsMod = await import('node:fs');
// Helper to resolve paths using the test's mocked environment
const testResolve = (p: string | undefined) => {
if (!p) return '';
try {
// Use the mocked fs.realpathSync if available, otherwise fallback
return fsMod.realpathSync(pathMod.resolve(p));
} catch {
return pathMod.resolve(p);
}
};
// Create a smarter mock for isWorkspaceHomeDir
vi.spyOn(actual.Storage.prototype, 'isWorkspaceHomeDir').mockImplementation(
function (this: Storage) {
const target = testResolve(pathMod.dirname(this.getGeminiDir()));
// Pick up the mocked home directory specifically from the 'os' mock
const home = testResolve(os.homedir());
return actual.normalizePath(target) === actual.normalizePath(home);
},
);
return {
...actual,
coreEvents: mockCoreEvents,
@@ -1516,29 +1491,20 @@ describe('Settings Loading and Merging', () => {
return pStr;
});
// Force the storage check to return true for this specific test
const isWorkspaceHomeDirSpy = vi
.spyOn(Storage.prototype, 'isWorkspaceHomeDir')
.mockReturnValue(true);
(mockFsExistsSync as Mock).mockImplementation(
(p: string) =>
// Only return true for workspace settings path to see if it gets loaded
p === mockWorkspaceSettingsPath,
);
try {
const settings = loadSettings(mockSymlinkDir);
const settings = loadSettings(mockSymlinkDir);
// Verify that even though the file exists, it was NOT loaded because realpath matched home
expect(fs.readFileSync).not.toHaveBeenCalledWith(
mockWorkspaceSettingsPath,
'utf-8',
);
expect(settings.workspace.settings).toEqual({});
} finally {
isWorkspaceHomeDirSpy.mockRestore();
}
// Verify that even though the file exists, it was NOT loaded because realpath matched home
expect(fs.readFileSync).not.toHaveBeenCalledWith(
mockWorkspaceSettingsPath,
'utf-8',
);
expect(settings.workspace.settings).toEqual({});
});
});
+21 -5
View File
@@ -637,8 +637,24 @@ export function loadSettings(
const systemSettingsPath = getSystemSettingsPath();
const systemDefaultsPath = getSystemDefaultsPath();
const storage = new Storage(workspaceDir);
const workspaceSettingsPath = storage.getWorkspaceSettingsPath();
// Resolve paths to their canonical representation to handle symlinks
const resolvedWorkspaceDir = path.resolve(workspaceDir);
const resolvedHomeDir = path.resolve(homedir());
let realWorkspaceDir = resolvedWorkspaceDir;
try {
// fs.realpathSync gets the "true" path, resolving any symlinks
realWorkspaceDir = fs.realpathSync(resolvedWorkspaceDir);
} catch (_e) {
// This is okay. The path might not exist yet, and that's a valid state.
}
// We expect homedir to always exist and be resolvable.
const realHomeDir = fs.realpathSync(resolvedHomeDir);
const workspaceSettingsPath = new Storage(
workspaceDir,
).getWorkspaceSettingsPath();
const load = (filePath: string): { settings: Settings; rawJson?: string } => {
try {
@@ -696,7 +712,7 @@ export function loadSettings(
settings: {} as Settings,
rawJson: undefined,
};
if (!storage.isWorkspaceHomeDir()) {
if (realWorkspaceDir !== realHomeDir) {
workspaceResult = load(workspaceSettingsPath);
}
@@ -784,11 +800,11 @@ export function loadSettings(
readOnly: false,
},
{
path: storage.isWorkspaceHomeDir() ? '' : workspaceSettingsPath,
path: realWorkspaceDir === realHomeDir ? '' : workspaceSettingsPath,
settings: workspaceSettings,
originalSettings: workspaceOriginalSettings,
rawJson: workspaceResult.rawJson,
readOnly: storage.isWorkspaceHomeDir(),
readOnly: realWorkspaceDir === realHomeDir,
},
isTrusted,
settingsErrors,
-20
View File
@@ -297,16 +297,6 @@ const SETTINGS_SCHEMA = {
'Retry on "exception TypeError: fetch failed sending request" errors.',
showInDialog: false,
},
maxAttempts: {
type: 'number',
label: 'Max Chat Model Attempts',
category: 'General',
requiresRestart: false,
default: 10,
description:
'Maximum number of attempts for requests to the main chat model. Cannot exceed 10.',
showInDialog: true,
},
debugKeystrokeLogging: {
type: 'boolean',
label: 'Debug Keystroke Logging',
@@ -1703,16 +1693,6 @@ const SETTINGS_SCHEMA = {
'Enable model steering (user hints) to guide the model during tool execution.',
showInDialog: true,
},
directWebFetch: {
type: 'boolean',
label: 'Direct Web Fetch',
category: 'Experimental',
requiresRestart: true,
default: false,
description:
'Enable web fetch behavior that bypasses LLM summarization.',
showInDialog: true,
},
},
},
@@ -411,6 +411,73 @@ describe('InputPrompt', () => {
unmount();
});
it('should submit command in shell mode when Enter pressed with suggestions visible but no arrow navigation', async () => {
props.shellModeActive = true;
props.buffer.setText('ls ');
mockedUseCommandCompletion.mockReturnValue({
...mockCommandCompletion,
showSuggestions: true,
suggestions: [
{ label: 'dir1', value: 'dir1' },
{ label: 'dir2', value: 'dir2' },
],
activeSuggestionIndex: 0,
});
const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />, {
uiActions,
});
// Press Enter without navigating — should dismiss suggestions and fall
// through to the main submit handler.
await act(async () => {
stdin.write('\r');
});
await waitFor(() => {
expect(mockCommandCompletion.resetCompletionState).toHaveBeenCalled();
expect(props.onSubmit).toHaveBeenCalledWith('ls'); // Assert fall-through (text is trimmed)
});
expect(mockCommandCompletion.handleAutocomplete).not.toHaveBeenCalled();
unmount();
});
it('should accept suggestion in shell mode when Enter pressed after arrow navigation', async () => {
props.shellModeActive = true;
props.buffer.setText('ls ');
mockedUseCommandCompletion.mockReturnValue({
...mockCommandCompletion,
showSuggestions: true,
suggestions: [
{ label: 'dir1', value: 'dir1' },
{ label: 'dir2', value: 'dir2' },
],
activeSuggestionIndex: 1,
});
const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />, {
uiActions,
});
// Press ArrowDown to navigate, then Enter to accept
await act(async () => {
stdin.write('\u001B[B'); // ArrowDown — sets hasUserNavigatedSuggestions
});
await waitFor(() =>
expect(mockCommandCompletion.navigateDown).toHaveBeenCalled(),
);
await act(async () => {
stdin.write('\r'); // Enter — should accept navigated suggestion
});
await waitFor(() => {
expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(1);
});
expect(props.onSubmit).not.toHaveBeenCalled();
unmount();
});
it('should NOT call shell history methods when not in shell mode', async () => {
props.buffer.setText('some text');
const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />, {
+34 -3
View File
@@ -259,6 +259,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
>(null);
const pasteTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const innerBoxRef = useRef<DOMElement>(null);
const hasUserNavigatedSuggestions = useRef(false);
const [reverseSearchActive, setReverseSearchActive] = useState(false);
const [commandSearchActive, setCommandSearchActive] = useState(false);
@@ -615,6 +616,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
setSuppressCompletion(
isHistoryNav || isCursorMovement || keyMatchers[Command.ESCAPE](key),
);
hasUserNavigatedSuggestions.current = false;
}
// TODO(jacobr): this special case is likely not needed anymore.
@@ -648,7 +650,13 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
Boolean(completion.promptCompletion.text) ||
reverseSearchActive ||
commandSearchActive;
if (isPlainTab) {
if (isPlainTab && shellModeActive) {
resetPlainTabPress();
if (!completion.showSuggestions) {
setSuppressCompletion(false);
}
} else if (isPlainTab) {
if (!hasTabCompletionInteraction) {
if (registerPlainTabPress() === 2) {
toggleCleanUiDetailsVisible();
@@ -892,7 +900,9 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
completion.isPerfectMatch &&
keyMatchers[Command.SUBMIT](key) &&
recentUnsafePasteTime === null &&
(!completion.showSuggestions || completion.activeSuggestionIndex <= 0)
(!completion.showSuggestions ||
(completion.activeSuggestionIndex <= 0 &&
!hasUserNavigatedSuggestions.current))
) {
handleSubmit(buffer.text);
return true;
@@ -908,11 +918,13 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
if (completion.suggestions.length > 1) {
if (keyMatchers[Command.COMPLETION_UP](key)) {
completion.navigateUp();
hasUserNavigatedSuggestions.current = true;
setExpandedSuggestionIndex(-1); // Reset expansion when navigating
return true;
}
if (keyMatchers[Command.COMPLETION_DOWN](key)) {
completion.navigateDown();
hasUserNavigatedSuggestions.current = true;
setExpandedSuggestionIndex(-1); // Reset expansion when navigating
return true;
}
@@ -930,6 +942,24 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
const isEnterKey = key.name === 'return' && !key.ctrl;
if (isEnterKey && shellModeActive) {
if (hasUserNavigatedSuggestions.current) {
completion.handleAutocomplete(
completion.activeSuggestionIndex,
);
setExpandedSuggestionIndex(-1);
hasUserNavigatedSuggestions.current = false;
return true;
}
completion.resetCompletionState();
setExpandedSuggestionIndex(-1);
hasUserNavigatedSuggestions.current = false;
if (buffer.text.trim()) {
handleSubmit(buffer.text);
}
return true;
}
if (isEnterKey && buffer.text.startsWith('/')) {
const { isArgumentCompletion, leafCommand } =
completion.slashCompletionRange;
@@ -1386,7 +1416,8 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
scrollOffset={activeCompletion.visibleStartIndex}
userInput={buffer.text}
mode={
completion.completionMode === CompletionMode.AT
completion.completionMode === CompletionMode.AT ||
completion.completionMode === CompletionMode.SHELL
? 'reverse'
: buffer.text.startsWith('/') &&
!reverseSearchActive &&
@@ -25,15 +25,15 @@ exports[`SettingsDialog > Initial Rendering > should render settings list with v
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -72,15 +72,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'accessibility settings
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -119,15 +119,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'all boolean settings d
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false* │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -166,15 +166,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'default state' correct
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -213,15 +213,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'file filtering setting
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -260,15 +260,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'focused on scope selec
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ > Apply To │
@@ -307,15 +307,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'mixed boolean and numb
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -354,15 +354,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'tools and security set
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging false │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -401,15 +401,15 @@ exports[`SettingsDialog > Snapshot Tests > should render 'various boolean settin
│ Plan Directory undefined │
│ The directory where planning artifacts are stored. If not specified, defaults t… │
│ │
│ Max Chat Model Attempts 10 │
│ Maximum number of attempts for requests to the main chat model. Cannot exceed 10. │
│ │
│ Debug Keystroke Logging true* │
│ Enable debug logging of keystrokes to the console. │
│ │
│ Enable Session Cleanup false │
│ Enable automatic session cleanup │
│ │
│ Keep chat history undefined │
│ Automatically delete chats older than this time period (e.g., "30d", "7d", "24h… │
│ │
│ ▼ │
│ │
│ Apply To │
@@ -0,0 +1,131 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { gitProvider } from './gitProvider.js';
import * as childProcess from 'node:child_process';
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
return {
...actual,
execFile: vi.fn(),
};
});
describe('gitProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('suggests git subcommands for cursorIndex 1', async () => {
const result = await gitProvider.getCompletions(['git', 'ch'], 1, '/tmp');
expect(result.exclusive).toBe(true);
expect(result.suggestions).toEqual(
expect.arrayContaining([expect.objectContaining({ value: 'checkout' })]),
);
expect(
result.suggestions.find((s) => s.value === 'commit'),
).toBeUndefined();
});
it('suggests branch names for checkout at cursorIndex 2', async () => {
vi.mocked(childProcess.execFile).mockImplementation(
(_cmd, _args, _opts, cb: unknown) => {
const callback = (typeof _opts === 'function' ? _opts : cb) as (
error: Error | null,
result: { stdout: string },
) => void;
callback(null, {
stdout: 'main\nfeature-branch\nfix/bug\nbranch(with)special\n',
});
return {} as ReturnType<typeof childProcess.execFile>;
},
);
const result = await gitProvider.getCompletions(
['git', 'checkout', 'feat'],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(1);
expect(result.suggestions[0].label).toBe('feature-branch');
expect(result.suggestions[0].value).toBe('feature-branch');
expect(childProcess.execFile).toHaveBeenCalledWith(
'git',
['branch', '--format=%(refname:short)'],
expect.any(Object),
expect.any(Function),
);
});
it('escapes branch names with shell metacharacters', async () => {
vi.mocked(childProcess.execFile).mockImplementation(
(_cmd, _args, _opts, cb: unknown) => {
const callback = (typeof _opts === 'function' ? _opts : cb) as (
error: Error | null,
result: { stdout: string },
) => void;
callback(null, { stdout: 'main\nbranch(with)special\n' });
return {} as ReturnType<typeof childProcess.execFile>;
},
);
const result = await gitProvider.getCompletions(
['git', 'checkout', 'branch('],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(1);
expect(result.suggestions[0].label).toBe('branch(with)special');
// On Windows, space escape is not done. But since UNIX_SHELL_SPECIAL_CHARS is mostly tested,
// we can use a matcher that checks if escaping was applied (it differs per platform but that's handled by escapeShellPath).
// Let's match the value against either unescaped (win) or escaped (unix).
const isWin = process.platform === 'win32';
expect(result.suggestions[0].value).toBe(
isWin ? 'branch(with)special' : 'branch\\(with\\)special',
);
});
it('returns empty results if git branch fails', async () => {
vi.mocked(childProcess.execFile).mockImplementation(
(_cmd, _args, _opts, cb: unknown) => {
const callback = (typeof _opts === 'function' ? _opts : cb) as (
error: Error,
stdout?: string,
) => void;
callback(new Error('Not a git repository'));
return {} as ReturnType<typeof childProcess.execFile>;
},
);
const result = await gitProvider.getCompletions(
['git', 'checkout', ''],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(0);
});
it('returns non-exclusive for unrecognized position', async () => {
const result = await gitProvider.getCompletions(
['git', 'commit', '-m', 'some message'],
3,
'/tmp',
);
expect(result.exclusive).toBe(false);
expect(result.suggestions).toHaveLength(0);
});
});
@@ -0,0 +1,93 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import type { ShellCompletionProvider, CompletionResult } from './types.js';
import { escapeShellPath } from '../useShellCompletion.js';
const execFileAsync = promisify(execFile);
const GIT_SUBCOMMANDS = [
'add',
'branch',
'checkout',
'commit',
'diff',
'merge',
'pull',
'push',
'rebase',
'status',
'switch',
];
export const gitProvider: ShellCompletionProvider = {
command: 'git',
async getCompletions(
tokens: string[],
cursorIndex: number,
cwd: string,
signal?: AbortSignal,
): Promise<CompletionResult> {
// We are completing the first argument (subcommand)
if (cursorIndex === 1) {
const partial = tokens[1] || '';
return {
suggestions: GIT_SUBCOMMANDS.filter((cmd) =>
cmd.startsWith(partial),
).map((cmd) => ({
label: cmd,
value: cmd,
description: 'git command',
})),
exclusive: true,
};
}
// We are completing the second argument (e.g. branch name)
if (cursorIndex === 2) {
const subcommand = tokens[1];
if (
subcommand === 'checkout' ||
subcommand === 'switch' ||
subcommand === 'merge' ||
subcommand === 'branch'
) {
const partial = tokens[2] || '';
try {
const { stdout } = await execFileAsync(
'git',
['branch', '--format=%(refname:short)'],
{ cwd, signal },
);
const branches = stdout
.split('\n')
.map((b) => b.trim())
.filter(Boolean);
return {
suggestions: branches
.filter((b) => b.startsWith(partial))
.map((b) => ({
label: b,
value: escapeShellPath(b),
description: 'branch',
})),
exclusive: true,
};
} catch {
// If git fails (e.g. not a git repo), return nothing
return { suggestions: [], exclusive: true };
}
}
}
// Unhandled git argument, fallback to default file completions
return { suggestions: [], exclusive: false };
},
};
@@ -0,0 +1,25 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { ShellCompletionProvider, CompletionResult } from './types.js';
import { gitProvider } from './gitProvider.js';
import { npmProvider } from './npmProvider.js';
const providers: ShellCompletionProvider[] = [gitProvider, npmProvider];
export async function getArgumentCompletions(
commandToken: string,
tokens: string[],
cursorIndex: number,
cwd: string,
signal?: AbortSignal,
): Promise<CompletionResult | null> {
const provider = providers.find((p) => p.command === commandToken);
if (!provider) {
return null;
}
return provider.getCompletions(tokens, cursorIndex, cwd, signal);
}
@@ -0,0 +1,106 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { npmProvider } from './npmProvider.js';
import * as fs from 'node:fs/promises';
vi.mock('node:fs/promises', () => ({
readFile: vi.fn(),
}));
describe('npmProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('suggests npm subcommands for cursorIndex 1', async () => {
const result = await npmProvider.getCompletions(['npm', 'ru'], 1, '/tmp');
expect(result.exclusive).toBe(true);
expect(result.suggestions).toEqual([
expect.objectContaining({ value: 'run' }),
]);
});
it('suggests package.json scripts for npm run at cursorIndex 2', async () => {
const mockPackageJson = {
scripts: {
start: 'node index.js',
build: 'tsc',
'build:dev': 'tsc --watch',
},
};
vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockPackageJson));
const result = await npmProvider.getCompletions(
['npm', 'run', 'bu'],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(2);
expect(result.suggestions[0].label).toBe('build');
expect(result.suggestions[0].value).toBe('build');
expect(result.suggestions[1].label).toBe('build:dev');
expect(result.suggestions[1].value).toBe('build:dev');
expect(fs.readFile).toHaveBeenCalledWith(
expect.stringContaining('package.json'),
'utf8',
);
});
it('escapes script names with shell metacharacters', async () => {
const mockPackageJson = {
scripts: {
'build(prod)': 'tsc',
'test:watch': 'vitest',
},
};
vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockPackageJson));
const result = await npmProvider.getCompletions(
['npm', 'run', 'bu'],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(1);
expect(result.suggestions[0].label).toBe('build(prod)');
// Windows does not escape spaces/parens in cmds by default in our function, but Unix does.
const isWin = process.platform === 'win32';
expect(result.suggestions[0].value).toBe(
isWin ? 'build(prod)' : 'build\\(prod\\)',
);
});
it('handles missing package.json gracefully', async () => {
vi.mocked(fs.readFile).mockRejectedValue(new Error('ENOENT'));
const result = await npmProvider.getCompletions(
['npm', 'run', ''],
2,
'/tmp',
);
expect(result.exclusive).toBe(true);
expect(result.suggestions).toHaveLength(0);
});
it('returns non-exclusive for unrecognized position', async () => {
const result = await npmProvider.getCompletions(
['npm', 'install', 'react'],
2,
'/tmp',
);
expect(result.exclusive).toBe(false);
expect(result.suggestions).toHaveLength(0);
});
});
@@ -0,0 +1,81 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import type { ShellCompletionProvider, CompletionResult } from './types.js';
import { escapeShellPath } from '../useShellCompletion.js';
const NPM_SUBCOMMANDS = [
'build',
'ci',
'dev',
'install',
'publish',
'run',
'start',
'test',
];
export const npmProvider: ShellCompletionProvider = {
command: 'npm',
async getCompletions(
tokens: string[],
cursorIndex: number,
cwd: string,
signal?: AbortSignal,
): Promise<CompletionResult> {
if (cursorIndex === 1) {
const partial = tokens[1] || '';
return {
suggestions: NPM_SUBCOMMANDS.filter((cmd) =>
cmd.startsWith(partial),
).map((cmd) => ({
label: cmd,
value: cmd,
description: 'npm command',
})),
exclusive: true,
};
}
if (cursorIndex === 2 && tokens[1] === 'run') {
const partial = tokens[2] || '';
try {
if (signal?.aborted) return { suggestions: [], exclusive: true };
const pkgJsonPath = path.join(cwd, 'package.json');
const content = await fs.readFile(pkgJsonPath, 'utf8');
const pkg = JSON.parse(content) as unknown;
const scripts =
pkg &&
typeof pkg === 'object' &&
'scripts' in pkg &&
pkg.scripts &&
typeof pkg.scripts === 'object'
? Object.keys(pkg.scripts)
: [];
return {
suggestions: scripts
.filter((s) => s.startsWith(partial))
.map((s) => ({
label: s,
value: escapeShellPath(s),
description: 'npm script',
})),
exclusive: true,
};
} catch {
// No package.json or invalid JSON
return { suggestions: [], exclusive: true };
}
}
return { suggestions: [], exclusive: false };
},
};
@@ -0,0 +1,24 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Suggestion } from '../../components/SuggestionsDisplay.js';
export interface CompletionResult {
suggestions: Suggestion[];
// If true, this prevents the shell from appending generic file/path completions
// to this list. Use this when the tool expects ONLY specific values (e.g. branches).
exclusive?: boolean;
}
export interface ShellCompletionProvider {
command: string; // The command trigger, e.g., 'git' or 'npm'
getCompletions(
tokens: string[], // List of arguments parsed from the input
cursorIndex: number, // Which token index the cursor is currently on
cwd: string,
signal?: AbortSignal,
): Promise<CompletionResult>;
}
@@ -28,6 +28,7 @@ import type { UseAtCompletionProps } from './useAtCompletion.js';
import { useAtCompletion } from './useAtCompletion.js';
import type { UseSlashCompletionProps } from './useSlashCompletion.js';
import { useSlashCompletion } from './useSlashCompletion.js';
import { useShellCompletion } from './useShellCompletion.js';
vi.mock('./useAtCompletion', () => ({
useAtCompletion: vi.fn(),
@@ -40,19 +41,35 @@ vi.mock('./useSlashCompletion', () => ({
})),
}));
vi.mock('./useShellCompletion', () => ({
useShellCompletion: vi.fn(() => ({
completionStart: 0,
completionEnd: 0,
query: '',
})),
}));
// Helper to set up mocks in a consistent way for both child hooks
const setupMocks = ({
atSuggestions = [],
slashSuggestions = [],
shellSuggestions = [],
isLoading = false,
isPerfectMatch = false,
slashCompletionRange = { completionStart: 0, completionEnd: 0 },
shellCompletionRange = { completionStart: 0, completionEnd: 0, query: '' },
}: {
atSuggestions?: Suggestion[];
slashSuggestions?: Suggestion[];
shellSuggestions?: Suggestion[];
isLoading?: boolean;
isPerfectMatch?: boolean;
slashCompletionRange?: { completionStart: number; completionEnd: number };
shellCompletionRange?: {
completionStart: number;
completionEnd: number;
query: string;
};
}) => {
// Mock for @-completions
(useAtCompletion as Mock).mockImplementation(
@@ -89,11 +106,25 @@ const setupMocks = ({
return slashCompletionRange;
},
);
// Mock for shell completions
(useShellCompletion as Mock).mockImplementation(
({ enabled, setSuggestions, setIsLoadingSuggestions }) => {
useEffect(() => {
if (enabled) {
setIsLoadingSuggestions(isLoading);
setSuggestions(shellSuggestions);
}
}, [enabled, setSuggestions, setIsLoadingSuggestions]);
return shellCompletionRange;
},
);
};
describe('useCommandCompletion', () => {
const mockCommandContext = {} as CommandContext;
const mockConfig = {
getEnablePromptCompletion: () => false,
getGeminiClient: vi.fn(),
} as unknown as Config;
const testRootDir = '/';
@@ -498,6 +529,7 @@ describe('useCommandCompletion', () => {
describe('prompt completion filtering', () => {
it('should not trigger prompt completion for line comments', async () => {
const mockConfig = {
getEnablePromptCompletion: () => true,
getGeminiClient: vi.fn(),
} as unknown as Config;
@@ -530,6 +562,7 @@ describe('useCommandCompletion', () => {
it('should not trigger prompt completion for block comments', async () => {
const mockConfig = {
getEnablePromptCompletion: () => true,
getGeminiClient: vi.fn(),
} as unknown as Config;
@@ -564,6 +597,7 @@ describe('useCommandCompletion', () => {
it('should trigger prompt completion for regular text when enabled', async () => {
const mockConfig = {
getEnablePromptCompletion: () => true,
getGeminiClient: vi.fn(),
} as unknown as Config;
@@ -13,6 +13,7 @@ import { isSlashCommand } from '../utils/commandUtils.js';
import { toCodePoints } from '../utils/textUtils.js';
import { useAtCompletion } from './useAtCompletion.js';
import { useSlashCompletion } from './useSlashCompletion.js';
import { useShellCompletion } from './useShellCompletion.js';
import type { PromptCompletion } from './usePromptCompletion.js';
import {
usePromptCompletion,
@@ -26,6 +27,7 @@ export enum CompletionMode {
AT = 'AT',
SLASH = 'SLASH',
PROMPT = 'PROMPT',
SHELL = 'SHELL',
}
export interface UseCommandCompletionReturn {
@@ -99,89 +101,105 @@ export function useCommandCompletion({
const cursorRow = buffer.cursor[0];
const cursorCol = buffer.cursor[1];
const { completionMode, query, completionStart, completionEnd } =
useMemo(() => {
const currentLine = buffer.lines[cursorRow] || '';
const codePoints = toCodePoints(currentLine);
// FIRST: Check for @ completion (scan backwards from cursor)
// This must happen before slash command check so that `/cmd @file`
// triggers file completion, not just slash command completion.
for (let i = cursorCol - 1; i >= 0; i--) {
const char = codePoints[i];
if (char === ' ') {
let backslashCount = 0;
for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
backslashCount++;
}
if (backslashCount % 2 === 0) {
break;
}
} else if (char === '@') {
let end = codePoints.length;
for (let i = cursorCol; i < codePoints.length; i++) {
if (codePoints[i] === ' ') {
let backslashCount = 0;
for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
backslashCount++;
}
if (backslashCount % 2 === 0) {
end = i;
break;
}
}
}
const pathStart = i + 1;
const partialPath = currentLine.substring(pathStart, end);
return {
completionMode: CompletionMode.AT,
query: partialPath,
completionStart: pathStart,
completionEnd: end,
};
}
}
// THEN: Check for slash command (only if no @ completion is active)
if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
return {
completionMode: CompletionMode.SLASH,
query: currentLine,
completionStart: 0,
completionEnd: currentLine.length,
};
}
// Check for prompt completion - only if enabled
const trimmedText = buffer.text.trim();
const isPromptCompletionEnabled = false;
if (
isPromptCompletionEnabled &&
trimmedText.length >= PROMPT_COMPLETION_MIN_LENGTH &&
!isSlashCommand(trimmedText) &&
!trimmedText.includes('@')
) {
return {
completionMode: CompletionMode.PROMPT,
query: trimmedText,
completionStart: 0,
completionEnd: trimmedText.length,
};
}
const {
completionMode,
query: memoQuery,
completionStart,
completionEnd,
} = useMemo(() => {
const currentLine = buffer.lines[cursorRow] || '';
const codePoints = toCodePoints(currentLine);
if (shellModeActive) {
return {
completionMode: CompletionMode.IDLE,
query: null,
completionMode:
currentLine.trim().length === 0
? CompletionMode.IDLE
: CompletionMode.SHELL,
query: '',
completionStart: -1,
completionEnd: -1,
};
}, [cursorRow, cursorCol, buffer.lines, buffer.text]);
}
// FIRST: Check for @ completion (scan backwards from cursor)
// This must happen before slash command check so that `/cmd @file`
// triggers file completion, not just slash command completion.
for (let i = cursorCol - 1; i >= 0; i--) {
const char = codePoints[i];
if (char === ' ') {
let backslashCount = 0;
for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
backslashCount++;
}
if (backslashCount % 2 === 0) {
break;
}
} else if (char === '@') {
let end = codePoints.length;
for (let i = cursorCol; i < codePoints.length; i++) {
if (codePoints[i] === ' ') {
let backslashCount = 0;
for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
backslashCount++;
}
if (backslashCount % 2 === 0) {
end = i;
break;
}
}
}
const pathStart = i + 1;
const partialPath = currentLine.substring(pathStart, end);
return {
completionMode: CompletionMode.AT,
query: partialPath,
completionStart: pathStart,
completionEnd: end,
};
}
}
// THEN: Check for slash command (only if no @ completion is active)
if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
return {
completionMode: CompletionMode.SLASH,
query: currentLine,
completionStart: 0,
completionEnd: currentLine.length,
};
}
// Check for prompt completion - only if enabled
const trimmedText = buffer.text.trim();
const isPromptCompletionEnabled = false;
if (
isPromptCompletionEnabled &&
trimmedText.length >= PROMPT_COMPLETION_MIN_LENGTH &&
!isSlashCommand(trimmedText) &&
!trimmedText.includes('@')
) {
return {
completionMode: CompletionMode.PROMPT,
query: trimmedText,
completionStart: 0,
completionEnd: trimmedText.length,
};
}
return {
completionMode: CompletionMode.IDLE,
query: null,
completionStart: -1,
completionEnd: -1,
};
}, [cursorRow, cursorCol, buffer.lines, buffer.text, shellModeActive]);
useAtCompletion({
enabled: active && completionMode === CompletionMode.AT,
pattern: query || '',
pattern: memoQuery || '',
config,
cwd,
setSuggestions,
@@ -191,7 +209,7 @@ export function useCommandCompletion({
const slashCompletionRange = useSlashCompletion({
enabled:
active && completionMode === CompletionMode.SLASH && !shellModeActive,
query,
query: memoQuery,
slashCommands,
commandContext,
setSuggestions,
@@ -199,9 +217,22 @@ export function useCommandCompletion({
setIsPerfectMatch,
});
const shellCompletionRange = useShellCompletion({
enabled: active && completionMode === CompletionMode.SHELL,
line: buffer.lines[cursorRow] || '',
cursorCol,
cwd,
setSuggestions,
setIsLoadingSuggestions,
});
const query =
completionMode === CompletionMode.SHELL
? shellCompletionRange.query
: memoQuery;
const promptCompletion = usePromptCompletion({
buffer,
config,
});
useEffect(() => {
@@ -258,6 +289,9 @@ export function useCommandCompletion({
if (completionMode === CompletionMode.SLASH) {
start = slashCompletionRange.completionStart;
end = slashCompletionRange.completionEnd;
} else if (completionMode === CompletionMode.SHELL) {
start = shellCompletionRange.completionStart;
end = shellCompletionRange.completionEnd;
}
if (start === -1 || end === -1) {
@@ -287,6 +321,7 @@ export function useCommandCompletion({
completionStart,
completionEnd,
slashCompletionRange,
shellCompletionRange,
],
);
@@ -307,6 +342,9 @@ export function useCommandCompletion({
if (completionMode === CompletionMode.SLASH) {
start = slashCompletionRange.completionStart;
end = slashCompletionRange.completionEnd;
} else if (completionMode === CompletionMode.SHELL) {
start = shellCompletionRange.completionStart;
end = shellCompletionRange.completionEnd;
}
// Add space padding for Tab completion (auto-execute gets padding from getCompletedText)
@@ -345,6 +383,7 @@ export function useCommandCompletion({
completionStart,
completionEnd,
slashCompletionRange,
shellCompletionRange,
getCompletedText,
],
);
@@ -0,0 +1,382 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import {
getTokenAtCursor,
escapeShellPath,
resolvePathCompletions,
scanPathExecutables,
} from './useShellCompletion.js';
import type { FileSystemStructure } from '@google/gemini-cli-test-utils';
import { createTmpDir, cleanupTmpDir } from '@google/gemini-cli-test-utils';
describe('useShellCompletion utilities', () => {
describe('getTokenAtCursor', () => {
it('should return empty token struct for empty line', () => {
expect(getTokenAtCursor('', 0)).toEqual({
token: '',
start: 0,
end: 0,
isFirstToken: true,
tokens: [''],
cursorIndex: 0,
commandToken: '',
});
});
it('should extract the first token at cursor position 0', () => {
const result = getTokenAtCursor('git status', 3);
expect(result).toEqual({
token: 'git',
start: 0,
end: 3,
isFirstToken: true,
tokens: ['git', 'status'],
cursorIndex: 0,
commandToken: 'git',
});
});
it('should extract the second token when cursor is on it', () => {
const result = getTokenAtCursor('git status', 7);
expect(result).toEqual({
token: 'status',
start: 4,
end: 10,
isFirstToken: false,
tokens: ['git', 'status'],
cursorIndex: 1,
commandToken: 'git',
});
});
it('should handle cursor at start of second token', () => {
const result = getTokenAtCursor('git status', 4);
expect(result).toEqual({
token: 'status',
start: 4,
end: 10,
isFirstToken: false,
tokens: ['git', 'status'],
cursorIndex: 1,
commandToken: 'git',
});
});
it('should handle escaped spaces', () => {
const result = getTokenAtCursor('cat my\\ file.txt', 16);
expect(result).toEqual({
token: 'my file.txt',
start: 4,
end: 16,
isFirstToken: false,
tokens: ['cat', 'my file.txt'],
cursorIndex: 1,
commandToken: 'cat',
});
});
it('should handle single-quoted strings', () => {
const result = getTokenAtCursor("cat 'my file.txt'", 17);
expect(result).toEqual({
token: 'my file.txt',
start: 4,
end: 17,
isFirstToken: false,
tokens: ['cat', 'my file.txt'],
cursorIndex: 1,
commandToken: 'cat',
});
});
it('should handle double-quoted strings', () => {
const result = getTokenAtCursor('cat "my file.txt"', 17);
expect(result).toEqual({
token: 'my file.txt',
start: 4,
end: 17,
isFirstToken: false,
tokens: ['cat', 'my file.txt'],
cursorIndex: 1,
commandToken: 'cat',
});
});
it('should handle cursor past all tokens (trailing space)', () => {
const result = getTokenAtCursor('git ', 4);
expect(result).toEqual({
token: '',
start: 4,
end: 4,
isFirstToken: false,
tokens: ['git', ''],
cursorIndex: 1,
commandToken: 'git',
});
});
it('should handle cursor in the middle of a word', () => {
const result = getTokenAtCursor('git checkout main', 7);
expect(result).toEqual({
token: 'checkout',
start: 4,
end: 12,
isFirstToken: false,
tokens: ['git', 'checkout', 'main'],
cursorIndex: 1,
commandToken: 'git',
});
});
it('should mark isFirstToken correctly for first word', () => {
const result = getTokenAtCursor('gi', 2);
expect(result?.isFirstToken).toBe(true);
});
it('should mark isFirstToken correctly for second word', () => {
const result = getTokenAtCursor('git sta', 7);
expect(result?.isFirstToken).toBe(false);
});
});
describe('escapeShellPath', () => {
it('should escape spaces', () => {
expect(escapeShellPath('my file.txt')).toBe('my\\ file.txt');
});
it('should escape parentheses', () => {
expect(escapeShellPath('file (copy).txt')).toBe('file\\ \\(copy\\).txt');
});
it('should not escape normal characters', () => {
expect(escapeShellPath('normal-file.txt')).toBe('normal-file.txt');
});
it('should escape tabs, newlines, carriage returns, and backslashes', () => {
expect(escapeShellPath('a\tb')).toBe('a\\\tb');
expect(escapeShellPath('a\nb')).toBe('a\\\nb');
expect(escapeShellPath('a\rb')).toBe('a\\\rb');
expect(escapeShellPath('a\\b')).toBe('a\\\\b');
});
it('should handle empty string', () => {
expect(escapeShellPath('')).toBe('');
});
});
describe('resolvePathCompletions', () => {
let tmpDir: string;
afterEach(async () => {
if (tmpDir) {
await cleanupTmpDir(tmpDir);
}
});
it('should list directory contents for empty partial', async () => {
const structure: FileSystemStructure = {
'file.txt': '',
subdir: {},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('', tmpDir);
const values = results.map((s) => s.label);
expect(values).toContain('subdir/');
expect(values).toContain('file.txt');
});
it('should filter by prefix', async () => {
const structure: FileSystemStructure = {
'abc.txt': '',
'def.txt': '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('a', tmpDir);
expect(results).toHaveLength(1);
expect(results[0].label).toBe('abc.txt');
});
it('should match case-insensitively', async () => {
const structure: FileSystemStructure = {
Desktop: {},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('desk', tmpDir);
expect(results).toHaveLength(1);
expect(results[0].label).toBe('Desktop/');
});
it('should append trailing slash to directories', async () => {
const structure: FileSystemStructure = {
mydir: {},
'myfile.txt': '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('my', tmpDir);
const dirSuggestion = results.find((s) => s.label.startsWith('mydir'));
expect(dirSuggestion?.label).toBe('mydir/');
expect(dirSuggestion?.description).toBe('directory');
});
it('should hide dotfiles by default', async () => {
const structure: FileSystemStructure = {
'.hidden': '',
visible: '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('', tmpDir);
const labels = results.map((s) => s.label);
expect(labels).not.toContain('.hidden');
expect(labels).toContain('visible');
});
it('should show dotfiles when query starts with a dot', async () => {
const structure: FileSystemStructure = {
'.hidden': '',
'.bashrc': '',
visible: '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('.h', tmpDir);
const labels = results.map((s) => s.label);
expect(labels).toContain('.hidden');
});
it('should show dotfiles in the current directory when query is exactly "."', async () => {
const structure: FileSystemStructure = {
'.hidden': '',
'.bashrc': '',
visible: '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('.', tmpDir);
const labels = results.map((s) => s.label);
expect(labels).toContain('.hidden');
expect(labels).toContain('.bashrc');
expect(labels).not.toContain('visible');
});
it('should handle dotfile completions within a subdirectory', async () => {
const structure: FileSystemStructure = {
subdir: {
'.secret': '',
'public.txt': '',
},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('subdir/.', tmpDir);
const labels = results.map((s) => s.label);
expect(labels).toContain('.secret');
expect(labels).not.toContain('public.txt');
});
it('should strip leading quotes to resolve inner directory contents', async () => {
const structure: FileSystemStructure = {
src: {
'index.ts': '',
},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('"src/', tmpDir);
expect(results).toHaveLength(1);
expect(results[0].label).toBe('index.ts');
const resultsSingleQuote = await resolvePathCompletions("'src/", tmpDir);
expect(resultsSingleQuote).toHaveLength(1);
expect(resultsSingleQuote[0].label).toBe('index.ts');
});
it('should properly escape resolutions with spaces inside stripped quote queries', async () => {
const structure: FileSystemStructure = {
'Folder With Spaces': {},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('"Fo', tmpDir);
expect(results).toHaveLength(1);
expect(results[0].label).toBe('Folder With Spaces/');
expect(results[0].value).toBe(escapeShellPath('Folder With Spaces/'));
});
it('should return empty array for non-existent directory', async () => {
const results = await resolvePathCompletions(
'/nonexistent/path/foo',
'/tmp',
);
expect(results).toEqual([]);
});
it('should handle tilde expansion', async () => {
// Just ensure ~ doesn't throw
const results = await resolvePathCompletions('~/', '/tmp');
// We can't assert specific files since it depends on the test runner's home
expect(Array.isArray(results)).toBe(true);
});
it('should escape special characters in results', async () => {
const structure: FileSystemStructure = {
'my file.txt': '',
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('my', tmpDir);
expect(results).toHaveLength(1);
expect(results[0].value).toBe('my\\ file.txt');
});
it('should sort directories before files', async () => {
const structure: FileSystemStructure = {
'b-file.txt': '',
'a-dir': {},
};
tmpDir = await createTmpDir(structure);
const results = await resolvePathCompletions('', tmpDir);
expect(results[0].description).toBe('directory');
expect(results[1].description).toBe('file');
});
});
describe('scanPathExecutables', () => {
it('should return an array of executables', async () => {
const results = await scanPathExecutables();
expect(Array.isArray(results)).toBe(true);
// Very basic sanity check: common commands should be found
if (process.platform !== 'win32') {
expect(results).toContain('ls');
} else {
expect(results).toContain('dir');
expect(results).toContain('cls');
expect(results).toContain('copy');
}
});
it('should support abort signal', async () => {
const controller = new AbortController();
controller.abort();
const results = await scanPathExecutables(controller.signal);
// May return empty or partial depending on timing
expect(Array.isArray(results)).toBe(true);
});
it('should handle empty PATH', async () => {
vi.stubEnv('PATH', '');
const results = await scanPathExecutables();
expect(results).toEqual([]);
vi.unstubAllEnvs();
});
});
});
@@ -0,0 +1,620 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { useEffect, useRef, useCallback, useMemo } from 'react';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import type { Suggestion } from '../components/SuggestionsDisplay.js';
import { debugLogger } from '@google/gemini-cli-core';
import { getArgumentCompletions } from './shell-completions/index.js';
/**
* Maximum number of suggestions to return to avoid freezing the React Ink UI.
*/
const MAX_SHELL_SUGGESTIONS = 100;
/**
* Debounce interval (ms) for file system completions.
*/
const FS_COMPLETION_DEBOUNCE_MS = 50;
// Backslash-quote shell metacharacters on non-Windows platforms.
// On Unix, backslash-quote shell metacharacters (spaces, parens, etc.).
// On Windows, cmd.exe doesn't use backslash-quoting and `\` is the path
// separator, so we leave the path as-is.
const UNIX_SHELL_SPECIAL_CHARS = /[ \t\n\r'"()&|;<>!#$`{}[\]*?\\]/g;
/**
* Escapes special shell characters in a path segment.
*/
export function escapeShellPath(segment: string): string {
if (process.platform === 'win32') {
return segment;
}
return segment.replace(UNIX_SHELL_SPECIAL_CHARS, '\\$&');
}
export interface TokenInfo {
/** The raw token text (without surrounding quotes but with internal escapes). */
token: string;
/** Offset in the original line where this token begins. */
start: number;
/** Offset in the original line where this token ends (exclusive). */
end: number;
/** Whether this is the first token (command position). */
isFirstToken: boolean;
/** The fully built list of tokens parsing the string. */
tokens: string[];
/** The index in the tokens list where the cursor lies. */
cursorIndex: number;
/** The command token (always tokens[0] if length > 0, otherwise empty string) */
commandToken: string;
}
export function getTokenAtCursor(
line: string,
cursorCol: number,
): TokenInfo | null {
const tokensInfo: Array<{ token: string; start: number; end: number }> = [];
let i = 0;
while (i < line.length) {
// Skip whitespace
if (line[i] === ' ' || line[i] === '\t') {
i++;
continue;
}
const tokenStart = i;
let token = '';
while (i < line.length) {
const ch = line[i];
// Backslash escape: consume the next char literally
if (ch === '\\' && i + 1 < line.length) {
token += line[i + 1];
i += 2;
continue;
}
// Single-quoted string
if (ch === "'") {
i++; // skip opening quote
while (i < line.length && line[i] !== "'") {
token += line[i];
i++;
}
if (i < line.length) i++; // skip closing quote
continue;
}
// Double-quoted string
if (ch === '"') {
i++; // skip opening quote
while (i < line.length && line[i] !== '"') {
if (line[i] === '\\' && i + 1 < line.length) {
token += line[i + 1];
i += 2;
} else {
token += line[i];
i++;
}
}
if (i < line.length) i++; // skip closing quote
continue;
}
// Unquoted whitespace ends the token
if (ch === ' ' || ch === '\t') {
break;
}
token += ch;
i++;
}
tokensInfo.push({ token, start: tokenStart, end: i });
}
const rawTokens = tokensInfo.map((t) => t.token);
const commandToken = rawTokens.length > 0 ? rawTokens[0] : '';
if (tokensInfo.length === 0) {
return {
token: '',
start: cursorCol,
end: cursorCol,
isFirstToken: true,
tokens: [''],
cursorIndex: 0,
commandToken: '',
};
}
// Find the token that contains or is immediately adjacent to the cursor
for (let idx = 0; idx < tokensInfo.length; idx++) {
const t = tokensInfo[idx];
if (cursorCol >= t.start && cursorCol <= t.end) {
return {
token: t.token,
start: t.start,
end: t.end,
isFirstToken: idx === 0,
tokens: rawTokens,
cursorIndex: idx,
commandToken,
};
}
}
// Cursor is past all tokens — treat as starting a new token at cursor position
// (useful when the user types a space and then presses Tab)
return {
token: '',
start: cursorCol,
end: cursorCol,
isFirstToken: tokensInfo.length === 0,
tokens: [...rawTokens, ''],
cursorIndex: rawTokens.length,
commandToken,
};
}
export async function scanPathExecutables(
signal?: AbortSignal,
): Promise<string[]> {
const pathEnv = process.env['PATH'] ?? '';
const dirs = pathEnv.split(path.delimiter).filter(Boolean);
const isWindows = process.platform === 'win32';
const pathExtList = isWindows
? (process.env['PATHEXT'] ?? '.EXE;.CMD;.BAT;.COM')
.split(';')
.filter(Boolean)
.map((e) => e.toLowerCase())
: [];
const seen = new Set<string>();
const executables: string[] = [];
// Add Windows shell built-ins
if (isWindows) {
const builtins = [
'assoc',
'break',
'call',
'cd',
'chcp',
'chdir',
'cls',
'color',
'copy',
'date',
'del',
'dir',
'echo',
'endlocal',
'erase',
'exit',
'for',
'ftype',
'goto',
'if',
'md',
'mkdir',
'mklink',
'move',
'path',
'pause',
'popd',
'prompt',
'pushd',
'rd',
'rem',
'ren',
'rename',
'rmdir',
'set',
'setlocal',
'shift',
'start',
'time',
'title',
'type',
'ver',
'verify',
'vol',
];
for (const builtin of builtins) {
seen.add(builtin);
executables.push(builtin);
}
}
const dirResults = await Promise.all(
dirs.map(async (dir) => {
if (signal?.aborted) return [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
const validEntries: string[] = [];
// Check executability in parallel (batched per directory)
await Promise.all(
entries.map(async (entry) => {
if (signal?.aborted) return;
if (!entry.isFile() && !entry.isSymbolicLink()) return;
const name = entry.name;
if (isWindows) {
const ext = path.extname(name).toLowerCase();
if (pathExtList.length > 0 && !pathExtList.includes(ext)) return;
}
try {
await fs.access(
path.join(dir, name),
fs.constants.R_OK | fs.constants.X_OK,
);
validEntries.push(name);
} catch {
// Not executable — skip
}
}),
);
return validEntries;
} catch {
// EACCES, ENOENT, etc. — skip this directory
return [];
}
}),
);
for (const names of dirResults) {
for (const name of names) {
if (!seen.has(name)) {
seen.add(name);
executables.push(name);
}
}
}
executables.sort();
return executables;
}
function expandTilde(inputPath: string): [string, boolean] {
if (
inputPath === '~' ||
inputPath.startsWith('~/') ||
inputPath.startsWith('~' + path.sep)
) {
return [path.join(os.homedir(), inputPath.slice(1)), true];
}
return [inputPath, false];
}
export async function resolvePathCompletions(
partial: string,
cwd: string,
signal?: AbortSignal,
): Promise<Suggestion[]> {
if (partial == null) return [];
// Input Sanitization
let strippedPartial = partial;
if (strippedPartial.startsWith('"') || strippedPartial.startsWith("'")) {
strippedPartial = strippedPartial.slice(1);
}
if (strippedPartial.endsWith('"') || strippedPartial.endsWith("'")) {
strippedPartial = strippedPartial.slice(0, -1);
}
// Normalize separators \ to /
const normalizedPartial = strippedPartial.replace(/\\/g, '/');
const [expandedPartial, didExpandTilde] = expandTilde(normalizedPartial);
// Directory Detection
const endsWithSep =
normalizedPartial.endsWith('/') || normalizedPartial === '';
const dirToRead = endsWithSep
? path.resolve(cwd, expandedPartial)
: path.resolve(cwd, path.dirname(expandedPartial));
const prefix = endsWithSep ? '' : path.basename(expandedPartial);
const prefixLower = prefix.toLowerCase();
const showDotfiles = prefix.startsWith('.');
let entries: Array<import('node:fs').Dirent>;
try {
if (signal?.aborted) return [];
entries = await fs.readdir(dirToRead, { withFileTypes: true });
} catch {
// EACCES, ENOENT, etc.
return [];
}
if (signal?.aborted) return [];
const suggestions: Suggestion[] = [];
for (const entry of entries) {
if (signal?.aborted) break;
const name = entry.name;
// Hide dotfiles unless query starts with '.'
if (name.startsWith('.') && !showDotfiles) continue;
// Case-insensitive matching
if (!name.toLowerCase().startsWith(prefixLower)) continue;
const isDir = entry.isDirectory();
const displayName = isDir ? name + '/' : name;
// Build the completion value relative to what the user typed
let completionValue: string;
if (endsWithSep) {
completionValue = normalizedPartial + displayName;
} else {
const parentPart = normalizedPartial.slice(
0,
normalizedPartial.length - path.basename(normalizedPartial).length,
);
completionValue = parentPart + displayName;
}
// Restore tilde if we expanded it
if (didExpandTilde) {
const homeDir = os.homedir().replace(/\\/g, '/');
if (completionValue.startsWith(homeDir)) {
completionValue = '~' + completionValue.slice(homeDir.length);
}
}
// Output formatting: Escape special characters in the completion value
// Since normalizedPartial stripped quotes, we escape the value directly.
const escapedValue = escapeShellPath(completionValue);
suggestions.push({
label: displayName,
value: escapedValue,
description: isDir ? 'directory' : 'file',
});
if (suggestions.length >= MAX_SHELL_SUGGESTIONS) break;
}
// Sort: directories first, then alphabetically
suggestions.sort((a, b) => {
const aIsDir = a.description === 'directory';
const bIsDir = b.description === 'directory';
if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
return a.label.localeCompare(b.label);
});
return suggestions;
}
export interface UseShellCompletionProps {
/** Whether shell completion is active. */
enabled: boolean;
/** The current line text. */
line: string;
/** The current cursor column. */
cursorCol: number;
/** The current working directory for path resolution. */
cwd: string;
/** Callback to set suggestions on the parent state. */
setSuggestions: (suggestions: Suggestion[]) => void;
/** Callback to set loading state on the parent. */
setIsLoadingSuggestions: (isLoading: boolean) => void;
}
export interface UseShellCompletionReturn {
completionStart: number;
completionEnd: number;
query: string;
}
export function useShellCompletion({
enabled,
line,
cursorCol,
cwd,
setSuggestions,
setIsLoadingSuggestions,
}: UseShellCompletionProps): UseShellCompletionReturn {
const pathCachePromiseRef = useRef<Promise<string[]> | null>(null);
const pathEnvRef = useRef<string>(process.env['PATH'] ?? '');
const abortRef = useRef<AbortController | null>(null);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
const tokenInfo = useMemo(
() => (enabled ? getTokenAtCursor(line, cursorCol) : null),
[enabled, line, cursorCol],
);
const {
token: query = '',
start: completionStart = -1,
end: completionEnd = -1,
isFirstToken: isCommandPosition = false,
tokens = [],
cursorIndex = -1,
commandToken = '',
} = tokenInfo || {};
// Invalidate PATH cache when $PATH changes
useEffect(() => {
const currentPath = process.env['PATH'] ?? '';
if (currentPath !== pathEnvRef.current) {
pathCachePromiseRef.current = null;
pathEnvRef.current = currentPath;
}
});
const performCompletion = useCallback(async () => {
if (!enabled || !tokenInfo) {
setSuggestions([]);
return;
}
// Skip flags
if (query.startsWith('-')) {
setSuggestions([]);
return;
}
// Cancel any in-flight request
if (abortRef.current) {
abortRef.current.abort();
}
const controller = new AbortController();
abortRef.current = controller;
const { signal } = controller;
try {
let results: Suggestion[];
if (isCommandPosition) {
setIsLoadingSuggestions(true);
if (!pathCachePromiseRef.current) {
// We don't pass the signal here because we want the cache to finish
// even if this specific completion request is aborted.
pathCachePromiseRef.current = scanPathExecutables();
}
const executables = await pathCachePromiseRef.current;
if (signal.aborted) return;
const queryLower = query.toLowerCase();
results = executables
.filter((cmd) => cmd.toLowerCase().startsWith(queryLower))
.sort((a, b) => {
// Prioritize shorter commands as they are likely common built-ins
if (a.length !== b.length) {
return a.length - b.length;
}
return a.localeCompare(b);
})
.slice(0, MAX_SHELL_SUGGESTIONS)
.map((cmd) => ({
label: cmd,
value: escapeShellPath(cmd),
description: 'command',
}));
} else {
const argumentCompletions = await getArgumentCompletions(
commandToken,
tokens,
cursorIndex,
cwd,
signal,
);
if (signal.aborted) return;
if (argumentCompletions?.exclusive) {
results = argumentCompletions.suggestions;
} else {
const pathSuggestions = await resolvePathCompletions(
query,
cwd,
signal,
);
if (signal.aborted) return;
results = [
...(argumentCompletions?.suggestions ?? []),
...pathSuggestions,
].slice(0, MAX_SHELL_SUGGESTIONS);
}
}
if (signal.aborted) return;
setSuggestions(results);
} catch (error) {
if (
!(
signal.aborted ||
(error instanceof Error && error.name === 'AbortError')
)
) {
debugLogger.warn(
`[WARN] shell completion failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
if (!signal.aborted) {
setSuggestions([]);
}
} finally {
if (!signal.aborted) {
setIsLoadingSuggestions(false);
}
}
}, [
enabled,
tokenInfo,
query,
isCommandPosition,
tokens,
cursorIndex,
commandToken,
cwd,
setSuggestions,
setIsLoadingSuggestions,
]);
useEffect(() => {
if (!enabled) {
setSuggestions([]);
setIsLoadingSuggestions(false);
}
}, [enabled, setSuggestions, setIsLoadingSuggestions]);
// Debounced effect to trigger completion
useEffect(() => {
if (!enabled) return;
if (debounceRef.current) {
clearTimeout(debounceRef.current);
}
debounceRef.current = setTimeout(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
performCompletion();
}, FS_COMPLETION_DEBOUNCE_MS);
return () => {
if (debounceRef.current) {
clearTimeout(debounceRef.current);
}
};
}, [enabled, performCompletion]);
// Cleanup on unmount
useEffect(
() => () => {
abortRef.current?.abort();
if (debounceRef.current) {
clearTimeout(debounceRef.current);
}
},
[],
);
return {
completionStart,
completionEnd,
query,
};
}
-2
View File
@@ -53,8 +53,6 @@
"ajv-formats": "^3.0.0",
"chardet": "^2.1.0",
"diff": "^8.0.3",
"dotenv": "^17.2.4",
"dotenv-expand": "^12.0.3",
"fast-levenshtein": "^2.0.6",
"fdir": "^6.4.6",
"fzf": "^0.5.2",
@@ -47,10 +47,7 @@ describe('Fallback Integration', () => {
const requestedModel = PREVIEW_GEMINI_MODEL;
// 3. Apply model selection
const result = applyModelSelection(config, {
model: requestedModel,
isChatModel: true,
});
const result = applyModelSelection(config, { model: requestedModel });
// 4. Expect fallback to Flash
expect(result.model).toBe(PREVIEW_GEMINI_FLASH_MODEL);
@@ -222,10 +222,7 @@ describe('policyHelpers', () => {
selectedModel: 'gemini-pro',
});
const result = applyModelSelection(config, {
model: 'gemini-pro',
isChatModel: true,
});
const result = applyModelSelection(config, { model: 'gemini-pro' });
expect(result.model).toBe('gemini-pro');
expect(result.maxAttempts).toBeUndefined();
expect(config.setActiveModel).toHaveBeenCalledWith('gemini-pro');
@@ -246,10 +243,7 @@ describe('policyHelpers', () => {
selectedModel: 'gemini-flash',
});
const result = applyModelSelection(config, {
model: 'gemini-pro',
isChatModel: true,
});
const result = applyModelSelection(config, { model: 'gemini-pro' });
expect(result.model).toBe('gemini-flash');
expect(result.config).toEqual({
@@ -259,33 +253,14 @@ describe('policyHelpers', () => {
expect(mockModelConfigService.getResolvedConfig).toHaveBeenCalledWith({
model: 'gemini-pro',
isChatModel: true,
});
expect(mockModelConfigService.getResolvedConfig).toHaveBeenCalledWith({
model: 'gemini-flash',
isChatModel: true,
});
expect(config.setActiveModel).toHaveBeenCalledWith('gemini-flash');
});
it('does not call setActiveModel if isChatModel is false', () => {
const config = createExtendedMockConfig();
mockModelConfigService.getResolvedConfig.mockReturnValue({
model: 'gemini-pro',
generateContentConfig: {},
});
mockAvailabilityService.selectFirstAvailable.mockReturnValue({
selectedModel: 'gemini-pro',
});
applyModelSelection(config, {
model: 'gemini-pro',
isChatModel: false,
});
expect(config.setActiveModel).not.toHaveBeenCalled();
});
it('consumes sticky attempt if indicated and isChatModel is true', () => {
it('consumes sticky attempt if indicated', () => {
const config = createExtendedMockConfig();
mockModelConfigService.getResolvedConfig.mockReturnValue({
model: 'gemini-pro',
@@ -296,36 +271,10 @@ describe('policyHelpers', () => {
attempts: 1,
});
const result = applyModelSelection(config, {
model: 'gemini-pro',
isChatModel: true,
});
const result = applyModelSelection(config, { model: 'gemini-pro' });
expect(mockAvailabilityService.consumeStickyAttempt).toHaveBeenCalledWith(
'gemini-pro',
);
expect(config.setActiveModel).toHaveBeenCalledWith('gemini-pro');
expect(result.maxAttempts).toBe(1);
});
it('consumes sticky attempt if indicated but does not call setActiveModel if isChatModel is false', () => {
const config = createExtendedMockConfig();
mockModelConfigService.getResolvedConfig.mockReturnValue({
model: 'gemini-pro',
generateContentConfig: {},
});
mockAvailabilityService.selectFirstAvailable.mockReturnValue({
selectedModel: 'gemini-pro',
attempts: 1,
});
const result = applyModelSelection(config, {
model: 'gemini-pro',
isChatModel: false,
});
expect(mockAvailabilityService.consumeStickyAttempt).toHaveBeenCalledWith(
'gemini-pro',
);
expect(config.setActiveModel).not.toHaveBeenCalled();
expect(result.maxAttempts).toBe(1);
});
@@ -342,7 +291,7 @@ describe('policyHelpers', () => {
const result = applyModelSelection(
config,
{ model: 'gemini-pro', isChatModel: true },
{ model: 'gemini-pro' },
{
consumeAttempt: false,
},
@@ -350,7 +299,6 @@ describe('policyHelpers', () => {
expect(
mockAvailabilityService.consumeStickyAttempt,
).not.toHaveBeenCalled();
expect(config.setActiveModel).toHaveBeenCalledWith('gemini-pro');
expect(result.maxAttempts).toBe(1);
});
});
@@ -214,9 +214,7 @@ export function applyModelSelection(
generateContentConfig = fallbackResolved.generateContentConfig;
}
if (modelConfigKey.isChatModel) {
config.setActiveModel(finalModel);
}
config.setActiveModel(finalModel);
if (selection.attempts && options.consumeAttempt !== false) {
config.getModelAvailabilityService().consumeStickyAttempt(finalModel);
@@ -28,11 +28,6 @@ vi.mock('node:fs', () => ({
readFile: vi.fn(),
rm: vi.fn(),
},
createWriteStream: vi.fn(() => ({
on: vi.fn(),
write: vi.fn(),
end: vi.fn(),
})),
}));
vi.mock('node:os');
vi.mock('node:path');
-24
View File
@@ -8,7 +8,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { Mock } from 'vitest';
import type { ConfigParameters, SandboxConfig } from './config.js';
import { Config, DEFAULT_FILE_FILTERING_OPTIONS } from './config.js';
import { DEFAULT_MAX_ATTEMPTS } from '../utils/retry.js';
import { ExperimentFlags } from '../code_assist/experiments/flagNames.js';
import { debugLogger } from '../utils/debugLogger.js';
import { ApprovalMode } from '../policy/types.js';
@@ -260,29 +259,6 @@ describe('Server Config (config.ts)', () => {
usageStatisticsEnabled: false,
};
describe('maxAttempts', () => {
it('should default to DEFAULT_MAX_ATTEMPTS', () => {
const config = new Config(baseParams);
expect(config.getMaxAttempts()).toBe(DEFAULT_MAX_ATTEMPTS);
});
it('should use provided maxAttempts if <= DEFAULT_MAX_ATTEMPTS', () => {
const config = new Config({
...baseParams,
maxAttempts: 5,
});
expect(config.getMaxAttempts()).toBe(5);
});
it('should cap maxAttempts at DEFAULT_MAX_ATTEMPTS', () => {
const config = new Config({
...baseParams,
maxAttempts: 20,
});
expect(config.getMaxAttempts()).toBe(DEFAULT_MAX_ATTEMPTS);
});
});
beforeEach(() => {
// Reset mocks if necessary
vi.clearAllMocks();
-18
View File
@@ -291,7 +291,6 @@ export interface ExtensionInstallMetadata {
allowPreRelease?: boolean;
}
import { DEFAULT_MAX_ATTEMPTS } from '../utils/retry.js';
import type { FileFilteringOptions } from './constants.js';
import {
DEFAULT_FILE_FILTERING_OPTIONS,
@@ -471,13 +470,11 @@ export interface ConfigParameters {
eventEmitter?: EventEmitter;
useWriteTodos?: boolean;
policyEngineConfig?: PolicyEngineConfig;
directWebFetch?: boolean;
policyUpdateConfirmationRequest?: PolicyUpdateConfirmationRequest;
output?: OutputSettings;
disableModelRouterForAuth?: AuthType[];
continueOnFailedApiCall?: boolean;
retryFetchErrors?: boolean;
maxAttempts?: number;
enableShellOutputEfficiency?: boolean;
shellToolInactivityTimeout?: number;
fakeResponses?: string;
@@ -636,7 +633,6 @@ export class Config {
readonly interactive: boolean;
private readonly ptyInfo: string;
private readonly trustedFolder: boolean | undefined;
private readonly directWebFetch: boolean;
private readonly useRipgrep: boolean;
private readonly enableInteractiveShell: boolean;
private readonly skipNextSpeakerCheck: boolean;
@@ -659,7 +655,6 @@ export class Config {
private readonly outputSettings: OutputSettings;
private readonly continueOnFailedApiCall: boolean;
private readonly retryFetchErrors: boolean;
private readonly maxAttempts: number;
private readonly enableShellOutputEfficiency: boolean;
private readonly shellToolInactivityTimeout: number;
readonly fakeResponses?: string;
@@ -831,7 +826,6 @@ export class Config {
this.interactive = params.interactive ?? false;
this.ptyInfo = params.ptyInfo ?? 'child_process';
this.trustedFolder = params.trustedFolder;
this.directWebFetch = params.directWebFetch ?? false;
this.useRipgrep = params.useRipgrep ?? true;
this.useBackgroundColor = params.useBackgroundColor ?? true;
this.enableInteractiveShell = params.enableInteractiveShell ?? false;
@@ -882,10 +876,6 @@ export class Config {
format: params.output?.format ?? OutputFormat.TEXT,
};
this.retryFetchErrors = params.retryFetchErrors ?? false;
this.maxAttempts = Math.min(
params.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
DEFAULT_MAX_ATTEMPTS,
);
this.disableYoloMode = params.disableYoloMode ?? false;
this.rawOutput = params.rawOutput ?? false;
this.acceptRawOutputRisk = params.acceptRawOutputRisk ?? false;
@@ -2095,10 +2085,6 @@ export class Config {
return this.approvedPlanPath;
}
getDirectWebFetch(): boolean {
return this.directWebFetch;
}
setApprovedPlanPath(path: string | undefined): void {
this.approvedPlanPath = path;
}
@@ -2422,10 +2408,6 @@ export class Config {
return this.retryFetchErrors;
}
getMaxAttempts(): number {
return this.maxAttempts;
}
getEnableShellOutputEfficiency(): boolean {
return this.enableShellOutputEfficiency;
}
-12
View File
@@ -14,7 +14,6 @@ import {
GOOGLE_ACCOUNTS_FILENAME,
isSubpath,
resolveToRealPath,
normalizePath,
} from '../utils/paths.js';
import { ProjectRegistry } from './projectRegistry.js';
import { StorageMigration } from './storageMigration.js';
@@ -143,17 +142,6 @@ export class Storage {
return path.join(this.targetDir, GEMINI_DIR);
}
/**
* Checks if the current workspace storage location is the same as the global/user storage location.
* This handles symlinks and platform-specific path normalization.
*/
isWorkspaceHomeDir(): boolean {
return (
normalizePath(resolveToRealPath(this.targetDir)) ===
normalizePath(resolveToRealPath(homedir()))
);
}
getAgentsDir(): string {
return path.join(this.targetDir, AGENTS_DIR_NAME);
}
+25 -47
View File
@@ -641,7 +641,7 @@ describe('BaseLlmClient', () => {
);
contentOptions = {
modelConfigKey: { model: 'test-model', isChatModel: false },
modelConfigKey: { model: 'test-model' },
contents: [{ role: 'user', parts: [{ text: 'Give me a color.' }] }],
abortSignal: abortController.signal,
promptId: 'content-prompt-id',
@@ -650,17 +650,12 @@ describe('BaseLlmClient', () => {
jsonOptions = {
...defaultOptions,
modelConfigKey: {
...defaultOptions.modelConfigKey,
isChatModel: true,
},
promptId: 'json-prompt-id',
};
});
it('should mark model as healthy on success', async () => {
const successfulModel = 'gemini-pro';
mockConfig.getActiveModel.mockReturnValue(successfulModel);
vi.mocked(mockAvailabilityService.selectFirstAvailable).mockReturnValue({
selectedModel: successfulModel,
skipped: [],
@@ -671,7 +666,7 @@ describe('BaseLlmClient', () => {
await client.generateContent({
...contentOptions,
modelConfigKey: { model: successfulModel, isChatModel: false },
modelConfigKey: { model: successfulModel },
role: LlmRole.UTILITY_TOOL,
});
@@ -683,55 +678,44 @@ describe('BaseLlmClient', () => {
it('marks the final attempted model healthy after a retry with availability enabled', async () => {
const firstModel = 'gemini-pro';
const fallbackModel = 'gemini-flash';
let activeModel = firstModel;
mockConfig.getActiveModel.mockImplementation(() => activeModel);
mockConfig.setActiveModel.mockImplementation((m) => {
activeModel = m;
});
vi.mocked(mockAvailabilityService.selectFirstAvailable)
.mockReturnValueOnce({ selectedModel: firstModel, skipped: [] })
.mockReturnValueOnce({ selectedModel: fallbackModel, skipped: [] });
// Mock generateContent to fail once and then succeed
mockGenerateContent
.mockResolvedValueOnce(createMockResponse(''))
.mockResolvedValueOnce(createMockResponse('retry-me'))
.mockResolvedValueOnce(createMockResponse('final-response'));
// 1. First call starts. applyModelSelection(firstModel) -> currentModel = firstModel.
// 2. apiCall() runs. getActiveModel() === firstModel. call(firstModel). returns ''.
// 3. retry triggers.
// 4. Second call starts. applyModelSelection(firstModel).
// selectFirstAvailable -> fallbackModel.
// setActiveModel(fallbackModel) -> activeModel = fallbackModel.
// returns fallbackModel.
// 5. apiCall() runs. getActiveModel() === fallbackModel. call(fallbackModel). returns 'final-response'.
// Run the real retryWithBackoff (with fake timers) to exercise the retry path
vi.useFakeTimers();
vi.mocked(retryWithBackoff).mockImplementation(async (fn) => {
// First call
let res = (await fn()) as GenerateContentResponse;
if (res.candidates?.[0]?.content?.parts?.[0]?.text === '') {
// Second call
activeModel = fallbackModel;
mockConfig.setActiveModel(fallbackModel);
res = (await fn()) as GenerateContentResponse;
}
mockAvailabilityService.markHealthy(activeModel);
return res;
});
const result = await client.generateContent({
const retryPromise = client.generateContent({
...contentOptions,
modelConfigKey: { model: firstModel, isChatModel: true },
modelConfigKey: { model: firstModel },
maxAttempts: 2,
role: LlmRole.UTILITY_TOOL,
});
expect(result).toEqual(createMockResponse('final-response'));
await vi.runAllTimersAsync();
await retryPromise;
await client.generateContent({
...contentOptions,
modelConfigKey: { model: firstModel },
maxAttempts: 2,
role: LlmRole.UTILITY_TOOL,
});
expect(mockConfig.setActiveModel).toHaveBeenCalledWith(firstModel);
expect(mockConfig.setActiveModel).toHaveBeenCalledWith(fallbackModel);
expect(mockAvailabilityService.markHealthy).toHaveBeenCalledWith(
fallbackModel,
);
expect(mockGenerateContent).toHaveBeenLastCalledWith(
expect.objectContaining({ model: fallbackModel }),
expect.any(String),
LlmRole.UTILITY_TOOL,
);
});
it('should consume sticky attempt if selection has attempts', async () => {
@@ -770,7 +754,6 @@ describe('BaseLlmClient', () => {
it('should mark healthy and honor availability selection when using generateJson', async () => {
const availableModel = 'gemini-json-pro';
mockConfig.getActiveModel.mockReturnValue(availableModel);
vi.mocked(mockAvailabilityService.selectFirstAvailable).mockReturnValue({
selectedModel: availableModel,
skipped: [],
@@ -787,15 +770,10 @@ describe('BaseLlmClient', () => {
return result;
});
const result = await client.generateJson({
...jsonOptions,
modelConfigKey: {
...jsonOptions.modelConfigKey,
isChatModel: false,
},
});
const result = await client.generateJson(jsonOptions);
expect(result).toEqual({ color: 'violet' });
expect(mockConfig.setActiveModel).toHaveBeenCalledWith(availableModel);
expect(mockAvailabilityService.markHealthy).toHaveBeenCalledWith(
availableModel,
);
+3 -6
View File
@@ -280,22 +280,19 @@ export class BaseLlmClient {
() => currentModel,
);
let initialActiveModel = this.config.getActiveModel();
try {
const apiCall = () => {
// Ensure we use the current active model
// in case a fallback occurred in a previous attempt.
const activeModel = this.config.getActiveModel();
if (activeModel !== initialActiveModel) {
initialActiveModel = activeModel;
if (activeModel !== currentModel) {
currentModel = activeModel;
// Re-resolve config if model changed during retry
const { model: resolvedModel, generateContentConfig } =
const { generateContentConfig } =
this.config.modelConfigService.getResolvedConfig({
...modelConfigKey,
model: activeModel,
});
currentModel = resolvedModel;
currentGenerateContentConfig = generateContentConfig;
}
const finalConfig: GenerateContentConfig = {
+7 -11
View File
@@ -957,21 +957,17 @@ export class GeminiClient {
() => currentAttemptModel,
);
let initialActiveModel = this.config.getActiveModel();
const apiCall = () => {
// AvailabilityService
const active = this.config.getActiveModel();
if (active !== initialActiveModel) {
initialActiveModel = active;
if (active !== currentAttemptModel) {
currentAttemptModel = active;
// Re-resolve config if model changed
const { model: resolvedModel, generateContentConfig } =
this.config.modelConfigService.getResolvedConfig({
...modelConfigKey,
model: active,
});
currentAttemptModel = resolvedModel;
currentAttemptGenerateContentConfig = generateContentConfig;
const newConfig = this.config.modelConfigService.getResolvedConfig({
...modelConfigKey,
model: currentAttemptModel,
});
currentAttemptGenerateContentConfig = newConfig.generateContentConfig;
}
const requestConfig: GenerateContentConfig = {
@@ -153,7 +153,6 @@ describe('GeminiChat', () => {
}),
getContentGenerator: vi.fn().mockReturnValue(mockContentGenerator),
getRetryFetchErrors: vi.fn().mockReturnValue(false),
getMaxAttempts: vi.fn().mockReturnValue(10),
getUserTier: vi.fn().mockReturnValue(undefined),
modelConfigService: {
getResolvedConfig: vi.fn().mockImplementation((modelConfigKey) => {
+7 -3
View File
@@ -18,7 +18,11 @@ import type {
} from '@google/genai';
import { toParts } from '../code_assist/converter.js';
import { createUserContent, FinishReason } from '@google/genai';
import { retryWithBackoff, isRetryableError } from '../utils/retry.js';
import {
retryWithBackoff,
isRetryableError,
DEFAULT_MAX_ATTEMPTS,
} from '../utils/retry.js';
import type { ValidationRequiredError } from '../utils/googleQuotaErrors.js';
import type { Config } from '../config/config.js';
import {
@@ -631,12 +635,12 @@ export class GeminiChat {
authType: this.config.getContentGeneratorConfig()?.authType,
retryFetchErrors: this.config.getRetryFetchErrors(),
signal: abortSignal,
maxAttempts: availabilityMaxAttempts ?? this.config.getMaxAttempts(),
maxAttempts: availabilityMaxAttempts,
getAvailabilityContext,
onRetry: (attempt, error, delayMs) => {
coreEvents.emitRetryAttempt({
attempt,
maxAttempts: availabilityMaxAttempts ?? this.config.getMaxAttempts(),
maxAttempts: availabilityMaxAttempts ?? DEFAULT_MAX_ATTEMPTS,
delayMs,
error: error instanceof Error ? error.message : String(error),
model: lastModelToUse,
@@ -94,7 +94,6 @@ describe('GeminiChat Network Retries', () => {
getToolRegistry: vi.fn().mockReturnValue({ getTool: vi.fn() }),
getContentGenerator: vi.fn().mockReturnValue(mockContentGenerator),
getRetryFetchErrors: vi.fn().mockReturnValue(false), // Default false
getMaxAttempts: vi.fn().mockReturnValue(10),
modelConfigService: {
getResolvedConfig: vi.fn().mockImplementation((modelConfigKey) => ({
model: modelConfigKey.model,
@@ -22,11 +22,6 @@ import { LlmRole } from '../telemetry/types.js';
vi.mock('node:fs', () => ({
appendFileSync: vi.fn(),
createWriteStream: vi.fn(() => ({
on: vi.fn(),
write: vi.fn(),
end: vi.fn(),
})),
}));
describe('RecordingContentGenerator', () => {
@@ -17,7 +17,6 @@ vi.mock('node:fs', () => ({
writeFile: vi.fn(),
unlink: vi.fn(),
mkdir: vi.fn(),
rename: vi.fn(),
},
}));
@@ -39,7 +38,6 @@ describe('FileTokenStorage', () => {
writeFile: ReturnType<typeof vi.fn>;
unlink: ReturnType<typeof vi.fn>;
mkdir: ReturnType<typeof vi.fn>;
rename: ReturnType<typeof vi.fn>;
};
const existingCredentials: OAuthCredentials = {
serverName: 'existing-server',
@@ -107,48 +105,12 @@ describe('FileTokenStorage', () => {
expect(result).toEqual(credentials);
});
it('should throw error with file path when file is corrupted', async () => {
it('should throw error for corrupted files', async () => {
mockFs.readFile.mockResolvedValue('corrupted-data');
try {
await storage.getCredentials('test-server');
expect.fail('Expected error to be thrown');
} catch (error) {
expect(error).toBeInstanceOf(Error);
const err = error as Error;
expect(err.message).toContain('Corrupted token file detected at:');
expect(err.message).toContain('mcp-oauth-tokens-v2.json');
expect(err.message).toContain('delete or rename');
}
});
});
describe('auth type switching', () => {
it('should throw error when trying to save credentials with corrupted file', async () => {
// Simulate corrupted file on first read
mockFs.readFile.mockResolvedValue('corrupted-data');
// Try to save new credentials (simulating switch from OAuth to API key)
const newCredentials: OAuthCredentials = {
serverName: 'new-auth-server',
token: {
accessToken: 'new-api-key',
tokenType: 'ApiKey',
},
updatedAt: Date.now(),
};
// Should throw error with file path
try {
await storage.setCredentials(newCredentials);
expect.fail('Expected error to be thrown');
} catch (error) {
expect(error).toBeInstanceOf(Error);
const err = error as Error;
expect(err.message).toContain('Corrupted token file detected at:');
expect(err.message).toContain('mcp-oauth-tokens-v2.json');
expect(err.message).toContain('delete or rename');
}
await expect(storage.getCredentials('test-server')).rejects.toThrow(
'Token file corrupted',
);
});
});
@@ -87,12 +87,7 @@ export class FileTokenStorage extends BaseTokenStorage {
'Unsupported state or unable to authenticate data',
)
) {
// Decryption failed - this can happen when switching between auth types
// or if the file is genuinely corrupted.
throw new Error(
`Corrupted token file detected at: ${this.tokenFilePath}\n` +
`Please delete or rename this file to resolve the issue.`,
);
throw new Error('Token file corrupted');
}
throw error;
}
+9 -172
View File
@@ -431,63 +431,6 @@ describe('PolicyEngine', () => {
});
describe('MCP server wildcard patterns', () => {
it('should match global wildcard (*)', async () => {
engine = new PolicyEngine({
rules: [
{ toolName: '*', decision: PolicyDecision.ALLOW, priority: 10 },
],
});
expect(
(await engine.check({ name: 'read_file' }, undefined)).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'my-server__tool' }, 'my-server')).decision,
).toBe(PolicyDecision.ALLOW);
});
it('should match any MCP tool when toolName is *__*', async () => {
engine = new PolicyEngine({
rules: [
{ toolName: '*__*', decision: PolicyDecision.ALLOW, priority: 10 },
],
defaultDecision: PolicyDecision.DENY,
});
expect((await engine.check({ name: 'mcp__tool' }, 'mcp')).decision).toBe(
PolicyDecision.ALLOW,
);
expect(
(await engine.check({ name: 'other__tool' }, 'other')).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'read_file' }, undefined)).decision,
).toBe(PolicyDecision.DENY);
});
it('should match specific tool across all servers when using *__tool', async () => {
engine = new PolicyEngine({
rules: [
{
toolName: '*__search',
decision: PolicyDecision.ALLOW,
priority: 10,
},
],
defaultDecision: PolicyDecision.DENY,
});
expect((await engine.check({ name: 'ws__search' }, 'ws')).decision).toBe(
PolicyDecision.ALLOW,
);
expect((await engine.check({ name: 'gh__search' }, 'gh')).decision).toBe(
PolicyDecision.ALLOW,
);
expect((await engine.check({ name: 'gh__list' }, 'gh')).decision).toBe(
PolicyDecision.DENY,
);
});
it('should match MCP server wildcard patterns', async () => {
const rules: PolicyRule[] = [
{
@@ -506,35 +449,26 @@ describe('PolicyEngine', () => {
// Should match my-server tools
expect(
(await engine.check({ name: 'my-server__tool1' }, 'my-server'))
.decision,
(await engine.check({ name: 'my-server__tool1' }, undefined)).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'my-server__another_tool' }, 'my-server'))
(await engine.check({ name: 'my-server__another_tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
// Should match blocked-server tools
expect(
(
await engine.check(
{ name: 'blocked-server__tool1' },
'blocked-server',
)
).decision,
(await engine.check({ name: 'blocked-server__tool1' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
expect(
(
await engine.check(
{ name: 'blocked-server__dangerous' },
'blocked-server',
)
).decision,
(await engine.check({ name: 'blocked-server__dangerous' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
// Should not match other patterns
expect(
(await engine.check({ name: 'other-server__tool' }, 'other-server'))
(await engine.check({ name: 'other-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.ASK_USER);
expect(
@@ -563,11 +497,11 @@ describe('PolicyEngine', () => {
// Specific tool deny should override server allow
expect(
(await engine.check({ name: 'my-server__dangerous-tool' }, 'my-server'))
(await engine.check({ name: 'my-server__dangerous-tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
expect(
(await engine.check({ name: 'my-server__safe-tool' }, 'my-server'))
(await engine.check({ name: 'my-server__safe-tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
});
@@ -2328,39 +2262,6 @@ describe('PolicyEngine', () => {
],
expected: [],
},
{
name: 'should handle global wildcard * in getExcludedTools',
rules: [
{
toolName: '*',
decision: PolicyDecision.DENY,
priority: 10,
},
],
expected: ['*'],
},
{
name: 'should handle MCP category wildcard *__* in getExcludedTools',
rules: [
{
toolName: '*__*',
decision: PolicyDecision.DENY,
priority: 10,
},
],
expected: ['*__*'],
},
{
name: 'should handle tool wildcard *__search in getExcludedTools',
rules: [
{
toolName: '*__search',
decision: PolicyDecision.DENY,
priority: 10,
},
],
expected: ['*__search'],
},
];
it.each(testCases)(
@@ -2557,68 +2458,4 @@ describe('PolicyEngine', () => {
expect(checkers[0].priority).toBe(2.5);
});
});
describe('Tool Annotations', () => {
it('should match tools by semantic annotations', async () => {
engine = new PolicyEngine({
rules: [
{
toolAnnotations: { readOnlyHint: true },
decision: PolicyDecision.ALLOW,
priority: 10,
},
],
defaultDecision: PolicyDecision.DENY,
});
const readOnlyTool = { name: 'read', args: {} };
const readOnlyMeta = { readOnlyHint: true, extra: 'info' };
const writeTool = { name: 'write', args: {} };
const writeMeta = { readOnlyHint: false };
expect(
(await engine.check(readOnlyTool, undefined, readOnlyMeta)).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check(writeTool, undefined, writeMeta)).decision,
).toBe(PolicyDecision.DENY);
expect((await engine.check(writeTool, undefined, {})).decision).toBe(
PolicyDecision.DENY,
);
});
it('should support scoped annotation rules', async () => {
engine = new PolicyEngine({
rules: [
{
toolName: '*__*',
toolAnnotations: { experimental: true },
decision: PolicyDecision.DENY,
priority: 20,
},
{
toolName: '*__*',
decision: PolicyDecision.ALLOW,
priority: 10,
},
],
});
expect(
(
await engine.check({ name: 'mcp__test' }, 'mcp', {
experimental: true,
})
).decision,
).toBe(PolicyDecision.DENY);
expect(
(
await engine.check({ name: 'mcp__stable' }, 'mcp', {
experimental: false,
})
).decision,
).toBe(PolicyDecision.ALLOW);
});
});
});
+20 -95
View File
@@ -27,73 +27,19 @@ import {
import { getToolAliases } from '../tools/tool-names.js';
function isWildcardPattern(name: string): boolean {
return name === '*' || name.includes('*');
return name.endsWith('__*');
}
/**
* Checks if a tool call matches a wildcard pattern.
* Supports global (*) and composite (server__*, *__tool, *__*) patterns.
*/
function matchesWildcard(
pattern: string,
toolName: string,
serverName: string | undefined,
): boolean {
if (pattern === '*') {
return true;
}
if (pattern.includes('__')) {
return matchesCompositePattern(pattern, toolName, serverName);
}
return toolName === pattern;
function getWildcardPrefix(pattern: string): string {
return pattern.slice(0, -3);
}
/**
* Matches composite patterns like "server__*", "*__tool", or "*__*".
*/
function matchesCompositePattern(
pattern: string,
toolName: string,
serverName: string | undefined,
): boolean {
const parts = pattern.split('__');
if (parts.length !== 2) return false;
const [patternServer, patternTool] = parts;
// 1. Identify the tool's components
const { actualServer, actualTool } = getToolMetadata(toolName, serverName);
// 2. Composite patterns require a server context
if (actualServer === undefined) {
function matchesWildcard(pattern: string, toolName: string): boolean {
if (!isWildcardPattern(pattern)) {
return false;
}
// 3. Robustness: if serverName is provided, toolName MUST be qualified by it.
// This prevents "malicious-server" from spoofing "trusted-server" by naming itself "trusted-server__malicious".
if (serverName !== undefined && !toolName.startsWith(serverName + '__')) {
return false;
}
// 4. Match components
const serverMatch = patternServer === '*' || patternServer === actualServer;
const toolMatch = patternTool === '*' || patternTool === actualTool;
return serverMatch && toolMatch;
}
/**
* Extracts the server and unqualified tool name from a tool call context.
*/
function getToolMetadata(toolName: string, serverName: string | undefined) {
const sepIndex = toolName.indexOf('__');
const isQualified = sepIndex !== -1;
return {
actualServer:
serverName ?? (isQualified ? toolName.substring(0, sepIndex) : undefined),
actualTool: isQualified ? toolName.substring(sepIndex + 2) : toolName,
};
const prefix = getWildcardPrefix(pattern);
return toolName.startsWith(prefix + '__');
}
function ruleMatches(
@@ -102,7 +48,6 @@ function ruleMatches(
stringifiedArgs: string | undefined,
serverName: string | undefined,
currentApprovalMode: ApprovalMode,
toolAnnotations?: Record<string, unknown>,
): boolean {
// Check if rule applies to current approval mode
if (rule.modes && rule.modes.length > 0) {
@@ -113,11 +58,18 @@ function ruleMatches(
// Check tool name if specified
if (rule.toolName) {
// Support wildcard patterns: "serverName__*" matches "serverName__anyTool"
if (isWildcardPattern(rule.toolName)) {
if (
!toolCall.name ||
!matchesWildcard(rule.toolName, toolCall.name, serverName)
) {
const prefix = getWildcardPrefix(rule.toolName);
if (serverName !== undefined) {
// Robust check: if serverName is provided, it MUST match the prefix exactly.
// This prevents "malicious-server" from spoofing "trusted-server" by naming itself "trusted-server__malicious".
if (serverName !== prefix) {
return false;
}
}
// Always verify the prefix, even if serverName matched
if (!toolCall.name || !matchesWildcard(rule.toolName, toolCall.name)) {
return false;
}
} else if (toolCall.name !== rule.toolName) {
@@ -125,18 +77,6 @@ function ruleMatches(
}
}
// Check annotations if specified
if (rule.toolAnnotations) {
if (!toolAnnotations) {
return false;
}
for (const [key, value] of Object.entries(rule.toolAnnotations)) {
if (toolAnnotations[key] !== value) {
return false;
}
}
}
// Check args pattern if specified
if (rule.argsPattern) {
// If rule has an args pattern but tool has no args, no match
@@ -217,7 +157,6 @@ export class PolicyEngine {
dir_path: string | undefined,
allowRedirection?: boolean,
rule?: PolicyRule,
toolAnnotations?: Record<string, unknown>,
): Promise<CheckResult> {
if (!command) {
return {
@@ -308,7 +247,6 @@ export class PolicyEngine {
const subResult = await this.check(
{ name: toolName, args: { command: subCmd, dir_path } },
serverName,
toolAnnotations,
);
// subResult.decision is already filtered through applyNonInteractiveMode by this.check()
@@ -366,7 +304,6 @@ export class PolicyEngine {
async check(
toolCall: FunctionCall,
serverName: string | undefined,
toolAnnotations?: Record<string, unknown>,
): Promise<CheckResult> {
let stringifiedArgs: string | undefined;
// Compute stringified args once before the loop
@@ -419,14 +356,7 @@ export class PolicyEngine {
for (const rule of this.rules) {
const match = toolCallsToTry.some((tc) =>
ruleMatches(
rule,
tc,
stringifiedArgs,
serverName,
this.approvalMode,
toolAnnotations,
),
ruleMatches(rule, tc, stringifiedArgs, serverName, this.approvalMode),
);
if (match) {
@@ -443,7 +373,6 @@ export class PolicyEngine {
shellDirPath,
rule.allowRedirection,
rule,
toolAnnotations,
);
decision = shellResult.decision;
if (shellResult.rule) {
@@ -470,9 +399,6 @@ export class PolicyEngine {
this.defaultDecision,
serverName,
shellDirPath,
undefined,
undefined,
toolAnnotations,
);
decision = shellResult.decision;
matchedRule = shellResult.rule;
@@ -491,7 +417,6 @@ export class PolicyEngine {
stringifiedArgs,
serverName,
this.approvalMode,
toolAnnotations,
)
) {
debugLogger.debug(
@@ -672,7 +597,7 @@ export class PolicyEngine {
for (const processed of processedTools) {
if (
isWildcardPattern(processed) &&
matchesWildcard(processed, toolName, undefined)
matchesWildcard(processed, toolName)
) {
// It's covered by a higher-priority wildcard rule.
// If that wildcard rule resulted in exclusion, this tool should also be excluded.
@@ -89,52 +89,6 @@ priority = 100
expect(result.errors).toHaveLength(0);
});
it('should parse toolAnnotations from TOML', async () => {
const result = await runLoadPoliciesFromToml(`
[[rule]]
toolName = "annotated-tool"
toolAnnotations = { readOnlyHint = true, custom = "value" }
decision = "allow"
priority = 70
`);
expect(result.rules).toHaveLength(1);
expect(result.rules[0].toolName).toBe('annotated-tool');
expect(result.rules[0].toolAnnotations).toEqual({
readOnlyHint: true,
custom: 'value',
});
expect(result.errors).toHaveLength(0);
});
it('should transform mcpName = "*" to wildcard toolName', async () => {
const result = await runLoadPoliciesFromToml(`
[[rule]]
mcpName = "*"
decision = "ask_user"
priority = 10
`);
expect(result.rules).toHaveLength(1);
expect(result.rules[0].toolName).toBe('*__*');
expect(result.rules[0].decision).toBe(PolicyDecision.ASK_USER);
expect(result.errors).toHaveLength(0);
});
it('should transform mcpName = "*" and specific toolName to wildcard prefix', async () => {
const result = await runLoadPoliciesFromToml(`
[[rule]]
mcpName = "*"
toolName = "search"
decision = "allow"
priority = 10
`);
expect(result.rules).toHaveLength(1);
expect(result.rules[0].toolName).toBe('*__search');
expect(result.errors).toHaveLength(0);
});
it('should transform commandRegex to argsPattern', async () => {
const result = await runLoadPoliciesFromToml(`
[[rule]]
-4
View File
@@ -46,7 +46,6 @@ const PolicyRuleSchema = z.object({
'priority must be <= 999 to prevent tier overflow. Priorities >= 1000 would jump to the next tier.',
}),
modes: z.array(z.nativeEnum(ApprovalMode)).optional(),
toolAnnotations: z.record(z.any()).optional(),
allow_redirection: z.boolean().optional(),
deny_message: z.string().optional(),
});
@@ -62,7 +61,6 @@ const SafetyCheckerRuleSchema = z.object({
commandRegex: z.string().optional(),
priority: z.number().int().default(0),
modes: z.array(z.nativeEnum(ApprovalMode)).optional(),
toolAnnotations: z.record(z.any()).optional(),
checker: z.discriminatedUnion('type', [
z.object({
type: z.literal('in-process'),
@@ -385,7 +383,6 @@ export async function loadPoliciesFromToml(
decision: rule.decision,
priority: transformPriority(rule.priority, tier),
modes: rule.modes,
toolAnnotations: rule.toolAnnotations,
allowRedirection: rule.allow_redirection,
source: `${tierName.charAt(0).toUpperCase() + tierName.slice(1)}: ${file}`,
denyMessage: rule.deny_message,
@@ -470,7 +467,6 @@ export async function loadPoliciesFromToml(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
checker: checker.checker as SafetyCheckerConfig,
modes: checker.modes,
toolAnnotations: checker.toolAnnotations,
source: `${tierName.charAt(0).toUpperCase() + tierName.slice(1)}: ${file}`,
};
-12
View File
@@ -115,12 +115,6 @@ export interface PolicyRule {
*/
argsPattern?: RegExp;
/**
* Metadata annotations provided by the tool (e.g. readOnlyHint).
* All keys and values in this record must match the tool's annotations.
*/
toolAnnotations?: Record<string, unknown>;
/**
* The decision to make when this rule matches.
*/
@@ -171,12 +165,6 @@ export interface SafetyCheckerRule {
*/
argsPattern?: RegExp;
/**
* Metadata annotations provided by the tool (e.g. readOnlyHint).
* All keys and values in this record must match the tool's annotations.
*/
toolAnnotations?: Record<string, unknown>;
/**
* Priority of this checker. Higher numbers run first.
* Default is 0.
@@ -71,7 +71,6 @@ describe('Tool Confirmation Policy Updates', () => {
isPathWithinWorkspace: () => true,
getDirectories: () => [rootDir],
}),
getDirectWebFetch: () => false,
storage: {
getProjectTempDir: () => path.join(os.tmpdir(), 'gemini-cli-temp'),
},
@@ -503,7 +503,7 @@ Use this tool when the user's query implies needing the content of several files
exports[`coreTools snapshots for specific models > Model: gemini-2.5-pro > snapshot for tool: replace 1`] = `
{
"description": "Replaces text within a file. By default, the tool expects to find and replace exactly ONE occurrence of \`old_string\`. If you want to replace multiple occurrences of the exact same string, set \`allow_multiple\` to true. This tool requires providing significant context around the change to ensure precise targeting. Always use the read_file tool to examine the file's current content before attempting a text replacement.
"description": "Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting. Always use the read_file tool to examine the file's current content before attempting a text replacement.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
@@ -512,15 +512,16 @@ exports[`coreTools snapshots for specific models > Model: gemini-2.5-pro > snaps
2. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic and that \`old_string\` and \`new_string\` are different.
3. \`instruction\` is the detailed instruction of what needs to be changed. It is important to Make it specific and detailed so developers or large language models can understand what needs to be changed and perform the changes on their own if necessary.
4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the instance(s) to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations and \`allow_multiple\` is not true, the tool will fail.
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
5. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
**Multiple replacements:** Set \`allow_multiple\` to true if you want to replace ALL occurrences that match \`old_string\` exactly.",
**Multiple replacements:** Set \`expected_replacements\` to the number of occurrences you want to replace. The tool will replace ALL occurrences that match \`old_string\` exactly. Ensure the number of replacements matches your expectation.",
"name": "replace",
"parametersJsonSchema": {
"properties": {
"allow_multiple": {
"description": "If true, the tool will replace all occurrences of \`old_string\`. If false (default), it will only succeed if exactly one occurrence is found.",
"type": "boolean",
"expected_replacements": {
"description": "Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.",
"minimum": 1,
"type": "number",
},
"file_path": {
"description": "The path to the file to modify.",
@@ -1022,12 +1023,12 @@ exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview >
exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview > snapshot for tool: google_web_search 1`] = `
{
"description": "Performs a grounded Google Search to find information across the internet. Returns a synthesized answer with citations (e.g., [1]) and source URIs. Best for finding up-to-date documentation, troubleshooting obscure errors, or broad research. Use this when you don't have a specific URL. If a search result requires deeper analysis, follow up by using 'web_fetch' on the provided URI.",
"description": "Performs a web search using Google Search (via the Gemini API) and returns the results. This tool is useful for finding information on the internet based on a query.",
"name": "google_web_search",
"parametersJsonSchema": {
"properties": {
"query": {
"description": "The search query. Supports natural language questions (e.g., 'Latest breaking changes in React 19') or specific technical queries.",
"description": "The search query to find information on the web.",
"type": "string",
},
},
@@ -1290,14 +1291,15 @@ Use this tool when the user's query implies needing the content of several files
exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview > snapshot for tool: replace 1`] = `
{
"description": "Replaces text within a file. By default, the tool expects to find and replace exactly ONE occurrence of \`old_string\`. If you want to replace multiple occurrences of the exact same string, set \`allow_multiple\` to true. This tool requires providing significant context around the change to ensure precise targeting.
"description": "Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences ONLY when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.",
"name": "replace",
"parametersJsonSchema": {
"properties": {
"allow_multiple": {
"description": "If true, the tool will replace all occurrences of \`old_string\`. If false (default), it will only succeed if exactly one occurrence is found.",
"type": "boolean",
"expected_replacements": {
"description": "Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.",
"minimum": 1,
"type": "number",
},
"file_path": {
"description": "The path to the file to modify.",
@@ -1373,13 +1375,20 @@ exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview >
exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview > snapshot for tool: save_memory 1`] = `
{
"description": "Persists global preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases. Unlike 'write_file', which is for project-specific files, this appends to a global memory file loaded in every workspace. If you are unsure whether a fact should be remembered globally, ask the user first. CRITICAL: Do not use for session-specific context or temporary data.",
"description": "
Saves concise global user context (preferences, facts) for use across ALL workspaces.
### CRITICAL: GLOBAL CONTEXT ONLY
NEVER save workspace-specific context, local paths, or commands (e.g. "The entry point is src/index.js", "The test command is npm test"). These are local to the current workspace and must NOT be saved globally. EXCLUSIVELY for context relevant across ALL workspaces.
- Use for "Remember X" or clear personal facts.
- Do NOT use for session context.",
"name": "save_memory",
"parametersJsonSchema": {
"additionalProperties": false,
"properties": {
"fact": {
"description": "A concise, global fact or preference (e.g., 'I prefer using tabs'). Do not include local paths or project-specific names.",
"description": "The specific fact or piece of information to remember. Should be a clear, self-contained statement.",
"type": "string",
},
},
@@ -1393,12 +1402,12 @@ exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview >
exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview > snapshot for tool: web_fetch 1`] = `
{
"description": "Analyzes and extracts information from up to 20 URLs. Ideal for documentation review, technical research, or reading raw code from GitHub. You can provide specific, complex instructions for the extraction (e.g., 'Summarize the breaking changes'). Provides cited answers based on the content. GitHub 'blob' URLs are automatically converted to raw versions for better processing. Supports HTTP/HTTPS only.",
"description": "Processes content from URL(s), including local and private network addresses (e.g., localhost), embedded in a prompt. Include up to 20 URLs and instructions (e.g., summarize, extract specific data) directly in the 'prompt' parameter.",
"name": "web_fetch",
"parametersJsonSchema": {
"properties": {
"prompt": {
"description": "A string containing the URL(s) and your specific analysis instructions. Be clear about what information you want to find or summarize. Supports up to 20 URLs.",
"description": "A comprehensive prompt that includes the URL(s) (up to 20) to fetch and specific instructions on how to process their content (e.g., "Summarize https://example.com/article and extract key points from https://another.com/data"). All URLs to be fetched must be valid and complete, starting with "http://" or "https://", and be fully-formed with a valid hostname (e.g., a domain name like "example.com" or an IP address). For example, "https://example.com" is valid, but "example.com" is not.",
"type": "string",
},
},
@@ -1412,16 +1421,17 @@ exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview >
exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview > snapshot for tool: write_file 1`] = `
{
"description": "Writes the complete content to a file, automatically creating missing parent directories. Overwrites existing files. The user has the ability to modify 'content' before it is saved. Best for new or small files; use 'replace' for targeted edits to large files.",
"description": "Writes content to a specified file in the local filesystem.
The user has the ability to modify \`content\`. If modified, this will be stated in the response.",
"name": "write_file",
"parametersJsonSchema": {
"properties": {
"content": {
"description": "The complete content to write. Provide the full file; do not use placeholders like '// ... rest of code'.",
"description": "The content to write to the file. Do not use omission placeholders like '(rest of methods ...)', '...', or 'unchanged code'; provide complete literal content.",
"type": "string",
},
"file_path": {
"description": "Path to the file.",
"description": "The path to the file to write to.",
"type": "string",
},
},
@@ -289,7 +289,7 @@ export const DEFAULT_LEGACY_SET: CoreToolSet = {
replace: {
name: EDIT_TOOL_NAME,
description: `Replaces text within a file. By default, the tool expects to find and replace exactly ONE occurrence of \`old_string\`. If you want to replace multiple occurrences of the exact same string, set \`allow_multiple\` to true. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
description: `Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
@@ -298,9 +298,9 @@ export const DEFAULT_LEGACY_SET: CoreToolSet = {
2. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic and that \`old_string\` and \`new_string\` are different.
3. \`instruction\` is the detailed instruction of what needs to be changed. It is important to Make it specific and detailed so developers or large language models can understand what needs to be changed and perform the changes on their own if necessary.
4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the instance(s) to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations and \`allow_multiple\` is not true, the tool will fail.
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
5. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
**Multiple replacements:** Set \`allow_multiple\` to true if you want to replace ALL occurrences that match \`old_string\` exactly.`,
**Multiple replacements:** Set \`expected_replacements\` to the number of occurrences you want to replace. The tool will replace ALL occurrences that match \`old_string\` exactly. Ensure the number of replacements matches your expectation.`,
parametersJsonSchema: {
type: 'object',
properties: {
@@ -336,10 +336,11 @@ A good instruction should concisely answer:
"The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic. Do not use omission placeholders like '(rest of methods ...)', '...', or 'unchanged code'; provide exact literal code.",
type: 'string',
},
allow_multiple: {
type: 'boolean',
expected_replacements: {
type: 'number',
description:
'If true, the tool will replace all occurrences of `old_string`. If false (default), it will only succeed if exactly one occurrence is found.',
'Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.',
minimum: 1,
},
},
required: ['file_path', 'instruction', 'old_string', 'new_string'],
@@ -63,17 +63,18 @@ export const GEMINI_3_SET: CoreToolSet = {
write_file: {
name: WRITE_FILE_TOOL_NAME,
description: `Writes the complete content to a file, automatically creating missing parent directories. Overwrites existing files. The user has the ability to modify 'content' before it is saved. Best for new or small files; use '${EDIT_TOOL_NAME}' for targeted edits to large files.`,
description: `Writes content to a specified file in the local filesystem.
The user has the ability to modify \`content\`. If modified, this will be stated in the response.`,
parametersJsonSchema: {
type: 'object',
properties: {
file_path: {
description: 'Path to the file.',
description: 'The path to the file to write to.',
type: 'string',
},
content: {
description:
"The complete content to write. Provide the full file; do not use placeholders like '// ... rest of code'.",
"The content to write to the file. Do not use omission placeholders like '(rest of methods ...)', '...', or 'unchanged code'; provide complete literal content.",
type: 'string',
},
},
@@ -290,7 +291,7 @@ export const GEMINI_3_SET: CoreToolSet = {
replace: {
name: EDIT_TOOL_NAME,
description: `Replaces text within a file. By default, the tool expects to find and replace exactly ONE occurrence of \`old_string\`. If you want to replace multiple occurrences of the exact same string, set \`allow_multiple\` to true. This tool requires providing significant context around the change to ensure precise targeting.
description: `Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences ONLY when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.`,
parametersJsonSchema: {
type: 'object',
@@ -313,10 +314,11 @@ The user has the ability to modify the \`new_string\` content. If modified, this
"The exact literal text to replace `old_string` with, unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic. Do not use omission placeholders like '(rest of methods ...)', '...', or 'unchanged code'; provide exact literal code.",
type: 'string',
},
allow_multiple: {
type: 'boolean',
expected_replacements: {
type: 'number',
description:
'If true, the tool will replace all occurrences of `old_string`. If false (default), it will only succeed if exactly one occurrence is found.',
'Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.',
minimum: 1,
},
},
required: ['file_path', 'instruction', 'old_string', 'new_string'],
@@ -325,14 +327,14 @@ The user has the ability to modify the \`new_string\` content. If modified, this
google_web_search: {
name: WEB_SEARCH_TOOL_NAME,
description: `Performs a grounded Google Search to find information across the internet. Returns a synthesized answer with citations (e.g., [1]) and source URIs. Best for finding up-to-date documentation, troubleshooting obscure errors, or broad research. Use this when you don't have a specific URL. If a search result requires deeper analysis, follow up by using '${WEB_FETCH_TOOL_NAME}' on the provided URI.`,
description:
'Performs a web search using Google Search (via the Gemini API) and returns the results. This tool is useful for finding information on the internet based on a query.',
parametersJsonSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description:
"The search query. Supports natural language questions (e.g., 'Latest breaking changes in React 19') or specific technical queries.",
description: 'The search query to find information on the web.',
},
},
required: ['query'],
@@ -342,13 +344,13 @@ The user has the ability to modify the \`new_string\` content. If modified, this
web_fetch: {
name: WEB_FETCH_TOOL_NAME,
description:
"Analyzes and extracts information from up to 20 URLs. Ideal for documentation review, technical research, or reading raw code from GitHub. You can provide specific, complex instructions for the extraction (e.g., 'Summarize the breaking changes'). Provides cited answers based on the content. GitHub 'blob' URLs are automatically converted to raw versions for better processing. Supports HTTP/HTTPS only.",
"Processes content from URL(s), including local and private network addresses (e.g., localhost), embedded in a prompt. Include up to 20 URLs and instructions (e.g., summarize, extract specific data) directly in the 'prompt' parameter.",
parametersJsonSchema: {
type: 'object',
properties: {
prompt: {
description:
'A string containing the URL(s) and your specific analysis instructions. Be clear about what information you want to find or summarize. Supports up to 20 URLs.',
'A comprehensive prompt that includes the URL(s) (up to 20) to fetch and specific instructions on how to process their content (e.g., "Summarize https://example.com/article and extract key points from https://another.com/data"). All URLs to be fetched must be valid and complete, starting with "http://" or "https://", and be fully-formed with a valid hostname (e.g., a domain name like "example.com" or an IP address). For example, "https://example.com" is valid, but "example.com" is not.',
type: 'string',
},
},
@@ -428,14 +430,21 @@ Use this tool when the user's query implies needing the content of several files
save_memory: {
name: MEMORY_TOOL_NAME,
description: `Persists global preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases. Unlike '${WRITE_FILE_TOOL_NAME}', which is for project-specific files, this appends to a global memory file loaded in every workspace. If you are unsure whether a fact should be remembered globally, ask the user first. CRITICAL: Do not use for session-specific context or temporary data.`,
description: `
Saves concise global user context (preferences, facts) for use across ALL workspaces.
### CRITICAL: GLOBAL CONTEXT ONLY
NEVER save workspace-specific context, local paths, or commands (e.g. "The entry point is src/index.js", "The test command is npm test"). These are local to the current workspace and must NOT be saved globally. EXCLUSIVELY for context relevant across ALL workspaces.
- Use for "Remember X" or clear personal facts.
- Do NOT use for session context.`,
parametersJsonSchema: {
type: 'object',
properties: {
fact: {
type: 'string',
description:
"A concise, global fact or preference (e.g., 'I prefer using tabs'). Do not include local paths or project-specific names.",
'The specific fact or piece of information to remember. Should be a clear, self-contained statement.',
},
},
required: ['fact'],
+12 -46
View File
@@ -934,7 +934,7 @@ function doIt() {
);
});
describe('allow_multiple', () => {
describe('expected_replacements', () => {
const testFile = 'replacements_test.txt';
let filePath: string;
@@ -944,70 +944,34 @@ function doIt() {
it.each([
{
name: 'succeed when allow_multiple is true and there are multiple occurrences',
name: 'succeed when occurrences match expected_replacements',
content: 'foo foo foo',
allow_multiple: true,
expected: 3,
shouldSucceed: true,
finalContent: 'bar bar bar',
},
{
name: 'succeed when allow_multiple is true and there is exactly 1 occurrence',
content: 'foo',
allow_multiple: true,
shouldSucceed: true,
finalContent: 'bar',
},
{
name: 'fail when allow_multiple is false and there are multiple occurrences',
name: 'fail when occurrences do not match expected_replacements',
content: 'foo foo foo',
allow_multiple: false,
expected: 2,
shouldSucceed: false,
expectedError: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
},
{
name: 'default to 1 expected replacement if allow_multiple not specified',
name: 'default to 1 expected replacement if not specified',
content: 'foo foo',
allow_multiple: undefined,
expected: undefined,
shouldSucceed: false,
expectedError: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
},
{
name: 'succeed when allow_multiple is false and there is exactly 1 occurrence',
content: 'foo',
allow_multiple: false,
shouldSucceed: true,
finalContent: 'bar',
},
{
name: 'fail when allow_multiple is true but there are 0 occurrences',
content: 'baz',
allow_multiple: true,
shouldSucceed: false,
expectedError: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
},
{
name: 'fail when allow_multiple is false but there are 0 occurrences',
content: 'baz',
allow_multiple: false,
shouldSucceed: false,
expectedError: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
},
])(
'should $name',
async ({
content,
allow_multiple,
shouldSucceed,
finalContent,
expectedError,
}) => {
async ({ content, expected, shouldSucceed, finalContent }) => {
fs.writeFileSync(filePath, content, 'utf8');
const params: EditToolParams = {
file_path: filePath,
instruction: 'Replace all foo with bar',
old_string: 'foo',
new_string: 'bar',
...(allow_multiple !== undefined && { allow_multiple }),
...(expected !== undefined && { expected_replacements: expected }),
};
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
@@ -1017,7 +981,9 @@ function doIt() {
if (finalContent)
expect(fs.readFileSync(filePath, 'utf8')).toBe(finalContent);
} else {
expect(result.error?.type).toBe(expectedError);
expect(result.error?.type).toBe(
ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
);
}
},
);
+25 -22
View File
@@ -138,8 +138,9 @@ async function calculateExactReplacement(
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;
const expectedReplacements = params.expected_replacements ?? 1;
if (!params.allow_multiple && exactOccurrences > 1) {
if (exactOccurrences > expectedReplacements) {
return {
newContent: currentContent,
occurrences: exactOccurrences,
@@ -255,33 +256,28 @@ async function calculateRegexReplacement(
// The final pattern captures leading whitespace (indentation) and then matches the token pattern.
// 'm' flag enables multi-line mode, so '^' matches the start of any line.
const finalPattern = `^([ \t]*)${pattern}`;
const flexibleRegex = new RegExp(finalPattern, 'm');
// Always use a global regex to count all potential occurrences for accurate validation.
const globalRegex = new RegExp(finalPattern, 'gm');
const matches = currentContent.match(globalRegex);
const match = flexibleRegex.exec(currentContent);
if (!matches) {
if (!match) {
return null;
}
const occurrences = matches.length;
const indentation = match[1] || '';
const newLines = normalizedReplace.split('\n');
const newBlockWithIndent = applyIndentation(newLines, indentation).join('\n');
// Use the appropriate regex for replacement based on allow_multiple.
const replaceRegex = new RegExp(
finalPattern,
params.allow_multiple ? 'gm' : 'm',
);
// Use replace with the regex to substitute the matched content.
// Since the regex doesn't have the 'g' flag, it will only replace the first occurrence.
const modifiedCode = currentContent.replace(
replaceRegex,
(_match, indentation) =>
applyIndentation(newLines, indentation || '').join('\n'),
flexibleRegex,
newBlockWithIndent,
);
return {
newContent: restoreTrailingNewline(currentContent, modifiedCode),
occurrences,
occurrences: 1, // This method is designed to find and replace only the first occurrence.
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
@@ -345,6 +341,7 @@ export async function calculateReplacement(
export function getErrorReplaceResult(
params: EditToolParams,
occurrences: number,
expectedReplacements: number,
finalOldString: string,
finalNewString: string,
) {
@@ -356,10 +353,13 @@ export function getErrorReplaceResult(
raw: `Failed to edit, 0 occurrences found for old_string in ${params.file_path}. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${READ_FILE_TOOL_NAME} tool to verify.`,
type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
};
} else if (!params.allow_multiple && occurrences !== 1) {
} else if (occurrences !== expectedReplacements) {
const occurrenceTerm =
expectedReplacements === 1 ? 'occurrence' : 'occurrences';
error = {
display: `Failed to edit, expected 1 occurrence but found ${occurrences}.`,
raw: `Failed to edit, Expected 1 occurrence but found ${occurrences} for old_string in file: ${params.file_path}. If you intended to replace multiple occurrences, set 'allow_multiple' to true.`,
display: `Failed to edit, expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences}.`,
raw: `Failed to edit, Expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences} for old_string in file: ${params.file_path}`,
type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
};
} else if (finalOldString === finalNewString) {
@@ -392,10 +392,10 @@ export interface EditToolParams {
new_string: string;
/**
* If true, the tool will replace all occurrences of `old_string` with `new_string`.
* If false (default), the tool will only succeed if exactly one occurrence is found.
* Number of replacements expected. Defaults to 1 if not specified.
* Use when you want to replace multiple occurrences.
*/
allow_multiple?: boolean;
expected_replacements?: number;
/**
* The instruction for what needs to be done.
@@ -517,6 +517,7 @@ class EditToolInvocation
const secondError = getErrorReplaceResult(
params,
secondAttemptResult.occurrences,
params.expected_replacements ?? 1,
secondAttemptResult.finalOldString,
secondAttemptResult.finalNewString,
);
@@ -561,6 +562,7 @@ class EditToolInvocation
params: EditToolParams,
abortSignal: AbortSignal,
): Promise<CalculatedEdit> {
const expectedReplacements = params.expected_replacements ?? 1;
let currentContent: string | null = null;
let fileExists = false;
let originalLineEnding: '\r\n' | '\n' = '\n'; // Default for new files
@@ -647,6 +649,7 @@ class EditToolInvocation
const initialError = getErrorReplaceResult(
params,
replacementResult.occurrences,
expectedReplacements,
replacementResult.finalOldString,
replacementResult.finalNewString,
);
@@ -1704,40 +1704,6 @@ describe('mcp-client', () => {
expect(callArgs.env!['GEMINI_CLI_EXT_VAR']).toBeUndefined();
});
it('should expand environment variables in mcpServerConfig.env and not redact them', async () => {
const mockedTransport = vi
.spyOn(SdkClientStdioLib, 'StdioClientTransport')
.mockReturnValue({} as SdkClientStdioLib.StdioClientTransport);
const originalEnv = process.env;
process.env = {
...originalEnv,
GEMINI_TEST_VAR: 'expanded-value',
};
try {
await createTransport(
'test-server',
{
command: 'test-command',
env: {
TEST_EXPANDED: 'Value is $GEMINI_TEST_VAR',
SECRET_KEY: 'intentional-secret-123',
},
},
false,
EMPTY_CONFIG,
);
const callArgs = mockedTransport.mock.calls[0][0];
expect(callArgs.env).toBeDefined();
expect(callArgs.env!['TEST_EXPANDED']).toBe('Value is expanded-value');
expect(callArgs.env!['SECRET_KEY']).toBe('intentional-secret-123');
} finally {
process.env = originalEnv;
}
});
describe('useGoogleCredentialProvider', () => {
beforeEach(() => {
// Mock GoogleAuth client
+7 -33
View File
@@ -70,7 +70,6 @@ import {
sanitizeEnvironment,
type EnvironmentSanitizationConfig,
} from '../services/environmentSanitization.js';
import { expandEnvVars } from '../utils/envExpansion.js';
import {
GEMINI_CLI_IDENTIFICATION_ENV_VAR,
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
@@ -784,16 +783,9 @@ function createTransportRequestInit(
mcpServerConfig: MCPServerConfig,
headers: Record<string, string>,
): RequestInit {
const expandedHeaders: Record<string, string> = {};
if (mcpServerConfig.headers) {
for (const [key, value] of Object.entries(mcpServerConfig.headers)) {
expandedHeaders[key] = expandEnvVars(value, process.env);
}
}
return {
headers: {
...expandedHeaders,
...mcpServerConfig.headers,
...headers,
},
};
@@ -1978,33 +1970,15 @@ export async function createTransport(
}
if (mcpServerConfig.command) {
// 1. Sanitize the base process environment to prevent unintended leaks of system-wide secrets.
const sanitizedEnv = sanitizeEnvironment(process.env, {
...sanitizationConfig,
enableEnvironmentVariableRedaction: true,
});
const finalEnv: Record<string, string> = {
[GEMINI_CLI_IDENTIFICATION_ENV_VAR]:
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
};
for (const [key, value] of Object.entries(sanitizedEnv)) {
if (value !== undefined) {
finalEnv[key] = value;
}
}
// Expand and merge explicit environment variables from the MCP configuration.
if (mcpServerConfig.env) {
for (const [key, value] of Object.entries(mcpServerConfig.env)) {
finalEnv[key] = expandEnvVars(value, process.env);
}
}
let transport: Transport = new StdioClientTransport({
command: mcpServerConfig.command,
args: mcpServerConfig.args || [],
env: finalEnv,
env: {
...sanitizeEnvironment(process.env, sanitizationConfig),
...(mcpServerConfig.env || {}),
[GEMINI_CLI_IDENTIFICATION_ENV_VAR]:
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
} as Record<string, string>,
cwd: mcpServerConfig.cwd,
stderr: 'pipe',
});
@@ -37,11 +37,6 @@ vi.mock('node:fs/promises', async (importOriginal) => {
vi.mock('fs', () => ({
mkdirSync: vi.fn(),
createWriteStream: vi.fn(() => ({
on: vi.fn(),
write: vi.fn(),
end: vi.fn(),
})),
}));
vi.mock('os');
+35 -368
View File
@@ -5,11 +5,7 @@
*/
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import {
WebFetchTool,
parsePrompt,
convertGithubUrlToRaw,
} from './web-fetch.js';
import { WebFetchTool, parsePrompt } from './web-fetch.js';
import type { Config } from '../config/config.js';
import { ApprovalMode } from '../policy/types.js';
import { ToolConfirmationOutcome } from './tools.js';
@@ -59,72 +55,6 @@ vi.mock('node:crypto', () => ({
randomUUID: vi.fn(),
}));
/**
* Helper to mock fetchWithTimeout with URL matching.
*/
const mockFetch = (url: string, response: Partial<Response> | Error) =>
vi
.spyOn(fetchUtils, 'fetchWithTimeout')
.mockImplementation(async (actualUrl) => {
if (actualUrl !== url) {
throw new Error(
`Unexpected fetch URL: expected "${url}", got "${actualUrl}"`,
);
}
if (response instanceof Error) {
throw response;
}
const headers = response.headers || new Headers();
// If we have text/arrayBuffer but no body, create a body mock
let body = response.body;
if (!body) {
let content: Uint8Array | undefined;
if (response.text) {
const text = await response.text();
content = new TextEncoder().encode(text);
} else if (response.arrayBuffer) {
const ab = await response.arrayBuffer();
content = new Uint8Array(ab);
}
if (content) {
body = {
getReader: () => {
let sent = false;
return {
read: async () => {
if (sent) return { done: true, value: undefined };
sent = true;
return { done: false, value: content };
},
releaseLock: () => {},
cancel: async () => {},
};
},
} as unknown as ReadableStream;
}
}
return {
ok: response.status ? response.status < 400 : true,
status: 200,
headers,
text: response.text || (() => Promise.resolve('')),
arrayBuffer:
response.arrayBuffer || (() => Promise.resolve(new ArrayBuffer(0))),
body: body || {
getReader: () => ({
read: async () => ({ done: true, value: undefined }),
releaseLock: () => {},
cancel: async () => {},
}),
},
...response,
} as unknown as Response;
});
describe('parsePrompt', () => {
it('should extract valid URLs separated by whitespace', () => {
const prompt = 'Go to https://example.com and http://google.com';
@@ -198,42 +128,6 @@ describe('parsePrompt', () => {
});
});
describe('convertGithubUrlToRaw', () => {
it('should convert valid github blob urls', () => {
expect(
convertGithubUrlToRaw('https://github.com/user/repo/blob/main/README.md'),
).toBe('https://raw.githubusercontent.com/user/repo/main/README.md');
});
it('should not convert non-blob github urls', () => {
expect(convertGithubUrlToRaw('https://github.com/user/repo')).toBe(
'https://github.com/user/repo',
);
});
it('should not convert urls with similar domain names', () => {
expect(
convertGithubUrlToRaw('https://mygithub.com/user/repo/blob/main'),
).toBe('https://mygithub.com/user/repo/blob/main');
});
it('should only replace the /blob/ that separates repo from branch', () => {
expect(
convertGithubUrlToRaw('https://github.com/blob/repo/blob/main/test.ts'),
).toBe('https://raw.githubusercontent.com/blob/repo/main/test.ts');
});
it('should not convert urls if blob is not in path', () => {
expect(
convertGithubUrlToRaw('https://github.com/user/repo/tree/main'),
).toBe('https://github.com/user/repo/tree/main');
});
it('should handle invalid urls gracefully', () => {
expect(convertGithubUrlToRaw('not-a-url')).toBe('not-a-url');
});
});
describe('WebFetchTool', () => {
let mockConfig: Config;
let bus: MessageBus;
@@ -248,7 +142,6 @@ describe('WebFetchTool', () => {
getProxy: vi.fn(),
getGeminiClient: mockGetGeminiClient,
getRetryFetchErrors: vi.fn().mockReturnValue(false),
getDirectWebFetch: vi.fn().mockReturnValue(false),
modelConfigService: {
getResolvedConfig: vi.fn().mockImplementation(({ model }) => ({
model,
@@ -260,79 +153,32 @@ describe('WebFetchTool', () => {
});
describe('validateToolParamValues', () => {
describe('standard mode', () => {
it.each([
{
name: 'empty prompt',
prompt: '',
expectedError: "The 'prompt' parameter cannot be empty",
},
{
name: 'prompt with no URLs',
prompt: 'hello world',
expectedError: "The 'prompt' must contain at least one valid URL",
},
{
name: 'prompt with malformed URLs',
prompt: 'fetch httpshttps://example.com',
expectedError: 'Error(s) in prompt URLs:',
},
])('should throw if $name', ({ prompt, expectedError }) => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ prompt })).toThrow(expectedError);
});
it('should pass if prompt contains at least one valid URL', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() =>
tool.build({ prompt: 'fetch https://example.com' }),
).not.toThrow();
});
});
describe('experimental mode', () => {
beforeEach(() => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
});
it('should throw if url is missing', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ prompt: 'foo' })).toThrow(
"params must have required property 'url'",
);
});
it('should throw if url is invalid', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ url: 'not-a-url' })).toThrow(
'Invalid URL: "not-a-url"',
);
});
it('should pass if url is valid', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ url: 'https://example.com' })).not.toThrow();
});
});
});
describe('getSchema', () => {
it('should return standard schema by default', () => {
it.each([
{
name: 'empty prompt',
prompt: '',
expectedError: "The 'prompt' parameter cannot be empty",
},
{
name: 'prompt with no URLs',
prompt: 'hello world',
expectedError: "The 'prompt' must contain at least one valid URL",
},
{
name: 'prompt with malformed URLs',
prompt: 'fetch httpshttps://example.com',
expectedError: 'Error(s) in prompt URLs:',
},
])('should throw if $name', ({ prompt, expectedError }) => {
const tool = new WebFetchTool(mockConfig, bus);
const schema = tool.getSchema();
expect(schema.parametersJsonSchema).toHaveProperty('properties.prompt');
expect(schema.parametersJsonSchema).not.toHaveProperty('properties.url');
expect(() => tool.build({ prompt })).toThrow(expectedError);
});
it('should return experimental schema when enabled', () => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
it('should pass if prompt contains at least one valid URL', () => {
const tool = new WebFetchTool(mockConfig, bus);
const schema = tool.getSchema();
expect(schema.parametersJsonSchema).toHaveProperty('properties.url');
expect(schema.parametersJsonSchema).not.toHaveProperty(
'properties.prompt',
);
expect(schema.parametersJsonSchema).toHaveProperty('required', ['url']);
expect(() =>
tool.build({ prompt: 'fetch https://example.com' }),
).not.toThrow();
});
});
@@ -359,7 +205,9 @@ describe('WebFetchTool', () => {
it('should return WEB_FETCH_FALLBACK_FAILED on fallback fetch failure', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(true);
mockFetch('https://private.ip/', new Error('fetch failed'));
vi.spyOn(fetchUtils, 'fetchWithTimeout').mockRejectedValue(
new Error('fetch failed'),
);
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://private.ip' };
const invocation = tool.build(params);
@@ -380,9 +228,10 @@ describe('WebFetchTool', () => {
it('should log telemetry when falling back due to private IP', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(true);
// Mock fetchWithTimeout to succeed so fallback proceeds
mockFetch('https://private.ip/', {
vi.spyOn(fetchUtils, 'fetchWithTimeout').mockResolvedValue({
ok: true,
text: () => Promise.resolve('some content'),
});
} as Response);
mockGenerateContent.mockResolvedValue({
candidates: [{ content: { parts: [{ text: 'fallback response' }] } }],
});
@@ -406,9 +255,10 @@ describe('WebFetchTool', () => {
candidates: [],
});
// Mock fetchWithTimeout to succeed so fallback proceeds
mockFetch('https://public.ip/', {
vi.spyOn(fetchUtils, 'fetchWithTimeout').mockResolvedValue({
ok: true,
text: () => Promise.resolve('some content'),
});
} as Response);
// Mock fallback LLM call
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'fallback response' }] } }],
@@ -470,10 +320,11 @@ describe('WebFetchTool', () => {
? new Headers({ 'content-type': contentType })
: new Headers();
mockFetch('https://example.com/', {
vi.spyOn(fetchUtils, 'fetchWithTimeout').mockResolvedValue({
ok: true,
headers,
text: () => Promise.resolve(content),
});
} as Response);
// Mock fallback LLM call to return the content passed to it
mockGenerateContent.mockImplementationOnce(async (_, req) => ({
@@ -522,24 +373,6 @@ describe('WebFetchTool', () => {
});
});
it('should handle URL param in confirmation details', async () => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(confirmationDetails).toEqual({
type: 'info',
title: 'Confirm Web Fetch',
prompt: 'Fetch https://example.com',
urls: ['https://example.com'],
onConfirm: expect.any(Function),
});
});
it('should convert github urls to raw format', async () => {
const tool = new WebFetchTool(mockConfig, bus);
const params = {
@@ -768,170 +601,4 @@ describe('WebFetchTool', () => {
expect(result.llmContent).toContain('Fetched content');
});
});
describe('execute (experimental)', () => {
beforeEach(() => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
});
it('should perform direct fetch and return text for plain text content', async () => {
const content = 'Plain text content';
mockFetch('https://example.com/', {
status: 200,
headers: new Headers({ 'content-type': 'text/plain' }),
text: () => Promise.resolve(content),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toBe(content);
expect(result.returnDisplay).toContain('Fetched text/plain content');
expect(fetchUtils.fetchWithTimeout).toHaveBeenCalledWith(
'https://example.com/',
expect.any(Number),
expect.objectContaining({
headers: expect.objectContaining({
Accept: expect.stringContaining('text/plain'),
}),
}),
);
});
it('should use html-to-text and preserve links for HTML content', async () => {
const content =
'<html><body><a href="https://link.com">Link</a></body></html>';
mockFetch('https://example.com/', {
status: 200,
headers: new Headers({ 'content-type': 'text/html' }),
text: () => Promise.resolve(content),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
await invocation.execute(new AbortController().signal);
expect(convert).toHaveBeenCalledWith(
content,
expect.objectContaining({
selectors: [
expect.objectContaining({
selector: 'a',
options: { ignoreHref: false, baseUrl: 'https://example.com/' },
}),
],
}),
);
});
it('should return base64 for image content', async () => {
const buffer = Buffer.from('fake-image-data');
mockFetch('https://example.com/image.png', {
status: 200,
headers: new Headers({ 'content-type': 'image/png' }),
arrayBuffer: () =>
Promise.resolve(
buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength,
),
),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com/image.png' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toEqual({
inlineData: {
data: buffer.toString('base64'),
mimeType: 'image/png',
},
});
});
it('should return raw response info for 4xx/5xx errors', async () => {
const errorBody = 'Not Found';
mockFetch('https://example.com/404', {
status: 404,
headers: new Headers({ 'x-test': 'val' }),
text: () => Promise.resolve(errorBody),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com/404' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('Request failed with status 404');
expect(result.llmContent).toContain('val');
expect(result.llmContent).toContain(errorBody);
expect(result.returnDisplay).toContain('Failed to fetch');
});
it('should throw error if Content-Length exceeds limit', async () => {
mockFetch('https://example.com/large', {
headers: new Headers({
'content-length': (11 * 1024 * 1024).toString(),
}),
});
const tool = new WebFetchTool(mockConfig, bus);
const invocation = tool.build({ url: 'https://example.com/large' });
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('Error');
expect(result.llmContent).toContain('exceeds size limit');
});
it('should throw error if stream exceeds limit', async () => {
const largeChunk = new Uint8Array(11 * 1024 * 1024);
mockFetch('https://example.com/large-stream', {
body: {
getReader: () => ({
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: largeChunk })
.mockResolvedValueOnce({ done: true }),
releaseLock: vi.fn(),
cancel: vi.fn().mockResolvedValue(undefined),
}),
} as unknown as ReadableStream,
});
const tool = new WebFetchTool(mockConfig, bus);
const invocation = tool.build({
url: 'https://example.com/large-stream',
});
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('Error');
expect(result.llmContent).toContain('exceeds size limit');
});
it('should return error if url is missing (experimental)', async () => {
const tool = new WebFetchTool(mockConfig, bus);
// Manually bypass build() validation to test executeExperimental safety check
const invocation = tool['createInvocation']({}, bus);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('Error: No URL provided.');
expect(result.error?.type).toBe(ToolErrorType.INVALID_TOOL_PARAMS);
});
it('should return error if url is invalid (experimental)', async () => {
const tool = new WebFetchTool(mockConfig, bus);
// Manually bypass build() validation to test executeExperimental safety check
const invocation = tool['createInvocation']({ url: 'not-a-url' }, bus);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('Error: Invalid URL "not-a-url"');
expect(result.error?.type).toBe(ToolErrorType.INVALID_TOOL_PARAMS);
});
});
});
+27 -278
View File
@@ -18,7 +18,6 @@ import type { Config } from '../config/config.js';
import { ApprovalMode } from '../policy/types.js';
import { getResponseText } from '../utils/partUtils.js';
import { fetchWithTimeout, isPrivateIp } from '../utils/fetch.js';
import { truncateString } from '../utils/textUtils.js';
import { convert } from 'html-to-text';
import {
logWebFetchFallbackAttempt,
@@ -34,10 +33,6 @@ import { LRUCache } from 'mnemonist';
const URL_FETCH_TIMEOUT_MS = 10000;
const MAX_CONTENT_LENGTH = 100000;
const MAX_EXPERIMENTAL_FETCH_SIZE = 10 * 1024 * 1024; // 10MB
const USER_AGENT =
'Mozilla/5.0 (compatible; Google-Gemini-CLI/1.0; +https://github.com/google-gemini/gemini-cli)';
const TRUNCATION_WARNING = '\n\n... [Content truncated due to size limit] ...';
// Rate limiting configuration
const RATE_LIMIT_WINDOW_MS = 60000; // 1 minute
@@ -112,23 +107,6 @@ export function parsePrompt(text: string): {
return { validUrls, errors };
}
/**
* Safely converts a GitHub blob URL to a raw content URL.
*/
export function convertGithubUrlToRaw(urlStr: string): string {
try {
const url = new URL(urlStr);
if (url.hostname === 'github.com' && url.pathname.includes('/blob/')) {
url.hostname = 'raw.githubusercontent.com';
url.pathname = url.pathname.replace(/^\/([^/]+\/[^/]+)\/blob\//, '/$1/');
return url.href;
}
} catch {
// Ignore invalid URLs
}
return urlStr;
}
// Interfaces for grounding metadata (similar to web-search.ts)
interface GroundingChunkWeb {
uri?: string;
@@ -157,11 +135,7 @@ export interface WebFetchToolParams {
/**
* The prompt containing URL(s) (up to 20) and instructions for processing their content.
*/
prompt?: string;
/**
* Direct URL to fetch (experimental mode).
*/
url?: string;
prompt: string;
}
interface ErrorWithStatus extends Error {
@@ -183,22 +157,21 @@ class WebFetchToolInvocation extends BaseToolInvocation<
}
private async executeFallback(signal: AbortSignal): Promise<ToolResult> {
const { validUrls: urls } = parsePrompt(this.params.prompt!);
const { validUrls: urls } = parsePrompt(this.params.prompt);
// For now, we only support one URL for fallback
let url = urls[0];
// Convert GitHub blob URL to raw URL
url = convertGithubUrlToRaw(url);
if (url.includes('github.com') && url.includes('/blob/')) {
url = url
.replace('github.com', 'raw.githubusercontent.com')
.replace('/blob/', '/');
}
try {
const response = await retryWithBackoff(
async () => {
const res = await fetchWithTimeout(url, URL_FETCH_TIMEOUT_MS, {
signal,
headers: {
'User-Agent': USER_AGENT,
},
});
const res = await fetchWithTimeout(url, URL_FETCH_TIMEOUT_MS);
if (!res.ok) {
const error = new Error(
`Request failed with status code ${res.status} ${res.statusText}`,
@@ -213,11 +186,7 @@ class WebFetchToolInvocation extends BaseToolInvocation<
},
);
const bodyBuffer = await this.readResponseWithLimit(
response,
MAX_EXPERIMENTAL_FETCH_SIZE,
);
const rawContent = bodyBuffer.toString('utf8');
const rawContent = await response.text();
const contentType = response.headers.get('content-type') || '';
let textContent: string;
@@ -238,11 +207,7 @@ class WebFetchToolInvocation extends BaseToolInvocation<
textContent = rawContent;
}
textContent = truncateString(
textContent,
MAX_CONTENT_LENGTH,
TRUNCATION_WARNING,
);
textContent = textContent.substring(0, MAX_CONTENT_LENGTH);
const geminiClient = this.config.getGeminiClient();
const fallbackPrompt = `The user requested the following: "${this.params.prompt}".
@@ -280,12 +245,10 @@ ${textContent}
}
getDescription(): string {
if (this.params.url) {
return `Fetching content from: ${this.params.url}`;
}
const prompt = this.params.prompt || '';
const displayPrompt =
prompt.length > 100 ? prompt.substring(0, 97) + '...' : prompt;
this.params.prompt.length > 100
? this.params.prompt.substring(0, 97) + '...'
: this.params.prompt;
return `Processing URLs and instructions from prompt: "${displayPrompt}"`;
}
@@ -298,24 +261,22 @@ ${textContent}
return false;
}
let urls: string[] = [];
let prompt = this.params.prompt || '';
if (this.params.url) {
urls = [this.params.url];
prompt = `Fetch ${this.params.url}`;
} else if (this.params.prompt) {
const { validUrls } = parsePrompt(this.params.prompt);
urls = validUrls;
}
// Perform GitHub URL conversion here
urls = urls.map((url) => convertGithubUrlToRaw(url));
// Perform GitHub URL conversion here to differentiate between user-provided
// URL and the actual URL to be fetched.
const { validUrls } = parsePrompt(this.params.prompt);
const urls = validUrls.map((url) => {
if (url.includes('github.com') && url.includes('/blob/')) {
return url
.replace('github.com', 'raw.githubusercontent.com')
.replace('/blob/', '/');
}
return url;
});
const confirmationDetails: ToolCallConfirmationDetails = {
type: 'info',
title: `Confirm Web Fetch`,
prompt,
prompt: this.params.prompt,
urls,
onConfirm: async (_outcome: ToolConfirmationOutcome) => {
// Mode transitions (e.g. AUTO_EDIT) and policy updates are now
@@ -325,189 +286,8 @@ ${textContent}
return confirmationDetails;
}
private async readResponseWithLimit(
response: Response,
limit: number,
): Promise<Buffer> {
const contentLength = response.headers.get('content-length');
if (contentLength && parseInt(contentLength, 10) > limit) {
throw new Error(`Content exceeds size limit of ${limit} bytes`);
}
if (!response.body) {
return Buffer.alloc(0);
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let totalLength = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalLength += value.length;
if (totalLength > limit) {
// Attempt to cancel the reader to stop the stream
await reader.cancel().catch(() => {});
throw new Error(`Content exceeds size limit of ${limit} bytes`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
return Buffer.concat(chunks);
}
private async executeExperimental(signal: AbortSignal): Promise<ToolResult> {
if (!this.params.url) {
return {
llmContent: 'Error: No URL provided.',
returnDisplay: 'Error: No URL provided.',
error: {
message: 'No URL provided.',
type: ToolErrorType.INVALID_TOOL_PARAMS,
},
};
}
let url: string;
try {
url = new URL(this.params.url).href;
} catch {
return {
llmContent: `Error: Invalid URL "${this.params.url}"`,
returnDisplay: `Error: Invalid URL "${this.params.url}"`,
error: {
message: `Invalid URL "${this.params.url}"`,
type: ToolErrorType.INVALID_TOOL_PARAMS,
},
};
}
// Convert GitHub blob URL to raw URL
url = convertGithubUrlToRaw(url);
try {
const response = await retryWithBackoff(
async () => {
const res = await fetchWithTimeout(url, URL_FETCH_TIMEOUT_MS, {
signal,
headers: {
Accept:
'text/markdown, text/plain;q=0.9, application/json;q=0.9, text/html;q=0.8, application/pdf;q=0.7, video/*;q=0.7, */*;q=0.5',
'User-Agent': USER_AGENT,
},
});
return res;
},
{
retryFetchErrors: this.config.getRetryFetchErrors(),
},
);
const contentType = response.headers.get('content-type') || '';
const status = response.status;
const bodyBuffer = await this.readResponseWithLimit(
response,
MAX_EXPERIMENTAL_FETCH_SIZE,
);
if (status >= 400) {
const rawResponseText = bodyBuffer.toString('utf8');
const headers: Record<string, string> = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
const errorContent = `Request failed with status ${status}
Headers: ${JSON.stringify(headers, null, 2)}
Response: ${truncateString(rawResponseText, 10000, '\n\n... [Error response truncated] ...')}`;
return {
llmContent: errorContent,
returnDisplay: `Failed to fetch ${url} (Status: ${status})`,
};
}
const lowContentType = contentType.toLowerCase();
if (
lowContentType.includes('text/markdown') ||
lowContentType.includes('text/plain') ||
lowContentType.includes('application/json')
) {
const text = truncateString(
bodyBuffer.toString('utf8'),
MAX_CONTENT_LENGTH,
TRUNCATION_WARNING,
);
return {
llmContent: text,
returnDisplay: `Fetched ${contentType} content from ${url}`,
};
}
if (lowContentType.includes('text/html')) {
const html = bodyBuffer.toString('utf8');
const textContent = truncateString(
convert(html, {
wordwrap: false,
selectors: [
{ selector: 'a', options: { ignoreHref: false, baseUrl: url } },
],
}),
MAX_CONTENT_LENGTH,
TRUNCATION_WARNING,
);
return {
llmContent: textContent,
returnDisplay: `Fetched and converted HTML content from ${url}`,
};
}
if (
lowContentType.startsWith('image/') ||
lowContentType.startsWith('video/') ||
lowContentType === 'application/pdf'
) {
const base64Data = bodyBuffer.toString('base64');
return {
llmContent: {
inlineData: {
data: base64Data,
mimeType: contentType.split(';')[0],
},
},
returnDisplay: `Fetched ${contentType} from ${url}`,
};
}
// Fallback for unknown types - try as text
const text = truncateString(
bodyBuffer.toString('utf8'),
MAX_CONTENT_LENGTH,
TRUNCATION_WARNING,
);
return {
llmContent: text,
returnDisplay: `Fetched ${contentType || 'unknown'} content from ${url}`,
};
} catch (e) {
const errorMessage = `Error during experimental fetch for ${url}: ${getErrorMessage(e)}`;
return {
llmContent: `Error: ${errorMessage}`,
returnDisplay: `Error: ${errorMessage}`,
error: {
message: errorMessage,
type: ToolErrorType.WEB_FETCH_FALLBACK_FAILED,
},
};
}
}
async execute(signal: AbortSignal): Promise<ToolResult> {
if (this.config.getDirectWebFetch()) {
return this.executeExperimental(signal);
}
const userPrompt = this.params.prompt!;
const userPrompt = this.params.prompt;
const { validUrls: urls } = parsePrompt(userPrompt);
const url = urls[0];
@@ -695,18 +475,6 @@ export class WebFetchTool extends BaseDeclarativeTool<
protected override validateToolParamValues(
params: WebFetchToolParams,
): string | null {
if (this.config.getDirectWebFetch()) {
if (!params.url) {
return "The 'url' parameter is required.";
}
try {
new URL(params.url);
} catch {
return `Invalid URL: "${params.url}"`;
}
return null;
}
if (!params.prompt || params.prompt.trim() === '') {
return "The 'prompt' parameter cannot be empty and must contain URL(s) and instructions.";
}
@@ -740,25 +508,6 @@ export class WebFetchTool extends BaseDeclarativeTool<
}
override getSchema(modelId?: string) {
const schema = resolveToolDeclaration(WEB_FETCH_DEFINITION, modelId);
if (this.config.getDirectWebFetch()) {
return {
...schema,
description:
'Fetch content from a URL directly. Send multiple requests for this tool if multiple URL fetches are needed.',
parametersJsonSchema: {
type: 'object',
properties: {
url: {
type: 'string',
description:
'The URL to fetch. Must be a valid http or https URL.',
},
},
required: ['url'],
},
};
}
return schema;
return resolveToolDeclaration(WEB_FETCH_DEFINITION, modelId);
}
}
+32 -26
View File
@@ -185,16 +185,12 @@ export async function ensureCorrectEdit(
unescapeStringForGeminiBug(originalParams.new_string) !==
originalParams.new_string;
const allowMultiple = originalParams.allow_multiple ?? false;
const expectedReplacements = originalParams.expected_replacements ?? 1;
let finalOldString = originalParams.old_string;
let occurrences = countOccurrences(currentContent, finalOldString);
const isOccurrencesMatch = allowMultiple
? occurrences > 0
: occurrences === 1;
if (isOccurrencesMatch) {
if (occurrences === expectedReplacements) {
if (newStringPotentiallyEscaped && !disableLLMCorrection) {
finalNewString = await correctNewStringEscaping(
baseLlmClient,
@@ -203,8 +199,30 @@ export async function ensureCorrectEdit(
abortSignal,
);
}
} else if (occurrences > 1 && !allowMultiple) {
// If user doesn't allow multiple but found multiple, return as-is (will fail validation later)
} else if (occurrences > expectedReplacements) {
const expectedReplacements = originalParams.expected_replacements ?? 1;
// If user expects multiple replacements, return as-is
if (occurrences === expectedReplacements) {
const result: CorrectedEditResult = {
params: { ...originalParams },
occurrences,
};
editCorrectionCache.set(cacheKey, result);
return result;
}
// If user expects 1 but found multiple, try to correct (existing behavior)
if (expectedReplacements === 1) {
const result: CorrectedEditResult = {
params: { ...originalParams },
occurrences,
};
editCorrectionCache.set(cacheKey, result);
return result;
}
// If occurrences don't match expected, return as-is (will fail validation later)
const result: CorrectedEditResult = {
params: { ...originalParams },
occurrences,
@@ -218,11 +236,7 @@ export async function ensureCorrectEdit(
);
occurrences = countOccurrences(currentContent, unescapedOldStringAttempt);
const isUnescapedOccurrencesMatch = allowMultiple
? occurrences > 0
: occurrences === 1;
if (isUnescapedOccurrencesMatch) {
if (occurrences === expectedReplacements) {
finalOldString = unescapedOldStringAttempt;
if (newStringPotentiallyEscaped && !disableLLMCorrection) {
finalNewString = await correctNewString(
@@ -282,11 +296,7 @@ export async function ensureCorrectEdit(
llmCorrectedOldString,
);
const isLlmOccurrencesMatch = allowMultiple
? llmOldOccurrences > 0
: llmOldOccurrences === 1;
if (isLlmOccurrencesMatch) {
if (llmOldOccurrences === expectedReplacements) {
finalOldString = llmCorrectedOldString;
occurrences = llmOldOccurrences;
@@ -312,7 +322,7 @@ export async function ensureCorrectEdit(
return result;
}
} else {
// Unescaping old_string resulted in > 1 occurrence but not allowMultiple
// Unescaping old_string resulted in > 1 occurrence
const result: CorrectedEditResult = {
params: { ...originalParams },
occurrences, // This will be > 1
@@ -326,7 +336,7 @@ export async function ensureCorrectEdit(
finalOldString,
finalNewString,
currentContent,
allowMultiple,
expectedReplacements,
);
finalOldString = targetString;
finalNewString = pair;
@@ -695,7 +705,7 @@ function trimPairIfPossible(
target: string,
trimIfTargetTrims: string,
currentContent: string,
allowMultiple: boolean,
expectedReplacements: number,
) {
const trimmedTargetString = trimPreservingTrailingNewline(target);
if (target.length !== trimmedTargetString.length) {
@@ -704,11 +714,7 @@ function trimPairIfPossible(
trimmedTargetString,
);
const isMatch = allowMultiple
? trimmedTargetOccurrences > 0
: trimmedTargetOccurrences === 1;
if (isMatch) {
if (trimmedTargetOccurrences === expectedReplacements) {
const trimmedReactiveString =
trimPreservingTrailingNewline(trimIfTargetTrims);
return {
@@ -1,117 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { expandEnvVars } from './envExpansion.js';
describe('expandEnvVars', () => {
const defaultEnv = {
USER: 'morty',
HOME: '/home/morty',
TEMP: 'C:\\Temp',
EMPTY: '',
};
describe('POSIX behavior (non-Windows)', () => {
beforeEach(() => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
});
afterEach(() => {
vi.restoreAllMocks();
});
it.each([
['$VAR (POSIX)', 'Hello $USER', defaultEnv, 'Hello morty'],
[
'${VAR} (POSIX)',
'Welcome to ${HOME}',
defaultEnv,
'Welcome to /home/morty',
],
[
'should NOT expand %VAR% on non-Windows',
'Data in %TEMP%',
defaultEnv,
'Data in %TEMP%',
],
[
'mixed formats (only POSIX expanded)',
'$USER lives in ${HOME} on %TEMP%',
defaultEnv,
'morty lives in /home/morty on %TEMP%',
],
[
'missing variables (POSIX only)',
'Missing $UNDEFINED and ${NONE} and %MISSING%',
defaultEnv,
'Missing and and %MISSING%',
],
[
'empty or undefined values',
'Value is "$EMPTY"',
defaultEnv,
'Value is ""',
],
[
'original string if no variables',
'No vars here',
defaultEnv,
'No vars here',
],
['literal values like "1234"', '1234', defaultEnv, '1234'],
['empty input string', '', defaultEnv, ''],
[
'complex paths',
'${HOME}/bin:$PATH',
{ ...defaultEnv, PATH: '/usr/bin' },
'/home/morty/bin:/usr/bin',
],
])('should handle %s', (_, input, env, expected) => {
expect(expandEnvVars(input, env)).toBe(expected);
});
});
describe('Windows behavior', () => {
beforeEach(() => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
});
afterEach(() => {
vi.restoreAllMocks();
});
it.each([
['$VAR (POSIX)', 'Hello $USER', defaultEnv, 'Hello morty'],
[
'${VAR} (POSIX)',
'Welcome to ${HOME}',
defaultEnv,
'Welcome to /home/morty',
],
[
'should expand %VAR% on Windows',
'Data in %TEMP%',
defaultEnv,
'Data in C:\\Temp',
],
[
'mixed formats (both expanded)',
'$USER lives in ${HOME} on %TEMP%',
defaultEnv,
'morty lives in /home/morty on C:\\Temp',
],
[
'missing variables (all expanded to empty)',
'Missing $UNDEFINED and ${NONE} and %MISSING%',
defaultEnv,
'Missing and and ',
],
])('should handle %s', (_, input, env, expected) => {
expect(expandEnvVars(input, env)).toBe(expected);
});
});
});
-54
View File
@@ -1,54 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { expand } from 'dotenv-expand';
/**
* Expands environment variables in a string using the provided environment record.
* Uses the standard `dotenv-expand` library to handle expansion consistently with
* other tools.
*
* Supports POSIX/Bash syntax ($VAR, ${VAR}).
* Note: Windows syntax (%VAR%) is not natively supported by dotenv-expand.
*
* @param str - The string containing environment variable placeholders.
* @param env - A record of environment variable names and their values.
* @returns The string with environment variables expanded. Missing variables resolve to an empty string.
*/
export function expandEnvVars(
str: string,
env: Record<string, string | undefined>,
): string {
if (!str) return str;
// 1. Pre-process Windows-style variables (%VAR%) since dotenv-expand only handles POSIX ($VAR).
// We only do this on Windows to limit the blast radius and avoid conflicts with other
// systems where % might be a literal character (e.g. in URLs or shell commands).
const isWindows = process.platform === 'win32';
const processedStr = isWindows
? str.replace(/%(\w+)%/g, (_, name) => env[name] ?? '')
: str;
// 2. Use dotenv-expand for POSIX/Bash syntax ($VAR, ${VAR}).
// dotenv-expand is designed to process an object of key-value pairs (like a .env file).
// To expand a single string, we wrap it in an object with a temporary key.
const dummyKey = '__GCLI_EXPAND_TARGET__';
// Filter out undefined values to satisfy the Record<string, string> requirement safely
const processEnv: Record<string, string> = {};
for (const [key, value] of Object.entries(env)) {
if (value !== undefined) {
processEnv[key] = value;
}
}
const result = expand({
parsed: { [dummyKey]: processedStr },
processEnv,
});
return result.parsed?.[dummyKey] ?? '';
}
+1 -15
View File
@@ -41,26 +41,12 @@ export function isPrivateIp(url: string): boolean {
export async function fetchWithTimeout(
url: string,
timeout: number,
options?: RequestInit,
): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
if (options?.signal) {
if (options.signal.aborted) {
controller.abort();
} else {
options.signal.addEventListener('abort', () => controller.abort(), {
once: true,
});
}
}
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
});
const response = await fetch(url, { signal: controller.signal });
return response;
} catch (error) {
if (isNodeError(error) && error.code === 'ABORT_ERR') {
+2 -2
View File
@@ -34,7 +34,7 @@ SOFTWARE.
License text not found.
============================================================
ajv@6.14.0
ajv@6.12.6
(https://github.com/ajv-validator/ajv.git)
The MIT License (MIT)
@@ -2241,7 +2241,7 @@ THE SOFTWARE.
============================================================
hono@4.12.2
hono@4.11.9
(git+https://github.com/honojs/hono.git)
MIT License
-14
View File
@@ -128,13 +128,6 @@
"default": false,
"type": "boolean"
},
"maxAttempts": {
"title": "Max Chat Model Attempts",
"description": "Maximum number of attempts for requests to the main chat model. Cannot exceed 10.",
"markdownDescription": "Maximum number of attempts for requests to the main chat model. Cannot exceed 10.\n\n- Category: `General`\n- Requires restart: `no`\n- Default: `10`",
"default": 10,
"type": "number"
},
"debugKeystrokeLogging": {
"title": "Debug Keystroke Logging",
"description": "Enable debug logging of keystrokes to the console.",
@@ -1636,13 +1629,6 @@
"markdownDescription": "Enable model steering (user hints) to guide the model during tool execution.\n\n- Category: `Experimental`\n- Requires restart: `no`\n- Default: `false`",
"default": false,
"type": "boolean"
},
"directWebFetch": {
"title": "Direct Web Fetch",
"description": "Enable web fetch behavior that bypasses LLM summarization.",
"markdownDescription": "Enable web fetch behavior that bypasses LLM summarization.\n\n- Category: `Experimental`\n- Requires restart: `yes`\n- Default: `false`",
"default": false,
"type": "boolean"
}
},
"additionalProperties": false
+23 -72
View File
@@ -45,13 +45,6 @@ function getPlatformArch() {
shellcheck: 'darwin.aarch64',
};
}
if (platform === 'win32' && arch === 'x64') {
return {
actionlint: 'windows_amd64',
// shellcheck is not used for Windows since it uses the .zip release
// which has a consistent name across architectures
};
}
throw new Error(`Unsupported platform/architecture: ${platform}/${arch}`);
}
@@ -65,52 +58,10 @@ const pythonVenvPythonPath = join(
process.platform === 'win32' ? 'python.exe' : 'python',
);
const isWindows = process.platform === 'win32';
const actionlintCheck = isWindows
? `where actionlint 2>nul`
: 'command -v actionlint';
const actionlintInstaller = isWindows
? `powershell -Command "` +
`New-Item -ItemType Directory -Force -Path '${TEMP_DIR}/actionlint' | Out-Null; ` +
`Invoke-WebRequest -Uri 'https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_${platformArch.actionlint}.zip' -OutFile '${TEMP_DIR}/.actionlint.zip'; ` +
`Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
`[System.IO.Compression.ZipFile]::ExtractToDirectory('${TEMP_DIR}/.actionlint.zip', '${TEMP_DIR}/actionlint')"`
: `
mkdir -p "${TEMP_DIR}/actionlint"
curl -sSLo "${TEMP_DIR}/.actionlint.tgz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_${platformArch.actionlint}.tar.gz"
tar -xzf "${TEMP_DIR}/.actionlint.tgz" -C "${TEMP_DIR}/actionlint"
`;
const shellcheckCheck = isWindows
? `where shellcheck 2>nul`
: 'command -v shellcheck';
const shellcheckInstaller = isWindows
? `powershell -Command "` +
`Invoke-WebRequest -Uri 'https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/shellcheck-v${SHELLCHECK_VERSION}.zip' -OutFile '${TEMP_DIR}/.shellcheck.zip'; ` +
`Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
`[System.IO.Compression.ZipFile]::ExtractToDirectory('${TEMP_DIR}/.shellcheck.zip', '${TEMP_DIR}/shellcheck')"`
: `
mkdir -p "${TEMP_DIR}/shellcheck"
curl -sSLo "${TEMP_DIR}/.shellcheck.txz" "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/shellcheck-v${SHELLCHECK_VERSION}.${platformArch.shellcheck}.tar.xz"
tar -xf "${TEMP_DIR}/.shellcheck.txz" -C "${TEMP_DIR}/shellcheck" --strip-components=1
`;
const yamllintCheck = isWindows
? `if exist "${PYTHON_VENV_PATH}\\Scripts\\yamllint.exe" (exit 0) else (exit 1)`
: `test -x "${PYTHON_VENV_PATH}/bin/yamllint"`;
const yamllintInstaller = isWindows
? `python -m venv "${PYTHON_VENV_PATH}" && ` +
`"${pythonVenvPythonPath}" -m pip install --upgrade pip && ` +
`"${pythonVenvPythonPath}" -m pip install "yamllint==${YAMLLINT_VERSION}" --index-url https://pypi.org/simple`
: `
python3 -m venv "${PYTHON_VENV_PATH}" && \
"${pythonVenvPythonPath}" -m pip install --upgrade pip && \
"${pythonVenvPythonPath}" -m pip install "yamllint==${YAMLLINT_VERSION}" --index-url https://pypi.org/simple
`;
const yamllintCheck =
process.platform === 'win32'
? `if exist "${PYTHON_VENV_PATH}\\Scripts\\yamllint.exe" (exit 0) else (exit 1)`
: `test -x "${PYTHON_VENV_PATH}/bin/yamllint"`;
/**
* @typedef {{
@@ -125,8 +76,12 @@ const yamllintInstaller = isWindows
*/
const LINTERS = {
actionlint: {
check: actionlintCheck,
installer: actionlintInstaller,
check: 'command -v actionlint',
installer: `
mkdir -p "${TEMP_DIR}/actionlint"
curl -sSLo "${TEMP_DIR}/.actionlint.tgz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_${platformArch.actionlint}.tar.gz"
tar -xzf "${TEMP_DIR}/.actionlint.tgz" -C "${TEMP_DIR}/actionlint"
`,
run: `
actionlint \
-color \
@@ -137,8 +92,12 @@ const LINTERS = {
`,
},
shellcheck: {
check: shellcheckCheck,
installer: shellcheckInstaller,
check: 'command -v shellcheck',
installer: `
mkdir -p "${TEMP_DIR}/shellcheck"
curl -sSLo "${TEMP_DIR}/.shellcheck.txz" "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/shellcheck-v${SHELLCHECK_VERSION}.${platformArch.shellcheck}.tar.xz"
tar -xf "${TEMP_DIR}/.shellcheck.txz" -C "${TEMP_DIR}/shellcheck" --strip-components=1
`,
run: `
git ls-files | grep -E '^([^.]+|.*\\.(sh|zsh|bash))' | xargs file --mime-type \
| grep "text/x-shellscript" | awk '{ print substr($1, 1, length($1)-1) }' \
@@ -153,7 +112,11 @@ const LINTERS = {
},
yamllint: {
check: yamllintCheck,
installer: yamllintInstaller,
installer: `
python3 -m venv "${PYTHON_VENV_PATH}" && \
"${pythonVenvPythonPath}" -m pip install --upgrade pip && \
"${pythonVenvPythonPath}" -m pip install "yamllint==${YAMLLINT_VERSION}" --index-url https://pypi.org/simple
`,
run: "git ls-files | grep -E '\\.(yaml|yml)' | xargs yamllint --format github",
},
};
@@ -162,20 +125,8 @@ function runCommand(command, stdio = 'inherit') {
try {
const env = { ...process.env };
const nodeBin = join(process.cwd(), 'node_modules', '.bin');
const sep = isWindows ? ';' : ':';
const pythonBin = isWindows
? join(PYTHON_VENV_PATH, 'Scripts')
: join(PYTHON_VENV_PATH, 'bin');
// Windows sometimes uses 'Path' instead of 'PATH'
const pathKey = 'Path' in env ? 'Path' : 'PATH';
env[pathKey] = [
nodeBin,
join(TEMP_DIR, 'actionlint'),
join(TEMP_DIR, 'shellcheck'),
pythonBin,
env[pathKey],
].join(sep);
execSync(command, { stdio, env, shell: true });
env.PATH = `${nodeBin}:${TEMP_DIR}/actionlint:${TEMP_DIR}/shellcheck:${PYTHON_VENV_PATH}/bin:${env.PATH}`;
execSync(command, { stdio, env });
return true;
} catch (_e) {
return false;