Gemini CLI Core - Core functionality library for the open-source AI agent that brings the power of Gemini directly into your terminal.
Overall
score
87%
Evaluation — 87%
↑ 1.01xAgent success when using this tile
Comprehensive utility functions for error handling, file operations, git integration, shell utilities, text processing, and system operations.
Specialized error classes and utility functions for robust error handling.
/**
* Base fatal error class for unrecoverable errors
*/
class FatalError extends Error {
constructor(message: string);
}
/**
* Fatal authentication error for auth failures
*/
class FatalAuthenticationError extends FatalError {
constructor(message: string);
}
/**
* Fatal input error for invalid user input
*/
class FatalInputError extends FatalError {
constructor(message: string);
}
/**
* Fatal sandbox error for sandbox-related failures
*/
class FatalSandboxError extends FatalError {
constructor(message: string);
}
/**
* Fatal configuration error for config issues
*/
class FatalConfigError extends FatalError {
constructor(message: string);
}
/**
* Fatal turn-limited error for exceeding turn limits
*/
class FatalTurnLimitedError extends FatalError {
constructor(message: string);
}
/**
* Forbidden access error (HTTP 403)
*/
class ForbiddenError extends Error {
constructor(message: string);
}
/**
* Unauthorized access error (HTTP 401)
*/
class UnauthorizedError extends Error {
constructor(message: string);
}
/**
* Bad request error (HTTP 400)
*/
class BadRequestError extends Error {
constructor(message: string);
}
/**
* Node.js error type guard
* @param error - Unknown error object
* @returns True if error is a Node.js ErrnoException
*/
function isNodeError(error: unknown): error is NodeJS.ErrnoException;
/**
* Extract error message from unknown error objects
* @param error - Unknown error object
* @returns Error message string
*/
function getErrorMessage(error: unknown): string;
/**
* Convert error to user-friendly format
* @param error - Unknown error object
* @returns Friendly error representation
*/
function toFriendlyError(error: unknown): unknown;Utilities for file system operations, path manipulation, and file processing.
/**
* Read file with encoding detection
* @param filePath - Path to file
* @returns File content as string
*/
function readFileWithEncoding(filePath: string): Promise<string>;
/**
* Write file with atomic operation
* @param filePath - Path to file
* @param content - File content
*/
function writeFileAtomic(filePath: string, content: string): Promise<void>;
/**
* Check if path exists and is readable
* @param filePath - Path to check
* @returns True if path exists and is readable
*/
function isReadableFile(filePath: string): Promise<boolean>;
/**
* Get file MIME type
* @param filePath - Path to file
* @returns MIME type string
*/
function getMimeType(filePath: string): string;
/**
* Calculate file hash
* @param filePath - Path to file
* @param algorithm - Hash algorithm (default: 'sha256')
* @returns File hash as hex string
*/
function calculateFileHash(filePath: string, algorithm?: string): Promise<string>;
/**
* Get directory size recursively
* @param dirPath - Directory path
* @returns Total size in bytes
*/
function getDirectorySize(dirPath: string): Promise<number>;
/**
* Copy directory recursively
* @param srcDir - Source directory
* @param destDir - Destination directory
* @param options - Copy options
*/
function copyDirectory(
srcDir: string,
destDir: string,
options?: {
overwrite?: boolean;
filter?: (src: string, dest: string) => boolean;
}
): Promise<void>;
/**
* Find files matching pattern
* @param pattern - Glob pattern
* @param options - Search options
* @returns Array of matching file paths
*/
function findFiles(
pattern: string,
options?: {
cwd?: string;
ignore?: string[];
absolute?: boolean;
}
): Promise<string[]>;Path manipulation and resolution utilities.
/**
* Resolve path relative to project root
* @param relativePath - Relative path
* @param projectRoot - Project root directory
* @returns Absolute path
*/
function resolveProjectPath(relativePath: string, projectRoot?: string): string;
/**
* Get relative path from one location to another
* @param from - From location
* @param to - To location
* @returns Relative path
*/
function getRelativePath(from: string, to: string): string;
/**
* Normalize path for cross-platform compatibility
* @param filePath - Path to normalize
* @returns Normalized path
*/
function normalizePath(filePath: string): string;
/**
* Check if path is within directory
* @param filePath - File path to check
* @param directoryPath - Directory path
* @returns True if file is within directory
*/
function isPathWithinDirectory(filePath: string, directoryPath: string): boolean;
/**
* Get file extension without dot
* @param filePath - File path
* @returns File extension
*/
function getFileExtension(filePath: string): string;
/**
* Get filename without extension
* @param filePath - File path
* @returns Filename without extension
*/
function getBasename(filePath: string): string;Git repository utilities and operations.
/**
* Check if directory is a git repository
* @param dirPath - Directory path
* @returns True if directory is a git repository
*/
function isGitRepository(dirPath: string): Promise<boolean>;
/**
* Get git repository root path
* @param startPath - Starting path for search
* @returns Git repository root path or null
*/
function getGitRoot(startPath: string): Promise<string | null>;
/**
* Get current git branch name
* @param repoPath - Repository path
* @returns Current branch name
*/
function getCurrentBranch(repoPath: string): Promise<string>;
/**
* Check if repository has uncommitted changes
* @param repoPath - Repository path
* @returns True if repository has uncommitted changes
*/
function hasUncommittedChanges(repoPath: string): Promise<boolean>;
/**
* Get list of modified files
* @param repoPath - Repository path
* @returns Array of modified file paths
*/
function getModifiedFiles(repoPath: string): Promise<string[]>;
/**
* Get git ignore patterns for path
* @param filePath - File path to check
* @param repoPath - Repository path
* @returns True if file should be ignored
*/
function isGitIgnored(filePath: string, repoPath: string): Promise<boolean>;
/**
* Parse .gitignore file
* @param gitignorePath - Path to .gitignore file
* @returns Array of ignore patterns
*/
function parseGitIgnore(gitignorePath: string): Promise<string[]>;Shell command utilities and process management.
/**
* Execute shell command with options
* @param command - Command to execute
* @param options - Execution options
* @returns Command result
*/
function executeShellCommand(
command: string,
options?: {
cwd?: string;
env?: Record<string, string>;
timeout?: number;
shell?: string;
}
): Promise<{
stdout: string;
stderr: string;
exitCode: number;
}>;
/**
* Execute command and stream output
* @param command - Command to execute
* @param options - Execution options
* @returns Async generator for output chunks
*/
function executeShellCommandStream(
command: string,
options?: {
cwd?: string;
env?: Record<string, string>;
shell?: string;
}
): AsyncGenerator<{type: 'stdout' | 'stderr', data: string}>;
/**
* Check if command exists in PATH
* @param commandName - Command name
* @returns True if command exists
*/
function commandExists(commandName: string): Promise<boolean>;
/**
* Quote shell arguments safely
* @param args - Arguments to quote
* @returns Quoted arguments array
*/
function quoteShellArgs(args: string[]): string[];
/**
* Parse shell command line
* @param commandLine - Command line string
* @returns Parsed arguments array
*/
function parseShellCommand(commandLine: string): string[];
/**
* Get system environment variables
* @returns Environment variables object
*/
function getSystemEnvironment(): Record<string, string>;
/**
* Set environment variable for process
* @param key - Environment variable key
* @param value - Environment variable value
*/
function setEnvironmentVariable(key: string, value: string): void;Text manipulation, formatting, and processing utilities.
/**
* Truncate text to maximum length
* @param text - Text to truncate
* @param maxLength - Maximum length
* @param ellipsis - Ellipsis string (default: '...')
* @returns Truncated text
*/
function truncateText(text: string, maxLength: number, ellipsis?: string): string;
/**
* Word wrap text to specified width
* @param text - Text to wrap
* @param width - Line width
* @returns Wrapped text
*/
function wordWrap(text: string, width: number): string;
/**
* Strip ANSI color codes from text
* @param text - Text with ANSI codes
* @returns Plain text
*/
function stripAnsiCodes(text: string): string;
/**
* Convert text to title case
* @param text - Text to convert
* @returns Title case text
*/
function toTitleCase(text: string): string;
/**
* Convert text to camelCase
* @param text - Text to convert
* @returns camelCase text
*/
function toCamelCase(text: string): string;
/**
* Convert text to kebab-case
* @param text - Text to convert
* @returns kebab-case text
*/
function toKebabCase(text: string): string;
/**
* Extract words from text
* @param text - Text to process
* @returns Array of words
*/
function extractWords(text: string): string[];
/**
* Calculate text similarity
* @param text1 - First text
* @param text2 - Second text
* @returns Similarity score (0-1)
*/
function calculateTextSimilarity(text1: string, text2: string): number;
/**
* Detect text encoding
* @param buffer - Text buffer
* @returns Detected encoding
*/
function detectTextEncoding(buffer: Buffer): string;Formatting utilities for content display and processing.
/**
* Format file size in human-readable format
* @param bytes - Size in bytes
* @returns Formatted size string
*/
function formatFileSize(bytes: number): string;
/**
* Format duration in human-readable format
* @param milliseconds - Duration in milliseconds
* @returns Formatted duration string
*/
function formatDuration(milliseconds: number): string;
/**
* Format date in relative format
* @param date - Date to format
* @returns Relative date string (e.g., '2 hours ago')
*/
function formatRelativeDate(date: Date): string;
/**
* Format JSON with syntax highlighting
* @param obj - Object to format
* @param options - Formatting options
* @returns Formatted JSON string
*/
function formatJson(
obj: any,
options?: {
indent?: number;
colors?: boolean;
maxDepth?: number;
}
): string;
/**
* Format code with syntax highlighting
* @param code - Code to format
* @param language - Programming language
* @returns Formatted code string
*/
function formatCode(code: string, language: string): string;
/**
* Format table data
* @param data - Table data
* @param options - Table options
* @returns Formatted table string
*/
function formatTable(
data: any[][],
options?: {
headers?: string[];
borders?: boolean;
alignment?: ('left' | 'center' | 'right')[];
}
): string;Retry mechanisms and resilience patterns.
/**
* Retry options configuration
*/
interface RetryOptions {
maxAttempts: number;
baseDelayMs: number;
maxDelayMs: number;
backoffMultiplier: number;
retryCondition?: (error: unknown) => boolean;
}
/**
* Retry function with exponential backoff
* @param fn - Function to retry
* @param options - Retry options
* @returns Function result or throws last error
*/
function withRetry<T>(
fn: () => Promise<T>,
options: RetryOptions
): Promise<T>;
/**
* Circuit breaker for preventing cascading failures
*/
class CircuitBreaker<T> {
constructor(
fn: (...args: any[]) => Promise<T>,
options: {
failureThreshold: number;
resetTimeoutMs: number;
monitoringPeriodMs: number;
}
);
execute(...args: any[]): Promise<T>;
getState(): 'closed' | 'open' | 'half-open';
}
/**
* Rate limiter for controlling request frequency
*/
class RateLimiter {
constructor(
maxRequests: number,
windowMs: number
);
async acquirePermit(): Promise<void>;
getRemainingPermits(): number;
}JSON schema validation and data validation utilities.
/**
* JSON schema validator
*/
class SchemaValidator {
constructor();
/**
* Validate data against JSON schema
* @param data - Data to validate
* @param schema - JSON schema
* @returns Validation result
*/
validate(data: any, schema: object): {
valid: boolean;
errors: string[];
};
/**
* Add custom format validator
* @param name - Format name
* @param validator - Validation function
*/
addFormat(name: string, validator: (value: string) => boolean): void;
}
/**
* Data validation utilities
*/
namespace Validators {
function isEmail(value: string): boolean;
function isUrl(value: string): boolean;
function isUuid(value: string): boolean;
function isIpAddress(value: string): boolean;
function isPhoneNumber(value: string): boolean;
function isValidJson(value: string): boolean;
function isValidRegex(pattern: string): boolean;
}Usage Examples:
import {
FatalConfigError,
getErrorMessage,
readFileWithEncoding,
executeShellCommand,
withRetry,
SchemaValidator,
formatFileSize,
calculateTextSimilarity
} from '@google/gemini-cli-core';
// Error handling
try {
// Some operation that might fail
throw new Error('Something went wrong');
} catch (error) {
if (error instanceof FatalConfigError) {
console.error('Fatal config error:', error.message);
process.exit(1);
} else {
console.error('Error:', getErrorMessage(error));
}
}
// File operations with error handling
try {
const content = await readFileWithEncoding('/path/to/file.txt');
console.log('File content:', content);
} catch (error) {
console.error('Failed to read file:', getErrorMessage(error));
}
// Shell command execution
const result = await executeShellCommand('git status --porcelain', {
cwd: '/project/root',
timeout: 10000
});
if (result.exitCode === 0) {
console.log('Git status output:', result.stdout);
} else {
console.error('Git command failed:', result.stderr);
}
// Retry with exponential backoff
const data = await withRetry(
async () => {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
},
{
maxAttempts: 3,
baseDelayMs: 1000,
maxDelayMs: 10000,
backoffMultiplier: 2,
retryCondition: (error) => {
return error instanceof Error && error.message.includes('HTTP 5');
}
}
);
// Schema validation
const validator = new SchemaValidator();
const userSchema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
age: { type: 'number', minimum: 0 }
},
required: ['name', 'email']
};
const userData = { name: 'John', email: 'john@example.com', age: 30 };
const validation = validator.validate(userData, userSchema);
if (validation.valid) {
console.log('User data is valid');
} else {
console.error('Validation errors:', validation.errors);
}
// Text processing
const similarity = calculateTextSimilarity(
'Hello, world!',
'Hello, universe!'
);
console.log(`Text similarity: ${(similarity * 100).toFixed(1)}%`);
// Formatting utilities
console.log('File size:', formatFileSize(1048576)); // "1.0 MB"
console.log('Duration:', formatDuration(125000)); // "2m 5s"Install with Tessl CLI
npx tessl i tessl/npm-google--gemini-cli-coredocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10