0
# Gemini CLI Core
1
2
Gemini CLI Core is a comprehensive TypeScript library that provides the foundational components for building AI-powered applications with Google's Gemini models. It offers a complete toolkit for content generation, tool execution, configuration management, and IDE integration, making it the core engine for sophisticated AI agent implementations.
3
4
## Package Information
5
6
- **Package Name**: @google/gemini-cli-core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Version**: 0.5.4
10
- **Installation**: `npm install @google/gemini-cli-core`
11
12
## Core Imports
13
14
```typescript
15
// Main client and configuration
16
import { GeminiClient, Config } from '@google/gemini-cli-core';
17
18
// Content generation
19
import {
20
createContentGenerator,
21
createContentGeneratorConfig,
22
AuthType
23
} from '@google/gemini-cli-core';
24
25
// Tools and utilities
26
import {
27
DeclarativeTool,
28
BaseToolInvocation,
29
ToolResult
30
} from '@google/gemini-cli-core';
31
32
// Services
33
import {
34
FileDiscoveryService,
35
Storage
36
} from '@google/gemini-cli-core';
37
```
38
39
CommonJS:
40
```javascript
41
const {
42
GeminiClient,
43
Config,
44
createContentGenerator
45
} = require('@google/gemini-cli-core');
46
```
47
48
## Basic Usage
49
50
```typescript
51
import {
52
Config,
53
GeminiClient,
54
AuthType
55
} from '@google/gemini-cli-core';
56
57
// Initialize configuration with required parameters
58
const config = new Config({
59
sessionId: 'example-session',
60
targetDir: process.cwd(),
61
debugMode: false,
62
cwd: process.cwd(),
63
model: 'gemini-1.5-flash'
64
});
65
66
// Initialize configuration and client
67
await config.initialize();
68
const client = config.getGeminiClient();
69
70
// Generate content with proper parameters
71
const contents = [{
72
role: 'user' as const,
73
parts: [{ text: 'Explain quantum computing' }]
74
}];
75
76
const response = await client.generateContent(
77
contents,
78
{}, // generation config
79
new AbortController().signal,
80
'gemini-1.5-flash'
81
);
82
83
console.log(response.text());
84
85
// Use chat session
86
const chat = await client.startChat();
87
const result = await chat.sendMessage(
88
{ message: 'List files in the current directory' },
89
'prompt-id-123'
90
);
91
```
92
93
## Architecture
94
95
Gemini CLI Core is built around several key architectural components:
96
97
- **Configuration System**: Centralized configuration management with support for multiple authentication methods, tool approval modes, and extensibility
98
- **Content Generation Layer**: Abstracted content generation with support for multiple providers (Gemini API, Vertex AI, Cloud Shell)
99
- **Tool Execution Framework**: Declarative tool system with validation, confirmation workflows, and extensible tool registry
100
- **Chat Management**: Stateful conversation handling with history management, compression, and turn-based execution
101
- **Service Architecture**: Modular services for file discovery, git operations, shell execution, and IDE integration
102
- **Telemetry System**: Comprehensive logging and metrics collection with OpenTelemetry integration
103
104
## Capabilities
105
106
### Configuration and Setup
107
108
Comprehensive configuration management with support for different authentication methods, tool approval modes, and extensibility settings.
109
110
```typescript { .api }
111
class Config {
112
constructor(parameters?: ConfigParameters);
113
114
// Core configuration methods
115
getModel(): string;
116
setModel(model: string): void;
117
getApiKey(): string | undefined;
118
setApiKey(key: string): void;
119
}
120
121
enum AuthType {
122
LOGIN_WITH_GOOGLE = 'oauth-personal',
123
USE_GEMINI = 'gemini-api-key',
124
USE_VERTEX_AI = 'vertex-ai',
125
CLOUD_SHELL = 'cloud-shell'
126
}
127
128
enum ApprovalMode {
129
DEFAULT = 'default',
130
AUTO_EDIT = 'autoEdit',
131
YOLO = 'yolo'
132
}
133
```
134
135
[Configuration](./configuration.md)
136
137
### Core AI Functionality
138
139
Powerful AI content generation and chat management with streaming support, tool integration, and conversation history management.
140
141
```typescript { .api }
142
class GeminiClient {
143
constructor(config: Config);
144
145
initialize(): Promise<void>;
146
isInitialized(): boolean;
147
startChat(extraHistory?: Content[]): Promise<GeminiChat>;
148
generateContent(
149
contents: Content[],
150
generationConfig: GenerateContentConfig,
151
abortSignal: AbortSignal,
152
model: string
153
): Promise<GenerateContentResponse>;
154
generateJson<T>(
155
contents: Content[],
156
schema: Record<string, unknown>,
157
abortSignal: AbortSignal,
158
model: string,
159
generationConfig?: GenerateContentConfig
160
): Promise<T>;
161
sendMessageStream(message: string): AsyncGenerator<GeminiEvent>;
162
}
163
164
class GeminiChat {
165
sendMessage(message: string | Part[]): Promise<GenerateContentResult>;
166
sendMessageStream(message: string | Part[]): AsyncGenerator<EnhancedGenerateContentResponse>;
167
getHistory(curated?: boolean): Content[];
168
setTools(tools: Tool[]): void;
169
}
170
```
171
172
[Core AI Functionality](./core-ai.md)
173
174
### Tools and Extensions
175
176
Extensible tool system for file operations, shell commands, web operations, and custom tool development.
177
178
```typescript { .api }
179
abstract class DeclarativeTool<TParams = any, TResult = any> {
180
abstract readonly name: string;
181
abstract readonly description: string;
182
abstract readonly parameters: object;
183
184
abstract invoke(params: TParams): Promise<ToolResult<TResult>>;
185
}
186
187
interface ToolResult<T = any> {
188
result: T;
189
confirmationState?: ToolConfirmationOutcome;
190
displayResult?: ToolResultDisplay;
191
}
192
193
enum Kind {
194
Read = 'Read',
195
Edit = 'Edit',
196
Delete = 'Delete',
197
Move = 'Move',
198
Search = 'Search',
199
Execute = 'Execute',
200
Think = 'Think',
201
Fetch = 'Fetch',
202
Other = 'Other'
203
}
204
```
205
206
[Tools and Extensions](./tools.md)
207
208
### Services and Utilities
209
210
Comprehensive service layer for file discovery, git operations, shell execution, and system integration.
211
212
```typescript { .api }
213
class FileDiscoveryService {
214
filterFiles(filePaths: string[], options?: FilterFilesOptions): string[];
215
shouldIgnoreFile(filePath: string, options?: FilterFilesOptions): boolean;
216
getGeminiIgnorePatterns(): string[];
217
}
218
219
class Storage {
220
static getGlobalGeminiDir(): string;
221
static getGlobalSettingsPath(): string;
222
223
getGeminiDir(): string;
224
getProjectRoot(): string;
225
getHistoryDir(): string;
226
}
227
```
228
229
[Services and Utilities](./services.md)
230
231
### IDE Integration
232
233
Deep integration capabilities for IDEs with context awareness, file monitoring, and installation utilities.
234
235
```typescript { .api }
236
interface IdeContext {
237
files: File[];
238
cwd: string;
239
}
240
241
interface File {
242
name: string;
243
path: string;
244
content: string;
245
cursor?: { line: number; column: number };
246
}
247
```
248
249
[IDE Integration](./ide-integration.md)
250
251
### MCP and OAuth
252
253
Model Context Protocol support with OAuth authentication for secure server integrations.
254
255
```typescript { .api }
256
class MCPOAuthProvider {
257
authenticate(
258
serverName: string,
259
config: MCPOAuthConfig,
260
mcpServerUrl?: string
261
): Promise<OAuthToken>;
262
263
getValidToken(serverName: string, config: MCPOAuthConfig): Promise<string | null>;
264
}
265
266
interface MCPOAuthConfig {
267
authorizationUrl: string;
268
tokenUrl: string;
269
clientId: string;
270
scopes?: string[];
271
}
272
```
273
274
[MCP and OAuth](./mcp-oauth.md)
275
276
### Error Handling and Utilities
277
278
Robust error handling system with specialized error types and utility functions for common operations.
279
280
```typescript { .api }
281
class FatalError extends Error {
282
constructor(message: string);
283
}
284
285
class FatalAuthenticationError extends FatalError {}
286
class FatalInputError extends FatalError {}
287
class FatalConfigError extends FatalError {}
288
289
function getErrorMessage(error: unknown): string;
290
function toFriendlyError(error: unknown): unknown;
291
```
292
293
[Error Handling and Utilities](./utilities.md)
294
295
### Telemetry and Monitoring
296
297
Comprehensive telemetry system with OpenTelemetry integration for monitoring AI interactions and system performance.
298
299
```typescript { .api }
300
enum TelemetryTarget {
301
GCP = 'GCP',
302
LOCAL = 'LOCAL'
303
}
304
305
function initializeTelemetry(target: TelemetryTarget): void;
306
function logUserPrompt(prompt: string, metadata?: object): void;
307
function logToolCall(toolName: string, params: object, result?: object): void;
308
function logApiRequest(model: string, request: object): void;
309
```
310
311
[Telemetry and Monitoring](./telemetry.md)