Compare commits

..

3 Commits

Author SHA1 Message Date
jacob314 413098e03a fix(shell): address rcFile security issues
- Only source rcFile if the workspace is a trusted folder

- Properly escape the rcFile path to prevent command injection
2026-04-21 17:18:35 -07:00
jacob314 66abea7a0e fix(shell): explicitly set PAGER=cat when rcFile is not used 2026-04-21 15:33:01 -07:00
Billy Biggs dc82a395ac Add support for a shellToolRcFile setting 2026-04-21 15:26:52 -07:00
15 changed files with 178 additions and 217 deletions
+5
View File
@@ -1452,6 +1452,11 @@ their corresponding top-level category object in your `settings.json` file.
performance.
- **Default:** `true`
- **`tools.shell.rcFile`** (string):
- **Description:** The path to a bash file (e.g., .bashrc) to source before
executing shell commands.
- **Default:** `undefined`
- **`tools.core`** (array):
- **Description:** Restrict the set of built-in tools with an allowlist. Match
semantics mirror tools.allowed; see the built-in tools documentation for
@@ -8,16 +8,7 @@ import { expect, describe, it, beforeEach, afterEach } from 'vitest';
import { TestRig } from './test-helper.js';
import { join } from 'node:path';
// Skip on macOS: every interactive test in this file is chronically flaky
// because the captured pty buffer contains the CLI's startup escape
// sequences (`q4;?m...true color warning`) instead of the streamed output,
// causing `expectText(...)` to time out. Reproducible across unrelated
// runs on `main` (24740161950, 24739323404) and on consecutive merge-queue
// gates for #25753 (24743605639, 24747624513) — different tests in the
// same describe fail on different runs. Not specific to any model.
const skipOnDarwin = process.platform === 'darwin';
describe.skipIf(skipOnDarwin)('Interactive Mode', () => {
describe('Interactive Mode', () => {
let rig: TestRig;
beforeEach(() => {
+1 -3
View File
@@ -134,9 +134,7 @@ describe('file-system', () => {
).toBeTruthy();
const newFileContent = rig.readFile(fileName);
// Trim to tolerate models that idiomatically append a trailing newline.
// This test is about path-with-spaces handling, not whitespace fidelity.
expect(newFileContent.trim()).toBe('hello');
expect(newFileContent).toBe('hello');
});
it('should perform a read-then-write sequence', async () => {
+2 -9
View File
@@ -81,10 +81,7 @@ describe('Plan Mode', () => {
await rig.run({
approvalMode: 'plan',
args:
'Create a file called plan.md in the plans directory with the ' +
'content "# Plan". Treat this as a Directive and write the file ' +
'immediately without proposing strategy or asking for confirmation.',
args: 'Create a file called plan.md in the plans directory.',
});
const toolLogs = rig.readToolLogs();
@@ -197,11 +194,7 @@ describe('Plan Mode', () => {
await rig.run({
approvalMode: 'plan',
args:
'Create a file called plan-no-session.md in the plans directory ' +
'with the content "# Plan". Treat this as a Directive and write ' +
'the file immediately without proposing strategy or asking for ' +
'confirmation.',
args: 'Create a file called plan-no-session.md in the plans directory.',
});
const toolLogs = rig.readToolLogs();
+53 -32
View File
@@ -449,8 +449,7 @@
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==",
"license": "(Apache-2.0 AND BSD-3-Clause)",
"peer": true
"license": "(Apache-2.0 AND BSD-3-Clause)"
},
"node_modules/@bundled-es-modules/cookie": {
"version": "2.0.1",
@@ -1474,7 +1473,6 @@
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.13.4.tgz",
"integrity": "sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@grpc/proto-loader": "^0.7.13",
"@js-sdsl/ordered-map": "^4.4.2"
@@ -2152,7 +2150,6 @@
"integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@octokit/auth-token": "^6.0.0",
"@octokit/graphql": "^9.0.2",
@@ -2333,7 +2330,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -2383,7 +2379,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.5.0.tgz",
"integrity": "sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
},
@@ -2758,7 +2753,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.5.0.tgz",
"integrity": "sha512-F8W52ApePshpoSrfsSk1H2yJn9aKjCrbpQF1M9Qii0GHzbfVeFUB+rc3X4aggyZD8x9Gu3Slua+s6krmq6Dt8g==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/semantic-conventions": "^1.29.0"
@@ -2792,7 +2786,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.5.0.tgz",
"integrity": "sha512-BeJLtU+f5Gf905cJX9vXFQorAr6TAfK3SPvTFqP+scfIpDQEJfRaGJWta7sJgP+m4dNtBf9y3yvBKVAZZtJQVA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0"
@@ -2847,7 +2840,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.5.0.tgz",
"integrity": "sha512-VzRf8LzotASEyNDUxTdaJ9IRJ1/h692WyArDBInf5puLCjxbICD6XkHgpuudis56EndyS7LYFmtTMny6UABNdQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0",
@@ -4054,7 +4046,6 @@
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -4328,7 +4319,6 @@
"integrity": "sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.58.2",
"@typescript-eslint/types": "8.58.2",
@@ -4603,6 +4593,56 @@
}
}
},
"node_modules/@vitest/eslint-plugin/node_modules/@typescript-eslint/scope-manager": {
"version": "8.47.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.47.0.tgz",
"integrity": "sha512-a0TTJk4HXMkfpFkL9/WaGTNuv7JWfFTQFJd6zS9dVAjKsojmv9HT55xzbEpnZoY+VUb+YXLMp+ihMLz/UlZfDg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.47.0",
"@typescript-eslint/visitor-keys": "8.47.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@vitest/eslint-plugin/node_modules/@typescript-eslint/types": {
"version": "8.47.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.47.0.tgz",
"integrity": "sha512-nHAE6bMKsizhA2uuYZbEbmp5z2UpffNrPEqiKIeN7VsV6UY/roxanWfoRrf6x/k9+Obf+GQdkm0nPU+vnMXo9A==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@vitest/eslint-plugin/node_modules/@typescript-eslint/visitor-keys": {
"version": "8.47.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.47.0.tgz",
"integrity": "sha512-SIV3/6eftCy1bNzCQoPmbWsRLujS8t5iDIZ4spZOBHqrM+yfX2ogg8Tt3PDTAVKw3sSCiUgg30uOAvK2r9zGjQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.47.0",
"eslint-visitor-keys": "^4.2.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@vitest/expect": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz",
@@ -5073,7 +5113,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -7151,8 +7190,7 @@
"version": "0.0.1581282",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz",
"integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==",
"license": "BSD-3-Clause",
"peer": true
"license": "BSD-3-Clause"
},
"node_modules/dezalgo": {
"version": "1.0.4",
@@ -7737,7 +7775,6 @@
"integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -8255,7 +8292,6 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@@ -9522,7 +9558,6 @@
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz",
"integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=16.9.0"
}
@@ -9782,7 +9817,6 @@
"resolved": "https://registry.npmjs.org/@jrichman/ink/-/ink-6.6.9.tgz",
"integrity": "sha512-RL9sSiLQZECnjbmBwjIHOp8yVGdWF7C/uifg7ISv/e+F3nLNsfl7FdUFQs8iZARFMJAYxMFpxW6OW+HSt9drwQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-escapes": "^7.0.0",
"ansi-styles": "^6.2.3",
@@ -13496,7 +13530,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -13507,7 +13540,6 @@
"integrity": "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"shell-quote": "^1.6.1",
"ws": "^7"
@@ -15627,7 +15659,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15850,8 +15881,7 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD",
"peer": true
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.20.3",
@@ -15859,7 +15889,6 @@
"integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.25.0",
"get-tsconfig": "^4.7.5"
@@ -16025,7 +16054,6 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -16093,7 +16121,6 @@
"integrity": "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.35.0",
"@typescript-eslint/types": "8.35.0",
@@ -16480,7 +16507,6 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.27.0",
"fdir": "^6.5.0",
@@ -17051,7 +17077,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -17064,7 +17089,6 @@
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4",
@@ -17703,7 +17727,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -18139,7 +18162,6 @@
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.3.tgz",
"integrity": "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@grpc/proto-loader": "^0.8.0",
"@js-sdsl/ordered-map": "^4.4.2"
@@ -18258,7 +18280,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
+1
View File
@@ -925,6 +925,7 @@ export async function loadCliConfig(
toolDiscoveryCommand: settings.tools?.discoveryCommand,
toolCallCommand: settings.tools?.callCommand,
mcpServerCommand,
shellToolRcFile: settings.tools?.shell?.rcFile,
mcpServers,
mcpEnablementCallbacks,
mcpEnabled,
+10
View File
@@ -1637,6 +1637,16 @@ const SETTINGS_SCHEMA = {
'Enable shell output efficiency optimizations for better performance.',
showInDialog: false,
},
rcFile: {
type: 'string',
label: 'Shell Tool RC File',
category: 'Tools',
requiresRestart: false,
default: undefined as string | undefined,
description:
'The path to a bash file (e.g., .bashrc) to source before executing shell commands.',
showInDialog: false,
},
},
},
@@ -42,7 +42,6 @@ import { initCommand } from '../ui/commands/initCommand.js';
import { mcpCommand } from '../ui/commands/mcpCommand.js';
import { memoryCommand } from '../ui/commands/memoryCommand.js';
import { modelCommand } from '../ui/commands/modelCommand.js';
import { noteCommand } from '../ui/commands/noteCommand.js';
import { oncallCommand } from '../ui/commands/oncallCommand.js';
import { permissionsCommand } from '../ui/commands/permissionsCommand.js';
import { planCommand } from '../ui/commands/planCommand.js';
@@ -185,7 +184,6 @@ export class BuiltinCommandLoader implements ICommandLoader {
: [mcpCommand]),
memoryCommand,
modelCommand,
noteCommand,
...(this.config?.getFolderTrust() ? [permissionsCommand] : []),
...(this.config?.isPlanEnabled() ? [planCommand] : []),
policiesCommand,
@@ -1,94 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import fs from 'node:fs/promises';
import path from 'node:path';
import { noteCommand } from './noteCommand.js';
import { type CommandContext } from './types.js';
vi.mock('node:fs/promises');
describe('noteCommand', () => {
const mockContext = {} as CommandContext;
const notesPath = path.join(process.cwd(), 'notes.md');
beforeEach(() => {
vi.clearAllMocks();
});
it('should return notes content when no args provided and file exists', async () => {
vi.mocked(fs.readFile).mockResolvedValue('existing note\n');
const result = await noteCommand.action!(mockContext, '');
expect(fs.readFile).toHaveBeenCalledWith(notesPath, 'utf8');
expect(result).toEqual({
type: 'message',
messageType: 'info',
content: expect.stringContaining('existing note'),
});
});
it('should return info message when no args provided and file does not exist (ENOENT)', async () => {
const error = new Error('File not found') as NodeJS.ErrnoException;
error.code = 'ENOENT';
vi.mocked(fs.readFile).mockRejectedValue(error);
const result = await noteCommand.action!(mockContext, ' ');
expect(result).toEqual({
type: 'message',
messageType: 'info',
content: 'No notes found. Use "/note <text>" to add one.',
});
});
it('should return error message when readFile fails with other error', async () => {
vi.mocked(fs.readFile).mockRejectedValue(new Error('Permission denied'));
const result = await noteCommand.action!(mockContext, '');
expect(result).toEqual({
type: 'message',
messageType: 'error',
content: expect.stringContaining(
'Failed to read notes: Permission denied',
),
});
});
it('should append trimmed note to file when args are provided', async () => {
const note = ' this is a new note ';
vi.mocked(fs.appendFile).mockResolvedValue(undefined);
const result = await noteCommand.action!(mockContext, note);
expect(fs.appendFile).toHaveBeenCalledWith(
notesPath,
`this is a new note\n`,
);
expect(result).toEqual({
type: 'message',
messageType: 'info',
content: expect.stringContaining('Note added'),
});
});
it('should return error message when append fails', async () => {
vi.mocked(fs.appendFile).mockRejectedValue(new Error('Permission denied'));
const result = await noteCommand.action!(mockContext, 'some note');
expect(result).toEqual({
type: 'message',
messageType: 'error',
content: expect.stringContaining(
'Failed to save note: Permission denied',
),
});
});
});
@@ -1,60 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import { isNodeError } from '@google/gemini-cli-core';
import { CommandKind, type SlashCommand } from './types.js';
export const noteCommand: SlashCommand = {
name: 'note',
description: 'Append a note to notes.md or view current notes',
kind: CommandKind.BUILT_IN,
autoExecute: true,
action: async (_context, args) => {
const notesPath = path.join(process.cwd(), 'notes.md');
if (!args || args.trim().length === 0) {
try {
const content = await fs.readFile(notesPath, 'utf8');
return {
type: 'message',
messageType: 'info',
content: `Current notes in ${notesPath}:\n\n${content}`,
};
} catch (error) {
if (isNodeError(error) && error.code === 'ENOENT') {
return {
type: 'message',
messageType: 'info',
content: 'No notes found. Use "/note <text>" to add one.',
};
}
return {
type: 'message',
messageType: 'error',
content: `Failed to read notes: ${error instanceof Error ? error.message : String(error)}`,
};
}
}
try {
const trimmedNote = args.trim();
await fs.appendFile(notesPath, `${trimmedNote}\n`);
return {
type: 'message',
messageType: 'info',
content: `Note added to ${notesPath}`,
};
} catch (error) {
return {
type: 'message',
messageType: 'error',
content: `Failed to save note: ${error instanceof Error ? error.message : String(error)}`,
};
}
},
};
+7
View File
@@ -602,6 +602,7 @@ export interface ConfigParameters {
toolDiscoveryCommand?: string;
toolCallCommand?: string;
mcpServerCommand?: string;
shellToolRcFile?: string;
mcpServers?: Record<string, MCPServerConfig>;
mcpEnablementCallbacks?: McpEnablementCallbacks;
userMemory?: string | HierarchicalMemory;
@@ -779,6 +780,7 @@ export class Config implements McpContext, AgentLoopContext {
private readonly toolDiscoveryCommand: string | undefined;
private readonly toolCallCommand: string | undefined;
private readonly mcpServerCommand: string | undefined;
private readonly shellToolRcFile: string | undefined;
private readonly mcpEnabled: boolean;
private readonly extensionsEnabled: boolean;
private mcpServers: Record<string, MCPServerConfig> | undefined;
@@ -1047,6 +1049,7 @@ export class Config implements McpContext, AgentLoopContext {
this.toolDiscoveryCommand = params.toolDiscoveryCommand;
this.toolCallCommand = params.toolCallCommand;
this.mcpServerCommand = params.mcpServerCommand;
this.shellToolRcFile = params.shellToolRcFile;
this.mcpServers = params.mcpServers;
this.mcpEnablementCallbacks = params.mcpEnablementCallbacks;
this.mcpEnabled = params.mcpEnabled ?? true;
@@ -2318,6 +2321,10 @@ export class Config implements McpContext, AgentLoopContext {
return this.mcpServerCommand;
}
getShellToolRcFile(): string | undefined {
return this.shellToolRcFile;
}
/**
* The user configured MCP servers (via gemini settings files).
*
+66
View File
@@ -164,6 +164,8 @@ describe('ShellTool', () => {
addPersistentApproval: vi.fn(),
addSessionApproval: vi.fn(),
},
getShellToolRcFile: vi.fn().mockReturnValue(undefined),
isTrustedFolder: vi.fn().mockReturnValue(true),
} as unknown as Config;
const bus = createMockMessageBus();
@@ -486,6 +488,70 @@ EOF`;
expect(mockShellExecutionService.mock.calls[0][0]).toMatch(/\nEOF\n\)\n/);
});
it('should source rcfile when shellToolRcFile setting is present and folder is trusted', async () => {
const rcFilePath = '~/.geminirc';
(mockConfig.getShellToolRcFile as Mock).mockReturnValue(rcFilePath);
(mockConfig.isTrustedFolder as Mock).mockReturnValue(true);
const invocation = shellTool.build({ command: 'my-command' });
const promise = invocation.execute({ abortSignal: mockAbortSignal });
resolveShellExecution();
await promise;
expect(mockShellExecutionService).toHaveBeenCalledWith(
expect.stringContaining(
`source '${rcFilePath.replace('~', '/home/user')}'; export PAGER=cat`,
),
expect.any(String),
expect.any(Function),
expect.any(AbortSignal),
false,
expect.any(Object),
);
});
it('should NOT source rcfile when shellToolRcFile setting is present but folder is untrusted', async () => {
const rcFilePath = '~/.geminirc';
(mockConfig.getShellToolRcFile as Mock).mockReturnValue(rcFilePath);
(mockConfig.isTrustedFolder as Mock).mockReturnValue(false);
const invocation = shellTool.build({ command: 'my-command' });
const promise = invocation.execute({ abortSignal: mockAbortSignal });
resolveShellExecution();
await promise;
expect(mockShellExecutionService).not.toHaveBeenCalledWith(
expect.stringContaining(`source '${rcFilePath}'`),
expect.any(String),
expect.any(Function),
expect.any(AbortSignal),
false,
expect.any(Object),
);
});
it('should properly escape quotes in rcFilePath', async () => {
const rcFilePath = "/path/with/'quotes'/rc";
(mockConfig.getShellToolRcFile as Mock).mockReturnValue(rcFilePath);
(mockConfig.isTrustedFolder as Mock).mockReturnValue(true);
const invocation = shellTool.build({ command: 'my-command' });
const promise = invocation.execute({ abortSignal: mockAbortSignal });
resolveShellExecution();
await promise;
expect(mockShellExecutionService).toHaveBeenCalledWith(
expect.stringContaining(
`source '/path/with/'\\''quotes'\\''/rc'; export PAGER=cat`,
),
expect.any(String),
expect.any(Function),
expect.any(AbortSignal),
false,
expect.any(Object),
);
});
it('should format error messages correctly', async () => {
const error = new Error('wrapped command failed');
const invocation = shellTool.build({ command: 'user-command' });
+24 -2
View File
@@ -50,7 +50,12 @@ import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { getShellDefinition } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import { toPathKey, isSubpath, resolveToRealPath } from '../utils/paths.js';
import {
homedir,
toPathKey,
isSubpath,
resolveToRealPath,
} from '../utils/paths.js';
import {
getProactiveToolSuggestions,
isNetworkReliantCommand,
@@ -462,13 +467,30 @@ export class ShellToolInvocation extends BaseToolInvocation<
const combinedController = new AbortController();
const onAbort = () => combinedController.abort();
let strippedCommandWithRc = strippedCommand;
if (!isWindows) {
strippedCommandWithRc = `export PAGER=cat GIT_PAGER=cat; ${strippedCommand}`;
const rcFilePath = this.context.config.getShellToolRcFile();
if (rcFilePath && this.context.config.isTrustedFolder()) {
let resolvedRcFilePath = rcFilePath;
if (rcFilePath === '~' || rcFilePath.startsWith('~/')) {
resolvedRcFilePath = homedir() + rcFilePath.substring(1);
}
const escapedRcFilePath = resolvedRcFilePath.replace(
/'/g,
() => "'\\''",
);
strippedCommandWithRc = `source '${escapedRcFilePath}'; ${strippedCommandWithRc}`;
}
}
try {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-shell-'));
tempFilePath = path.join(tempDir, 'pgrep.tmp');
// pgrep is not available on Windows, so we can't get background PIDs
const commandToExecute = this.wrapCommandForPgrep(
strippedCommand,
strippedCommandWithRc,
tempFilePath,
isWindows,
);
+2 -5
View File
@@ -11,10 +11,7 @@ import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { env } from 'node:process';
import { setTimeout as sleep } from 'node:timers/promises';
import {
PREVIEW_GEMINI_FLASH_MODEL,
GEMINI_DIR,
} from '@google/gemini-cli-core';
import { PREVIEW_GEMINI_MODEL, GEMINI_DIR } from '@google/gemini-cli-core';
export { GEMINI_DIR };
import * as pty from '@lydell/node-pty';
import stripAnsi from 'strip-ansi';
@@ -478,7 +475,7 @@ export class TestRig {
...(env['GEMINI_TEST_TYPE'] === 'integration'
? {
model: {
name: PREVIEW_GEMINI_FLASH_MODEL,
name: PREVIEW_GEMINI_MODEL,
},
}
: {}),
+6
View File
@@ -2509,6 +2509,12 @@
"markdownDescription": "Enable shell output efficiency optimizations for better performance.\n\n- Category: `Tools`\n- Requires restart: `no`\n- Default: `true`",
"default": true,
"type": "boolean"
},
"rcFile": {
"title": "Shell Tool RC File",
"description": "The path to a bash file (e.g., .bashrc) to source before executing shell commands.",
"markdownDescription": "The path to a bash file (e.g., .bashrc) to source before executing shell commands.\n\n- Category: `Tools`\n- Requires restart: `no`",
"type": "string"
}
},
"additionalProperties": false