Compare commits

...

16 Commits

Author SHA1 Message Date
gemini-cli-robot 7598ef35a8 chore(release): v0.2.2 2025-08-28 15:59:01 +00:00
Taylor Mullen 32204dcaa7 Revert "Hotfix/retry stream 6777 (#6881)"
This reverts commit 86fd6419a3.
2025-08-26 23:30:39 -07:00
Taylor Mullen d2a4abe4cc Revert "[cherrypic][hotfix] Do not call nextSpeakerCheck in case of API error (#7140)"
This reverts commit dc21a06b54.
2025-08-26 23:30:33 -07:00
Taylor Mullen 2f6cf270ec Revert "Hotfix/metrics stream error (#7156)"
This reverts commit 0910b35812.
2025-08-26 23:30:27 -07:00
gemini-cli-robot 3a8ec2d83c chore(release): v0.2.0 2025-08-27 01:16:04 +00:00
Shreya Keshive 9dd36d6310 Fix sandbox npm command (#7176) 2025-08-27 00:39:26 +00:00
Silvio Junior 0910b35812 Hotfix/metrics stream error (#7156)
Co-authored-by: Victor May <mayvic@google.com>
2025-08-26 15:28:04 -07:00
Silvio Junior dc21a06b54 [cherrypic][hotfix] Do not call nextSpeakerCheck in case of API error (#7140) 2025-08-26 16:28:13 -04:00
N. Taylor Mullen 8e4b9da54f fix(ci): allow release branches to run (#7060) (#7061) 2025-08-25 17:09:03 -07:00
Abhi 4811eef801 fix(keyboard): Implement Tab and Backspace handling for Kitty Protocol (#7006) (Cherry-pick) (#7051) 2025-08-25 15:29:57 -07:00
Jerop Kipruto d354dc1450 cherrypick workflow fixes into preview release branch (#7052) 2025-08-25 15:29:36 -07:00
Conrad Irwin daea8f3c56 Zed preview patches (#7036)
Co-authored-by: Agus Zubiaga <agus@zed.dev>
Co-authored-by: Antonio Scandurra <me@as-cii.com>
2025-08-25 14:17:06 -07:00
Silvio Junior 86fd6419a3 Hotfix/retry stream 6777 (#6881)
Co-authored-by: Victor May <mayvic@google.com>
2025-08-22 17:37:13 -04:00
Shreya Keshive dda33bb360 chore(release): v0.2.0-preview.2 (#6868)
Co-authored-by: gemini-cli-robot <gemini-cli-robot@google.com>
2025-08-22 16:04:12 -04:00
Shreya Keshive 07b7df5c7b Merge #6677 into release branch for hot fix. (#6850) 2025-08-22 14:49:37 -04:00
gemini-cli-robot b06e8dbaef chore(release): v0.2.0-preview.0 2025-08-20 02:17:59 +00:00
18 changed files with 589 additions and 201 deletions
+2 -2
View File
@@ -4,11 +4,11 @@ on:
push:
branches:
- 'main'
- 'release'
- 'release/**'
pull_request:
branches:
- 'main'
- 'release'
- 'release/**'
merge_group:
concurrency:
+3
View File
@@ -40,3 +40,6 @@ packages/cli/src/generated/
packages/core/src/generated/
.integration-tests/
packages/vscode-ide-companion/*.vsix
# GHA credentials
gha-creds-*.json
+6 -6
View File
@@ -1,12 +1,12 @@
{
"name": "@google/gemini-cli",
"version": "0.1.21",
"version": "0.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@google/gemini-cli",
"version": "0.1.21",
"version": "0.2.2",
"workspaces": [
"packages/*"
],
@@ -12474,7 +12474,7 @@
},
"packages/cli": {
"name": "@google/gemini-cli",
"version": "0.1.21",
"version": "0.2.2",
"dependencies": {
"@google/gemini-cli-core": "file:../core",
"@google/genai": "1.13.0",
@@ -12657,7 +12657,7 @@
},
"packages/core": {
"name": "@google/gemini-cli-core",
"version": "0.1.21",
"version": "0.2.2",
"dependencies": {
"@google/genai": "1.13.0",
"@modelcontextprotocol/sdk": "^1.11.0",
@@ -12776,7 +12776,7 @@
},
"packages/test-utils": {
"name": "@google/gemini-cli-test-utils",
"version": "0.1.21",
"version": "0.2.2",
"license": "Apache-2.0",
"devDependencies": {
"typescript": "^5.3.3"
@@ -12787,7 +12787,7 @@
},
"packages/vscode-ide-companion": {
"name": "gemini-cli-vscode-ide-companion",
"version": "0.1.21",
"version": "0.2.2",
"license": "LICENSE",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.15.1",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.1.21",
"version": "0.2.2",
"engines": {
"node": ">=20.0.0"
},
@@ -14,7 +14,7 @@
"url": "git+https://github.com/google-gemini/gemini-cli.git"
},
"config": {
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.21"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.2.2"
},
"scripts": {
"start": "node scripts/start.js",
@@ -36,7 +36,7 @@
"test:e2e": "cross-env VERBOSE=true KEEP_OUTPUT=true npm run test:integration:sandbox:none",
"test:integration:all": "npm run test:integration:sandbox:none && npm run test:integration:sandbox:docker && npm run test:integration:sandbox:podman",
"test:integration:sandbox:none": "GEMINI_SANDBOX=false vitest run --root ./integration-tests",
"test:integration:sandbox:docker": "npm run build:sandbox && GEMINI_SANDBOX=docker vitest run --root ./integration-tests",
"test:integration:sandbox:docker": "GEMINI_SANDBOX=docker npm run build:sandbox && GEMINI_SANDBOX=docker vitest run --root ./integration-tests",
"test:integration:sandbox:podman": "GEMINI_SANDBOX=podman vitest run --root ./integration-tests",
"lint": "eslint . --ext .ts,.tsx && eslint integration-tests",
"lint:fix": "eslint . --fix && eslint integration-tests --fix",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.1.21",
"version": "0.2.2",
"description": "Gemini CLI",
"repository": {
"type": "git",
@@ -25,7 +25,7 @@
"dist"
],
"config": {
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.21"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.2.2"
},
"dependencies": {
"@google/gemini-cli-core": "file:../core",
@@ -220,7 +220,7 @@ describe('ideCommand', () => {
}),
expect.any(Number),
);
});
}, 10000);
it('should show an error if installation fails', async () => {
mockInstall.mockResolvedValue({
+33 -4
View File
@@ -187,10 +187,6 @@ export const ideCommand = (config: Config | null): SlashCommand | null => {
);
const result = await installer.install();
if (result.success) {
config.setIdeMode(true);
context.services.settings.setValue(SettingScope.User, 'ideMode', true);
}
context.ui.addItem(
{
type: result.success ? 'info' : 'error',
@@ -198,6 +194,39 @@ export const ideCommand = (config: Config | null): SlashCommand | null => {
},
Date.now(),
);
if (result.success) {
context.services.settings.setValue(SettingScope.User, 'ideMode', true);
// Poll for up to 5 seconds for the extension to activate.
for (let i = 0; i < 10; i++) {
await config.setIdeModeAndSyncConnection(true);
if (
ideClient.getConnectionStatus().status ===
IDEConnectionStatus.Connected
) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
const { messageType, content } = getIdeStatusMessage(ideClient);
if (messageType === 'error') {
context.ui.addItem(
{
type: messageType,
text: `Failed to automatically enable IDE integration. To fix this, run the CLI in a new terminal window.`,
},
Date.now(),
);
} else {
context.ui.addItem(
{
type: messageType,
text: content,
},
Date.now(),
);
}
}
},
};
@@ -10,7 +10,11 @@ import fs from 'node:fs/promises';
import { vi, describe, expect, it, afterEach, beforeEach } from 'vitest';
import * as gitUtils from '../../utils/gitUtils.js';
import { setupGithubCommand } from './setupGithubCommand.js';
import {
setupGithubCommand,
updateGitignore,
GITHUB_WORKFLOW_PATHS,
} from './setupGithubCommand.js';
import { CommandContext, ToolActionReturn } from './types.js';
import * as commandUtils from '../utils/commandUtils.js';
@@ -51,12 +55,7 @@ describe('setupGithubCommand', async () => {
const fakeRepoRoot = scratchDir;
const fakeReleaseVersion = 'v1.2.3';
const workflows = [
'gemini-cli.yml',
'gemini-issue-automated-triage.yml',
'gemini-issue-scheduled-triage.yml',
'gemini-pr-review.yml',
];
const workflows = GITHUB_WORKFLOW_PATHS.map((p) => path.basename(p));
for (const workflow of workflows) {
vi.mocked(global.fetch).mockReturnValueOnce(
Promise.resolve(new Response(workflow)),
@@ -102,5 +101,138 @@ describe('setupGithubCommand', async () => {
const contents = await fs.readFile(workflowFile, 'utf8');
expect(contents).toContain(workflow);
}
// Verify that .gitignore was created with the expected entries
const gitignorePath = path.join(scratchDir, '.gitignore');
const gitignoreExists = await fs
.access(gitignorePath)
.then(() => true)
.catch(() => false);
expect(gitignoreExists).toBe(true);
if (gitignoreExists) {
const gitignoreContent = await fs.readFile(gitignorePath, 'utf8');
expect(gitignoreContent).toContain('.gemini/');
expect(gitignoreContent).toContain('gha-creds-*.json');
}
});
});
describe('updateGitignore', () => {
let scratchDir = '';
beforeEach(async () => {
scratchDir = await fs.mkdtemp(path.join(os.tmpdir(), 'update-gitignore-'));
});
afterEach(async () => {
if (scratchDir) await fs.rm(scratchDir, { recursive: true });
});
it('creates a new .gitignore file when none exists', async () => {
await updateGitignore(scratchDir);
const gitignorePath = path.join(scratchDir, '.gitignore');
const content = await fs.readFile(gitignorePath, 'utf8');
expect(content).toBe('.gemini/\ngha-creds-*.json\n');
});
it('appends entries to existing .gitignore file', async () => {
const gitignorePath = path.join(scratchDir, '.gitignore');
const existingContent = '# Existing content\nnode_modules/\n';
await fs.writeFile(gitignorePath, existingContent);
await updateGitignore(scratchDir);
const content = await fs.readFile(gitignorePath, 'utf8');
expect(content).toBe(
'# Existing content\nnode_modules/\n\n.gemini/\ngha-creds-*.json\n',
);
});
it('does not add duplicate entries', async () => {
const gitignorePath = path.join(scratchDir, '.gitignore');
const existingContent = '.gemini/\nsome-other-file\ngha-creds-*.json\n';
await fs.writeFile(gitignorePath, existingContent);
await updateGitignore(scratchDir);
const content = await fs.readFile(gitignorePath, 'utf8');
expect(content).toBe(existingContent);
});
it('adds only missing entries when some already exist', async () => {
const gitignorePath = path.join(scratchDir, '.gitignore');
const existingContent = '.gemini/\nsome-other-file\n';
await fs.writeFile(gitignorePath, existingContent);
await updateGitignore(scratchDir);
const content = await fs.readFile(gitignorePath, 'utf8');
// Should add only the missing gha-creds-*.json entry
expect(content).toBe('.gemini/\nsome-other-file\n\ngha-creds-*.json\n');
expect(content).toContain('gha-creds-*.json');
// Should not duplicate .gemini/ entry
expect((content.match(/\.gemini\//g) || []).length).toBe(1);
});
it('does not get confused by entries in comments or as substrings', async () => {
const gitignorePath = path.join(scratchDir, '.gitignore');
const existingContent = [
'# This is a comment mentioning .gemini/ folder',
'my-app.gemini/config',
'# Another comment with gha-creds-*.json pattern',
'some-other-gha-creds-file.json',
'',
].join('\n');
await fs.writeFile(gitignorePath, existingContent);
await updateGitignore(scratchDir);
const content = await fs.readFile(gitignorePath, 'utf8');
// Should add both entries since they don't actually exist as gitignore rules
expect(content).toContain('.gemini/');
expect(content).toContain('gha-creds-*.json');
// Verify the entries were added (not just mentioned in comments)
const lines = content
.split('\n')
.map((line) => line.split('#')[0].trim())
.filter((line) => line);
expect(lines).toContain('.gemini/');
expect(lines).toContain('gha-creds-*.json');
expect(lines).toContain('my-app.gemini/config');
expect(lines).toContain('some-other-gha-creds-file.json');
});
it('handles file system errors gracefully', async () => {
// Try to update gitignore in a non-existent directory
const nonExistentDir = path.join(scratchDir, 'non-existent');
// This should not throw an error
await expect(updateGitignore(nonExistentDir)).resolves.toBeUndefined();
});
it('handles permission errors gracefully', async () => {
const consoleSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
const fsModule = await import('node:fs');
const writeFileSpy = vi
.spyOn(fsModule.promises, 'writeFile')
.mockRejectedValue(new Error('Permission denied'));
await expect(updateGitignore(scratchDir)).resolves.toBeUndefined();
expect(consoleSpy).toHaveBeenCalledWith(
'Failed to update .gitignore:',
expect.any(Error),
);
writeFileSpy.mockRestore();
consoleSpy.mockRestore();
});
});
@@ -24,6 +24,14 @@ import {
} from './types.js';
import { getUrlOpenCommand } from '../../ui/utils/commandUtils.js';
export const GITHUB_WORKFLOW_PATHS = [
'gemini-dispatch/gemini-dispatch.yml',
'gemini-assistant/gemini-invoke.yml',
'issue-triage/gemini-triage.yml',
'issue-triage/gemini-scheduled-triage.yml',
'pr-review/gemini-review.yml',
];
// Generate OS-specific commands to open the GitHub pages needed for setup.
function getOpenUrlsCommands(readmeUrl: string): string[] {
// Determine the OS-specific command to open URLs, ex: 'open', 'xdg-open', etc
@@ -44,6 +52,46 @@ function getOpenUrlsCommands(readmeUrl: string): string[] {
return commands;
}
// Add Gemini CLI specific entries to .gitignore file
export async function updateGitignore(gitRepoRoot: string): Promise<void> {
const gitignoreEntries = ['.gemini/', 'gha-creds-*.json'];
const gitignorePath = path.join(gitRepoRoot, '.gitignore');
try {
// Check if .gitignore exists and read its content
let existingContent = '';
let fileExists = true;
try {
existingContent = await fs.promises.readFile(gitignorePath, 'utf8');
} catch (_error) {
// File doesn't exist
fileExists = false;
}
if (!fileExists) {
// Create new .gitignore file with the entries
const contentToWrite = gitignoreEntries.join('\n') + '\n';
await fs.promises.writeFile(gitignorePath, contentToWrite);
} else {
// Check which entries are missing
const missingEntries = gitignoreEntries.filter(
(entry) =>
!existingContent
.split(/\r?\n/)
.some((line) => line.split('#')[0].trim() === entry),
);
if (missingEntries.length > 0) {
const contentToAdd = '\n' + missingEntries.join('\n') + '\n';
await fs.promises.appendFile(gitignorePath, contentToAdd);
}
}
} catch (error) {
console.debug('Failed to update .gitignore:', error);
// Continue without failing the whole command
}
}
export const setupGithubCommand: SlashCommand = {
name: 'setup-github',
description: 'Set up GitHub Actions',
@@ -91,15 +139,8 @@ export const setupGithubCommand: SlashCommand = {
// Download each workflow in parallel - there aren't enough files to warrant
// a full workerpool model here.
const workflows = [
'gemini-cli/gemini-cli.yml',
'issue-triage/gemini-issue-automated-triage.yml',
'issue-triage/gemini-issue-scheduled-triage.yml',
'pr-review/gemini-pr-review.yml',
];
const downloads = [];
for (const workflow of workflows) {
for (const workflow of GITHUB_WORKFLOW_PATHS) {
downloads.push(
(async () => {
const endpoint = `https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/${releaseTag}/examples/workflows/${workflow}`;
@@ -146,11 +187,14 @@ export const setupGithubCommand: SlashCommand = {
abortController.abort();
});
// Add entries to .gitignore file
await updateGitignore(gitRepoRoot);
// Print out a message
const commands = [];
commands.push('set -eEuo pipefail');
commands.push(
`echo "Successfully downloaded ${workflows.length} workflows. Follow the steps in ${readmeUrl} (skipping the /setup-github step) to complete setup."`,
`echo "Successfully downloaded ${GITHUB_WORKFLOW_PATHS.length} workflows and updated .gitignore. Follow the steps in ${readmeUrl} (skipping the /setup-github step) to complete setup."`,
);
commands.push(...getOpenUrlsCommands(readmeUrl));
@@ -17,6 +17,8 @@ import { EventEmitter } from 'events';
import {
KITTY_KEYCODE_ENTER,
KITTY_KEYCODE_NUMPAD_ENTER,
KITTY_KEYCODE_TAB,
KITTY_KEYCODE_BACKSPACE,
} from '../utils/platformConstants.js';
// Mock the 'ink' module to control stdin
@@ -278,10 +280,86 @@ describe('KeypressContext - Kitty Protocol', () => {
});
});
describe('Tab and Backspace handling', () => {
it('should recognize Tab key in kitty protocol', async () => {
const keyHandler = vi.fn();
const { result } = renderHook(() => useKeypressContext(), { wrapper });
act(() => result.current.subscribe(keyHandler));
act(() => {
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_TAB}u`);
});
expect(keyHandler).toHaveBeenCalledWith(
expect.objectContaining({
name: 'tab',
kittyProtocol: true,
shift: false,
}),
);
});
it('should recognize Shift+Tab in kitty protocol', async () => {
const keyHandler = vi.fn();
const { result } = renderHook(() => useKeypressContext(), { wrapper });
act(() => result.current.subscribe(keyHandler));
// Modifier 2 is Shift
act(() => {
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_TAB};2u`);
});
expect(keyHandler).toHaveBeenCalledWith(
expect.objectContaining({
name: 'tab',
kittyProtocol: true,
shift: true,
}),
);
});
it('should recognize Backspace key in kitty protocol', async () => {
const keyHandler = vi.fn();
const { result } = renderHook(() => useKeypressContext(), { wrapper });
act(() => result.current.subscribe(keyHandler));
act(() => {
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_BACKSPACE}u`);
});
expect(keyHandler).toHaveBeenCalledWith(
expect.objectContaining({
name: 'backspace',
kittyProtocol: true,
meta: false,
}),
);
});
it('should recognize Option+Backspace in kitty protocol', async () => {
const keyHandler = vi.fn();
const { result } = renderHook(() => useKeypressContext(), { wrapper });
act(() => result.current.subscribe(keyHandler));
// Modifier 3 is Alt/Option
act(() => {
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_BACKSPACE};3u`);
});
expect(keyHandler).toHaveBeenCalledWith(
expect.objectContaining({
name: 'backspace',
kittyProtocol: true,
meta: true,
}),
);
});
});
describe('paste mode', () => {
it('should handle multiline paste as a single event', async () => {
const keyHandler = vi.fn();
const pastedText = 'This \nis \na \nmultiline \npaste.';
const pastedText = 'This \n is \n a \n multiline \n paste.';
const { result } = renderHook(() => useKeypressContext(), {
wrapper,
@@ -22,8 +22,10 @@ import { PassThrough } from 'stream';
import {
BACKSLASH_ENTER_DETECTION_WINDOW_MS,
KITTY_CTRL_C,
KITTY_KEYCODE_BACKSPACE,
KITTY_KEYCODE_ENTER,
KITTY_KEYCODE_NUMPAD_ENTER,
KITTY_KEYCODE_TAB,
MAX_KITTY_SEQUENCE_LENGTH,
} from '../utils/platformConstants.js';
@@ -134,6 +136,30 @@ export function KeypressProvider({
};
}
if (keyCode === KITTY_KEYCODE_TAB) {
return {
name: 'tab',
ctrl,
meta: alt,
shift,
paste: false,
sequence,
kittyProtocol: true,
};
}
if (keyCode === KITTY_KEYCODE_BACKSPACE) {
return {
name: 'backspace',
ctrl,
meta: alt,
shift,
paste: false,
sequence,
kittyProtocol: true,
};
}
if (
keyCode === KITTY_KEYCODE_ENTER ||
keyCode === KITTY_KEYCODE_NUMPAD_ENTER
@@ -22,6 +22,8 @@ export const KITTY_CTRL_C = '[99;5u';
*/
export const KITTY_KEYCODE_ENTER = 13;
export const KITTY_KEYCODE_NUMPAD_ENTER = 57414;
export const KITTY_KEYCODE_TAB = 9;
export const KITTY_KEYCODE_BACKSPACE = 127;
/**
* Timing constants for terminal interactions
+10 -1
View File
@@ -84,6 +84,8 @@ export type AgentCapabilities = z.infer<typeof agentCapabilitiesSchema>;
export type AuthMethod = z.infer<typeof authMethodSchema>;
export type PromptCapabilities = z.infer<typeof promptCapabilitiesSchema>;
export type ClientResponse = z.infer<typeof clientResponseSchema>;
export type ClientNotification = z.infer<typeof clientNotificationSchema>;
@@ -270,8 +272,15 @@ export const mcpServerSchema = z.object({
name: z.string(),
});
export const promptCapabilitiesSchema = z.object({
audio: z.boolean().optional(),
embeddedContext: z.boolean().optional(),
image: z.boolean().optional(),
});
export const agentCapabilitiesSchema = z.object({
loadSession: z.boolean(),
loadSession: z.boolean().optional(),
promptCapabilities: promptCapabilitiesSchema.optional(),
});
export const authMethodSchema = z.object({
+210 -156
View File
@@ -99,6 +99,11 @@ class GeminiAgent {
authMethods,
agentCapabilities: {
loadSession: false,
promptCapabilities: {
image: true,
audio: true,
embeddedContext: true,
},
},
};
}
@@ -374,74 +379,75 @@ class Session {
);
}
const invocation = tool.build(args);
const confirmationDetails =
await invocation.shouldConfirmExecute(abortSignal);
try {
const invocation = tool.build(args);
if (confirmationDetails) {
const content: acp.ToolCallContent[] = [];
const confirmationDetails =
await invocation.shouldConfirmExecute(abortSignal);
if (confirmationDetails.type === 'edit') {
content.push({
type: 'diff',
path: confirmationDetails.fileName,
oldText: confirmationDetails.originalContent,
newText: confirmationDetails.newContent,
if (confirmationDetails) {
const content: acp.ToolCallContent[] = [];
if (confirmationDetails.type === 'edit') {
content.push({
type: 'diff',
path: confirmationDetails.fileName,
oldText: confirmationDetails.originalContent,
newText: confirmationDetails.newContent,
});
}
const params: acp.RequestPermissionRequest = {
sessionId: this.id,
options: toPermissionOptions(confirmationDetails),
toolCall: {
toolCallId: callId,
status: 'pending',
title: invocation.getDescription(),
content,
locations: invocation.toolLocations(),
kind: tool.kind,
},
};
const output = await this.client.requestPermission(params);
const outcome =
output.outcome.outcome === 'cancelled'
? ToolConfirmationOutcome.Cancel
: z
.nativeEnum(ToolConfirmationOutcome)
.parse(output.outcome.optionId);
await confirmationDetails.onConfirm(outcome);
switch (outcome) {
case ToolConfirmationOutcome.Cancel:
return errorResponse(
new Error(`Tool "${fc.name}" was canceled by the user.`),
);
case ToolConfirmationOutcome.ProceedOnce:
case ToolConfirmationOutcome.ProceedAlways:
case ToolConfirmationOutcome.ProceedAlwaysServer:
case ToolConfirmationOutcome.ProceedAlwaysTool:
case ToolConfirmationOutcome.ModifyWithEditor:
break;
default: {
const resultOutcome: never = outcome;
throw new Error(`Unexpected: ${resultOutcome}`);
}
}
} else {
await this.sendUpdate({
sessionUpdate: 'tool_call',
toolCallId: callId,
status: 'in_progress',
title: invocation.getDescription(),
content: [],
locations: invocation.toolLocations(),
kind: tool.kind,
});
}
const params: acp.RequestPermissionRequest = {
sessionId: this.id,
options: toPermissionOptions(confirmationDetails),
toolCall: {
toolCallId: callId,
status: 'pending',
title: invocation.getDescription(),
content,
locations: invocation.toolLocations(),
kind: tool.kind,
},
};
const output = await this.client.requestPermission(params);
const outcome =
output.outcome.outcome === 'cancelled'
? ToolConfirmationOutcome.Cancel
: z
.nativeEnum(ToolConfirmationOutcome)
.parse(output.outcome.optionId);
await confirmationDetails.onConfirm(outcome);
switch (outcome) {
case ToolConfirmationOutcome.Cancel:
return errorResponse(
new Error(`Tool "${fc.name}" was canceled by the user.`),
);
case ToolConfirmationOutcome.ProceedOnce:
case ToolConfirmationOutcome.ProceedAlways:
case ToolConfirmationOutcome.ProceedAlwaysServer:
case ToolConfirmationOutcome.ProceedAlwaysTool:
case ToolConfirmationOutcome.ModifyWithEditor:
break;
default: {
const resultOutcome: never = outcome;
throw new Error(`Unexpected: ${resultOutcome}`);
}
}
} else {
await this.sendUpdate({
sessionUpdate: 'tool_call',
toolCallId: callId,
status: 'in_progress',
title: invocation.getDescription(),
content: [],
locations: invocation.toolLocations(),
kind: tool.kind,
});
}
try {
const toolResult: ToolResult = await invocation.execute(abortSignal);
const content = toToolCallContent(toolResult);
@@ -488,45 +494,59 @@ class Session {
message: acp.ContentBlock[],
abortSignal: AbortSignal,
): Promise<Part[]> {
const FILE_URI_SCHEME = 'file://';
const embeddedContext: acp.EmbeddedResourceResource[] = [];
const parts = message.map((part) => {
switch (part.type) {
case 'text':
return { text: part.text };
case 'resource_link':
case 'image':
case 'audio':
return {
fileData: {
mimeData: part.mimeType,
name: part.name,
fileUri: part.uri,
inlineData: {
mimeType: part.mimeType,
data: part.data,
},
};
case 'resource_link': {
if (part.uri.startsWith(FILE_URI_SCHEME)) {
return {
fileData: {
mimeData: part.mimeType,
name: part.name,
fileUri: part.uri.slice(FILE_URI_SCHEME.length),
},
};
} else {
return { text: `@${part.uri}` };
}
}
case 'resource': {
return {
fileData: {
mimeData: part.resource.mimeType,
name: part.resource.uri,
fileUri: part.resource.uri,
},
};
embeddedContext.push(part.resource);
return { text: `@${part.resource.uri}` };
}
default: {
throw new Error(`Unexpected chunk type: '${part.type}'`);
const unreachable: never = part;
throw new Error(`Unexpected chunk type: '${unreachable}'`);
}
}
});
const atPathCommandParts = parts.filter((part) => 'fileData' in part);
if (atPathCommandParts.length === 0) {
if (atPathCommandParts.length === 0 && embeddedContext.length === 0) {
return parts;
}
const atPathToResolvedSpecMap = new Map<string, string>();
// Get centralized file discovery service
const fileDiscovery = this.config.getFileService();
const respectGitIgnore = this.config.getFileFilteringRespectGitIgnore();
const pathSpecsToRead: string[] = [];
const atPathToResolvedSpecMap = new Map<string, string>();
const contentLabelsForDisplay: string[] = [];
const ignoredPaths: string[] = [];
@@ -634,6 +654,7 @@ class Session {
contentLabelsForDisplay.push(pathName);
}
}
// Construct the initial part of the query for the LLM
let initialQueryText = '';
for (let i = 0; i < parts.length; i++) {
@@ -687,94 +708,123 @@ class Session {
`Ignored ${ignoredPaths.length} ${ignoreType} files: ${ignoredPaths.join(', ')}`,
);
}
// Fallback for lone "@" or completely invalid @-commands resulting in empty initialQueryText
if (pathSpecsToRead.length === 0) {
const processedQueryParts: Part[] = [{ text: initialQueryText }];
if (pathSpecsToRead.length === 0 && embeddedContext.length === 0) {
// Fallback for lone "@" or completely invalid @-commands resulting in empty initialQueryText
console.warn('No valid file paths found in @ commands to read.');
return [{ text: initialQueryText }];
}
const processedQueryParts: Part[] = [{ text: initialQueryText }];
const toolArgs = {
paths: pathSpecsToRead,
respectGitIgnore, // Use configuration setting
};
const callId = `${readManyFilesTool.name}-${Date.now()}`;
try {
const invocation = readManyFilesTool.build(toolArgs);
await this.sendUpdate({
sessionUpdate: 'tool_call',
toolCallId: callId,
status: 'in_progress',
title: invocation.getDescription(),
content: [],
locations: invocation.toolLocations(),
kind: readManyFilesTool.kind,
});
const result = await invocation.execute(abortSignal);
const content = toToolCallContent(result) || {
type: 'content',
content: {
type: 'text',
text: `Successfully read: ${contentLabelsForDisplay.join(', ')}`,
},
if (pathSpecsToRead.length > 0) {
const toolArgs = {
paths: pathSpecsToRead,
respectGitIgnore, // Use configuration setting
};
await this.sendUpdate({
sessionUpdate: 'tool_call_update',
toolCallId: callId,
status: 'completed',
content: content ? [content] : [],
});
if (Array.isArray(result.llmContent)) {
const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
processedQueryParts.push({
text: '\n--- Content from referenced files ---',
const callId = `${readManyFilesTool.name}-${Date.now()}`;
try {
const invocation = readManyFilesTool.build(toolArgs);
await this.sendUpdate({
sessionUpdate: 'tool_call',
toolCallId: callId,
status: 'in_progress',
title: invocation.getDescription(),
content: [],
locations: invocation.toolLocations(),
kind: readManyFilesTool.kind,
});
for (const part of result.llmContent) {
if (typeof part === 'string') {
const match = fileContentRegex.exec(part);
if (match) {
const filePathSpecInContent = match[1]; // This is a resolved pathSpec
const fileActualContent = match[2].trim();
processedQueryParts.push({
text: `\nContent from @${filePathSpecInContent}:\n`,
});
processedQueryParts.push({ text: fileActualContent });
} else {
processedQueryParts.push({ text: part });
}
} else {
// part is a Part object.
processedQueryParts.push(part);
}
}
processedQueryParts.push({ text: '\n--- End of content ---' });
} else {
console.warn(
'read_many_files tool returned no content or empty content.',
);
}
return processedQueryParts;
} catch (error: unknown) {
await this.sendUpdate({
sessionUpdate: 'tool_call_update',
toolCallId: callId,
status: 'failed',
content: [
{
type: 'content',
content: {
type: 'text',
text: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`,
},
const result = await invocation.execute(abortSignal);
const content = toToolCallContent(result) || {
type: 'content',
content: {
type: 'text',
text: `Successfully read: ${contentLabelsForDisplay.join(', ')}`,
},
],
};
await this.sendUpdate({
sessionUpdate: 'tool_call_update',
toolCallId: callId,
status: 'completed',
content: content ? [content] : [],
});
if (Array.isArray(result.llmContent)) {
const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
processedQueryParts.push({
text: '\n--- Content from referenced files ---',
});
for (const part of result.llmContent) {
if (typeof part === 'string') {
const match = fileContentRegex.exec(part);
if (match) {
const filePathSpecInContent = match[1]; // This is a resolved pathSpec
const fileActualContent = match[2].trim();
processedQueryParts.push({
text: `\nContent from @${filePathSpecInContent}:\n`,
});
processedQueryParts.push({ text: fileActualContent });
} else {
processedQueryParts.push({ text: part });
}
} else {
// part is a Part object.
processedQueryParts.push(part);
}
}
} else {
console.warn(
'read_many_files tool returned no content or empty content.',
);
}
} catch (error: unknown) {
await this.sendUpdate({
sessionUpdate: 'tool_call_update',
toolCallId: callId,
status: 'failed',
content: [
{
type: 'content',
content: {
type: 'text',
text: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`,
},
},
],
});
throw error;
}
}
if (embeddedContext.length > 0) {
processedQueryParts.push({
text: '\n--- Content from referenced context ---',
});
throw error;
for (const contextPart of embeddedContext) {
processedQueryParts.push({
text: `\nContent from @${contextPart.uri}:\n`,
});
if ('text' in contextPart) {
processedQueryParts.push({
text: contextPart.text,
});
} else {
processedQueryParts.push({
inlineData: {
mimeType: contextPart.mimeType ?? 'application/octet-stream',
data: contextPart.blob,
},
});
}
}
}
return processedQueryParts;
}
debug(msg: string) {
@@ -785,6 +835,10 @@ class Session {
}
function toToolCallContent(toolResult: ToolResult): acp.ToolCallContent | null {
if (toolResult.error?.message) {
throw new Error(toolResult.error.message);
}
if (toolResult.returnDisplay) {
if (typeof toolResult.returnDisplay === 'string') {
return {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-core",
"version": "0.1.21",
"version": "0.2.2",
"description": "Gemini CLI Core",
"repository": {
"type": "git",
+17 -6
View File
@@ -104,8 +104,13 @@ export class IdeClient {
this.setState(IDEConnectionStatus.Connecting);
const ideInfoFromFile = await this.getIdeInfoFromFile();
const workspacePath =
ideInfoFromFile.workspacePath ??
process.env['GEMINI_CLI_IDE_WORKSPACE_PATH'];
const { isValid, error } = IdeClient.validateWorkspacePath(
process.env['GEMINI_CLI_IDE_WORKSPACE_PATH'],
workspacePath,
this.currentIdeDisplayName,
process.cwd(),
);
@@ -115,7 +120,7 @@ export class IdeClient {
return;
}
const portFromFile = await this.getPortFromFile();
const portFromFile = ideInfoFromFile.port;
if (portFromFile) {
const connected = await this.establishConnection(portFromFile);
if (connected) {
@@ -311,7 +316,10 @@ export class IdeClient {
return port;
}
private async getPortFromFile(): Promise<string | undefined> {
private async getIdeInfoFromFile(): Promise<{
port?: string;
workspacePath?: string;
}> {
try {
const ideProcessId = await getIdeProcessId();
const portFile = path.join(
@@ -319,10 +327,13 @@ export class IdeClient {
`gemini-ide-server-${ideProcessId}.json`,
);
const portFileContents = await fs.promises.readFile(portFile, 'utf8');
const port = JSON.parse(portFileContents).port;
return port.toString();
const ideInfo = JSON.parse(portFileContents);
return {
port: ideInfo?.port?.toString(),
workspacePath: ideInfo?.workspacePath,
};
} catch (_) {
return undefined;
return {};
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-test-utils",
"version": "0.1.21",
"version": "0.2.2",
"private": true,
"main": "src/index.ts",
"license": "Apache-2.0",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "gemini-cli-vscode-ide-companion",
"displayName": "Gemini CLI Companion",
"description": "Enable Gemini CLI with direct access to your IDE workspace.",
"version": "0.1.21",
"version": "0.2.2",
"publisher": "google",
"icon": "assets/icon.png",
"repository": {