1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import * as path from 'node:path';
import process from 'node:process';
import {
AuthType,
ContentGeneratorConfig,
createContentGeneratorConfig,
} from '../core/contentGenerator.js';
import { ToolRegistry } from '../tools/tool-registry.js';
import { LSTool } from '../tools/ls.js';
import { ReadFileTool } from '../tools/read-file.js';
import { GrepTool } from '../tools/grep.js';
import { GlobTool } from '../tools/glob.js';
import { EditTool } from '../tools/edit.js';
import { ShellTool } from '../tools/shell.js';
import { WriteFileTool } from '../tools/write-file.js';
import { WebFetchTool } from '../tools/web-fetch.js';
import { ReadManyFilesTool } from '../tools/read-many-files.js';
import { MemoryTool, setGeminiMdFilename } from '../tools/memoryTool.js';
import { WebSearchTool } from '../tools/web-search.js';
import { GeminiClient } from '../core/client.js';
import { GEMINI_CONFIG_DIR as GEMINI_DIR } from '../tools/memoryTool.js';
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { GitService } from '../services/gitService.js';
import { getProjectTempDir } from '../utils/paths.js';
import {
initializeTelemetry,
DEFAULT_TELEMETRY_TARGET,
DEFAULT_OTLP_ENDPOINT,
TelemetryTarget,
StartSessionEvent,
} from '../telemetry/index.js';
import {
DEFAULT_GEMINI_EMBEDDING_MODEL,
DEFAULT_GEMINI_FLASH_MODEL,
} from './models.js';
import { ClearcutLogger } from '../telemetry/clearcut-logger/clearcut-logger.js';
export enum ApprovalMode {
DEFAULT = 'default',
AUTO_EDIT = 'autoEdit',
YOLO = 'yolo',
}
export interface AccessibilitySettings {
disableLoadingPhrases?: boolean;
}
export interface BugCommandSettings {
urlTemplate: string;
}
export interface TelemetrySettings {
enabled?: boolean;
target?: TelemetryTarget;
otlpEndpoint?: string;
logPrompts?: boolean;
}
export class MCPServerConfig {
constructor(
// For stdio transport
readonly command?: string,
readonly args?: string[],
readonly env?: Record<string, string>,
readonly cwd?: string,
// For sse transport
readonly url?: string,
// For streamable http transport
readonly httpUrl?: string,
// For websocket transport
readonly tcp?: string,
// Common
readonly timeout?: number,
readonly trust?: boolean,
// Metadata
readonly description?: string,
) {}
}
export interface SandboxConfig {
command: 'docker' | 'podman' | 'sandbox-exec';
image: string;
}
export type FlashFallbackHandler = (
currentModel: string,
fallbackModel: string,
) => Promise<boolean>;
export interface ConfigParameters {
sessionId: string;
embeddingModel?: string;
sandbox?: SandboxConfig;
targetDir: string;
debugMode: boolean;
question?: string;
fullContext?: boolean;
coreTools?: string[];
excludeTools?: string[];
toolDiscoveryCommand?: string;
toolCallCommand?: string;
mcpServerCommand?: string;
mcpServers?: Record<string, MCPServerConfig>;
userMemory?: string;
geminiMdFileCount?: number;
approvalMode?: ApprovalMode;
showMemoryUsage?: boolean;
contextFileName?: string | string[];
accessibility?: AccessibilitySettings;
telemetry?: TelemetrySettings;
usageStatisticsEnabled?: boolean;
fileFiltering?: {
respectGitIgnore?: boolean;
enableRecursiveFileSearch?: boolean;
};
checkpointing?: boolean;
proxy?: string;
cwd: string;
fileDiscoveryService?: FileDiscoveryService;
bugCommand?: BugCommandSettings;
model: string;
extensionContextFilePaths?: string[];
}
export class Config {
private toolRegistry!: ToolRegistry;
private readonly sessionId: string;
private contentGeneratorConfig!: ContentGeneratorConfig;
private readonly embeddingModel: string;
private readonly sandbox: SandboxConfig | undefined;
private readonly targetDir: string;
private readonly debugMode: boolean;
private readonly question: string | undefined;
private readonly fullContext: boolean;
private readonly coreTools: string[] | undefined;
private readonly excludeTools: string[] | undefined;
private readonly toolDiscoveryCommand: string | undefined;
private readonly toolCallCommand: string | undefined;
private readonly mcpServerCommand: string | undefined;
private readonly mcpServers: Record<string, MCPServerConfig> | undefined;
private userMemory: string;
private geminiMdFileCount: number;
private approvalMode: ApprovalMode;
private readonly showMemoryUsage: boolean;
private readonly accessibility: AccessibilitySettings;
private readonly telemetrySettings: TelemetrySettings;
private readonly usageStatisticsEnabled: boolean;
private geminiClient!: GeminiClient;
private readonly fileFiltering: {
respectGitIgnore: boolean;
enableRecursiveFileSearch: boolean;
};
private fileDiscoveryService: FileDiscoveryService | null = null;
private gitService: GitService | undefined = undefined;
private readonly checkpointing: boolean;
private readonly proxy: string | undefined;
private readonly cwd: string;
private readonly bugCommand: BugCommandSettings | undefined;
private readonly model: string;
private readonly extensionContextFilePaths: string[];
private modelSwitchedDuringSession: boolean = false;
flashFallbackHandler?: FlashFallbackHandler;
constructor(params: ConfigParameters) {
this.sessionId = params.sessionId;
this.embeddingModel =
params.embeddingModel ?? DEFAULT_GEMINI_EMBEDDING_MODEL;
this.sandbox = params.sandbox;
this.targetDir = path.resolve(params.targetDir);
this.debugMode = params.debugMode;
this.question = params.question;
this.fullContext = params.fullContext ?? false;
this.coreTools = params.coreTools;
this.excludeTools = params.excludeTools;
this.toolDiscoveryCommand = params.toolDiscoveryCommand;
this.toolCallCommand = params.toolCallCommand;
this.mcpServerCommand = params.mcpServerCommand;
this.mcpServers = params.mcpServers;
this.userMemory = params.userMemory ?? '';
this.geminiMdFileCount = params.geminiMdFileCount ?? 0;
this.approvalMode = params.approvalMode ?? ApprovalMode.DEFAULT;
this.showMemoryUsage = params.showMemoryUsage ?? false;
this.accessibility = params.accessibility ?? {};
this.telemetrySettings = {
enabled: params.telemetry?.enabled ?? false,
target: params.telemetry?.target ?? DEFAULT_TELEMETRY_TARGET,
otlpEndpoint: params.telemetry?.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT,
logPrompts: params.telemetry?.logPrompts ?? true,
};
this.usageStatisticsEnabled = params.usageStatisticsEnabled ?? true;
this.fileFiltering = {
respectGitIgnore: params.fileFiltering?.respectGitIgnore ?? true,
enableRecursiveFileSearch:
params.fileFiltering?.enableRecursiveFileSearch ?? true,
};
this.checkpointing = params.checkpointing ?? false;
this.proxy = params.proxy;
this.cwd = params.cwd ?? process.cwd();
this.fileDiscoveryService = params.fileDiscoveryService ?? null;
this.bugCommand = params.bugCommand;
this.model = params.model;
this.extensionContextFilePaths = params.extensionContextFilePaths ?? [];
if (params.contextFileName) {
setGeminiMdFilename(params.contextFileName);
}
if (this.telemetrySettings.enabled) {
initializeTelemetry(this);
}
if (this.getUsageStatisticsEnabled()) {
ClearcutLogger.getInstance(this)?.logStartSessionEvent(
new StartSessionEvent(this),
);
} else {
console.log('Data collection is disabled.');
}
}
async refreshAuth(authMethod: AuthType) {
// Check if this is actually a switch to a different auth method
const previousAuthType = this.contentGeneratorConfig?.authType;
const _isAuthMethodSwitch =
previousAuthType && previousAuthType !== authMethod;
// Always use the original default model when switching auth methods
// This ensures users don't stay on Flash after switching between auth types
// and allows API key users to get proper fallback behavior from getEffectiveModel
const modelToUse = this.model; // Use the original default model
// Temporarily clear contentGeneratorConfig to prevent getModel() from returning
// the previous session's model (which might be Flash)
this.contentGeneratorConfig = undefined!;
const contentConfig = await createContentGeneratorConfig(
modelToUse,
authMethod,
this,
);
const gc = new GeminiClient(this);
this.geminiClient = gc;
this.toolRegistry = await createToolRegistry(this);
await gc.initialize(contentConfig);
this.contentGeneratorConfig = contentConfig;
// Reset the session flag since we're explicitly changing auth and using default model
this.modelSwitchedDuringSession = false;
// Note: In the future, we may want to reset any cached state when switching auth methods
}
getSessionId(): string {
return this.sessionId;
}
getContentGeneratorConfig(): ContentGeneratorConfig {
return this.contentGeneratorConfig;
}
getModel(): string {
return this.contentGeneratorConfig?.model || this.model;
}
setModel(newModel: string): void {
if (this.contentGeneratorConfig) {
this.contentGeneratorConfig.model = newModel;
this.modelSwitchedDuringSession = true;
}
}
isModelSwitchedDuringSession(): boolean {
return this.modelSwitchedDuringSession;
}
resetModelToDefault(): void {
if (this.contentGeneratorConfig) {
this.contentGeneratorConfig.model = this.model; // Reset to the original default model
this.modelSwitchedDuringSession = false;
}
}
setFlashFallbackHandler(handler: FlashFallbackHandler): void {
this.flashFallbackHandler = handler;
}
getEmbeddingModel(): string {
return this.embeddingModel;
}
getSandbox(): SandboxConfig | undefined {
return this.sandbox;
}
getTargetDir(): string {
return this.targetDir;
}
getProjectRoot(): string {
return this.targetDir;
}
getToolRegistry(): Promise<ToolRegistry> {
return Promise.resolve(this.toolRegistry);
}
getDebugMode(): boolean {
return this.debugMode;
}
getQuestion(): string | undefined {
return this.question;
}
getFullContext(): boolean {
return this.fullContext;
}
getCoreTools(): string[] | undefined {
return this.coreTools;
}
getExcludeTools(): string[] | undefined {
return this.excludeTools;
}
getToolDiscoveryCommand(): string | undefined {
return this.toolDiscoveryCommand;
}
getToolCallCommand(): string | undefined {
return this.toolCallCommand;
}
getMcpServerCommand(): string | undefined {
return this.mcpServerCommand;
}
getMcpServers(): Record<string, MCPServerConfig> | undefined {
return this.mcpServers;
}
getUserMemory(): string {
return this.userMemory;
}
setUserMemory(newUserMemory: string): void {
this.userMemory = newUserMemory;
}
getGeminiMdFileCount(): number {
return this.geminiMdFileCount;
}
setGeminiMdFileCount(count: number): void {
this.geminiMdFileCount = count;
}
getApprovalMode(): ApprovalMode {
return this.approvalMode;
}
setApprovalMode(mode: ApprovalMode): void {
this.approvalMode = mode;
}
getShowMemoryUsage(): boolean {
return this.showMemoryUsage;
}
getAccessibility(): AccessibilitySettings {
return this.accessibility;
}
getTelemetryEnabled(): boolean {
return this.telemetrySettings.enabled ?? false;
}
getTelemetryLogPromptsEnabled(): boolean {
return this.telemetrySettings.logPrompts ?? true;
}
getTelemetryOtlpEndpoint(): string {
return this.telemetrySettings.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT;
}
getTelemetryTarget(): TelemetryTarget {
return this.telemetrySettings.target ?? DEFAULT_TELEMETRY_TARGET;
}
getGeminiClient(): GeminiClient {
return this.geminiClient;
}
getGeminiDir(): string {
return path.join(this.targetDir, GEMINI_DIR);
}
getProjectTempDir(): string {
return getProjectTempDir(this.getProjectRoot());
}
getEnableRecursiveFileSearch(): boolean {
return this.fileFiltering.enableRecursiveFileSearch;
}
getFileFilteringRespectGitIgnore(): boolean {
return this.fileFiltering.respectGitIgnore;
}
getCheckpointingEnabled(): boolean {
return this.checkpointing;
}
getProxy(): string | undefined {
return this.proxy;
}
getWorkingDir(): string {
return this.cwd;
}
getBugCommand(): BugCommandSettings | undefined {
return this.bugCommand;
}
getFileService(): FileDiscoveryService {
if (!this.fileDiscoveryService) {
this.fileDiscoveryService = new FileDiscoveryService(this.targetDir);
}
return this.fileDiscoveryService;
}
getUsageStatisticsEnabled(): boolean {
return this.usageStatisticsEnabled;
}
getExtensionContextFilePaths(): string[] {
return this.extensionContextFilePaths;
}
async getGitService(): Promise<GitService> {
if (!this.gitService) {
this.gitService = new GitService(this.targetDir);
await this.gitService.initialize();
}
return this.gitService;
}
}
export function createToolRegistry(config: Config): Promise<ToolRegistry> {
const registry = new ToolRegistry(config);
const targetDir = config.getTargetDir();
const tools = config.getCoreTools()
? new Set(config.getCoreTools())
: undefined;
const excludeTools = config.getExcludeTools()
? new Set(config.getExcludeTools())
: undefined;
// helper to create & register core tools that are enabled
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const registerCoreTool = (ToolClass: any, ...args: unknown[]) => {
// check both the tool name (.Name) and the class name (.name)
if (
// coreTools contain tool name
(!tools || tools.has(ToolClass.Name) || tools.has(ToolClass.name)) &&
// excludeTools don't contain tool name
(!excludeTools ||
(!excludeTools.has(ToolClass.Name) &&
!excludeTools.has(ToolClass.name)))
) {
registry.registerTool(new ToolClass(...args));
}
};
registerCoreTool(LSTool, targetDir, config);
registerCoreTool(ReadFileTool, targetDir, config);
registerCoreTool(GrepTool, targetDir);
registerCoreTool(GlobTool, targetDir, config);
registerCoreTool(EditTool, config);
registerCoreTool(WriteFileTool, config);
registerCoreTool(WebFetchTool, config);
registerCoreTool(ReadManyFilesTool, targetDir, config);
registerCoreTool(ShellTool, config);
registerCoreTool(MemoryTool);
registerCoreTool(WebSearchTool, config);
return (async () => {
await registry.discoverTools();
return registry;
})();
}
// Export model constants for use in CLI
export { DEFAULT_GEMINI_FLASH_MODEL };
|