Compare commits

..

17 Commits

Author SHA1 Message Date
Sehoon Shon affe6856f1 fix(cli): address PR comments for /note command (v3) 2026-04-21 22:15:39 -07:00
Sehoon Shon f727139c72 feat(cli): add /note slash command to append or view notes 2026-04-21 22:03:59 -07:00
Sandy Tao ffb28c772b test(e2e): default integration tests to Flash Preview (#25753) 2026-04-21 22:21:52 +00:00
Adam Weidman d6f88f8720 fix(core): remove duplicate initialize call on agents refreshed (#25670) 2026-04-21 20:17:21 +00:00
Jason Matthew Suhari 194c779f9b fix(cli): start auto memory in ACP sessions (#25626) 2026-04-21 20:06:30 +00:00
Vedant Mahajan 189c0ac0a0 feat: add /new as alias for /clear and refine command description (#17865) 2026-04-21 20:04:40 +00:00
euxaristia c47233a474 fix(core): disable detached mode in Bun to prevent immediate SIGHUP of child processes (#22620) 2026-04-21 20:01:28 +00:00
JAYADITYA 8999a885f0 fix(cli): ensure theme dialog labels are rendered for all themes (#24599)
Co-authored-by: cynthialong0-0 <82900738+cynthialong0-0@users.noreply.github.com>
2026-04-21 19:57:15 +00:00
Coco Sheng 93a8d9001c fix(cli): use newline in shell command wrapping to avoid breaking heredocs (#25537) 2026-04-21 19:12:50 +00:00
PRAS Samin cdc5cccc13 feat: detect new files in @ recommendations with watcher based updates (#25256) 2026-04-21 18:35:14 +00:00
Mahima Shanware a4e98c0a4c fix(core): resolve nested plan directory duplication and relative path policies (#25138) 2026-04-21 18:20:57 +00:00
Spencer c260550146 feat(telemetry): add flag for enabling traces specifically (#25343) 2026-04-21 18:07:32 +00:00
Danyel Cabello 7f8f3309a6 Allow dots on GEMINI_API_KEY (#25497) 2026-04-21 11:43:39 -07:00
Muhammad Ahsan Farooq ebebbbfc20 Fix/allow for session persistence (#25176) 2026-04-21 11:20:07 -07:00
Gordon Hui 27344833cb feat(vertex): add settings for Vertex AI request routing (#25513) 2026-04-21 17:48:30 +00:00
cynthialong0-0 aee2cde1a3 feat(test): refactor the memory usage test to use metrics from CLI process instead of test runner (#25708) 2026-04-21 17:06:22 +00:00
Mundur 2c14954010 Fix: Disallow overriding IDE stdio via workspace .env (RCE) (#25022)
Co-authored-by: Tommaso Sciortino <sciortino@gmail.com>
2026-04-21 10:31:10 -07:00
91 changed files with 2313 additions and 554 deletions
+1 -2
View File
@@ -331,7 +331,6 @@ Storage whenever Gemini CLI exits Plan Mode to start the implementation.
#!/usr/bin/env bash
# Extract the plan filename from the tool input JSON
plan_filename=$(jq -r '.tool_input.plan_filename // empty')
plan_filename=$(basename -- "$plan_filename")
# Construct the absolute path using the GEMINI_PLANS_DIR environment variable
plan_path="$GEMINI_PLANS_DIR/$plan_filename"
@@ -360,7 +359,7 @@ To register this `AfterTool` hook, add it to your `settings.json`:
{
"name": "archive-plan",
"type": "command",
"command": "./.gemini/hooks/archive-plan.sh"
"command": "~/.gemini/hooks/archive-plan.sh"
}
]
}
+18 -11
View File
@@ -35,17 +35,18 @@ The observability system provides:
You control telemetry behavior through the `.gemini/settings.json` file.
Environment variables can override these settings.
| Setting | Environment Variable | Description | Values | Default |
| -------------- | -------------------------------- | --------------------------------------------------- | ----------------- | ----------------------- |
| `enabled` | `GEMINI_TELEMETRY_ENABLED` | Enable or disable telemetry | `true`/`false` | `false` |
| `target` | `GEMINI_TELEMETRY_TARGET` | Where to send telemetry data | `"gcp"`/`"local"` | `"local"` |
| `otlpEndpoint` | `GEMINI_TELEMETRY_OTLP_ENDPOINT` | OTLP collector endpoint | URL string | `http://localhost:4317` |
| `otlpProtocol` | `GEMINI_TELEMETRY_OTLP_PROTOCOL` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
| `outfile` | `GEMINI_TELEMETRY_OUTFILE` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
| `logPrompts` | `GEMINI_TELEMETRY_LOG_PROMPTS` | Include prompts in telemetry logs | `true`/`false` | `true` |
| `useCollector` | `GEMINI_TELEMETRY_USE_COLLECTOR` | Use external OTLP collector (advanced) | `true`/`false` | `false` |
| `useCliAuth` | `GEMINI_TELEMETRY_USE_CLI_AUTH` | Use CLI credentials for telemetry (GCP target only) | `true`/`false` | `false` |
| - | `GEMINI_CLI_SURFACE` | Optional custom label for traffic reporting | string | - |
| Setting | Environment Variable | Description | Values | Default |
| -------------- | --------------------------------- | --------------------------------------------------- | ----------------- | ----------------------- |
| `enabled` | `GEMINI_TELEMETRY_ENABLED` | Enable or disable telemetry | `true`/`false` | `false` |
| `traces` | `GEMINI_TELEMETRY_TRACES_ENABLED` | Enable detailed attribute tracing | `true`/`false` | `false` |
| `target` | `GEMINI_TELEMETRY_TARGET` | Where to send telemetry data | `"gcp"`/`"local"` | `"local"` |
| `otlpEndpoint` | `GEMINI_TELEMETRY_OTLP_ENDPOINT` | OTLP collector endpoint | URL string | `http://localhost:4317` |
| `otlpProtocol` | `GEMINI_TELEMETRY_OTLP_PROTOCOL` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
| `outfile` | `GEMINI_TELEMETRY_OUTFILE` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
| `logPrompts` | `GEMINI_TELEMETRY_LOG_PROMPTS` | Include prompts in telemetry logs | `true`/`false` | `true` |
| `useCollector` | `GEMINI_TELEMETRY_USE_COLLECTOR` | Use external OTLP collector (advanced) | `true`/`false` | `false` |
| `useCliAuth` | `GEMINI_TELEMETRY_USE_CLI_AUTH` | Use CLI credentials for telemetry (GCP target only) | `true`/`false` | `false` |
| - | `GEMINI_CLI_SURFACE` | Optional custom label for traffic reporting | string | - |
**Note on boolean environment variables:** For boolean settings like `enabled`,
setting the environment variable to `true` or `1` enables the feature.
@@ -1235,6 +1236,12 @@ These metrics follow standard [OpenTelemetry GenAI semantic conventions].
Traces provide an "under-the-hood" view of agent and backend operations. Use
traces to debug tool interactions and optimize performance.
<!-- prettier-ignore -->
> [!NOTE]
> Detailed trace attributes (like full prompts and tool outputs) are disabled by default
> to minimize overhead. You must explicitly set `telemetry.traces` to `true` (or set
> `GEMINI_TELEMETRY_TRACES_ENABLED=true`) to capture them.
Every trace captures rich metadata via standard span attributes.
<details open>
+26
View File
@@ -436,6 +436,20 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `"ask"`
- **Values:** `"ask"`, `"always"`, `"never"`
- **`billing.vertexAi.requestType`** (enum):
- **Description:** Sets the X-Vertex-AI-LLM-Request-Type header for Vertex AI
requests.
- **Default:** `undefined`
- **Values:** `"dedicated"`, `"shared"`
- **Requires restart:** Yes
- **`billing.vertexAi.sharedRequestType`** (enum):
- **Description:** Sets the X-Vertex-AI-LLM-Shared-Request-Type header for
Vertex AI requests.
- **Default:** `undefined`
- **Values:** `"priority"`, `"flex"`
- **Requires restart:** Yes
#### `model`
- **`model.name`** (string):
@@ -1359,6 +1373,12 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `true`
- **Requires restart:** Yes
- **`context.fileFiltering.enableFileWatcher`** (boolean):
- **Description:** Enable file watcher updates for @ file suggestions
(experimental).
- **Default:** `false`
- **Requires restart:** Yes
- **`context.fileFiltering.enableRecursiveFileSearch`** (boolean):
- **Description:** Enable recursive file search functionality when completing
@ references in the prompt.
@@ -1998,6 +2018,8 @@ see [Telemetry](../cli/telemetry.md).
- **Properties:**
- **`enabled`** (boolean): Whether or not telemetry is enabled.
- **`traces`** (boolean): Whether detailed traces with large attributes (like
tool outputs and file reads) are captured. Defaults to `false`.
- **`target`** (string): The destination for collected telemetry. Supported
values are `local` and `gcp`.
- **`otlpEndpoint`** (string): The endpoint for the OTLP Exporter.
@@ -2198,6 +2220,10 @@ the `advanced.excludedEnvVars` setting in your `settings.json` file.
- Set to `true` or `1` to enable telemetry. Any other value is treated as
disabling it.
- Overrides the `telemetry.enabled` setting.
- **`GEMINI_TELEMETRY_TRACES_ENABLED`**:
- Set to `true` or `1` to enable detailed tracing with large attributes. Any
other value is treated as disabling it.
- Overrides the `telemetry.traces` setting.
- **`GEMINI_TELEMETRY_TARGET`**:
- Sets the telemetry target (`local` or `gcp`).
- Overrides the `telemetry.target` setting.
+45 -1
View File
@@ -305,7 +305,7 @@ describe('plan_mode', () => {
settings,
},
prompt:
'Enter plan mode and plan to create a new module called foo. The plan should be saved as foo-plan.md. Then, exit plan mode.',
'I agree with your strategy. Please enter plan mode and draft the plan to create a new module called foo. The plan should be saved as foo-plan.md. Then, exit plan mode.',
assert: async (rig, result) => {
const enterPlanCalled = await rig.waitForToolCall('enter_plan_mode');
expect(
@@ -376,4 +376,48 @@ describe('plan_mode', () => {
assertModelHasOutput(result);
},
});
evalTest('USUALLY_PASSES', {
name: 'should handle nested plan directories correctly',
suiteName: 'plan_mode',
suiteType: 'behavioral',
approvalMode: ApprovalMode.PLAN,
params: {
settings,
},
prompt:
'Please create a new architectural plan in a nested folder called "architecture/frontend-v2.md" within the plans directory. The plan should contain the text "# Frontend V2 Plan". Then, exit plan mode',
assert: async (rig, result) => {
await rig.waitForTelemetryReady();
const toolLogs = rig.readToolLogs();
const writeCalls = toolLogs.filter((log) =>
['write_file', 'replace'].includes(log.toolRequest.name),
);
const wroteToNestedPath = writeCalls.some((log) => {
try {
const args = JSON.parse(log.toolRequest.args);
if (!args.file_path) return false;
// In plan mode, paths can be passed as relative (architecture/frontend-v2.md)
// or they might be resolved as absolute by the tool depending on the exact mock state.
// We strictly ensure it ends exactly with the expected nested path and doesn't contain extra nesting.
const normalizedPath = args.file_path.replace(/\\/g, '/');
return (
normalizedPath === 'architecture/frontend-v2.md' ||
normalizedPath.endsWith('/plans/architecture/frontend-v2.md')
);
} catch {
return false;
}
});
expect(
wroteToNestedPath,
'Expected model to successfully target the nested plan file path',
).toBe(true);
assertModelHasOutput(result);
},
});
});
+1
View File
@@ -70,6 +70,7 @@ describe('ACP telemetry', () => {
GEMINI_API_KEY: 'fake-key',
GEMINI_CLI_HOME: rig.homeDir!,
GEMINI_TELEMETRY_ENABLED: 'true',
GEMINI_TELEMETRY_TRACES_ENABLED: 'true',
GEMINI_TELEMETRY_TARGET: 'local',
GEMINI_TELEMETRY_OUTFILE: telemetryPath,
},
@@ -8,7 +8,16 @@ import { expect, describe, it, beforeEach, afterEach } from 'vitest';
import { TestRig } from './test-helper.js';
import { join } from 'node:path';
describe('Interactive Mode', () => {
// 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', () => {
let rig: TestRig;
beforeEach(() => {
+3 -1
View File
@@ -134,7 +134,9 @@ describe('file-system', () => {
).toBeTruthy();
const newFileContent = rig.readFile(fileName);
expect(newFileContent).toBe('hello');
// 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');
});
it('should perform a read-then-write sequence', async () => {
+9 -2
View File
@@ -81,7 +81,10 @@ describe('Plan Mode', () => {
await rig.run({
approvalMode: 'plan',
args: 'Create a file called plan.md in the plans directory.',
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.',
});
const toolLogs = rig.readToolLogs();
@@ -194,7 +197,11 @@ describe('Plan Mode', () => {
await rig.run({
approvalMode: 'plan',
args: 'Create a file called plan-no-session.md in the plans directory.',
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.',
});
const toolLogs = rig.readToolLogs();
+36 -36
View File
@@ -1,55 +1,55 @@
{
"version": 1,
"updatedAt": "2026-04-10T15:36:04.547Z",
"updatedAt": "2026-04-20T18:04:59.671Z",
"scenarios": {
"multi-turn-conversation": {
"heapUsedBytes": 120082704,
"heapTotalBytes": 177586176,
"rssBytes": 269172736,
"externalBytes": 4304053,
"timestamp": "2026-04-10T15:35:17.603Z"
"heapUsedMB": 68.8,
"heapTotalMB": 91.2,
"rssMB": 215.4,
"externalMB": 93.8,
"timestamp": "2026-04-20T18:02:40.101Z"
},
"multi-function-call-repo-search": {
"heapUsedBytes": 104644984,
"heapTotalBytes": 111575040,
"rssBytes": 204079104,
"externalBytes": 4304053,
"timestamp": "2026-04-10T15:35:22.480Z"
"heapUsedMB": 73.5,
"heapTotalMB": 93.1,
"rssMB": 223.6,
"externalMB": 97.7,
"timestamp": "2026-04-20T18:02:42.032Z"
},
"idle-session-startup": {
"heapUsedBytes": 119813672,
"heapTotalBytes": 177061888,
"rssBytes": 267943936,
"externalBytes": 4304053,
"timestamp": "2026-04-10T15:35:08.035Z"
"heapUsedMB": 69.8,
"heapTotalMB": 92.4,
"rssMB": 217.4,
"externalMB": 93.8,
"timestamp": "2026-04-20T18:02:36.294Z"
},
"simple-prompt-response": {
"heapUsedBytes": 119722064,
"heapTotalBytes": 177324032,
"rssBytes": 268812288,
"externalBytes": 4304053,
"timestamp": "2026-04-10T15:35:12.770Z"
"heapUsedMB": 69.5,
"heapTotalMB": 92.4,
"rssMB": 216.1,
"externalMB": 93.8,
"timestamp": "2026-04-20T18:02:38.198Z"
},
"resume-large-chat-with-messages": {
"heapUsedBytes": 106545568,
"heapTotalBytes": 111509504,
"rssBytes": 202596352,
"externalBytes": 4306101,
"timestamp": "2026-04-10T15:36:04.547Z"
"heapUsedMB": 887.1,
"heapTotalMB": 954.3,
"rssMB": 1109.6,
"externalMB": 103.2,
"timestamp": "2026-04-20T18:04:59.671Z"
},
"resume-large-chat": {
"heapUsedBytes": 106513760,
"heapTotalBytes": 111509504,
"rssBytes": 202596352,
"externalBytes": 4306101,
"timestamp": "2026-04-10T15:35:59.528Z"
"heapUsedMB": 885.6,
"heapTotalMB": 955.6,
"rssMB": 1107.8,
"externalMB": 110.5,
"timestamp": "2026-04-20T18:04:06.526Z"
},
"large-chat": {
"heapUsedBytes": 106471568,
"heapTotalBytes": 111509504,
"rssBytes": 202596352,
"externalBytes": 4306101,
"timestamp": "2026-04-10T15:35:53.180Z"
"heapUsedMB": 158.5,
"heapTotalMB": 193,
"rssMB": 787.9,
"externalMB": 104,
"timestamp": "2026-04-20T18:03:12.486Z"
}
}
}
+30 -8
View File
@@ -16,15 +16,21 @@ import {
mkdirSync,
rmSync,
} from 'node:fs';
import { randomUUID } from 'node:crypto';
import { randomUUID, createHash } from 'node:crypto';
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASELINES_PATH = join(__dirname, 'baselines.json');
const UPDATE_BASELINES = process.env['UPDATE_MEMORY_BASELINES'] === 'true';
function getProjectHash(projectRoot: string): string {
return createHash('sha256').update(projectRoot).digest('hex');
}
const TOLERANCE_PERCENT = 10;
// Fake API key for tests using fake responses
const TEST_ENV = { GEMINI_API_KEY: 'fake-memory-test-key' };
const TEST_ENV = {
GEMINI_API_KEY: 'fake-memory-test-key',
GEMINI_MEMORY_MONITOR_INTERVAL: '100',
};
describe('Memory Usage Tests', () => {
let harness: MemoryTestHarness;
@@ -56,6 +62,7 @@ describe('Memory Usage Tests', () => {
});
const result = await harness.runScenario(
rig,
'idle-session-startup',
async (recordSnapshot) => {
await rig.run({
@@ -85,6 +92,7 @@ describe('Memory Usage Tests', () => {
});
const result = await harness.runScenario(
rig,
'simple-prompt-response',
async (recordSnapshot) => {
await rig.run({
@@ -122,6 +130,7 @@ describe('Memory Usage Tests', () => {
];
const result = await harness.runScenario(
rig,
'multi-turn-conversation',
async (recordSnapshot) => {
// Run through all turns as a piped sequence
@@ -144,6 +153,9 @@ describe('Memory Usage Tests', () => {
);
} else {
harness.assertWithinBaseline(result);
harness.assertMemoryReturnsToBaseline(result.snapshots, 20);
const { leaked, message } = harness.analyzeSnapshots(result.snapshots);
if (leaked) console.warn(`${message}`);
}
});
@@ -168,6 +180,7 @@ describe('Memory Usage Tests', () => {
);
const result = await harness.runScenario(
rig,
'multi-function-call-repo-search',
async (recordSnapshot) => {
await rig.run({
@@ -189,6 +202,7 @@ describe('Memory Usage Tests', () => {
);
} else {
harness.assertWithinBaseline(result);
harness.assertMemoryReturnsToBaseline(result.snapshots, 20);
}
});
@@ -228,6 +242,7 @@ describe('Memory Usage Tests', () => {
});
const result = await harness.runScenario(
rig,
'large-chat',
async (recordSnapshot) => {
await rig.run({
@@ -257,19 +272,21 @@ describe('Memory Usage Tests', () => {
});
const result = await harness.runScenario(
rig,
'resume-large-chat',
async (recordSnapshot) => {
// Ensure the history file is linked
const targetChatsDir = join(
rig.testDir!,
rig.homeDir!,
'.gemini',
'tmp',
'test-project-hash',
getProjectHash(rig.testDir!),
'chats',
);
mkdirSync(targetChatsDir, { recursive: true });
const targetHistoryPath = join(
targetChatsDir,
'large-chat-session.json',
'session-large-chat.json',
);
if (existsSync(targetHistoryPath)) rmSync(targetHistoryPath);
copyFileSync(sharedHistoryPath, targetHistoryPath);
@@ -302,19 +319,21 @@ describe('Memory Usage Tests', () => {
});
const result = await harness.runScenario(
rig,
'resume-large-chat-with-messages',
async (recordSnapshot) => {
// Ensure the history file is linked
const targetChatsDir = join(
rig.testDir!,
rig.homeDir!,
'.gemini',
'tmp',
'test-project-hash',
getProjectHash(rig.testDir!),
'chats',
);
mkdirSync(targetChatsDir, { recursive: true });
const targetHistoryPath = join(
targetChatsDir,
'large-chat-session.json',
'session-large-chat.json',
);
if (existsSync(targetHistoryPath)) rmSync(targetHistoryPath);
copyFileSync(sharedHistoryPath, targetHistoryPath);
@@ -457,6 +476,9 @@ async function generateSharedLargeChatData(tempDir: string) {
// Generate responses for resumed chat
const resumeResponsesStream = createWriteStream(resumeResponsesPath);
for (let i = 0; i < 5; i++) {
// Doubling up on non-streaming responses to satisfy classifier and complexity checks
resumeResponsesStream.write(JSON.stringify(complexityResponse) + '\n');
resumeResponsesStream.write(JSON.stringify(summaryResponse) + '\n');
resumeResponsesStream.write(JSON.stringify(complexityResponse) + '\n');
resumeResponsesStream.write(
JSON.stringify({
+61 -53
View File
@@ -449,7 +449,8 @@
"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)"
"license": "(Apache-2.0 AND BSD-3-Clause)",
"peer": true
},
"node_modules/@bundled-es-modules/cookie": {
"version": "2.0.1",
@@ -1473,6 +1474,7 @@
"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"
@@ -2150,6 +2152,7 @@
"integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@octokit/auth-token": "^6.0.0",
"@octokit/graphql": "^9.0.2",
@@ -2330,6 +2333,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -2379,6 +2383,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.5.0.tgz",
"integrity": "sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
},
@@ -2753,6 +2758,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.5.0.tgz",
"integrity": "sha512-F8W52ApePshpoSrfsSk1H2yJn9aKjCrbpQF1M9Qii0GHzbfVeFUB+rc3X4aggyZD8x9Gu3Slua+s6krmq6Dt8g==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/semantic-conventions": "^1.29.0"
@@ -2786,6 +2792,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.5.0.tgz",
"integrity": "sha512-BeJLtU+f5Gf905cJX9vXFQorAr6TAfK3SPvTFqP+scfIpDQEJfRaGJWta7sJgP+m4dNtBf9y3yvBKVAZZtJQVA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0"
@@ -2840,6 +2847,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.5.0.tgz",
"integrity": "sha512-VzRf8LzotASEyNDUxTdaJ9IRJ1/h692WyArDBInf5puLCjxbICD6XkHgpuudis56EndyS7LYFmtTMny6UABNdQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0",
@@ -4046,6 +4054,7 @@
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -4319,6 +4328,7 @@
"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",
@@ -4593,56 +4603,6 @@
}
}
},
"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",
@@ -5113,6 +5073,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -7190,7 +7151,8 @@
"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"
"license": "BSD-3-Clause",
"peer": true
},
"node_modules/dezalgo": {
"version": "1.0.4",
@@ -7775,6 +7737,7 @@
"integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -8292,6 +8255,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@@ -9558,6 +9522,7 @@
"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"
}
@@ -9817,6 +9782,7 @@
"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",
@@ -13530,6 +13496,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -13540,6 +13507,7 @@
"integrity": "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"shell-quote": "^1.6.1",
"ws": "^7"
@@ -15659,6 +15627,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15881,7 +15850,8 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
"license": "0BSD",
"peer": true
},
"node_modules/tsx": {
"version": "4.20.3",
@@ -15889,6 +15859,7 @@
"integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.25.0",
"get-tsconfig": "^4.7.5"
@@ -16054,6 +16025,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -16121,6 +16093,7 @@
"integrity": "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.35.0",
"@typescript-eslint/types": "8.35.0",
@@ -16507,6 +16480,7 @@
"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",
@@ -17077,6 +17051,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -17089,6 +17064,7 @@
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4",
@@ -17727,6 +17703,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -18054,6 +18031,7 @@
"ajv": "^8.17.1",
"ajv-formats": "^3.0.0",
"chardet": "^2.1.0",
"chokidar": "^5.0.0",
"diff": "^8.0.3",
"dotenv": "^17.2.4",
"dotenv-expand": "^12.0.3",
@@ -18161,6 +18139,7 @@
"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"
@@ -18203,6 +18182,21 @@
"url": "https://github.com/sponsors/epoberezkin"
}
},
"packages/core/node_modules/chokidar": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz",
"integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==",
"license": "MIT",
"dependencies": {
"readdirp": "^5.0.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"packages/core/node_modules/dotenv": {
"version": "17.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",
@@ -18264,6 +18258,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -18271,6 +18266,19 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"packages/core/node_modules/readdirp": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz",
"integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
},
"packages/core/node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -98,6 +98,7 @@ export function createMockConfig(
getMcpServers: vi.fn().mockReturnValue({}),
}),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getGitService: vi.fn(),
validatePathAccess: vi.fn().mockReturnValue(undefined),
getShellExecutionConfig: vi.fn().mockReturnValue({
+34
View File
@@ -41,6 +41,8 @@ import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { ApprovalMode } from '@google/gemini-cli-core/src/policy/types.js';
const startMemoryServiceMock = vi.hoisted(() => vi.fn());
vi.mock('../config/config.js', () => ({
loadCliConfig: vi.fn(),
}));
@@ -101,6 +103,7 @@ vi.mock(
const actual = await importOriginal();
return {
...actual,
startMemoryService: startMemoryServiceMock,
updatePolicy: vi.fn(),
createPolicyUpdater: vi.fn(),
ReadManyFilesTool: vi.fn(),
@@ -148,6 +151,8 @@ describe('GeminiAgent', () => {
let agent: GeminiAgent;
beforeEach(() => {
vi.clearAllMocks();
startMemoryServiceMock.mockResolvedValue(undefined);
mockConfig = {
refreshAuth: vi.fn(),
initialize: vi.fn(),
@@ -155,6 +160,7 @@ describe('GeminiAgent', () => {
getFileSystemService: vi.fn(),
setFileSystemService: vi.fn(),
getContentGeneratorConfig: vi.fn(),
isAutoMemoryEnabled: vi.fn().mockReturnValue(false),
getActiveModel: vi.fn().mockReturnValue('gemini-pro'),
getModel: vi.fn().mockReturnValue('gemini-pro'),
getGeminiClient: vi.fn().mockReturnValue({
@@ -354,6 +360,34 @@ describe('GeminiAgent', () => {
vi.useRealTimers();
});
it('should start auto memory for new ACP sessions when enabled', async () => {
mockConfig.getContentGeneratorConfig = vi.fn().mockReturnValue({
apiKey: 'test-key',
});
mockConfig.isAutoMemoryEnabled = vi.fn().mockReturnValue(true);
await agent.newSession({
cwd: '/tmp',
mcpServers: [],
});
expect(startMemoryServiceMock).toHaveBeenCalledWith(mockConfig);
});
it('should not start auto memory for new ACP sessions when disabled', async () => {
mockConfig.getContentGeneratorConfig = vi.fn().mockReturnValue({
apiKey: 'test-key',
});
mockConfig.isAutoMemoryEnabled = vi.fn().mockReturnValue(false);
await agent.newSession({
cwd: '/tmp',
mcpServers: [],
});
expect(startMemoryServiceMock).not.toHaveBeenCalled();
});
it('should return modes without plan mode when plan is disabled', async () => {
mockConfig.getContentGeneratorConfig = vi.fn().mockReturnValue({
apiKey: 'test-key',
+3
View File
@@ -76,6 +76,7 @@ import { randomUUID } from 'node:crypto';
import { loadCliConfig, type CliArgs } from '../config/config.js';
import { runExitCleanup } from '../utils/cleanup.js';
import { SessionSelector } from '../utils/sessionUtils.js';
import { startAutoMemoryIfEnabled } from '../utils/autoMemory.js';
import { CommandHandler } from './commandHandler.js';
@@ -324,6 +325,7 @@ export class GeminiAgent {
await config.initialize();
startupProfiler.flush(config);
startAutoMemoryIfEnabled(config);
const geminiClient = config.getGeminiClient();
const chat = await geminiClient.startChat();
@@ -465,6 +467,7 @@ export class GeminiAgent {
// which starts the MCP servers and other heavy resources.
await config.initialize();
startupProfiler.flush(config);
startAutoMemoryIfEnabled(config);
return config;
}
+1
View File
@@ -100,6 +100,7 @@ describe('GeminiAgent Session Resume', () => {
unsubscribe: vi.fn(),
},
getApprovalMode: vi.fn().mockReturnValue('default'),
isAutoMemoryEnabled: vi.fn().mockReturnValue(false),
isPlanEnabled: vi.fn().mockReturnValue(true),
getModel: vi.fn().mockReturnValue('gemini-pro'),
getHasAccessToPreviewModel: vi.fn().mockReturnValue(false),
+1
View File
@@ -1032,6 +1032,7 @@ export async function loadCliConfig(
recordResponses: argv.recordResponses,
retryFetchErrors: settings.general?.retryFetchErrors,
billing: settings.billing,
vertexAiRouting: settings.billing?.vertexAi,
maxAttempts: settings.general?.maxAttempts,
ptyInfo: ptyInfo?.name,
disableLLMCorrection: settings.tools?.disableLLMCorrection,
+6 -1
View File
@@ -78,7 +78,12 @@ export function getMergeStrategyForPath(
export const USER_SETTINGS_PATH = Storage.getGlobalSettingsPath();
export const USER_SETTINGS_DIR = path.dirname(USER_SETTINGS_PATH);
export const DEFAULT_EXCLUDED_ENV_VARS = ['DEBUG', 'DEBUG_MODE'];
export const DEFAULT_EXCLUDED_ENV_VARS = [
'DEBUG',
'DEBUG_MODE',
'GEMINI_CLI_IDE_SERVER_STDIO_COMMAND',
'GEMINI_CLI_IDE_SERVER_STDIO_ARGS',
];
const AUTH_ENV_VAR_WHITELIST = [
'GEMINI_API_KEY',
@@ -138,6 +138,10 @@ describe('SettingsSchema', () => {
getSettingsSchema().context.properties.fileFiltering.properties
?.enableRecursiveFileSearch,
).toBeDefined();
expect(
getSettingsSchema().context.properties.fileFiltering.properties
?.enableFileWatcher,
).toBeDefined();
expect(
getSettingsSchema().context.properties.fileFiltering.properties
?.customIgnoreFilePaths,
@@ -313,6 +317,22 @@ describe('SettingsSchema', () => {
).toBe(false);
});
it('should have Vertex AI routing settings in schema', () => {
const vertexAi =
getSettingsSchema().billing.properties.vertexAi.properties;
expect(vertexAi.requestType).toBeDefined();
expect(vertexAi.requestType.type).toBe('enum');
expect(
vertexAi.requestType.options?.map((option) => option.value),
).toEqual(['dedicated', 'shared']);
expect(vertexAi.sharedRequestType).toBeDefined();
expect(vertexAi.sharedRequestType.type).toBe('enum');
expect(
vertexAi.sharedRequestType.options?.map((option) => option.value),
).toEqual(['priority', 'flex']);
});
it('should have folderTrustFeature setting in schema', () => {
expect(
getSettingsSchema().security.properties.folderTrust.properties.enabled,
+56
View File
@@ -21,6 +21,7 @@ import {
type AgentOverride,
type CustomTheme,
type SandboxConfig,
type VertexAiRoutingConfig,
} from '@google/gemini-cli-core';
import type { SessionRetentionSettings } from './settings.js';
import { DEFAULT_MIN_RETENTION } from '../utils/sessionCleanup.js';
@@ -990,6 +991,45 @@ const SETTINGS_SCHEMA = {
{ value: 'never', label: 'Never use credits' },
],
},
vertexAi: {
type: 'object',
label: 'Vertex AI',
category: 'Advanced',
requiresRestart: true,
default: undefined as VertexAiRoutingConfig | undefined,
description: 'Vertex AI request routing settings.',
showInDialog: false,
properties: {
requestType: {
type: 'enum',
label: 'Vertex AI Request Type',
category: 'Advanced',
requiresRestart: true,
default: undefined as VertexAiRoutingConfig['requestType'],
description:
'Sets the X-Vertex-AI-LLM-Request-Type header for Vertex AI requests.',
showInDialog: false,
options: [
{ value: 'dedicated', label: 'Dedicated' },
{ value: 'shared', label: 'Shared' },
],
},
sharedRequestType: {
type: 'enum',
label: 'Vertex AI Shared Request Type',
category: 'Advanced',
requiresRestart: true,
default: undefined as VertexAiRoutingConfig['sharedRequestType'],
description:
'Sets the X-Vertex-AI-LLM-Shared-Request-Type header for Vertex AI requests.',
showInDialog: false,
options: [
{ value: 'priority', label: 'Priority' },
{ value: 'flex', label: 'Flex' },
],
},
},
},
},
},
@@ -1431,6 +1471,17 @@ const SETTINGS_SCHEMA = {
description: 'Respect .geminiignore files when searching.',
showInDialog: true,
},
enableFileWatcher: {
type: 'boolean',
label: 'Enable File Watcher',
category: 'Context',
requiresRestart: true,
default: false,
description: oneLine`
Enable file watcher updates for @ file suggestions (experimental).
`,
showInDialog: false,
},
enableRecursiveFileSearch: {
type: 'boolean',
label: 'Enable Recursive File Search',
@@ -3020,6 +3071,11 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
description: 'Protocol for OTLP exporters.',
enum: ['grpc', 'http'],
},
traces: {
type: 'boolean',
description:
'Whether detailed traces with large attributes are captured.',
},
logPrompts: {
type: 'boolean',
description: 'Whether prompts are logged in telemetry payloads.',
@@ -42,6 +42,7 @@ 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';
@@ -184,6 +185,7 @@ export class BuiltinCommandLoader implements ICommandLoader {
: [mcpCommand]),
memoryCommand,
modelCommand,
noteCommand,
...(this.config?.getFolderTrust() ? [permissionsCommand] : []),
...(this.config?.isPlanEnabled() ? [planCommand] : []),
policiesCommand,
@@ -89,6 +89,7 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
getAccessibility: vi.fn().mockReturnValue({}),
getTelemetryEnabled: vi.fn().mockReturnValue(false),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getTelemetryOtlpEndpoint: vi.fn().mockReturnValue(''),
getTelemetryOtlpProtocol: vi.fn().mockReturnValue('grpc'),
getTelemetryTarget: vi.fn().mockReturnValue(''),
+2 -7
View File
@@ -92,7 +92,6 @@ import {
ApiKeyUpdatedEvent,
LegacyAgentProtocol,
type InjectionSource,
startMemoryService,
} from '@google/gemini-cli-core';
import { validateAuthMethod } from '../config/auth.js';
import process from 'node:process';
@@ -125,6 +124,7 @@ import { type BackgroundTask } from './hooks/useExecutionLifecycle.js';
import { useVim } from './hooks/vim.js';
import { type LoadableSettingScope, SettingScope } from '../config/settings.js';
import { type InitializationResult } from '../core/initializer.js';
import { startAutoMemoryIfEnabled } from '../utils/autoMemory.js';
import { useFocus } from './hooks/useFocus.js';
import { useKeypress, type Key } from './hooks/useKeypress.js';
import { KeypressPriority } from './contexts/KeypressContext.js';
@@ -486,12 +486,7 @@ export const AppContainer = (props: AppContainerProps) => {
setConfigInitialized(true);
startupProfiler.flush(config);
// Fire-and-forget Auto Memory service (skill extraction from past sessions)
if (config.isAutoMemoryEnabled()) {
startMemoryService(config).catch((e) => {
debugLogger.error('Failed to start memory service:', e);
});
}
startAutoMemoryIfEnabled(config);
const sessionStartSource = resumedSessionData
? SessionStartSource.Resume
+1 -1
View File
@@ -52,7 +52,7 @@ export function ApiAuthDialog({
height: 4,
},
inputFilter: (text) =>
text.replace(/[^a-zA-Z0-9_-]/g, '').replace(/[\r\n]/g, ''),
text.replace(/[^a-zA-Z0-9_.-]/g, '').replace(/[\r\n]/g, ''),
singleLine: true,
});
+3 -2
View File
@@ -16,8 +16,9 @@ import { MessageType } from '../types.js';
import { randomUUID } from 'node:crypto';
export const clearCommand: SlashCommand = {
name: 'clear',
description: 'Clear the screen and conversation history',
name: 'clear (new)',
altNames: ['new'],
description: 'Clear the screen and start a new session',
kind: CommandKind.BUILT_IN,
autoExecute: true,
action: async (context, _args) => {
@@ -0,0 +1,94 @@
/**
* @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',
),
});
});
});
@@ -0,0 +1,60 @@
/**
* @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)}`,
};
}
},
};
@@ -159,6 +159,7 @@ Implement a comprehensive authentication system with multiple providers.
isTrustedFolder: () => true,
getPreferredEditor: () => undefined,
getSessionId: () => 'test-session-id',
getProjectRoot: () => mockTargetDir,
storage: {
getPlansDir: () => mockPlansDir,
},
@@ -466,6 +467,7 @@ Implement a comprehensive authentication system with multiple providers.
getIdeMode: () => false,
isTrustedFolder: () => true,
getSessionId: () => 'test-session-id',
getProjectRoot: () => mockTargetDir,
storage: {
getPlansDir: () => mockPlansDir,
},
@@ -85,6 +85,7 @@ function usePlanContent(planPath: string, config: Config): PlanContentState {
const pathError = await validatePlanPath(
planPath,
config.storage.getPlansDir(),
config.getProjectRoot(),
);
if (ignore) return;
if (pathError) {
@@ -219,7 +219,7 @@ describe('Hint Visibility', () => {
<ThemeDialog {...baseProps} settings={settings} />,
{
settings,
uiState: { terminalBackgroundColor: '#FFFFFF' },
uiState: { terminalBackgroundColor: '#123456' },
},
);
+16 -7
View File
@@ -287,11 +287,15 @@ export function ThemeDialog({
const itemWithExtras = item as typeof item & {
themeWarning?: string;
themeMatch?: string;
themeNameDisplay?: string;
themeTypeDisplay?: string;
};
if (item.themeNameDisplay && item.themeTypeDisplay) {
const match = item.themeNameDisplay.match(/^(.*) \((.*)\)$/);
let themeNamePart: React.ReactNode = item.themeNameDisplay;
if (itemWithExtras.themeNameDisplay) {
const match =
itemWithExtras.themeNameDisplay.match(/^(.*) \((.*)\)$/);
let themeNamePart: React.ReactNode =
itemWithExtras.themeNameDisplay;
if (match) {
themeNamePart = (
<>
@@ -303,10 +307,15 @@ export function ThemeDialog({
return (
<Text color={titleColor} wrap="truncate" key={item.key}>
{themeNamePart}{' '}
<Text color={theme.text.secondary}>
{item.themeTypeDisplay}
</Text>
{themeNamePart}
{itemWithExtras.themeTypeDisplay ? (
<>
{' '}
<Text color={theme.text.secondary}>
{itemWithExtras.themeTypeDisplay}
</Text>
</>
) : null}
{itemWithExtras.themeMatch && (
<Text color={theme.status.success}>
{itemWithExtras.themeMatch}
@@ -52,6 +52,7 @@ describe('ToolConfirmationQueue', () => {
getModel: () => 'gemini-pro',
getDebugMode: () => false,
getTargetDir: () => '/mock/target/dir',
getProjectRoot: () => '/mock/project/root',
getFileSystemService: () => ({
readFile: vi.fn().mockResolvedValue('Plan content'),
}),
@@ -16,7 +16,7 @@ exports[`Initial Theme Selection > should default to a dark theme when terminal
│ 9. Shades Of Purple Dark │ 1 - print("Hello, " + name) │ │
│ 10. Solarized Dark │ 1 + print(f"Hello, {name}!") │ │
│ 11. Tokyo Night Dark │ │ │
│ 12. ANSI Light └─────────────────────────────────────────────────┘ │
│ 12. ANSI Light (Incompatible) └─────────────────────────────────────────────────┘ │
│ ▼ │
│ │
│ (Use Enter to select, Tab to configure scope, Esc to close) │
@@ -32,7 +32,7 @@ exports[`Initial Theme Selection > should default to a light theme when terminal
│ ▲ ┌─────────────────────────────────────────────────┐ │
│ 1. ANSI Light │ │ │
│ 2. Ayu Light │ 1 # function │ │
│ ● 3. Default Light │ 2 def fibonacci(n): │ │
│ ● 3. Default Light (Matches terminal) │ 2 def fibonacci(n): │ │
│ 4. GitHub Light │ 3 a, b = 0, 1 │ │
│ 5. GitHub Light Colorblind Light (Mat… │ 4 for _ in range(n): │ │
│ 6. Google Code Light │ 5 a, b = b, a + b │ │
@@ -66,7 +66,7 @@ exports[`Initial Theme Selection > should use the theme from settings even if te
│ 9. Shades Of Purple Dark │ 1 - print("Hello, " + name) │ │
│ 10. Solarized Dark │ 1 + print(f"Hello, {name}!") │ │
│ 11. Tokyo Night Dark │ │ │
│ 12. ANSI Light └─────────────────────────────────────────────────┘ │
│ 12. ANSI Light (Incompatible) └─────────────────────────────────────────────────┘ │
│ ▼ │
│ │
│ (Use Enter to select, Tab to configure scope, Esc to close) │
@@ -105,7 +105,7 @@ exports[`ThemeDialog Snapshots > should render correctly in theme selection mode
│ 9. Shades Of Purple Dark │ 1 - print("Hello, " + name) │ │
│ 10. Solarized Dark │ 1 + print(f"Hello, {name}!") │ │
│ 11. Tokyo Night Dark │ │ │
│ 12. ANSI Light └─────────────────────────────────────────────────┘ │
│ 12. ANSI Light (Incompatible) └─────────────────────────────────────────────────┘ │
│ ▼ │
│ │
│ (Use Enter to select, Tab to configure scope, Esc to close) │
@@ -130,7 +130,7 @@ exports[`ThemeDialog Snapshots > should render correctly in theme selection mode
│ 9. Shades Of Purple Dark │ 1 - print("Hello, " + name) │ │
│ 10. Solarized Dark │ 1 + print(f"Hello, {name}!") │ │
│ 11. Tokyo Night Dark │ │ │
│ 12. ANSI Light └─────────────────────────────────────────────────┘ │
│ 12. ANSI Light (Incompatible) └─────────────────────────────────────────────────┘ │
│ ▼ │
│ ╭─────────────────────────────────────────────────╮ │
│ │ DEVELOPER TOOLS (Not visible to users) │ │
@@ -553,6 +553,38 @@ describe('useAtCompletion', () => {
]);
});
it('should pass enableFileWatcher flag into FileSearchFactory options', async () => {
const structure: FileSystemStructure = {
src: {
'index.ts': '',
},
};
testRootDir = await createTmpDir(structure);
const createSpy = vi.spyOn(FileSearchFactory, 'create');
const configWithWatcher = {
getFileFilteringOptions: vi.fn(() => ({
respectGitIgnore: true,
respectGeminiIgnore: true,
enableFileWatcher: true,
})),
getEnableRecursiveFileSearch: () => true,
getFileFilteringEnableFuzzySearch: () => true,
} as unknown as Config;
const { result } = await renderHook(() =>
useTestHarnessForAtCompletion(true, '', configWithWatcher, testRootDir),
);
await waitFor(() => {
expect(result.current.suggestions.length).toBeGreaterThan(0);
});
expect(createSpy).toHaveBeenCalled();
const firstCallArg = createSpy.mock.calls[0]?.[0];
expect(firstCallArg?.enableFileWatcher).toBe(true);
});
it('should reset and re-initialize when the cwd changes', async () => {
const structure1: FileSystemStructure = { 'file1.txt': '' };
const rootDir1 = await createTmpDir(structure1);
+31 -5
View File
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { useEffect, useReducer, useRef } from 'react';
import { useCallback, useEffect, useReducer, useRef } from 'react';
import { setTimeout as setTimeoutPromise } from 'node:timers/promises';
import * as path from 'node:path';
import {
@@ -224,15 +224,28 @@ export function useAtCompletion(props: UseAtCompletionProps): void {
setIsLoadingSuggestions(state.isLoading);
}, [state.isLoading, setIsLoadingSuggestions]);
const resetFileSearchState = () => {
const disposeFileSearchers = useCallback(async () => {
const searchers = [...fileSearchMap.current.values()];
fileSearchMap.current.clear();
initEpoch.current += 1;
const closePromises: Array<Promise<void>> = [];
for (const searcher of searchers) {
if (searcher.close) {
closePromises.push(searcher.close());
}
}
await Promise.all(closePromises);
}, []);
const resetFileSearchState = useCallback(() => {
void disposeFileSearchers();
dispatch({ type: 'RESET' });
};
}, [disposeFileSearchers]);
useEffect(() => {
resetFileSearchState();
}, [cwd, config]);
}, [cwd, config, resetFileSearchState]);
useEffect(() => {
const workspaceContext = config?.getWorkspaceContext?.();
@@ -242,7 +255,18 @@ export function useAtCompletion(props: UseAtCompletionProps): void {
workspaceContext.onDirectoriesChanged(resetFileSearchState);
return unsubscribe;
}, [config]);
}, [config, resetFileSearchState]);
useEffect(
() => () => {
void disposeFileSearchers();
searchAbortController.current?.abort();
if (slowSearchTimer.current) {
clearTimeout(slowSearchTimer.current);
}
},
[disposeFileSearchers],
);
// Reacts to user input (`pattern`) ONLY.
useEffect(() => {
@@ -295,6 +319,8 @@ export function useAtCompletion(props: UseAtCompletionProps): void {
),
cache: true,
cacheTtl: 30,
enableFileWatcher:
config?.getFileFilteringOptions()?.enableFileWatcher ?? false,
enableRecursiveFileSearch:
config?.getEnableRecursiveFileSearch() ?? true,
enableFuzzySearch:
@@ -16,7 +16,7 @@ import {
afterEach,
type Mock,
} from 'vitest';
import { NoopSandboxManager } from '@google/gemini-cli-core';
import { NoopSandboxManager, escapeShellArg } from '@google/gemini-cli-core';
const mockIsBinary = vi.hoisted(() => vi.fn());
const mockShellExecutionService = vi.hoisted(() => vi.fn());
@@ -76,7 +76,21 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
isBinary: mockIsBinary,
};
});
vi.mock('node:fs');
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
const mockFs = {
...actual,
existsSync: vi.fn(),
mkdtempSync: vi.fn(),
unlinkSync: vi.fn(),
readFileSync: vi.fn(),
rmSync: vi.fn(),
};
return {
...mockFs,
default: mockFs,
};
});
vi.mock('node:os', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:os')>();
const mocked = {
@@ -154,6 +168,7 @@ describe('useExecutionLifecycle', () => {
);
mockIsBinary.mockReturnValue(false);
vi.mocked(fs.existsSync).mockReturnValue(false);
vi.mocked(fs.mkdtempSync).mockReturnValue('/tmp/gemini-shell-abcdef');
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
@@ -239,8 +254,9 @@ describe('useExecutionLifecycle', () => {
}),
],
});
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
const wrappedCommand = `{ ls -l; }; __code=$?; pwd > "${tmpFile}"; exit $__code`;
const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
const escapedTmpFile = escapeShellArg(tmpFile, 'bash');
const wrappedCommand = `{\nls -l\n}\n__code=$?; pwd > ${escapedTmpFile}; exit $__code`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
'/test/dir',
@@ -349,11 +365,9 @@ describe('useExecutionLifecycle', () => {
);
});
// Verify it's using the non-pty shell
const wrappedCommand = `{ stream; }; __code=$?; pwd > "${path.join(
os.tmpdir(),
'shell_pwd_abcdef.tmp',
)}"; exit $__code`;
const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
const escapedTmpFile = escapeShellArg(tmpFile, 'bash');
const wrappedCommand = `{\nstream\n}\n__code=$?; pwd > ${escapedTmpFile}; exit $__code`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
'/test/dir',
@@ -644,7 +658,7 @@ describe('useExecutionLifecycle', () => {
type: 'error',
text: 'An unexpected error occurred: Synchronous spawn error',
});
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
// Verify that the temporary file was cleaned up
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
@@ -652,7 +666,7 @@ describe('useExecutionLifecycle', () => {
describe('Directory Change Warning', () => {
it('should show a warning if the working directory changes', async () => {
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue('/test/dir/new'); // A different directory
@@ -20,12 +20,12 @@ import {
ShellExecutionService,
ExecutionLifecycleService,
CoreToolCallStatus,
escapeShellArg,
} from '@google/gemini-cli-core';
import { type PartListUnion } from '@google/genai';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import { SHELL_COMMAND_NAME } from '../constants.js';
import { formatBytes } from '../utils/formatters.js';
import crypto from 'node:crypto';
import path from 'node:path';
import os from 'node:os';
import fs from 'node:fs';
@@ -362,18 +362,6 @@ export const useExecutionLifecycle = (
let commandToExecute = rawQuery;
let pwdFilePath: string | undefined;
// On non-windows, wrap the command to capture the final working directory.
if (!isWindows) {
let command = rawQuery.trim();
const pwdFileName = `shell_pwd_${crypto.randomBytes(6).toString('hex')}.tmp`;
pwdFilePath = path.join(os.tmpdir(), pwdFileName);
// Ensure command ends with a separator before adding our own.
if (!command.endsWith(';') && !command.endsWith('&')) {
command += ';';
}
commandToExecute = `{ ${command} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
}
const executeCommand = async () => {
let cumulativeStdout: string | AnsiOutput = '';
let isBinaryStream = false;
@@ -403,9 +391,23 @@ export const useExecutionLifecycle = (
};
abortSignal.addEventListener('abort', abortHandler, { once: true });
onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
try {
// On non-windows, wrap the command to capture the final working directory.
if (!isWindows) {
let command = rawQuery.trim();
if (command.endsWith('\\')) {
command += ' ';
}
const tmpDir = fs.mkdtempSync(
path.join(os.tmpdir(), 'gemini-shell-'),
);
pwdFilePath = path.join(tmpDir, 'pwd.tmp');
const escapedPwdFilePath = escapeShellArg(pwdFilePath, 'bash');
commandToExecute = `{\n${command}\n}\n__code=$?; pwd > ${escapedPwdFilePath}; exit $__code`;
}
onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
const activeTheme = themeManager.getActiveTheme();
const shellExecutionConfig = {
...config.getShellExecutionConfig(),
@@ -630,8 +632,18 @@ export const useExecutionLifecycle = (
);
} finally {
abortSignal.removeEventListener('abort', abortHandler);
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
fs.unlinkSync(pwdFilePath);
if (pwdFilePath) {
const tmpDir = path.dirname(pwdFilePath);
try {
if (fs.existsSync(pwdFilePath)) {
fs.unlinkSync(pwdFilePath);
}
if (fs.existsSync(tmpDir)) {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
} catch {
// Ignore cleanup errors
}
}
dispatch({ type: 'SET_ACTIVE_PTY', pid: null });
+21
View File
@@ -0,0 +1,21 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
debugLogger,
startMemoryService,
type Config,
} from '@google/gemini-cli-core';
export function startAutoMemoryIfEnabled(config: Config): void {
if (!config.isAutoMemoryEnabled()) {
return;
}
startMemoryService(config).catch((e) => {
debugLogger.error('Failed to start memory service:', e);
});
}
+1
View File
@@ -56,6 +56,7 @@
"ajv": "^8.17.1",
"ajv-formats": "^3.0.0",
"chardet": "^2.1.0",
"chokidar": "^5.0.0",
"diff": "^8.0.3",
"dotenv": "^17.2.4",
"dotenv-expand": "^12.0.3",
+47
View File
@@ -538,5 +538,52 @@ describe('a2aUtils', () => {
expect(output).toContain('Artifact (Data):');
expect(output).not.toContain('Answer from history');
});
it('should return message log as activity items', () => {
const reassembler = new A2AResultReassembler();
reassembler.update({
kind: 'status-update',
taskId: 't1',
contextId: 'ctx1',
status: {
state: 'working',
message: {
kind: 'message',
role: 'agent',
parts: [{ kind: 'text', text: 'Message 1' }],
} as Message,
},
} as unknown as SendMessageResult);
reassembler.update({
kind: 'status-update',
taskId: 't1',
contextId: 'ctx1',
status: {
state: 'working',
message: {
kind: 'message',
role: 'agent',
parts: [{ kind: 'text', text: 'Message 2' }],
} as Message,
},
} as unknown as SendMessageResult);
const items = reassembler.toActivityItems();
expect(items).toHaveLength(2);
expect(items[0]).toEqual({
id: 'msg-0',
type: 'thought',
content: 'Message 1',
status: 'completed',
});
expect(items[1]).toEqual({
id: 'msg-1',
type: 'thought',
content: 'Message 2',
status: 'completed',
});
});
});
});
+31 -15
View File
@@ -124,6 +124,7 @@ export class A2AResultReassembler {
private pushMessage(message: Message | undefined) {
if (!message) return;
if (message.role === 'user') return; // Skip user messages reflected by server
const text = extractPartsText(message.parts, '');
if (text && this.messageLog[this.messageLog.length - 1] !== text) {
this.messageLog.push(text);
@@ -135,21 +136,36 @@ export class A2AResultReassembler {
*/
toActivityItems(): SubagentActivityItem[] {
const isAuthRequired = this.messageLog.includes(AUTH_REQUIRED_MSG);
return [
isAuthRequired
? {
id: 'auth-required',
type: 'thought',
content: AUTH_REQUIRED_MSG,
status: 'running',
}
: {
id: 'pending',
type: 'thought',
content: 'Working...',
status: 'running',
},
];
const items: SubagentActivityItem[] = [];
if (isAuthRequired) {
items.push({
id: 'auth-required',
type: 'thought',
content: AUTH_REQUIRED_MSG,
status: 'running',
});
}
this.messageLog.forEach((msg, index) => {
items.push({
id: `msg-${index}`,
type: 'thought',
content: msg.trim(),
status: 'completed',
});
});
if (items.length === 0 && !isAuthRequired) {
items.push({
id: 'pending',
type: 'thought',
content: 'Working...',
status: 'running',
});
}
return items;
}
/**
+1
View File
@@ -194,6 +194,7 @@ class DelegateInvocation extends BaseToolInvocation<
{
operation: GeminiCliOperation.AgentCall,
logPrompts: this.context.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.context.config.getTelemetryTracesEnabled(),
sessionId: this.context.config.getSessionId(),
attributes: {
[GEN_AI_AGENT_NAME]: this.definition.name,
@@ -95,8 +95,8 @@ Test System Prompt`;
});
// Trigger the refresh action that follows reloading
// @ts-expect-error accessing private method for testing
await config.onAgentsRefreshed();
await config.getAgentRegistry().reload();
// 4. Verify the agent is UNREGISTERED
const finalAgents = agentRegistry.getAllDefinitions().map((d) => d.name);
@@ -237,8 +237,8 @@ Test System Prompt`;
});
// Trigger the refresh action that follows reloading
// @ts-expect-error accessing private method for testing
await config.onAgentsRefreshed();
await config.getAgentRegistry().reload();
expect(agentRegistry.getAllDefinitions().map((d) => d.name)).toContain(
agentName,
+25
View File
@@ -836,12 +836,37 @@ describe('Server Config (config.ts)', () => {
undefined,
undefined,
undefined,
undefined,
);
// Verify that contentGeneratorConfig is updated
expect(config.getContentGeneratorConfig()).toEqual(mockContentConfig);
expect(GeminiClient).toHaveBeenCalledWith(config);
});
it('should pass Vertex AI routing settings when refreshing auth', async () => {
const vertexAiRouting = {
requestType: 'shared' as const,
sharedRequestType: 'priority' as const,
};
const config = new Config({
...baseParams,
vertexAiRouting,
});
vi.mocked(createContentGeneratorConfig).mockResolvedValue({});
await config.refreshAuth(AuthType.USE_VERTEX_AI);
expect(createContentGeneratorConfig).toHaveBeenCalledWith(
config,
AuthType.USE_VERTEX_AI,
undefined,
undefined,
undefined,
vertexAiRouting,
);
});
it('should reset model availability status', async () => {
const config = new Config(baseParams);
const service = config.getModelAvailabilityService();
+18 -2
View File
@@ -23,6 +23,7 @@ import {
createContentGeneratorConfig,
type ContentGenerator,
type ContentGeneratorConfig,
type VertexAiRoutingConfig,
} from '../core/contentGenerator.js';
import type { OverageStrategy } from '../billing/billing.js';
import { PromptRegistry } from '../prompts/prompt-registry.js';
@@ -204,6 +205,7 @@ export interface PlanSettings {
export interface TelemetrySettings {
enabled?: boolean;
traces?: boolean;
target?: TelemetryTarget;
otlpEndpoint?: string;
otlpProtocol?: 'grpc' | 'http';
@@ -614,6 +616,7 @@ export interface ConfigParameters {
fileFiltering?: {
respectGitIgnore?: boolean;
respectGeminiIgnore?: boolean;
enableFileWatcher?: boolean;
enableRecursiveFileSearch?: boolean;
enableFuzzySearch?: boolean;
maxFileCount?: number;
@@ -731,6 +734,7 @@ export interface ConfigParameters {
billing?: {
overageStrategy?: OverageStrategy;
};
vertexAiRouting?: VertexAiRoutingConfig;
}
export class Config implements McpContext, AgentLoopContext {
@@ -796,6 +800,7 @@ export class Config implements McpContext, AgentLoopContext {
private readonly fileFiltering: {
respectGitIgnore: boolean;
respectGeminiIgnore: boolean;
enableFileWatcher: boolean;
enableRecursiveFileSearch: boolean;
enableFuzzySearch: boolean;
maxFileCount: number;
@@ -936,6 +941,7 @@ export class Config implements McpContext, AgentLoopContext {
private readonly billing: {
overageStrategy: OverageStrategy;
};
private readonly vertexAiRouting: VertexAiRoutingConfig | undefined;
private readonly enableAgents: boolean;
private agents: AgentSettings;
@@ -1058,6 +1064,7 @@ export class Config implements McpContext, AgentLoopContext {
this.accessibility = params.accessibility ?? {};
this.telemetrySettings = {
enabled: params.telemetry?.enabled ?? false,
traces: params.telemetry?.traces ?? false,
target: params.telemetry?.target ?? DEFAULT_TELEMETRY_TARGET,
otlpEndpoint: params.telemetry?.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT,
otlpProtocol: params.telemetry?.otlpProtocol,
@@ -1075,6 +1082,10 @@ export class Config implements McpContext, AgentLoopContext {
respectGeminiIgnore:
params.fileFiltering?.respectGeminiIgnore ??
DEFAULT_FILE_FILTERING_OPTIONS.respectGeminiIgnore,
enableFileWatcher:
params.fileFiltering?.enableFileWatcher ??
DEFAULT_FILE_FILTERING_OPTIONS.enableFileWatcher ??
true,
enableRecursiveFileSearch:
params.fileFiltering?.enableRecursiveFileSearch ?? true,
enableFuzzySearch: params.fileFiltering?.enableFuzzySearch ?? true,
@@ -1362,6 +1373,7 @@ export class Config implements McpContext, AgentLoopContext {
this.billing = {
overageStrategy: params.billing?.overageStrategy ?? 'ask',
};
this.vertexAiRouting = params.vertexAiRouting;
if (params.contextFileName) {
setGeminiMdFilename(params.contextFileName);
@@ -1549,6 +1561,7 @@ export class Config implements McpContext, AgentLoopContext {
apiKey,
baseUrl,
customHeaders,
this.vertexAiRouting,
);
this.contentGenerator = await createContentGenerator(
newContentGeneratorConfig,
@@ -2727,6 +2740,10 @@ export class Config implements McpContext, AgentLoopContext {
return this.telemetrySettings.enabled ?? false;
}
getTelemetryTracesEnabled(): boolean {
return this.telemetrySettings.traces ?? false;
}
getTelemetryLogPromptsEnabled(): boolean {
return this.telemetrySettings.logPrompts ?? true;
}
@@ -2820,6 +2837,7 @@ export class Config implements McpContext, AgentLoopContext {
return {
respectGitIgnore: this.fileFiltering.respectGitIgnore,
respectGeminiIgnore: this.fileFiltering.respectGeminiIgnore,
enableFileWatcher: this.fileFiltering.enableFileWatcher,
maxFileCount: this.fileFiltering.maxFileCount,
searchTimeout: this.fileFiltering.searchTimeout,
customIgnoreFilePaths: this.fileFiltering.customIgnoreFilePaths,
@@ -3811,8 +3829,6 @@ export class Config implements McpContext, AgentLoopContext {
}
private onAgentsRefreshed = async () => {
await this.agentRegistry.initialize();
// Propagate updates to the active chat session
const client = this.geminiClient;
if (client?.isInitialized()) {
+3
View File
@@ -7,6 +7,7 @@
export interface FileFilteringOptions {
respectGitIgnore: boolean;
respectGeminiIgnore: boolean;
enableFileWatcher?: boolean;
maxFileCount?: number;
searchTimeout?: number;
customIgnoreFilePaths: string[];
@@ -16,6 +17,7 @@ export interface FileFilteringOptions {
export const DEFAULT_MEMORY_FILE_FILTERING_OPTIONS: FileFilteringOptions = {
respectGitIgnore: false,
respectGeminiIgnore: true,
enableFileWatcher: false,
maxFileCount: 20000,
searchTimeout: 5000,
customIgnoreFilePaths: [],
@@ -25,6 +27,7 @@ export const DEFAULT_MEMORY_FILE_FILTERING_OPTIONS: FileFilteringOptions = {
export const DEFAULT_FILE_FILTERING_OPTIONS: FileFilteringOptions = {
respectGitIgnore: true,
respectGeminiIgnore: true,
enableFileWatcher: false,
maxFileCount: 20000,
searchTimeout: 5000,
customIgnoreFilePaths: [],
@@ -95,7 +95,7 @@ For example:
# Active Approval Mode: Plan
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`/tmp/plans/\` and get user approval before editing source code.
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`../plans/\` and get user approval before editing source code.
## Available Tools
The following tools are available in Plan Mode:
@@ -111,8 +111,8 @@ The following tools are available in Plan Mode:
</available_tools>
## Rules
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`/tmp/plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`/tmp/plans/\`. They cannot modify source code.
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`../plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`../plans/\`. They cannot modify source code.
3. **Efficiency:** Autonomously combine discovery and drafting phases to minimize conversational turns. If the request is ambiguous, use \`ask_user\` to clarify. Use multi-select to offer flexibility and include detailed descriptions for each option to help the user understand the implications of their choice.
4. **Inquiries and Directives:** Distinguish between Inquiries and Directives to minimize unnecessary planning.
- **Inquiries:** If the request is an **Inquiry** (e.g., "How does X work?"), answer directly. DO NOT create a plan.
@@ -136,7 +136,7 @@ The depth of your consultation should be proportional to the task's complexity.
**CRITICAL:** You MUST NOT proceed to Step 3 (Draft) or Step 4 (Review & Approval) in the same turn as your initial strategy proposal. You MUST wait for user feedback and reach a clear agreement before drafting or submitting the plan.
### 3. Draft
Write the implementation plan to \`/tmp/plans/\`. The plan's structure adapts to the task:
Write the implementation plan to \`../plans/\`. The plan's structure adapts to the task:
- **Simple Tasks:** Include a bulleted list of specific **Changes** and **Verification** steps.
- **Standard Tasks:** Include an **Objective**, **Key Files & Context**, **Implementation Steps**, and **Verification & Testing**.
- **Complex Tasks:** Include **Background & Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives Considered**, a phased **Implementation Plan**, **Verification**, and **Migration & Rollback** strategies.
@@ -275,7 +275,7 @@ For example:
# Active Approval Mode: Plan
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`/tmp/plans/\` and get user approval before editing source code.
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`../plans/\` and get user approval before editing source code.
## Available Tools
The following tools are available in Plan Mode:
@@ -291,8 +291,8 @@ The following tools are available in Plan Mode:
</available_tools>
## Rules
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`/tmp/plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`/tmp/plans/\`. They cannot modify source code.
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`../plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`../plans/\`. They cannot modify source code.
3. **Efficiency:** Autonomously combine discovery and drafting phases to minimize conversational turns. If the request is ambiguous, use \`ask_user\` to clarify. Use multi-select to offer flexibility and include detailed descriptions for each option to help the user understand the implications of their choice.
4. **Inquiries and Directives:** Distinguish between Inquiries and Directives to minimize unnecessary planning.
- **Inquiries:** If the request is an **Inquiry** (e.g., "How does X work?"), answer directly. DO NOT create a plan.
@@ -316,7 +316,7 @@ The depth of your consultation should be proportional to the task's complexity.
**CRITICAL:** You MUST NOT proceed to Step 3 (Draft) or Step 4 (Review & Approval) in the same turn as your initial strategy proposal. You MUST wait for user feedback and reach a clear agreement before drafting or submitting the plan.
### 3. Draft
Write the implementation plan to \`/tmp/plans/\`. The plan's structure adapts to the task:
Write the implementation plan to \`../plans/\`. The plan's structure adapts to the task:
- **Simple Tasks:** Include a bulleted list of specific **Changes** and **Verification** steps.
- **Standard Tasks:** Include an **Objective**, **Key Files & Context**, **Implementation Steps**, and **Verification & Testing**.
- **Complex Tasks:** Include **Background & Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives Considered**, a phased **Implementation Plan**, **Verification**, and **Migration & Rollback** strategies.
@@ -326,7 +326,7 @@ Write the implementation plan to \`/tmp/plans/\`. The plan's structure adapts to
ONLY use the \`exit_plan_mode\` tool to present the plan for formal approval AFTER you have reached an informal agreement with the user in the chat regarding the proposed strategy. When called, this tool will present the plan and formally request approval.
## Approved Plan
An approved plan is available for this task at \`/tmp/plans/feature-x.md\`.
An approved plan is available for this task at \`../plans/feature-x.md\`.
- **Read First:** You MUST read this file using the \`read_file\` tool before proposing any changes or starting discovery.
- **Iterate:** Default to refining the existing approved plan.
- **New Plan:** Only create a new plan file if the user explicitly asks for a "new plan".
@@ -576,7 +576,7 @@ For example:
# Active Approval Mode: Plan
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`/tmp/project-temp/plans/\` and get user approval before editing source code.
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`plans/\` and get user approval before editing source code.
## Available Tools
The following tools are available in Plan Mode:
@@ -592,8 +592,8 @@ The following tools are available in Plan Mode:
</available_tools>
## Rules
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`/tmp/project-temp/plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`/tmp/project-temp/plans/\`. They cannot modify source code.
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`plans/\`. They cannot modify source code.
3. **Efficiency:** Autonomously combine discovery and drafting phases to minimize conversational turns. If the request is ambiguous, use \`ask_user\` to clarify. Use multi-select to offer flexibility and include detailed descriptions for each option to help the user understand the implications of their choice.
4. **Inquiries and Directives:** Distinguish between Inquiries and Directives to minimize unnecessary planning.
- **Inquiries:** If the request is an **Inquiry** (e.g., "How does X work?"), answer directly. DO NOT create a plan.
@@ -617,7 +617,7 @@ The depth of your consultation should be proportional to the task's complexity.
**CRITICAL:** You MUST NOT proceed to Step 3 (Draft) or Step 4 (Review & Approval) in the same turn as your initial strategy proposal. You MUST wait for user feedback and reach a clear agreement before drafting or submitting the plan.
### 3. Draft
Write the implementation plan to \`/tmp/project-temp/plans/\`. The plan's structure adapts to the task:
Write the implementation plan to \`plans/\`. The plan's structure adapts to the task:
- **Simple Tasks:** Include a bulleted list of specific **Changes** and **Verification** steps.
- **Standard Tasks:** Include an **Objective**, **Key Files & Context**, **Implementation Steps**, and **Verification & Testing**.
- **Complex Tasks:** Include **Background & Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives Considered**, a phased **Implementation Plan**, **Verification**, and **Migration & Rollback** strategies.
@@ -385,6 +385,44 @@ describe('createContentGenerator', () => {
);
});
it('should include Vertex AI routing headers for Vertex AI requests', async () => {
const mockConfig = {
getModel: vi.fn().mockReturnValue('gemini-pro'),
getProxy: vi.fn().mockReturnValue(undefined),
getUsageStatisticsEnabled: () => false,
getClientName: vi.fn().mockReturnValue(undefined),
} as unknown as Config;
const mockGenerator = {
models: {},
} as unknown as GoogleGenAI;
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator as never);
await createContentGenerator(
{
apiKey: 'test-api-key',
vertexai: true,
authType: AuthType.USE_VERTEX_AI,
vertexAiRouting: {
requestType: 'shared',
sharedRequestType: 'priority',
},
},
mockConfig,
);
expect(GoogleGenAI).toHaveBeenCalledWith(
expect.objectContaining({
httpOptions: expect.objectContaining({
headers: expect.objectContaining({
'X-Vertex-AI-LLM-Request-Type': 'shared',
'X-Vertex-AI-LLM-Shared-Request-Type': 'priority',
}),
}),
}),
);
});
it('should pass api key as Authorization Header when GEMINI_API_KEY_AUTH_MECHANISM is set to bearer', async () => {
const mockConfig = {
getModel: vi.fn().mockReturnValue('gemini-pro'),
@@ -887,6 +925,25 @@ describe('createContentGeneratorConfig', () => {
expect(config.vertexai).toBe(true);
});
it('should include Vertex AI routing settings in content generator config', async () => {
vi.stubEnv('GOOGLE_API_KEY', 'env-google-key');
const vertexAiRouting = {
requestType: 'shared' as const,
sharedRequestType: 'priority' as const,
};
const config = await createContentGeneratorConfig(
mockConfig,
AuthType.USE_VERTEX_AI,
undefined,
undefined,
undefined,
vertexAiRouting,
);
expect(config.vertexAiRouting).toEqual(vertexAiRouting);
});
it('should configure for Vertex AI using GCP project and location when set', async () => {
vi.stubEnv('GOOGLE_API_KEY', undefined);
vi.stubEnv('GOOGLE_CLOUD_PROJECT', 'env-gcp-project');
@@ -99,9 +99,21 @@ export type ContentGeneratorConfig = {
proxy?: string;
baseUrl?: string;
customHeaders?: Record<string, string>;
vertexAiRouting?: VertexAiRoutingConfig;
};
export type VertexAiRequestType = 'dedicated' | 'shared';
export type VertexAiSharedRequestType = 'priority' | 'flex';
export interface VertexAiRoutingConfig {
requestType?: VertexAiRequestType;
sharedRequestType?: VertexAiSharedRequestType;
}
const LOCAL_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
const VERTEX_AI_REQUEST_TYPE_HEADER = 'X-Vertex-AI-LLM-Request-Type';
const VERTEX_AI_SHARED_REQUEST_TYPE_HEADER =
'X-Vertex-AI-LLM-Shared-Request-Type';
function validateBaseUrl(baseUrl: string): void {
let url: URL;
@@ -122,6 +134,7 @@ export async function createContentGeneratorConfig(
apiKey?: string,
baseUrl?: string,
customHeaders?: Record<string, string>,
vertexAiRouting?: VertexAiRoutingConfig,
): Promise<ContentGeneratorConfig> {
const geminiApiKey =
apiKey ||
@@ -140,6 +153,7 @@ export async function createContentGeneratorConfig(
proxy: config?.getProxy(),
baseUrl,
customHeaders,
vertexAiRouting,
};
// If we are using Google auth or we are in Cloud Shell, there is nothing else to validate for now
@@ -280,6 +294,21 @@ export async function createContentGenerator(
if (config.customHeaders) {
headers = { ...headers, ...config.customHeaders };
}
if (
config.authType === AuthType.USE_VERTEX_AI &&
config.vertexAiRouting
) {
const { requestType, sharedRequestType } = config.vertexAiRouting;
headers = {
...headers,
...(requestType
? { [VERTEX_AI_REQUEST_TYPE_HEADER]: requestType }
: {}),
...(sharedRequestType
? { [VERTEX_AI_SHARED_REQUEST_TYPE_HEADER]: sharedRequestType }
: {}),
};
}
if (gcConfig?.getUsageStatisticsEnabled()) {
const installationManager = new InstallationManager();
const installationId = installationManager.getInstallationId();
@@ -153,6 +153,7 @@ describe('GeminiChat', () => {
promptId: 'test-session-id',
getSessionId: () => 'test-session-id',
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
getUsageStatisticsEnabled: () => true,
getDebugMode: () => false,
getContentGeneratorConfig: vi.fn().mockImplementation(() => ({
@@ -96,6 +96,7 @@ describe('GeminiChat Network Retries', () => {
promptId: 'test-session-id',
getSessionId: () => 'test-session-id',
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
getUsageStatisticsEnabled: () => true,
getDebugMode: () => false,
getContentGeneratorConfig: vi.fn().mockReturnValue({
@@ -73,6 +73,7 @@ describe('LoggingContentGenerator', () => {
authType: 'API_KEY',
}),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(true),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
refreshUserQuotaIfStale: vi.fn().mockResolvedValue(undefined),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Config;
@@ -361,6 +361,7 @@ export class LoggingContentGenerator implements ContentGenerator {
{
operation: GeminiCliOperation.LLMCall,
logPrompts: this.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.config.getTelemetryTracesEnabled(),
sessionId: this.config.getSessionId(),
attributes: {
[GEN_AI_REQUEST_MODEL]: req.model,
@@ -452,6 +453,7 @@ export class LoggingContentGenerator implements ContentGenerator {
{
operation: GeminiCliOperation.LLMCall,
logPrompts: this.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.config.getTelemetryTracesEnabled(),
sessionId: this.config.getSessionId(),
attributes: {
[GEN_AI_REQUEST_MODEL]: req.model,
@@ -607,6 +609,7 @@ export class LoggingContentGenerator implements ContentGenerator {
{
operation: GeminiCliOperation.LLMCall,
logPrompts: this.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.config.getTelemetryTracesEnabled(),
sessionId: this.config.getSessionId(),
attributes: {
[GEN_AI_REQUEST_MODEL]: req.model,
+1
View File
@@ -93,6 +93,7 @@ describe('Core System Prompt (prompts.ts)', () => {
getToolRegistry: vi.fn().mockReturnValue(mockRegistry),
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
getSandboxEnabled: vi.fn().mockReturnValue(false),
getProjectRoot: vi.fn().mockReturnValue('/tmp/project-temp'),
storage: {
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
@@ -7,6 +7,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { PromptProvider } from './promptProvider.js';
import type { Config } from '../config/config.js';
import { makeRelative } from '../utils/paths.js';
import {
getAllGeminiMdFilenames,
DEFAULT_CONTEXT_FILENAME,
@@ -58,6 +59,7 @@ describe('PromptProvider', () => {
).getToolRegistry?.() as unknown as ToolRegistry;
},
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
getProjectRoot: vi.fn().mockReturnValue('/tmp/project-temp'),
topicState: new TopicState(),
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
getSandboxEnabled: vi.fn().mockReturnValue(false),
@@ -236,7 +238,14 @@ describe('PromptProvider', () => {
expect(prompt).toContain(
'`write_file` and `replace` may ONLY be used to write .md plan files',
);
expect(prompt).toContain('/tmp/project-temp/plans/');
const expectedRelativePath = makeRelative(
mockConfig.storage.getPlansDir(),
mockConfig.getProjectRoot(),
).replaceAll('\\', '/');
expect(prompt).toContain(
`write .md plan files to \`${expectedRelativePath}/\``,
);
});
});
+14 -3
View File
@@ -8,7 +8,7 @@ import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import type { HierarchicalMemory } from '../config/memory.js';
import { GEMINI_DIR } from '../utils/paths.js';
import { GEMINI_DIR, makeRelative } from '../utils/paths.js';
import { ApprovalMode } from '../policy/types.js';
import * as snippets from './snippets.js';
import * as legacySnippets from './snippets.legacy.js';
@@ -199,8 +199,19 @@ export class PromptProvider {
() => ({
interactive: interactiveMode,
planModeToolsList,
plansDir: context.config.storage.getPlansDir(),
approvedPlanPath: context.config.getApprovedPlanPath(),
plansDir: makeRelative(
context.config.storage.getPlansDir(),
context.config.getProjectRoot(),
).replaceAll('\\', '/'),
approvedPlanPath: (() => {
const approvedPath = context.config.getApprovedPlanPath();
return approvedPath
? makeRelative(
approvedPath,
context.config.getProjectRoot(),
).replaceAll('\\', '/')
: undefined;
})(),
}),
isPlanMode,
),
+4 -2
View File
@@ -170,7 +170,9 @@ ${renderUserMemory(userMemory, contextFilenames)}
export function renderPreamble(options?: PreambleOptions): string {
if (!options) return '';
return 'You are Gemini CLI, a software engineering assistant focused on safety and efficiency.';
return options.interactive
? 'You are Gemini CLI, an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and effectively.'
: 'You are Gemini CLI, an autonomous CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and effectively.';
}
export function renderCoreMandates(options?: CoreMandatesOptions): string {
@@ -192,7 +194,7 @@ export function renderCoreMandates(options?: CoreMandatesOptions): string {
# Core Mandates
## Security & System Integrity
- **Credential Protection:** Never log, print, or commit secrets, API keys, or credentials. Rigorously protect \`.env\` files, \`.git\`, and system configuration folders.
- **Credential Protection:** Never log, print, or commit secrets, API keys, or sensitive credentials. Rigorously protect \`.env\` files, \`.git\`, and system configuration folders.
- **Source Control:** Do not stage or commit changes unless specifically requested by the user.
## Context Efficiency:
+50 -2
View File
@@ -239,7 +239,7 @@ describe('policy.ts', () => {
});
describe('updatePolicy', () => {
it('should set AUTO_EDIT mode for auto-edit transition tools', async () => {
it('should set AUTO_EDIT mode for auto-edit transition tools and publish policy update', async () => {
const mockConfig = {
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
setApprovalMode: vi.fn(),
@@ -266,7 +266,54 @@ describe('policy.ts', () => {
expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
ApprovalMode.AUTO_EDIT,
);
expect(mockMessageBus.publish).not.toHaveBeenCalled();
expect(mockMessageBus.publish).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageBusType.UPDATE_POLICY,
toolName: 'replace',
persist: false,
}),
);
});
it('should preserve the original mode set when a session allow triggers AUTO_EDIT', async () => {
let currentMode = ApprovalMode.DEFAULT;
const mockConfig = {
getApprovalMode: vi.fn(() => currentMode),
setApprovalMode: vi.fn((mode: ApprovalMode) => {
currentMode = mode;
}),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Mocked<Config>;
(mockConfig as unknown as { config: Config }).config =
mockConfig as Config;
const mockMessageBus = {
publish: vi.fn(),
} as unknown as Mocked<MessageBus>;
const tool = { name: 'replace' } as AnyDeclarativeTool;
await updatePolicy(
tool,
ToolConfirmationOutcome.ProceedAlways,
undefined,
mockConfig,
mockMessageBus,
);
expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
ApprovalMode.AUTO_EDIT,
);
expect(mockMessageBus.publish).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageBusType.UPDATE_POLICY,
toolName: 'replace',
persist: false,
modes: [
ApprovalMode.DEFAULT,
ApprovalMode.AUTO_EDIT,
ApprovalMode.YOLO,
],
}),
);
});
it('should handle standard policy updates (persist=false)', async () => {
@@ -858,6 +905,7 @@ describe('Plan Mode Denial Consistency', () => {
getEnableHooks: vi.fn().mockReturnValue(false),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.PLAN), // Key: Plan Mode
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
setApprovalMode: vi.fn(),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
getUsageStatisticsEnabled: vi.fn().mockReturnValue(false),
+2 -2
View File
@@ -119,16 +119,16 @@ export async function updatePolicy(
messageBus: MessageBus,
toolInvocation?: AnyToolInvocation,
): Promise<void> {
const currentMode = context.config.getApprovalMode();
// Mode Transitions (AUTO_EDIT)
if (isAutoEditTransition(tool, outcome)) {
context.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
return;
}
// Determine persist scope if we are persisting.
let persistScope: 'workspace' | 'user' | undefined;
let modes: ApprovalMode[] | undefined;
const currentMode = context.config.getApprovalMode();
// If this is an 'Always Allow' selection, we restrict it to the current mode
// and more permissive modes.
@@ -178,6 +178,7 @@ describe('Scheduler (Orchestrator)', () => {
setApprovalMode: vi.fn(),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Mocked<Config>;
@@ -1517,6 +1518,7 @@ describe('Scheduler MCP Progress', () => {
setApprovalMode: vi.fn(),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Mocked<Config>;
+1
View File
@@ -196,6 +196,7 @@ export class Scheduler {
{
operation: GeminiCliOperation.ScheduleToolCalls,
logPrompts: this.context.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.context.config.getTelemetryTracesEnabled(),
sessionId: this.context.config.getSessionId(),
},
async ({ metadata: spanMetadata }) => {
@@ -71,6 +71,7 @@ function createMockConfig(overrides: Partial<Config> = {}): Config {
getEnableHooks: () => true,
getExperiments: () => {},
getTelemetryLogPromptsEnabled: () => false,
getTelemetryTracesEnabled: () => false,
getPolicyEngine: () =>
({
check: async () => ({ decision: 'allow' }),
@@ -218,6 +218,7 @@ describe('Scheduler Parallel Execution', () => {
setApprovalMode: vi.fn(),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Mocked<Config>;
@@ -84,6 +84,7 @@ export class ToolExecutor {
{
operation: GeminiCliOperation.ToolCall,
logPrompts: this.config.getTelemetryLogPromptsEnabled(),
tracesEnabled: this.config.getTelemetryTracesEnabled(),
sessionId: this.config.getSessionId(),
attributes: {
[GEN_AI_TOOL_NAME]: toolName,
@@ -531,12 +531,18 @@ export class ShellExecutionService {
cwd: finalCwd,
} = prepared;
// Bun's child_process does not properly call setsid() for detached
// processes, leaving children in the parent's session without a
// controlling terminal. They receive SIGHUP immediately. Disable
// detached mode in Bun; killProcessGroup already falls back to
// direct-pid kill when the group kill fails.
const isBun = 'bun' in process.versions;
const child = cpSpawn(finalExecutable, finalArgs, {
cwd: finalCwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsVerbatimArguments: isWindows ? false : undefined,
shell: false,
detached: !isWindows,
detached: !isWindows && !isBun,
env: finalEnv,
});
+5
View File
@@ -60,6 +60,10 @@ export async function resolveTelemetrySettings(options: {
parseBooleanEnvFlag(env['GEMINI_TELEMETRY_ENABLED']) ??
settings.enabled;
const traces =
parseBooleanEnvFlag(env['GEMINI_TELEMETRY_TRACES_ENABLED']) ??
settings.traces;
const rawTarget =
argv.telemetryTarget ??
env['GEMINI_TELEMETRY_TARGET'] ??
@@ -110,6 +114,7 @@ export async function resolveTelemetrySettings(options: {
return {
enabled,
traces,
target,
otlpEndpoint,
otlpProtocol,
@@ -37,6 +37,7 @@ describe('conseca-logger', () => {
getTelemetryEnabled: vi.fn().mockReturnValue(true),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(true),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
isInteractive: vi.fn().mockReturnValue(true),
getExperiments: vi.fn().mockReturnValue({ experimentIds: [] }),
getContentGeneratorConfig: vi.fn().mockReturnValue({ authType: 'oauth' }),
+115 -5
View File
@@ -216,6 +216,7 @@ describe('loggers', () => {
getTelemetryEnabled: () => true,
getUsageStatisticsEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
getFileFilteringRespectGitIgnore: () => true,
getFileFilteringAllowBuildArtifacts: () => false,
getDebugMode: () => true,
@@ -313,6 +314,7 @@ describe('loggers', () => {
getSessionId: () => 'test-session-id',
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
getUsageStatisticsEnabled: () => true,
isInteractive: () => false,
getExperiments: () => undefined,
@@ -352,6 +354,7 @@ describe('loggers', () => {
getSessionId: () => 'test-session-id',
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => false,
getTelemetryTracesEnabled: () => false,
getTargetDir: () => 'target-dir',
getUsageStatisticsEnabled: () => true,
isInteractive: () => false,
@@ -392,6 +395,7 @@ describe('loggers', () => {
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => true,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -493,10 +497,10 @@ describe('loggers', () => {
'gen_ai.output.messages':
'[{"finish_reason":"stop","role":"system","parts":[{"type":"text","content":"candidate 1"}]}]',
'gen_ai.response.finish_reasons': ['stop'],
'gen_ai.operation.name': 'generate_content',
'gen_ai.response.model': 'test-model',
'gen_ai.usage.input_tokens': 17,
'gen_ai.usage.output_tokens': 50,
'gen_ai.operation.name': 'generate_content',
'gen_ai.output.type': 'text',
'gen_ai.request.choice.count': 1,
'gen_ai.request.seed': 678,
@@ -564,6 +568,57 @@ describe('loggers', () => {
});
});
it('should not log input and output messages when traces are disabled', () => {
const mockConfigNoTraces = {
getSessionId: () => 'test-session-id',
getTargetDir: () => 'target-dir',
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false, // Disabled
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
getContentGeneratorConfig: () => undefined,
} as unknown as Config;
const event = new ApiResponseEvent(
'test-model',
100,
{ prompt_id: 'prompt-id-1', contents: [] },
{ candidates: [] },
AuthType.LOGIN_WITH_GOOGLE,
undefined,
'test-response',
);
logApiResponse(mockConfigNoTraces, event);
expect(mockLogger.emit).toHaveBeenCalledWith(
expect.objectContaining({
body: 'GenAI operation details from test-model. Status: 200. Duration: 100ms.',
attributes: expect.objectContaining({
'event.name': 'gen_ai.client.inference.operation.details',
'gen_ai.operation.name': 'generate_content',
}),
}),
);
const emitCalls = mockLogger.emit.mock.calls;
const detailsCall = emitCalls.find(
(call) =>
call[0].attributes &&
call[0].attributes['event.name'] ===
'gen_ai.client.inference.operation.details',
);
expect(
detailsCall![0].attributes['gen_ai.input.messages'],
).toBeUndefined();
expect(
detailsCall![0].attributes['gen_ai.output.messages'],
).toBeUndefined();
});
it('should log an API response with a role', () => {
const event = new ApiResponseEvent(
'test-model',
@@ -596,6 +651,7 @@ describe('loggers', () => {
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => true,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -674,8 +730,6 @@ describe('loggers', () => {
'gen_ai.request.temperature': 1,
'gen_ai.request.top_p': 2,
'gen_ai.request.top_k': 3,
'gen_ai.input.messages':
'[{"role":"user","parts":[{"type":"text","content":"Hello"}]}]',
'gen_ai.operation.name': 'generate_content',
'gen_ai.output.type': 'text',
'gen_ai.request.choice.count': 1,
@@ -683,6 +737,8 @@ describe('loggers', () => {
'gen_ai.request.frequency_penalty': 10,
'gen_ai.request.presence_penalty': 6,
'gen_ai.request.max_tokens': 8000,
'gen_ai.input.messages':
'[{"role":"user","parts":[{"type":"text","content":"Hello"}]}]',
'server.address': 'foo.com',
'server.port': 8080,
'gen_ai.request.stop_sequences': ['stop', 'please stop'],
@@ -724,6 +780,52 @@ describe('loggers', () => {
});
});
it('should not log input messages when traces are disabled', () => {
const mockConfigNoTraces = {
getSessionId: () => 'test-session-id',
getTargetDir: () => 'target-dir',
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false, // Disabled
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
getContentGeneratorConfig: () => undefined,
} as unknown as Config;
const event = new ApiErrorEvent(
'test-model',
'error',
100,
{ prompt_id: 'prompt-id-1', contents: [] },
AuthType.LOGIN_WITH_GOOGLE,
'ApiError',
500,
);
logApiError(mockConfigNoTraces, event);
expect(mockLogger.emit).toHaveBeenCalledWith(
expect.objectContaining({
attributes: expect.objectContaining({
'event.name': 'gen_ai.client.inference.operation.details',
}),
}),
);
const emitCalls = mockLogger.emit.mock.calls;
const detailsCall = emitCalls.find(
(call) =>
call[0].attributes &&
call[0].attributes['event.name'] ===
'gen_ai.client.inference.operation.details',
);
expect(
detailsCall![0].attributes['gen_ai.input.messages'],
).toBeUndefined();
});
it('should log an API error with a role', () => {
const event = new ApiErrorEvent(
'test-model',
@@ -756,6 +858,7 @@ describe('loggers', () => {
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -833,7 +936,8 @@ describe('loggers', () => {
getTargetDir: () => 'target-dir',
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true, // Enabled
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => true, // Enabled
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -922,7 +1026,8 @@ describe('loggers', () => {
getTargetDir: () => 'target-dir',
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => false, // Disabled
getTelemetryLogPromptsEnabled: () => false,
getTelemetryTracesEnabled: () => false, // Disabled
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -978,6 +1083,7 @@ describe('loggers', () => {
getSessionId: () => 'test-session-id',
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -1140,6 +1246,7 @@ describe('loggers', () => {
getCoreTools: () => ['ls', 'read-file'],
getApprovalMode: () => 'default',
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
getFileFilteringRespectGitIgnore: () => true,
getFileFilteringAllowBuildArtifacts: () => false,
getDebugMode: () => true,
@@ -1170,6 +1277,7 @@ describe('loggers', () => {
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -1829,6 +1937,7 @@ describe('loggers', () => {
getUsageStatisticsEnabled: () => true,
getTelemetryEnabled: () => true,
getTelemetryLogPromptsEnabled: () => true,
getTelemetryTracesEnabled: () => false,
isInteractive: () => false,
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
@@ -2423,6 +2532,7 @@ describe('loggers', () => {
getExperiments: () => undefined,
getExperimentsAsync: async () => undefined,
getTelemetryLogPromptsEnabled: () => false,
getTelemetryTracesEnabled: () => false,
getContentGeneratorConfig: () => undefined,
} as unknown as Config;
+50 -10
View File
@@ -115,7 +115,11 @@ describe('runInDevTraceSpan', () => {
const fn = vi.fn(async () => 'result');
const result = await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
fn,
);
@@ -123,14 +127,22 @@ describe('runInDevTraceSpan', () => {
expect(trace.getTracer).toHaveBeenCalled();
expect(mockTracer.startActiveSpan).toHaveBeenCalledWith(
GeminiCliOperation.LLMCall,
{},
{
attributes: {
[GEN_AI_CONVERSATION_ID]: 'test-session-id',
},
},
expect.any(Function),
);
});
it('should set default attributes on the span metadata', async () => {
await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async ({ metadata }) => {
expect(metadata.attributes[GEN_AI_OPERATION_NAME]).toBe(
GeminiCliOperation.LLMCall,
@@ -148,7 +160,11 @@ describe('runInDevTraceSpan', () => {
it('should set span attributes from metadata on completion', async () => {
await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async ({ metadata }) => {
metadata.input = { query: 'hello' };
metadata.output = { response: 'world' };
@@ -175,7 +191,11 @@ describe('runInDevTraceSpan', () => {
const error = new Error('test error');
await expect(
runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async () => {
throw error;
},
@@ -197,7 +217,11 @@ describe('runInDevTraceSpan', () => {
}
const resultStream = await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async () => testStream(),
);
@@ -219,7 +243,11 @@ describe('runInDevTraceSpan', () => {
}
const resultStream = await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async () => testStream(),
);
@@ -233,7 +261,11 @@ describe('runInDevTraceSpan', () => {
}
const resultStream = await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async () => testStream(),
);
@@ -259,7 +291,11 @@ describe('runInDevTraceSpan', () => {
}
const resultStream = await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async () => errorStream(),
);
@@ -278,7 +314,11 @@ describe('runInDevTraceSpan', () => {
});
await runInDevTraceSpan(
{ operation: GeminiCliOperation.LLMCall, sessionId: 'test-session-id' },
{
operation: GeminiCliOperation.LLMCall,
sessionId: 'test-session-id',
tracesEnabled: true,
},
async ({ metadata }) => {
metadata.input = 'trigger error';
},
+38 -14
View File
@@ -125,10 +125,17 @@ export async function runInDevTraceSpan<R>(
operation: GeminiCliOperation;
logPrompts?: boolean;
sessionId: string;
tracesEnabled?: boolean;
},
fn: ({ metadata }: { metadata: SpanMetadata }) => Promise<R>,
): Promise<R> {
const { operation, logPrompts, sessionId, ...restOfSpanOpts } = opts;
const { operation, logPrompts, sessionId, tracesEnabled, ...restOfSpanOpts } =
opts;
restOfSpanOpts.attributes = {
...restOfSpanOpts.attributes,
[GEN_AI_CONVERSATION_ID]: sessionId,
};
const tracer = trace.getTracer(TRACER_NAME, TRACER_VERSION);
return tracer.startActiveSpan(operation, restOfSpanOpts, async (span) => {
@@ -148,24 +155,41 @@ export async function runInDevTraceSpan<R>(
}
spanEnded = true;
try {
if (logPrompts !== false) {
if (meta.input !== undefined) {
const truncated = truncateForTelemetry(meta.input);
if (truncated !== undefined) {
span.setAttribute(GEN_AI_INPUT_MESSAGES, truncated);
if (tracesEnabled) {
if (logPrompts !== false) {
if (meta.input !== undefined) {
const truncated = truncateForTelemetry(meta.input);
if (truncated !== undefined) {
span.setAttribute(GEN_AI_INPUT_MESSAGES, truncated);
}
}
if (meta.output !== undefined) {
const truncated = truncateForTelemetry(meta.output);
if (truncated !== undefined) {
span.setAttribute(GEN_AI_OUTPUT_MESSAGES, truncated);
}
}
}
if (meta.output !== undefined) {
const truncated = truncateForTelemetry(meta.output);
for (const [key, value] of Object.entries(meta.attributes)) {
const truncated = truncateForTelemetry(value);
if (truncated !== undefined) {
span.setAttribute(GEN_AI_OUTPUT_MESSAGES, truncated);
span.setAttribute(key, truncated);
}
}
}
for (const [key, value] of Object.entries(meta.attributes)) {
const truncated = truncateForTelemetry(value);
if (truncated !== undefined) {
span.setAttribute(key, truncated);
} else {
// Add basic attributes even when traces are disabled
for (const [key, value] of Object.entries(meta.attributes)) {
if (
key === GEN_AI_OPERATION_NAME ||
key === GEN_AI_AGENT_NAME ||
key === GEN_AI_AGENT_DESCRIPTION ||
key === GEN_AI_CONVERSATION_ID
) {
const truncated = truncateForTelemetry(value);
if (truncated !== undefined) {
span.setAttribute(key, truncated);
}
}
}
}
if (meta.error) {
+17 -6
View File
@@ -387,6 +387,13 @@ export class ToolCallEvent implements BaseTelemetryEvent {
}
export const EVENT_API_REQUEST = 'gemini_cli.api_request';
function shouldIncludePayloads(config: Config): boolean {
return (
config.getTelemetryTracesEnabled() && config.getTelemetryLogPromptsEnabled()
);
}
export class ApiRequestEvent implements BaseTelemetryEvent {
'event.name': 'api_request';
'event.timestamp': string;
@@ -443,7 +450,7 @@ export class ApiRequestEvent implements BaseTelemetryEvent {
attributes['server.port'] = this.prompt.server.port;
}
if (config.getTelemetryLogPromptsEnabled() && this.prompt.contents) {
if (shouldIncludePayloads(config) && this.prompt.contents) {
attributes['gen_ai.input.messages'] = JSON.stringify(
toInputMessages(this.prompt.contents),
);
@@ -540,7 +547,7 @@ export class ApiErrorEvent implements BaseTelemetryEvent {
attributes['server.port'] = this.prompt.server.port;
}
if (config.getTelemetryLogPromptsEnabled() && this.prompt.contents) {
if (shouldIncludePayloads(config) && this.prompt.contents) {
attributes['gen_ai.input.messages'] = JSON.stringify(
toInputMessages(this.prompt.contents),
);
@@ -707,9 +714,13 @@ export class ApiResponseEvent implements BaseTelemetryEvent {
'event.timestamp': this['event.timestamp'],
'gen_ai.response.id': this.response.response_id,
'gen_ai.response.finish_reasons': this.finish_reasons,
'gen_ai.output.messages': JSON.stringify(
toOutputMessages(this.response.candidates),
),
...(shouldIncludePayloads(config)
? {
'gen_ai.output.messages': JSON.stringify(
toOutputMessages(this.response.candidates),
),
}
: {}),
...toGenerateContentConfigAttributes(this.prompt.generate_content_config),
...getConventionAttributes(this),
};
@@ -719,7 +730,7 @@ export class ApiResponseEvent implements BaseTelemetryEvent {
attributes['server.port'] = this.prompt.server.port;
}
if (config.getTelemetryLogPromptsEnabled() && this.prompt.contents) {
if (shouldIncludePayloads(config) && this.prompt.contents) {
attributes['gen_ai.input.messages'] = JSON.stringify(
toInputMessages(this.prompt.contents),
);
@@ -58,12 +58,12 @@ export function getShellToolDescription(
if (os.platform() === 'win32') {
const backgroundInstructions = enableInteractiveShell
? `For background execution, use is_background: true instead of PowerShell background constructs.`
? `To run a command in the background, set the \`${SHELL_PARAM_IS_BACKGROUND}\` parameter to true. Do NOT use PowerShell background constructs.`
: 'Command can start background processes using PowerShell constructs such as `Start-Process -NoNewWindow` or `Start-Job`.';
return `This tool executes a given shell command as \`powershell.exe -NoProfile -Command <command>\`. ${backgroundInstructions}${efficiencyGuidelines}${returnedInfo}`;
} else {
const backgroundInstructions = enableInteractiveShell
? `For background execution, use is_background: true instead of &.`
? `To run a command in the background, set the \`${SHELL_PARAM_IS_BACKGROUND}\` parameter to true. Do NOT use \`&\` to background commands.`
: 'Command can start background processes using `&`.';
return `This tool executes a given shell command as \`bash -c <command>\`. ${backgroundInstructions} Command is executed as a subprocess that leads its own process group. Command process group can be terminated as \`kill -- -PGID\` or signaled as \`kill -s SIGNAL -- -PGID\`.${efficiencyGuidelines}${returnedInfo}`;
}
@@ -95,7 +95,8 @@ export const DEFAULT_LEGACY_SET: CoreToolSet = {
type: 'string',
},
[READ_FILE_PARAM_START_LINE]: {
description: 'Optional 1-based starting line number.',
description:
'Optional: The 1-based line number to start reading from.',
type: 'number',
},
[READ_FILE_PARAM_END_LINE]: {
@@ -347,7 +348,18 @@ export const DEFAULT_LEGACY_SET: CoreToolSet = {
replace: {
name: EDIT_TOOL_NAME,
description: `Replaces exact old_string with new_string. Fails if not exactly one match, unless allow_multiple is true.`,
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.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
Expectation for required parameters:
1. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
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.
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.`,
parametersJsonSchema: {
type: 'object',
properties: {
@@ -104,7 +104,8 @@ export const GEMINI_3_SET: CoreToolSet = {
type: 'string',
},
[READ_FILE_PARAM_START_LINE]: {
description: 'Optional 1-based starting line number.',
description:
'Optional: The 1-based line number to start reading from.',
type: 'number',
},
[READ_FILE_PARAM_END_LINE]: {
@@ -187,7 +188,7 @@ export const GEMINI_3_SET: CoreToolSet = {
grep_search_ripgrep: {
name: GREP_TOOL_NAME,
description:
"Fast ripgrep-powered search. Always prefer this over run_shell_command('grep').",
'Searches for a regular expression pattern within file contents. This tool is FAST and optimized, powered by ripgrep. PREFERRED over standard `run_shell_command("grep ...")` due to better performance and automatic output limiting (defaults to 100 matches, but can be increased via `total_max_matches`).',
parametersJsonSchema: {
type: 'object',
properties: {
@@ -354,7 +355,8 @@ export const GEMINI_3_SET: CoreToolSet = {
replace: {
name: EDIT_TOOL_NAME,
description: `Replaces exact old_string with new_string. Fails if not exactly one match, unless allow_multiple is true.`,
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.
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.`,
parametersJsonSchema: {
type: 'object',
properties: {
+3 -2
View File
@@ -107,6 +107,7 @@ describe('EditTool', () => {
getGeminiClient: vi.fn().mockReturnValue(geminiClient),
getBaseLlmClient: vi.fn().mockReturnValue(baseLlmClient),
getTargetDir: () => rootDir,
getProjectRoot: () => rootDir,
getApprovalMode: vi.fn(),
setApprovalMode: vi.fn(),
getWorkspaceContext: () => createMockWorkspaceContext(rootDir),
@@ -1336,8 +1337,8 @@ function doIt() {
vi.mocked(mockConfig.isPlanMode).mockReturnValue(true);
vi.mocked(mockConfig.storage.getPlansDir).mockReturnValue(plansDir);
const filePath = path.join(rootDir, 'test-file.txt');
const planFilePath = path.join(plansDir, 'test-file.txt');
const filePath = 'test-file.txt';
const planFilePath = path.join(plansDir, filePath);
const initialContent = 'some initial content';
fs.writeFileSync(planFilePath, initialContent, 'utf8');
+27 -6
View File
@@ -58,6 +58,7 @@ import { EDIT_DEFINITION } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import { detectOmissionPlaceholders } from './omissionPlaceholderDetector.js';
import { discoverJitContext, appendJitContext } from './jit-context.js';
import { resolveAndValidatePlanPath } from '../utils/planUtils.js';
const ENABLE_FUZZY_MATCH_RECOVERY = true;
const FUZZY_MATCH_THRESHOLD = 0.1; // Allow up to 10% weighted difference
@@ -465,11 +466,21 @@ class EditToolInvocation
() => this.config.getApprovalMode(),
);
if (this.config.isPlanMode()) {
const safeFilename = path.basename(this.params.file_path);
this.resolvedPath = path.join(
this.config.storage.getPlansDir(),
safeFilename,
);
try {
this.resolvedPath = resolveAndValidatePlanPath(
this.params.file_path,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (e) {
debugLogger.error(
'Failed to resolve plan path during EditTool invocation setup',
e,
);
// Validation fails, set resolvedPath to something that will fail validation downstream or just the raw path.
// It's safer to store it so validation in execute() or getConfirmationDetails() catches it.
this.resolvedPath = this.params.file_path;
}
} else if (!path.isAbsolute(this.params.file_path)) {
const result = correctPath(this.params.file_path, this.config);
if (result.success) {
@@ -1054,7 +1065,17 @@ export class EditTool
}
let resolvedPath: string;
if (!path.isAbsolute(params.file_path)) {
if (this.config.isPlanMode()) {
try {
resolvedPath = resolveAndValidatePlanPath(
params.file_path,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
} else if (!path.isAbsolute(params.file_path)) {
const result = correctPath(params.file_path, this.config);
if (result.success) {
resolvedPath = result.correctedPath;
+10 -3
View File
@@ -42,6 +42,7 @@ describe('ExitPlanModeTool', () => {
mockConfig = {
getTargetDir: vi.fn().mockReturnValue(tempRootDir),
getProjectRoot: vi.fn().mockReturnValue(tempRootDir),
setApprovalMode: vi.fn(),
setApprovedPlanPath: vi.fn(),
storage: {
@@ -72,8 +73,10 @@ describe('ExitPlanModeTool', () => {
const createPlanFile = (name: string, content: string) => {
const filePath = path.join(mockPlansDir, name);
// Ensure parent directory exists for nested tests
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
return path.join('plans', name);
return name;
};
describe('shouldConfirmExecute', () => {
@@ -482,7 +485,11 @@ Ask the user for specific feedback on how to improve the plan.`,
});
it('should reject non-existent plan file', async () => {
const result = await validatePlanPath('ghost.md', mockPlansDir);
const result = await validatePlanPath(
'ghost.md',
mockPlansDir,
tempRootDir,
);
expect(result).toContain('Plan file does not exist');
});
@@ -497,7 +504,7 @@ Ask the user for specific feedback on how to improve the plan.`,
});
expect(result).toBe(
`Access denied: plan path (${path.join(mockPlansDir, 'malicious.md')}) must be within the designated plans directory (${mockPlansDir}).`,
`Access denied: plan path (malicious.md) must be within the designated plans directory (${mockPlansDir}).`,
);
});
+19 -16
View File
@@ -19,9 +19,12 @@ import type { MessageBus } from '../confirmation-bus/message-bus.js';
import path from 'node:path';
import type { Config } from '../config/config.js';
import { EXIT_PLAN_MODE_TOOL_NAME } from './tool-names.js';
import { validatePlanPath, validatePlanContent } from '../utils/planUtils.js';
import {
validatePlanPath,
validatePlanContent,
resolveAndValidatePlanPath,
} from '../utils/planUtils.js';
import { ApprovalMode } from '../policy/types.js';
import { resolveToRealPath, isSubpath } from '../utils/paths.js';
import { logPlanExecution } from '../telemetry/loggers.js';
import { PlanExecutionEvent } from '../telemetry/types.js';
import { getExitPlanModeDefinition } from './definitions/coreTools.js';
@@ -59,18 +62,14 @@ export class ExitPlanModeTool extends BaseDeclarativeTool<
if (!params.plan_filename || params.plan_filename.trim() === '') {
return 'plan_filename is required.';
}
const safeFilename = path.basename(params.plan_filename);
const plansDir = resolveToRealPath(this.config.storage.getPlansDir());
const resolvedPath = path.join(
this.config.storage.getPlansDir(),
safeFilename,
);
const realPath = resolveToRealPath(resolvedPath);
if (!isSubpath(plansDir, realPath)) {
return `Access denied: plan path (${resolvedPath}) must be within the designated plans directory (${plansDir}).`;
try {
resolveAndValidatePlanPath(
params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (e) {
return e instanceof Error ? e.message : String(e);
}
return null;
@@ -122,6 +121,7 @@ export class ExitPlanModeInvocation extends BaseToolInvocation<
const pathError = await validatePlanPath(
this.params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
if (pathError) {
this.planValidationError = pathError;
@@ -179,8 +179,11 @@ export class ExitPlanModeInvocation extends BaseToolInvocation<
* Note: Validation is done in validateToolParamValues, so this assumes the path is valid.
*/
private getResolvedPlanPath(): string {
const safeFilename = path.basename(this.params.plan_filename);
return path.join(this.config.storage.getPlansDir(), safeFilename);
return resolveAndValidatePlanPath(
this.params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
}
async execute({ abortSignal: _signal }: ExecuteOptions): Promise<ToolResult> {
+59 -33
View File
@@ -96,6 +96,7 @@ describe('ShellTool', () => {
let mockShellOutputCallback: (event: ShellOutputEvent) => void;
let resolveExecutionPromise: (result: ShellExecutionResult) => void;
let tempRootDir: string;
let extractedTmpFile: string;
beforeEach(() => {
vi.clearAllMocks();
@@ -197,16 +198,28 @@ describe('ShellTool', () => {
process.env['ComSpec'] =
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
extractedTmpFile = '';
// Capture the output callback to simulate streaming events from the service
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
return {
pid: 12345,
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
};
});
mockShellExecutionService.mockImplementation(
(
cmd: string,
_cwd: string,
callback: (event: ShellOutputEvent) => void,
) => {
mockShellOutputCallback = callback;
const match = cmd.match(/pgrep -g 0 >([^ ]+)/);
if (match) {
extractedTmpFile = match[1].replace(/['"]/g, ''); // remove any quotes if present
}
return {
pid: 12345,
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
};
},
);
mockShellBackground.mockImplementation(() => {
resolveExecutionPromise({
@@ -293,17 +306,16 @@ describe('ShellTool', () => {
it('should wrap command on linux and parse pgrep output', async () => {
const invocation = shellTool.build({ command: 'my-command &' });
const promise = invocation.execute({ abortSignal: mockAbortSignal });
resolveShellExecution({ pid: 54321 });
// Simulate pgrep output file creation by the shell command
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
fs.writeFileSync(tmpFile, `54321${os.EOL}54322${os.EOL}`);
fs.writeFileSync(extractedTmpFile, `54321${os.EOL}54322${os.EOL}`);
resolveShellExecution({ pid: 54321 });
const result = await promise;
const wrappedCommand = `(\n${'my-command &'}\n); __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
tempRootDir,
expect.any(Function),
expect.any(AbortSignal),
@@ -316,7 +328,7 @@ describe('ShellTool', () => {
);
expect(result.llmContent).toContain('Background PIDs: 54322');
// The file should be deleted by the tool
expect(fs.existsSync(tmpFile)).toBe(false);
expect(fs.existsSync(extractedTmpFile)).toBe(false);
});
it('should add a space when command ends with a backslash to prevent escaping newline', async () => {
@@ -325,10 +337,8 @@ describe('ShellTool', () => {
resolveShellExecution();
await promise;
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
const wrappedCommand = `(\nls\\ \n); __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
tempRootDir,
expect.any(Function),
expect.any(AbortSignal),
@@ -343,10 +353,8 @@ describe('ShellTool', () => {
resolveShellExecution();
await promise;
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
const wrappedCommand = `(\nls # comment\n); __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
tempRootDir,
expect.any(Function),
expect.any(AbortSignal),
@@ -365,10 +373,8 @@ describe('ShellTool', () => {
resolveShellExecution();
await promise;
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
const wrappedCommand = `(\n${'ls'}\n); __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
subdir,
expect.any(Function),
expect.any(AbortSignal),
@@ -390,10 +396,8 @@ describe('ShellTool', () => {
resolveShellExecution();
await promise;
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
const wrappedCommand = `(\n${'ls'}\n); __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
path.join(tempRootDir, 'subdir'),
expect.any(Function),
expect.any(AbortSignal),
@@ -462,6 +466,26 @@ describe('ShellTool', () => {
20000,
);
it('should correctly wrap heredoc commands', async () => {
const command = `cat << 'EOF'
hello world
EOF`;
const invocation = shellTool.build({ command });
const promise = invocation.execute({ abortSignal: mockAbortSignal });
resolveShellExecution();
await promise;
expect(mockShellExecutionService).toHaveBeenCalledWith(
expect.stringMatching(/pgrep -g 0 >.*gemini-shell-.*[/\\]pgrep\.tmp/),
tempRootDir,
expect.any(Function),
expect.any(AbortSignal),
false,
expect.any(Object),
);
expect(mockShellExecutionService.mock.calls[0][0]).toMatch(/\nEOF\n\)\n/);
});
it('should format error messages correctly', async () => {
const error = new Error('wrapped command failed');
const invocation = shellTool.build({ command: 'user-command' });
@@ -562,10 +586,13 @@ describe('ShellTool', () => {
it('should clean up the temp file on synchronous execution error', async () => {
const error = new Error('sync spawn error');
mockShellExecutionService.mockImplementation(() => {
// Create the temp file before throwing to simulate it being left behind
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
fs.writeFileSync(tmpFile, '');
mockShellExecutionService.mockImplementation((cmd: string) => {
const match = cmd.match(/pgrep -g 0 >([^ ]+)/);
if (match) {
extractedTmpFile = match[1].replace(/['"]/g, ''); // remove any quotes if present
// Create the temp file before throwing to simulate it being left behind
fs.writeFileSync(extractedTmpFile, '');
}
throw error;
});
@@ -574,8 +601,7 @@ describe('ShellTool', () => {
invocation.execute({ abortSignal: mockAbortSignal }),
).rejects.toThrow(error);
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
expect(fs.existsSync(tmpFile)).toBe(false);
expect(fs.existsSync(extractedTmpFile)).toBe(false);
});
it('should not log "missing pgrep output" when process is backgrounded', async () => {
+25 -12
View File
@@ -8,7 +8,6 @@ import fsPromises from 'node:fs/promises';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import crypto from 'node:crypto';
import { debugLogger } from '../index.js';
import { type SandboxPermissions } from '../services/sandboxManager.js';
import { ToolErrorType } from './tool-error.js';
@@ -42,6 +41,7 @@ import {
parseCommandDetails,
hasRedirection,
normalizeCommand,
escapeShellArg,
} from '../utils/shell-utils.js';
import { SHELL_TOOL_NAME } from './tool-names.js';
import { PARAM_ADDITIONAL_PERMISSIONS } from './definitions/base-declarations.js';
@@ -111,7 +111,8 @@ export class ShellToolInvocation extends BaseToolInvocation<
if (trimmed.endsWith('\\')) {
trimmed += ' ';
}
return `(\n${trimmed}\n); __code=$?; pgrep -g 0 >${tempFilePath} 2>&1; exit $__code;`;
const escapedTempFilePath = escapeShellArg(tempFilePath, 'bash');
return `(\n${trimmed}\n)\n__code=$?; pgrep -g 0 >${escapedTempFilePath} 2>&1; exit $__code;`;
}
private getContextualDetails(): string {
@@ -450,10 +451,8 @@ export class ShellToolInvocation extends BaseToolInvocation<
}
const isWindows = os.platform() === 'win32';
const tempFileName = `shell_pgrep_${crypto
.randomBytes(6)
.toString('hex')}.tmp`;
const tempFilePath = path.join(os.tmpdir(), tempFileName);
let tempFilePath = '';
let tempDir = '';
const timeoutMs = this.context.config.getShellToolInactivityTimeout();
const timeoutController = new AbortController();
@@ -463,8 +462,10 @@ export class ShellToolInvocation extends BaseToolInvocation<
const combinedController = new AbortController();
const onAbort = () => combinedController.abort();
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,
@@ -638,7 +639,10 @@ export class ShellToolInvocation extends BaseToolInvocation<
if (tempFileExists) {
const pgrepContent = await fsPromises.readFile(tempFilePath, 'utf8');
const pgrepLines = pgrepContent.split(os.EOL).filter(Boolean);
const pgrepLines = pgrepContent
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
for (const line of pgrepLines) {
if (!/^\d+$/.test(line)) {
if (
@@ -935,10 +939,19 @@ export class ShellToolInvocation extends BaseToolInvocation<
if (timeoutTimer) clearTimeout(timeoutTimer);
signal.removeEventListener('abort', onAbort);
timeoutController.signal.removeEventListener('abort', onAbort);
try {
await fsPromises.unlink(tempFilePath);
} catch {
// Ignore errors during unlink
if (tempFilePath) {
try {
await fsPromises.unlink(tempFilePath);
} catch {
// Ignore errors during unlink
}
}
if (tempDir) {
try {
await fsPromises.rm(tempDir, { recursive: true, force: true });
} catch {
// Ignore errors during rm
}
}
}
}
@@ -76,6 +76,7 @@ vi.mocked(IdeClient.getInstance).mockResolvedValue(
const fsService = new StandardFileSystemService();
const mockConfigInternal = {
getTargetDir: () => rootDir,
getProjectRoot: () => rootDir,
getApprovalMode: vi.fn(() => ApprovalMode.DEFAULT),
setApprovalMode: vi.fn(),
getGeminiClient: vi.fn(), // Initialize as a plain mock function
@@ -1113,4 +1114,26 @@ describe('WriteFileTool', () => {
);
});
});
describe('plan mode path handling', () => {
const abortSignal = new AbortController().signal;
it('should correctly resolve nested paths in plan mode', async () => {
vi.mocked(mockConfig.isPlanMode).mockReturnValue(true);
// Extend storage mock with getPlansDir
mockConfig.storage.getPlansDir = vi.fn().mockReturnValue(plansDir);
const nestedFilePath = 'conductor/tracks/test.md';
const invocation = tool.build({
file_path: nestedFilePath,
content: 'nested content',
});
await invocation.execute({ abortSignal });
const expectedWritePath = path.join(plansDir, 'conductor/tracks/test.md');
expect(fs.existsSync(expectedWritePath)).toBe(true);
expect(fs.readFileSync(expectedWritePath, 'utf8')).toBe('nested content');
});
});
});
+29 -6
View File
@@ -49,6 +49,7 @@ import { debugLogger } from '../utils/debugLogger.js';
import { WRITE_FILE_DEFINITION } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import { detectOmissionPlaceholders } from './omissionPlaceholderDetector.js';
import { resolveAndValidatePlanPath } from '../utils/planUtils.js';
import { isGemini3Model } from '../config/models.js';
import { discoverJitContext, appendJitContext } from './jit-context.js';
@@ -168,11 +169,20 @@ class WriteFileToolInvocation extends BaseToolInvocation<
);
if (this.config.isPlanMode()) {
const safeFilename = path.basename(this.params.file_path);
this.resolvedPath = path.join(
this.config.storage.getPlansDir(),
safeFilename,
);
try {
this.resolvedPath = resolveAndValidatePlanPath(
this.params.file_path,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (e) {
debugLogger.error(
'Failed to resolve plan path during WriteFileTool invocation setup',
e,
);
// Validation fails, set resolvedPath to something that will fail validation downstream or just the raw path.
this.resolvedPath = this.params.file_path;
}
} else {
this.resolvedPath = path.resolve(
this.config.getTargetDir(),
@@ -499,7 +509,20 @@ export class WriteFileTool
return `Missing or empty "file_path"`;
}
const resolvedPath = path.resolve(this.config.getTargetDir(), filePath);
let resolvedPath: string;
if (this.config.isPlanMode()) {
try {
resolvedPath = resolveAndValidatePlanPath(
filePath,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
} else {
resolvedPath = path.resolve(this.config.getTargetDir(), filePath);
}
const validationError = this.config.validatePathAccess(resolvedPath);
if (validationError) {
@@ -6,6 +6,7 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import path from 'node:path';
import fs from 'node:fs/promises';
import { FileSearchFactory, AbortError, filter } from './fileSearch.js';
import { createTmpDir, cleanupTmpDir } from '@google/gemini-cli-test-utils';
import * as crawler from './crawler.js';
@@ -150,6 +151,70 @@ describe('FileSearch', () => {
]);
});
it('should include newly created directory when watcher is enabled', async () => {
tmpDir = await createTmpDir({
src: ['main.js'],
});
const fileSearch = FileSearchFactory.create({
projectRoot: tmpDir,
fileDiscoveryService: new FileDiscoveryService(tmpDir, {
respectGitIgnore: false,
respectGeminiIgnore: false,
}),
ignoreDirs: [],
cache: false,
cacheTtl: 0,
enableFileWatcher: true,
enableRecursiveFileSearch: true,
enableFuzzySearch: true,
});
await fileSearch.initialize();
await new Promise((resolve) => setTimeout(resolve, 300));
await fs.mkdir(path.join(tmpDir, 'new-folder'));
await new Promise((resolve) => setTimeout(resolve, 1200));
const results = await fileSearch.search('new-folder');
expect(results).toContain('new-folder/');
});
it('should include newly created file and remove it after deletion when watcher is enabled', async () => {
tmpDir = await createTmpDir({
src: ['main.js'],
});
const fileSearch = FileSearchFactory.create({
projectRoot: tmpDir,
fileDiscoveryService: new FileDiscoveryService(tmpDir, {
respectGitIgnore: false,
respectGeminiIgnore: false,
}),
ignoreDirs: [],
cache: false,
cacheTtl: 0,
enableFileWatcher: true,
enableRecursiveFileSearch: true,
enableFuzzySearch: true,
});
await fileSearch.initialize();
await new Promise((resolve) => setTimeout(resolve, 300));
const filePath = path.join(tmpDir, 'watcher-file.txt');
await fs.writeFile(filePath, 'hello');
await new Promise((resolve) => setTimeout(resolve, 1200));
let results = await fileSearch.search('watcher-file');
expect(results).toContain('watcher-file.txt');
await fs.rm(filePath, { force: true });
await new Promise((resolve) => setTimeout(resolve, 1200));
results = await fileSearch.search('watcher-file');
expect(results).not.toContain('watcher-file.txt');
});
it('should filter results with a search pattern', async () => {
tmpDir = await createTmpDir({
src: {
+124 -13
View File
@@ -12,6 +12,8 @@ import { crawl } from './crawler.js';
import { AsyncFzf, type FzfResultItem } from 'fzf';
import { unescapePath } from '../paths.js';
import type { FileDiscoveryService } from '../../services/fileDiscoveryService.js';
import { FileWatcher, type FileWatcherEvent } from './fileWatcher.js';
import { debugLogger } from '../debugLogger.js';
// Tiebreaker: Prefers shorter paths.
const byLengthAsc = (a: { item: string }, b: { item: string }) =>
@@ -57,6 +59,7 @@ export interface FileSearchOptions {
fileDiscoveryService: FileDiscoveryService;
cache: boolean;
cacheTtl: number;
enableFileWatcher?: boolean;
enableRecursiveFileSearch: boolean;
enableFuzzySearch: boolean;
maxDepth?: number;
@@ -126,13 +129,16 @@ export interface SearchOptions {
export interface FileSearch {
initialize(): Promise<void>;
search(pattern: string, options?: SearchOptions): Promise<string[]>;
close?(): Promise<void>;
}
class RecursiveFileSearch implements FileSearch {
private ignore: Ignore | undefined;
private resultCache: ResultCache | undefined;
private allFiles: string[] = [];
private allFiles: Set<string> = new Set();
private fzf: AsyncFzf<string[]> | undefined;
private fileWatcher: FileWatcher | undefined;
private rebuildTimer: NodeJS.Timeout | undefined;
constructor(private readonly options: FileSearchOptions) {}
@@ -142,17 +148,112 @@ class RecursiveFileSearch implements FileSearch {
this.options.ignoreDirs,
);
this.allFiles = await crawl({
crawlDirectory: this.options.projectRoot,
cwd: this.options.projectRoot,
ignore: this.ignore,
cache: this.options.cache,
cacheTtl: this.options.cacheTtl,
maxDepth: this.options.maxDepth,
maxFiles: this.options.maxFiles ?? 20000,
});
this.allFiles = new Set(
await crawl({
crawlDirectory: this.options.projectRoot,
cwd: this.options.projectRoot,
ignore: this.ignore,
cache: this.options.cache,
cacheTtl: this.options.cacheTtl,
maxDepth: this.options.maxDepth,
maxFiles: this.options.maxFiles ?? 20000,
}),
);
this.buildResultCache();
if (this.options.enableFileWatcher) {
const directoryFilter = this.ignore.getDirectoryFilter();
this.fileWatcher = new FileWatcher(
this.options.projectRoot,
(event) => this.handleFileWatcherEvent(event),
{
shouldIgnore: (relativePath) => directoryFilter(`${relativePath}/`),
onError(error) {
debugLogger.error('File search watcher error: ', error);
},
},
);
this.fileWatcher.start();
}
}
private scheduleRebuild(): void {
if (this.rebuildTimer) {
clearTimeout(this.rebuildTimer);
}
this.rebuildTimer = setTimeout(() => {
this.rebuildTimer = undefined;
this.buildResultCache();
}, 150);
}
private handleFileWatcherEvent(event: FileWatcherEvent): void {
const normalizedPath = event.relativePath.replaceAll('\\', '/');
if (!normalizedPath || normalizedPath === '.') {
return;
}
const fileFilter = this.ignore?.getFileFilter();
const directoryFilter = this.ignore?.getDirectoryFilter();
let changed = false;
switch (event.eventType) {
case 'add': {
if (
fileFilter?.(normalizedPath) ||
this.allFiles.size >= (this.options.maxFiles ?? 20000)
) {
return;
}
const sizeBefore = this.allFiles.size;
this.allFiles.add(normalizedPath);
changed = this.allFiles.size !== sizeBefore;
break;
}
case 'unlink': {
changed = this.allFiles.delete(normalizedPath);
break;
}
case 'addDir': {
const directoryPath = normalizedPath.endsWith('/')
? normalizedPath
: `${normalizedPath}/`;
if (
directoryFilter?.(directoryPath) ||
this.allFiles.size >= (this.options.maxFiles ?? 20000)
) {
return;
}
const sizeBefore = this.allFiles.size;
this.allFiles.add(directoryPath);
changed = this.allFiles.size !== sizeBefore;
break;
}
case 'unlinkDir': {
const directoryPath = normalizedPath.endsWith('/')
? normalizedPath
: `${normalizedPath}/`;
const toDelete: string[] = [];
for (const file of this.allFiles) {
if (file === directoryPath || file.startsWith(directoryPath)) {
toDelete.push(file);
}
}
changed = toDelete.length > 0;
for (const file of toDelete) {
this.allFiles.delete(file);
}
break;
}
default:
return;
}
if (changed) {
this.scheduleRebuild();
}
}
async search(
@@ -222,14 +323,24 @@ class RecursiveFileSearch implements FileSearch {
return results;
}
async close(): Promise<void> {
await this.fileWatcher?.close();
this.fileWatcher = undefined;
if (this.rebuildTimer) {
clearTimeout(this.rebuildTimer);
this.rebuildTimer = undefined;
}
}
private buildResultCache(): void {
this.resultCache = new ResultCache(this.allFiles);
const allFiles = [...this.allFiles];
this.resultCache = new ResultCache(allFiles);
if (this.options.enableFuzzySearch) {
// The v1 algorithm is much faster since it only looks at the first
// occurrence of the pattern. We use it for search spaces that have >20k
// files, because the v2 algorithm is just too slow in those cases.
this.fzf = new AsyncFzf(this.allFiles, {
fuzzy: this.allFiles.length > 20000 ? 'v1' : 'v2',
this.fzf = new AsyncFzf(allFiles, {
fuzzy: allFiles.length > 20000 ? 'v1' : 'v2',
forward: false,
tiebreakers: [byBasenamePrefix, byMatchPosFromEnd, byLengthAsc],
});
@@ -0,0 +1,220 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanupTmpDir, createTmpDir } from '@google/gemini-cli-test-utils';
import { FileWatcher, type FileWatcherEvent } from './fileWatcher.js';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const waitForEvent = async (
events: FileWatcherEvent[],
predicate: (event: FileWatcherEvent) => boolean,
timeoutMs = 4000,
) => {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
if (events.some(predicate)) {
return;
}
await sleep(50);
}
throw new Error('Timed out waiting for watcher event');
};
describe('FileWatcher', () => {
const tmpDirs: string[] = [];
afterEach(async () => {
await Promise.all(tmpDirs.map((dir) => cleanupTmpDir(dir)));
tmpDirs.length = 0;
vi.restoreAllMocks();
});
it('should emit relative add and unlink events for files', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(tmpDir, (event) => {
events.push(event);
});
watcher.start();
await sleep(500);
const fileName = 'new-file.txt';
const filePath = path.join(tmpDir, fileName);
await fs.writeFile(filePath, 'hello');
await sleep(1200);
await fs.rm(filePath, { force: true });
await sleep(1200);
await watcher.close();
expect(events).toContainEqual({ eventType: 'add', relativePath: fileName });
expect(events).toContainEqual({
eventType: 'unlink',
relativePath: fileName,
});
});
it('should skip ignored paths', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(
tmpDir,
(event) => {
events.push(event);
},
{
shouldIgnore: (relativePath) => relativePath.startsWith('ignored'),
},
);
watcher.start();
await sleep(500);
await fs.writeFile(path.join(tmpDir, 'ignored.txt'), 'x');
await fs.writeFile(path.join(tmpDir, 'kept.txt'), 'x');
await sleep(1200);
await watcher.close();
expect(events.some((event) => event.relativePath === 'ignored.txt')).toBe(
false,
);
expect(events).toContainEqual({
eventType: 'add',
relativePath: 'kept.txt',
});
});
it('should emit addDir and unlinkDir events for directories', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(tmpDir, (event) => {
events.push(event);
});
watcher.start();
await sleep(500);
const dirName = 'new-folder';
const dirPath = path.join(tmpDir, dirName);
await fs.mkdir(dirPath);
await waitForEvent(
events,
(event) => event.eventType === 'addDir' && event.relativePath === dirName,
);
await fs.rm(dirPath, { recursive: true, force: true });
await waitForEvent(
events,
(event) =>
event.eventType === 'unlinkDir' && event.relativePath === dirName,
);
await watcher.close();
});
it('should normalize nested paths without leading dot prefix', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(tmpDir, (event) => {
events.push(event);
});
watcher.start();
await sleep(500);
await fs.mkdir(path.join(tmpDir, 'nested'), { recursive: true });
await fs.writeFile(path.join(tmpDir, 'nested', 'file.txt'), 'data');
await waitForEvent(
events,
(event) =>
event.eventType === 'add' && event.relativePath === 'nested/file.txt',
);
const nestedFileEvent = events.find(
(event) =>
event.eventType === 'add' && event.relativePath.endsWith('/file.txt'),
);
expect(nestedFileEvent).toBeDefined();
expect(nestedFileEvent!.relativePath.startsWith('./')).toBe(false);
expect(nestedFileEvent!.relativePath.includes('\\')).toBe(false);
await watcher.close();
});
it('should not emit new events after stop is called', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(tmpDir, (event) => {
events.push(event);
});
watcher.start();
await sleep(500);
const beforeStopFile = path.join(tmpDir, 'before-stop.txt');
await fs.writeFile(beforeStopFile, 'x');
await waitForEvent(
events,
(event) =>
event.eventType === 'add' && event.relativePath === 'before-stop.txt',
);
await watcher.close();
const afterStopCount = events.length;
await fs.writeFile(path.join(tmpDir, 'after-stop.txt'), 'x');
await sleep(600);
expect(events.length).toBe(afterStopCount);
});
it('should be safe to start and stop multiple times', async () => {
const tmpDir = await createTmpDir({});
tmpDirs.push(tmpDir);
const events: FileWatcherEvent[] = [];
const watcher = new FileWatcher(tmpDir, (event) => {
events.push(event);
});
watcher.start();
watcher.start();
await sleep(500);
await fs.writeFile(path.join(tmpDir, 'idempotent.txt'), 'x');
await waitForEvent(
events,
(event) =>
event.eventType === 'add' && event.relativePath === 'idempotent.txt',
);
await watcher.close();
await watcher.close();
expect(events.length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,103 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { watch, type FSWatcher } from 'chokidar';
import path from 'node:path';
export type FileWatcherEvent = {
eventType: 'add' | 'unlink' | 'addDir' | 'unlinkDir';
relativePath: string;
};
export type FileWatcherCallback = (event: FileWatcherEvent) => void;
type FileWatcherOptions = {
shouldIgnore?: (relativePath: string) => boolean;
onError?: (error: unknown) => void;
};
export class FileWatcher {
private watcher: FSWatcher | null = null;
constructor(
private readonly projectRoot: string,
private readonly onEvent: FileWatcherCallback,
private readonly options: FileWatcherOptions = {},
) {}
private normalizeRelativePath(filePath: string): string {
const relativeOrOriginal = path.isAbsolute(filePath)
? path.relative(this.projectRoot, filePath)
: filePath;
const normalized = relativeOrOriginal.replaceAll('\\', '/');
if (normalized === '' || normalized === '.') {
return '';
}
if (normalized.startsWith('./')) {
return normalized.slice(2);
}
return normalized;
}
start(): void {
if (this.watcher) {
return;
}
this.watcher = watch(this.projectRoot, {
cwd: this.projectRoot,
ignoreInitial: true,
awaitWriteFinish: false,
followSymlinks: false,
persistent: true,
ignored: (filePath: string) => {
if (!this.options.shouldIgnore) {
return false;
}
const relativePath = this.normalizeRelativePath(filePath);
if (!relativePath) {
return false;
}
return this.options.shouldIgnore(relativePath);
},
});
this.watcher
.on('add', (relativePath: string) => {
this.onEvent({
eventType: 'add',
relativePath: this.normalizeRelativePath(relativePath),
});
})
.on('unlink', (relativePath: string) => {
this.onEvent({
eventType: 'unlink',
relativePath: this.normalizeRelativePath(relativePath),
});
})
.on('addDir', (relativePath: string) => {
this.onEvent({
eventType: 'addDir',
relativePath: this.normalizeRelativePath(relativePath),
});
})
.on('unlinkDir', (relativePath: string) => {
this.onEvent({
eventType: 'unlinkDir',
relativePath: this.normalizeRelativePath(relativePath),
});
})
.on('error', (error: unknown) => {
this.options.onError?.(error);
});
}
async close(): Promise<void> {
await this.watcher?.close();
this.watcher = null;
}
}
+15 -9
View File
@@ -31,30 +31,36 @@ describe('planUtils', () => {
describe('validatePlanPath', () => {
it('should return null for a valid path within plans directory', async () => {
const planPath = path.join('plans', 'test.md');
const fullPath = path.join(tempRootDir, planPath);
const planPath = 'test.md';
const fullPath = path.join(plansDir, planPath);
fs.writeFileSync(fullPath, '# My Plan');
const result = await validatePlanPath(planPath, plansDir);
const result = await validatePlanPath(planPath, plansDir, tempRootDir);
expect(result).toBeNull();
});
it('should return error for non-existent file', async () => {
const planPath = path.join('plans', 'ghost.md');
const result = await validatePlanPath(planPath, plansDir);
const planPath = 'ghost.md';
const result = await validatePlanPath(planPath, plansDir, tempRootDir);
expect(result).toContain('Plan file does not exist');
});
it('should detect path traversal via symbolic links', async () => {
const maliciousPath = path.join('plans', 'malicious.md');
const fullMaliciousPath = path.join(tempRootDir, maliciousPath);
const outsideFile = path.join(tempRootDir, 'outside.txt');
const maliciousPath = 'malicious.md';
const fullMaliciousPath = path.join(plansDir, maliciousPath);
// Create a file outside the plans directory
const outsideFile = path.join(tempRootDir, 'outside.md');
fs.writeFileSync(outsideFile, 'secret content');
// Create a symbolic link pointing outside the plans directory
fs.symlinkSync(outsideFile, fullMaliciousPath);
const result = await validatePlanPath(maliciousPath, plansDir);
const result = await validatePlanPath(
maliciousPath,
plansDir,
tempRootDir,
);
expect(result).toContain('Access denied');
});
});
+69 -14
View File
@@ -22,31 +22,86 @@ export const PlanErrorMessages = {
READ_FAILURE: (detail: string) => `Failed to read plan file: ${detail}`,
} as const;
/**
* Resolves a plan file path and strictly validates it against the plans directory boundary.
* Useful for tools that need to write or read plans.
* @param planPath The untrusted file path provided by the model.
* @param plansDir The authorized project plans directory.
* @returns The safely resolved path string.
* @throws Error if the path is empty, malicious, or escapes boundaries.
*/
export function resolveAndValidatePlanPath(
planPath: string,
plansDir: string,
projectRoot: string,
): string {
const trimmedPath = planPath.trim();
if (!trimmedPath) {
throw new Error('Plan file path must be non-empty.');
}
// 1. Handle case where agent provided an absolute path
if (path.isAbsolute(trimmedPath)) {
if (
isSubpath(resolveToRealPath(plansDir), resolveToRealPath(trimmedPath))
) {
return trimmedPath;
}
}
// 2. Handle case where agent provided a path relative to the project root
const resolvedFromProjectRoot = path.resolve(projectRoot, trimmedPath);
if (
isSubpath(
resolveToRealPath(plansDir),
resolveToRealPath(resolvedFromProjectRoot),
)
) {
return resolvedFromProjectRoot;
}
// 3. Handle default case where agent provided a path relative to the plans directory
const resolvedPath = path.resolve(plansDir, trimmedPath);
const realPath = resolveToRealPath(resolvedPath);
const realPlansDir = resolveToRealPath(plansDir);
if (!isSubpath(realPlansDir, realPath)) {
throw new Error(
PlanErrorMessages.PATH_ACCESS_DENIED(trimmedPath, plansDir),
);
}
return resolvedPath;
}
/**
* Validates a plan file path for safety (traversal) and existence.
* @param planPath The untrusted path to the plan file.
* @param plansDir The authorized project plans directory.
* @param targetDir The current working directory (project root).
* @param projectRoot The root directory of the project.
* @returns An error message if validation fails, or null if successful.
*/
export async function validatePlanPath(
planPath: string,
plansDir: string,
projectRoot: string,
): Promise<string | null> {
const safeFilename = path.basename(planPath);
const resolvedPath = path.join(plansDir, safeFilename);
const realPath = resolveToRealPath(resolvedPath);
const realPlansDir = resolveToRealPath(plansDir);
if (!isSubpath(realPlansDir, realPath)) {
return PlanErrorMessages.PATH_ACCESS_DENIED(planPath, realPlansDir);
try {
const resolvedPath = resolveAndValidatePlanPath(
planPath,
plansDir,
projectRoot,
);
if (!(await fileExists(resolvedPath))) {
return PlanErrorMessages.FILE_NOT_FOUND(planPath);
}
return null;
} catch {
return PlanErrorMessages.PATH_ACCESS_DENIED(
planPath,
resolveToRealPath(plansDir),
);
}
if (!(await fileExists(resolvedPath))) {
return PlanErrorMessages.FILE_NOT_FOUND(planPath);
}
return null;
}
/**
+12 -12
View File
@@ -10,10 +10,10 @@ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
* Baseline entry for a single memory test scenario.
*/
export interface MemoryBaseline {
heapUsedBytes: number;
heapTotalBytes: number;
rssBytes: number;
externalBytes: number;
heapUsedMB: number;
heapTotalMB: number;
rssMB: number;
externalMB: number;
timestamp: string;
}
@@ -61,18 +61,18 @@ export function updateBaseline(
path: string,
scenarioName: string,
measured: {
heapUsedBytes: number;
heapTotalBytes: number;
rssBytes: number;
externalBytes: number;
heapUsedMB: number;
heapTotalMB: number;
rssMB: number;
externalMB: number;
},
): void {
const baselines = loadBaselines(path);
baselines.scenarios[scenarioName] = {
heapUsedBytes: measured.heapUsedBytes,
heapTotalBytes: measured.heapTotalBytes,
rssBytes: measured.rssBytes,
externalBytes: measured.externalBytes,
heapUsedMB: measured.heapUsedMB,
heapTotalMB: measured.heapTotalMB,
rssMB: measured.rssMB,
externalMB: measured.externalMB,
timestamp: new Date().toISOString(),
};
saveBaselines(path, baselines);
+78 -166
View File
@@ -4,10 +4,9 @@
* SPDX-License-Identifier: Apache-2.0
*/
import v8 from 'node:v8';
import { setTimeout as sleep } from 'node:timers/promises';
import { loadBaselines, updateBaseline } from './memory-baselines.js';
import type { MemoryBaseline, MemoryBaselineFile } from './memory-baselines.js';
import type { TestRig } from './test-rig.js';
/** Configuration for asciichart plot function. */
interface PlotConfig {
@@ -28,9 +27,6 @@ export interface MemorySnapshot {
heapTotal: number;
rss: number;
external: number;
arrayBuffers: number;
heapSizeLimit: number;
heapSpaces: any[];
}
/**
@@ -64,16 +60,13 @@ export interface MemoryTestHarnessOptions {
gcDelayMs?: number;
/** Number of samples to take for median calculation. Default: 3 */
sampleCount?: number;
/** Pause in ms between samples. Default: 50 */
samplePauseMs?: number;
}
/**
* MemoryTestHarness provides infrastructure for running memory usage tests.
*
* It handles:
* - Forcing V8 garbage collection to reduce noise
* - Taking V8 heap snapshots for accurate memory measurement
* - Extracting memory metrics from CLI process telemetry
* - Comparing against baselines with configurable tolerance
* - Generating ASCII chart reports of memory trends
*/
@@ -81,88 +74,45 @@ export class MemoryTestHarness {
private baselines: MemoryBaselineFile;
private readonly baselinesPath: string;
private readonly defaultTolerancePercent: number;
private readonly gcCycles: number;
private readonly gcDelayMs: number;
private readonly sampleCount: number;
private readonly samplePauseMs: number;
private allResults: MemoryTestResult[] = [];
constructor(options: MemoryTestHarnessOptions) {
this.baselinesPath = options.baselinesPath;
this.defaultTolerancePercent = options.defaultTolerancePercent ?? 10;
this.gcCycles = options.gcCycles ?? 3;
this.gcDelayMs = options.gcDelayMs ?? 100;
this.sampleCount = options.sampleCount ?? 3;
this.samplePauseMs = options.samplePauseMs ?? 50;
this.baselines = loadBaselines(this.baselinesPath);
}
/**
* Force garbage collection multiple times and take a V8 heap snapshot.
* Forces GC multiple times with delays to allow weak references and
* FinalizationRegistry callbacks to run, reducing measurement noise.
* Extract memory snapshot from TestRig telemetry.
*/
async takeSnapshot(label: string = 'snapshot'): Promise<MemorySnapshot> {
await this.forceGC();
const memUsage = process.memoryUsage();
const heapStats = v8.getHeapStatistics();
return {
timestamp: Date.now(),
label,
heapUsed: memUsage.heapUsed,
heapTotal: memUsage.heapTotal,
rss: memUsage.rss,
external: memUsage.external,
arrayBuffers: memUsage.arrayBuffers,
heapSizeLimit: heapStats.heap_size_limit,
heapSpaces: v8.getHeapSpaceStatistics(),
};
}
/**
* Take multiple snapshot samples and return the median to reduce noise.
*/
async takeMedianSnapshot(
label: string = 'median',
count?: number,
async takeSnapshot(
rig: TestRig,
label: string = 'snapshot',
strategy: 'peak' | 'last' = 'last',
): Promise<MemorySnapshot> {
const samples: MemorySnapshot[] = [];
const numSamples = count ?? this.sampleCount;
for (let i = 0; i < numSamples; i++) {
samples.push(await this.takeSnapshot(`${label}_sample_${i}`));
if (i < numSamples - 1) {
await sleep(this.samplePauseMs);
}
}
// Sort by heapUsed and take the median
samples.sort((a, b) => a.heapUsed - b.heapUsed);
const medianIdx = Math.floor(samples.length / 2);
const median = samples[medianIdx]!;
const metrics = rig.readMemoryMetrics(strategy);
return {
...median,
timestamp: metrics.timestamp,
label,
timestamp: Date.now(),
heapUsed: metrics.heapUsed,
heapTotal: metrics.heapTotal,
rss: metrics.rss,
external: metrics.external,
};
}
/**
* Run a memory test scenario.
*
* Takes before/after snapshots around the scenario function, collects
* intermediate snapshots if the scenario provides them, and compares
* the result against the stored baseline.
*
* @param rig - The TestRig instance running the CLI
* @param name - Scenario name (must match baseline key)
* @param fn - Async function that executes the scenario. Receives a
* `recordSnapshot` callback for recording intermediate snapshots.
* @param tolerancePercent - Override default tolerance for this scenario
*/
async runScenario(
rig: TestRig,
name: string,
fn: (
recordSnapshot: (label: string) => Promise<MemorySnapshot>,
@@ -172,27 +122,49 @@ export class MemoryTestHarness {
const tolerance = tolerancePercent ?? this.defaultTolerancePercent;
const snapshots: MemorySnapshot[] = [];
// Record initial snapshot
const beforeSnap = await this.takeSnapshot(rig, 'before');
snapshots.push(beforeSnap);
// Record a callback for intermediate snapshots
const recordSnapshot = async (label: string): Promise<MemorySnapshot> => {
const snap = await this.takeMedianSnapshot(label);
// Small delay to allow telemetry to flush if needed
await rig.waitForTelemetryReady();
const snap = await this.takeSnapshot(rig, label);
snapshots.push(snap);
return snap;
};
// Before snapshot
const beforeSnap = await this.takeMedianSnapshot('before');
snapshots.push(beforeSnap);
// Run the scenario
await fn(recordSnapshot);
// After snapshot (median of multiple samples)
const afterSnap = await this.takeMedianSnapshot('after');
// Final wait for telemetry to ensure everything is flushed
await rig.waitForTelemetryReady();
// After snapshot
const afterSnap = await this.takeSnapshot(rig, 'after');
snapshots.push(afterSnap);
// Calculate peak values
const peakHeapUsed = Math.max(...snapshots.map((s) => s.heapUsed));
const peakRss = Math.max(...snapshots.map((s) => s.rss));
// Calculate peak values from ALL snapshots seen during the scenario
const allSnapshots = rig.readAllMemorySnapshots();
const scenarioSnapshots = allSnapshots.filter(
(s) =>
s.timestamp >= beforeSnap.timestamp &&
s.timestamp <= afterSnap.timestamp,
);
const peakHeapUsed = Math.max(
...scenarioSnapshots.map((s) => s.heapUsed),
...snapshots.map((s) => s.heapUsed),
);
const peakRss = Math.max(
...scenarioSnapshots.map((s) => s.rss),
...snapshots.map((s) => s.rss),
);
const peakExternal = Math.max(
...scenarioSnapshots.map((s) => s.external),
...snapshots.map((s) => s.external),
);
// Get baseline
const baseline = this.baselines.scenarios[name];
@@ -202,15 +174,12 @@ export class MemoryTestHarness {
let withinTolerance = true;
if (baseline) {
const measuredMB = afterSnap.heapUsed / (1024 * 1024);
deltaPercent =
((afterSnap.heapUsed - baseline.heapUsedBytes) /
baseline.heapUsedBytes) *
100;
((measuredMB - baseline.heapUsedMB) / baseline.heapUsedMB) * 100;
withinTolerance = deltaPercent <= tolerance;
}
const peakExternal = Math.max(...snapshots.map((s) => s.external));
const result: MemoryTestResult = {
scenarioName: name,
snapshots,
@@ -248,16 +217,16 @@ export class MemoryTestHarness {
return; // Don't fail if no baseline exists yet
}
const measuredMB = result.finalHeapUsed / (1024 * 1024);
const deltaPercent =
((result.finalHeapUsed - result.baseline.heapUsedBytes) /
result.baseline.heapUsedBytes) *
((measuredMB - result.baseline.heapUsedMB) / result.baseline.heapUsedMB) *
100;
if (deltaPercent > tolerance) {
throw new Error(
`Memory regression detected for "${result.scenarioName}"!\n` +
` Measured: ${formatMB(result.finalHeapUsed)} heap used\n` +
` Baseline: ${formatMB(result.baseline.heapUsedBytes)} heap used\n` +
` Baseline: ${result.baseline.heapUsedMB.toFixed(1)} MB heap used\n` +
` Delta: ${deltaPercent.toFixed(1)}% (tolerance: ${tolerance}%)\n` +
` Peak heap: ${formatMB(result.peakHeapUsed)}\n` +
` Peak RSS: ${formatMB(result.peakRss)}\n` +
@@ -270,20 +239,22 @@ export class MemoryTestHarness {
* Update the baseline for a scenario with the current measured values.
*/
updateScenarioBaseline(result: MemoryTestResult): void {
const lastSnapshot = result.snapshots[result.snapshots.length - 1];
updateBaseline(this.baselinesPath, result.scenarioName, {
heapUsedBytes: result.finalHeapUsed,
heapTotalBytes:
result.snapshots[result.snapshots.length - 1]?.heapTotal ?? 0,
rssBytes: result.finalRss,
externalBytes: result.finalExternal,
heapUsedMB: Number((result.finalHeapUsed / (1024 * 1024)).toFixed(1)),
heapTotalMB: Number(
((lastSnapshot?.heapTotal ?? 0) / (1024 * 1024)).toFixed(1),
),
rssMB: Number((result.finalRss / (1024 * 1024)).toFixed(1)),
externalMB: Number((result.finalExternal / (1024 * 1024)).toFixed(1)),
});
// Reload baselines after update
this.baselines = loadBaselines(this.baselinesPath);
}
/**
* Analyze snapshots to detect sustained leaks across 3 snapshots.
* A leak is flagged if growth is observed in both phases for any heap space.
* Analyze snapshots to detect sustained leaks.
* A leak is flagged if growth is observed in both phases.
*/
analyzeSnapshots(
snapshots: MemorySnapshot[],
@@ -297,55 +268,20 @@ export class MemoryTestHarness {
const snap2 = snapshots[snapshots.length - 2];
const snap3 = snapshots[snapshots.length - 1];
if (!snap1 || !snap2 || !snap3) {
return { leaked: false, message: 'Missing snapshots' };
}
const growth1 = snap2.heapUsed - snap1.heapUsed;
const growth2 = snap3.heapUsed - snap2.heapUsed;
const spaceNames = new Set<string>();
snap1.heapSpaces.forEach((s: any) => spaceNames.add(s.space_name));
snap2.heapSpaces.forEach((s: any) => spaceNames.add(s.space_name));
snap3.heapSpaces.forEach((s: any) => spaceNames.add(s.space_name));
const leaked = growth1 > thresholdBytes && growth2 > thresholdBytes;
let message = leaked
? `Memory bloat detected: sustained growth (${formatMB(growth1)} -> ${formatMB(growth2)})`
: `No sustained growth detected above threshold.`;
let hasSustainedGrowth = false;
const growthDetails: string[] = [];
for (const name of spaceNames) {
const size1 =
snap1.heapSpaces.find((s: any) => s.space_name === name)
?.space_used_size ?? 0;
const size2 =
snap2.heapSpaces.find((s: any) => s.space_name === name)
?.space_used_size ?? 0;
const size3 =
snap3.heapSpaces.find((s: any) => s.space_name === name)
?.space_used_size ?? 0;
const growth1 = size2 - size1;
const growth2 = size3 - size2;
if (growth1 > thresholdBytes && growth2 > thresholdBytes) {
hasSustainedGrowth = true;
growthDetails.push(
`${name}: sustained growth (${formatMB(growth1)} -> ${formatMB(growth2)})`,
);
}
}
let message = '';
if (hasSustainedGrowth) {
message =
`Memory bloat detected in heap spaces:\n ` +
growthDetails.join('\n ');
} else {
message = `No sustained growth detected in any heap space above threshold.`;
}
return { leaked: hasSustainedGrowth, message };
return { leaked, message };
}
/**
* Assert that memory returns to a baseline level after a peak.
* Useful for verifying that large tool outputs are not retained.
* Useful for verifying that large tool outputs or history are not retained.
*/
assertMemoryReturnsToBaseline(
snapshots: MemorySnapshot[],
@@ -355,26 +291,22 @@ export class MemoryTestHarness {
throw new Error('Need at least 3 snapshots to check return to baseline');
}
const baseline = snapshots[0]; // Assume first is baseline
const peak = snapshots.reduce(
(max, s) => (s.heapUsed > max.heapUsed ? s : max),
snapshots[0],
);
const final = snapshots[snapshots.length - 1];
if (!baseline || !peak || !final) {
throw new Error('Missing snapshots for return to baseline check');
// Find the first non-zero snapshot as baseline
const baseline = snapshots.find((s) => s.heapUsed > 0);
if (!baseline) {
return; // No memory reported yet
}
const final = snapshots[snapshots.length - 1]!;
const tolerance = baseline.heapUsed * (tolerancePercent / 100);
const delta = final.heapUsed - baseline.heapUsed;
if (delta > tolerance) {
throw new Error(
`Memory did not return to baseline!\n` +
` Baseline: ${formatMB(baseline.heapUsed)}\n` +
` Peak: ${formatMB(peak.heapUsed)}\n` +
` Final: ${formatMB(final.heapUsed)}\n` +
` Baseline: ${formatMB(baseline.heapUsed)} (${baseline.label})\n` +
` Final: ${formatMB(final.heapUsed)} (${final.label})\n` +
` Delta: ${formatMB(delta)} (tolerance: ${formatMB(tolerance)})`,
);
}
@@ -397,7 +329,7 @@ export class MemoryTestHarness {
for (const result of resultsToReport) {
const measured = formatMB(result.finalHeapUsed);
const baseline = result.baseline
? formatMB(result.baseline.heapUsedBytes)
? `${result.baseline.heapUsedMB.toFixed(1)} MB`
: 'N/A';
const delta = result.baseline
? `${result.deltaPercent >= 0 ? '+' : ''}${result.deltaPercent.toFixed(1)}%`
@@ -461,26 +393,6 @@ export class MemoryTestHarness {
console.log(report);
return report;
}
/**
* Force V8 garbage collection.
* Runs multiple GC cycles with delays to allow weak references
* and FinalizationRegistry callbacks to run.
*/
private async forceGC(): Promise<void> {
if (typeof globalThis.gc !== 'function') {
throw new Error(
'global.gc() not available. Run with --expose-gc for accurate measurements.',
);
}
for (let i = 0; i < this.gcCycles; i++) {
globalThis.gc();
if (i < this.gcCycles - 1) {
await sleep(this.gcDelayMs);
}
}
}
}
/**
+133 -3
View File
@@ -11,7 +11,10 @@ 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_MODEL, GEMINI_DIR } from '@google/gemini-cli-core';
import {
PREVIEW_GEMINI_FLASH_MODEL,
GEMINI_DIR,
} from '@google/gemini-cli-core';
export { GEMINI_DIR };
import * as pty from '@lydell/node-pty';
import stripAnsi from 'strip-ansi';
@@ -475,7 +478,7 @@ export class TestRig {
...(env['GEMINI_TEST_TYPE'] === 'integration'
? {
model: {
name: PREVIEW_GEMINI_MODEL,
name: PREVIEW_GEMINI_FLASH_MODEL,
},
}
: {}),
@@ -1475,7 +1478,7 @@ export class TestRig {
readMetric(metricName: string): TelemetryMetric | null {
const logs = this._readAndParseTelemetryLog();
for (const logData of logs) {
if (logData.scopeMetrics) {
if (logData && logData.scopeMetrics) {
for (const scopeMetric of logData.scopeMetrics) {
for (const metric of scopeMetric.metrics) {
if (metric.descriptor.name === `gemini_cli.${metricName}`) {
@@ -1488,6 +1491,133 @@ export class TestRig {
return null;
}
readMemoryMetrics(strategy: 'peak' | 'last' = 'peak'): {
timestamp: number;
heapUsed: number;
heapTotal: number;
rss: number;
external: number;
} {
const snapshots = this._getMemorySnapshots();
if (snapshots.length === 0) {
return {
timestamp: Date.now(),
heapUsed: 0,
heapTotal: 0,
rss: 0,
external: 0,
};
}
if (strategy === 'last') {
const last = snapshots[snapshots.length - 1];
return {
timestamp: last.timestamp,
heapUsed: last.heapUsed,
heapTotal: last.heapTotal,
rss: last.rss,
external: last.external,
};
}
// Find the snapshot with the highest RSS
let peak = snapshots[0];
for (const snapshot of snapshots) {
if (snapshot.rss > peak.rss) {
peak = snapshot;
}
}
// Fallback: if we didn't find any RSS but found heap, use the max heap
if (peak.rss === 0) {
for (const snapshot of snapshots) {
if (snapshot.heapUsed > peak.heapUsed) {
peak = snapshot;
}
}
}
return {
timestamp: peak.timestamp,
heapUsed: peak.heapUsed,
heapTotal: peak.heapTotal,
rss: peak.rss,
external: peak.external,
};
}
readAllMemorySnapshots(): {
timestamp: number;
heapUsed: number;
heapTotal: number;
rss: number;
external: number;
}[] {
return this._getMemorySnapshots();
}
private _getMemorySnapshots(): {
timestamp: number;
heapUsed: number;
heapTotal: number;
rss: number;
external: number;
}[] {
const snapshots: Record<
string,
{
timestamp: number;
heapUsed: number;
heapTotal: number;
rss: number;
external: number;
}
> = {};
const logs = this._readAndParseTelemetryLog();
for (const logData of logs) {
if (logData && logData.scopeMetrics) {
for (const scopeMetric of logData.scopeMetrics) {
for (const metric of scopeMetric.metrics) {
if (metric.descriptor.name === 'gemini_cli.memory.usage') {
for (const dp of metric.dataPoints) {
const sessionId =
(dp.attributes?.['session.id'] as string) || 'unknown';
const component =
(dp.attributes?.['component'] as string) || 'unknown';
const seconds = dp.startTime?.[0] || 0;
const nanos = dp.startTime?.[1] || 0;
const timeKey = `${sessionId}-${component}-${seconds}-${nanos}`;
if (!snapshots[timeKey]) {
snapshots[timeKey] = {
timestamp: seconds * 1000 + Math.floor(nanos / 1000000),
rss: 0,
heapUsed: 0,
heapTotal: 0,
external: 0,
};
}
const type = dp.attributes?.['memory_type'];
const value = dp.value?.max ?? dp.value?.sum ?? 0;
if (type === 'heap_used') snapshots[timeKey].heapUsed = value;
else if (type === 'heap_total')
snapshots[timeKey].heapTotal = value;
else if (type === 'rss') snapshots[timeKey].rss = value;
else if (type === 'external')
snapshots[timeKey].external = value;
}
}
}
}
}
}
return Object.values(snapshots).sort((a, b) => a.timestamp - b.timestamp);
}
async runInteractive(options?: {
args?: string | string[];
approvalMode?: 'default' | 'auto_edit' | 'yolo' | 'plan';
+34
View File
@@ -626,6 +626,29 @@
"default": "ask",
"type": "string",
"enum": ["ask", "always", "never"]
},
"vertexAi": {
"title": "Vertex AI",
"description": "Vertex AI request routing settings.",
"markdownDescription": "Vertex AI request routing settings.\n\n- Category: `Advanced`\n- Requires restart: `yes`",
"type": "object",
"properties": {
"requestType": {
"title": "Vertex AI Request Type",
"description": "Sets the X-Vertex-AI-LLM-Request-Type header for Vertex AI requests.",
"markdownDescription": "Sets the X-Vertex-AI-LLM-Request-Type header for Vertex AI requests.\n\n- Category: `Advanced`\n- Requires restart: `yes`",
"type": "string",
"enum": ["dedicated", "shared"]
},
"sharedRequestType": {
"title": "Vertex AI Shared Request Type",
"description": "Sets the X-Vertex-AI-LLM-Shared-Request-Type header for Vertex AI requests.",
"markdownDescription": "Sets the X-Vertex-AI-LLM-Shared-Request-Type header for Vertex AI requests.\n\n- Category: `Advanced`\n- Requires restart: `yes`",
"type": "string",
"enum": ["priority", "flex"]
}
},
"additionalProperties": false
}
},
"additionalProperties": false
@@ -2370,6 +2393,13 @@
"default": true,
"type": "boolean"
},
"enableFileWatcher": {
"title": "Enable File Watcher",
"description": "Enable file watcher updates for @ file suggestions (experimental).",
"markdownDescription": "Enable file watcher updates for @ file suggestions (experimental).\n\n- Category: `Context`\n- Requires restart: `yes`\n- Default: `false`",
"default": false,
"type": "boolean"
},
"enableRecursiveFileSearch": {
"title": "Enable Recursive File Search",
"description": "Enable recursive file search functionality when completing @ references in the prompt.",
@@ -3597,6 +3627,10 @@
"description": "Protocol for OTLP exporters.",
"enum": ["grpc", "http"]
},
"traces": {
"type": "boolean",
"description": "Whether detailed traces with large attributes are captured."
},
"logPrompts": {
"type": "boolean",
"description": "Whether prompts are logged in telemetry payloads."