or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcore-ai.mdide-integration.mdindex.mdmcp-oauth.mdservices.mdtelemetry.mdtools.mdutilities.md

utilities.mddocs/

0

# Error Handling and Utilities

1

2

Comprehensive utility functions for error handling, file operations, git integration, shell utilities, text processing, and system operations.

3

4

## Capabilities

5

6

### Error Handling

7

8

Specialized error classes and utility functions for robust error handling.

9

10

```typescript { .api }

11

/**

12

* Base fatal error class for unrecoverable errors

13

*/

14

class FatalError extends Error {

15

constructor(message: string);

16

}

17

18

/**

19

* Fatal authentication error for auth failures

20

*/

21

class FatalAuthenticationError extends FatalError {

22

constructor(message: string);

23

}

24

25

/**

26

* Fatal input error for invalid user input

27

*/

28

class FatalInputError extends FatalError {

29

constructor(message: string);

30

}

31

32

/**

33

* Fatal sandbox error for sandbox-related failures

34

*/

35

class FatalSandboxError extends FatalError {

36

constructor(message: string);

37

}

38

39

/**

40

* Fatal configuration error for config issues

41

*/

42

class FatalConfigError extends FatalError {

43

constructor(message: string);

44

}

45

46

/**

47

* Fatal turn-limited error for exceeding turn limits

48

*/

49

class FatalTurnLimitedError extends FatalError {

50

constructor(message: string);

51

}

52

53

/**

54

* Forbidden access error (HTTP 403)

55

*/

56

class ForbiddenError extends Error {

57

constructor(message: string);

58

}

59

60

/**

61

* Unauthorized access error (HTTP 401)

62

*/

63

class UnauthorizedError extends Error {

64

constructor(message: string);

65

}

66

67

/**

68

* Bad request error (HTTP 400)

69

*/

70

class BadRequestError extends Error {

71

constructor(message: string);

72

}

73

74

/**

75

* Node.js error type guard

76

* @param error - Unknown error object

77

* @returns True if error is a Node.js ErrnoException

78

*/

79

function isNodeError(error: unknown): error is NodeJS.ErrnoException;

80

81

/**

82

* Extract error message from unknown error objects

83

* @param error - Unknown error object

84

* @returns Error message string

85

*/

86

function getErrorMessage(error: unknown): string;

87

88

/**

89

* Convert error to user-friendly format

90

* @param error - Unknown error object

91

* @returns Friendly error representation

92

*/

93

function toFriendlyError(error: unknown): unknown;

94

```

95

96

### File System Utilities

97

98

Utilities for file system operations, path manipulation, and file processing.

99

100

```typescript { .api }

101

/**

102

* Read file with encoding detection

103

* @param filePath - Path to file

104

* @returns File content as string

105

*/

106

function readFileWithEncoding(filePath: string): Promise<string>;

107

108

/**

109

* Write file with atomic operation

110

* @param filePath - Path to file

111

* @param content - File content

112

*/

113

function writeFileAtomic(filePath: string, content: string): Promise<void>;

114

115

/**

116

* Check if path exists and is readable

117

* @param filePath - Path to check

118

* @returns True if path exists and is readable

119

*/

120

function isReadableFile(filePath: string): Promise<boolean>;

121

122

/**

123

* Get file MIME type

124

* @param filePath - Path to file

125

* @returns MIME type string

126

*/

127

function getMimeType(filePath: string): string;

128

129

/**

130

* Calculate file hash

131

* @param filePath - Path to file

132

* @param algorithm - Hash algorithm (default: 'sha256')

133

* @returns File hash as hex string

134

*/

135

function calculateFileHash(filePath: string, algorithm?: string): Promise<string>;

136

137

/**

138

* Get directory size recursively

139

* @param dirPath - Directory path

140

* @returns Total size in bytes

141

*/

142

function getDirectorySize(dirPath: string): Promise<number>;

143

144

/**

145

* Copy directory recursively

146

* @param srcDir - Source directory

147

* @param destDir - Destination directory

148

* @param options - Copy options

149

*/

150

function copyDirectory(

151

srcDir: string,

152

destDir: string,

153

options?: {

154

overwrite?: boolean;

155

filter?: (src: string, dest: string) => boolean;

156

}

157

): Promise<void>;

158

159

/**

160

* Find files matching pattern

161

* @param pattern - Glob pattern

162

* @param options - Search options

163

* @returns Array of matching file paths

164

*/

165

function findFiles(

166

pattern: string,

167

options?: {

168

cwd?: string;

169

ignore?: string[];

170

absolute?: boolean;

171

}

172

): Promise<string[]>;

173

```

174

175

### Path Utilities

176

177

Path manipulation and resolution utilities.

178

179

```typescript { .api }

180

/**

181

* Resolve path relative to project root

182

* @param relativePath - Relative path

183

* @param projectRoot - Project root directory

184

* @returns Absolute path

185

*/

186

function resolveProjectPath(relativePath: string, projectRoot?: string): string;

187

188

/**

189

* Get relative path from one location to another

190

* @param from - From location

191

* @param to - To location

192

* @returns Relative path

193

*/

194

function getRelativePath(from: string, to: string): string;

195

196

/**

197

* Normalize path for cross-platform compatibility

198

* @param filePath - Path to normalize

199

* @returns Normalized path

200

*/

201

function normalizePath(filePath: string): string;

202

203

/**

204

* Check if path is within directory

205

* @param filePath - File path to check

206

* @param directoryPath - Directory path

207

* @returns True if file is within directory

208

*/

209

function isPathWithinDirectory(filePath: string, directoryPath: string): boolean;

210

211

/**

212

* Get file extension without dot

213

* @param filePath - File path

214

* @returns File extension

215

*/

216

function getFileExtension(filePath: string): string;

217

218

/**

219

* Get filename without extension

220

* @param filePath - File path

221

* @returns Filename without extension

222

*/

223

function getBasename(filePath: string): string;

224

```

225

226

### Git Utilities

227

228

Git repository utilities and operations.

229

230

```typescript { .api }

231

/**

232

* Check if directory is a git repository

233

* @param dirPath - Directory path

234

* @returns True if directory is a git repository

235

*/

236

function isGitRepository(dirPath: string): Promise<boolean>;

237

238

/**

239

* Get git repository root path

240

* @param startPath - Starting path for search

241

* @returns Git repository root path or null

242

*/

243

function getGitRoot(startPath: string): Promise<string | null>;

244

245

/**

246

* Get current git branch name

247

* @param repoPath - Repository path

248

* @returns Current branch name

249

*/

250

function getCurrentBranch(repoPath: string): Promise<string>;

251

252

/**

253

* Check if repository has uncommitted changes

254

* @param repoPath - Repository path

255

* @returns True if repository has uncommitted changes

256

*/

257

function hasUncommittedChanges(repoPath: string): Promise<boolean>;

258

259

/**

260

* Get list of modified files

261

* @param repoPath - Repository path

262

* @returns Array of modified file paths

263

*/

264

function getModifiedFiles(repoPath: string): Promise<string[]>;

265

266

/**

267

* Get git ignore patterns for path

268

* @param filePath - File path to check

269

* @param repoPath - Repository path

270

* @returns True if file should be ignored

271

*/

272

function isGitIgnored(filePath: string, repoPath: string): Promise<boolean>;

273

274

/**

275

* Parse .gitignore file

276

* @param gitignorePath - Path to .gitignore file

277

* @returns Array of ignore patterns

278

*/

279

function parseGitIgnore(gitignorePath: string): Promise<string[]>;

280

```

281

282

### Shell Utilities

283

284

Shell command utilities and process management.

285

286

```typescript { .api }

287

/**

288

* Execute shell command with options

289

* @param command - Command to execute

290

* @param options - Execution options

291

* @returns Command result

292

*/

293

function executeShellCommand(

294

command: string,

295

options?: {

296

cwd?: string;

297

env?: Record<string, string>;

298

timeout?: number;

299

shell?: string;

300

}

301

): Promise<{

302

stdout: string;

303

stderr: string;

304

exitCode: number;

305

}>;

306

307

/**

308

* Execute command and stream output

309

* @param command - Command to execute

310

* @param options - Execution options

311

* @returns Async generator for output chunks

312

*/

313

function executeShellCommandStream(

314

command: string,

315

options?: {

316

cwd?: string;

317

env?: Record<string, string>;

318

shell?: string;

319

}

320

): AsyncGenerator<{type: 'stdout' | 'stderr', data: string}>;

321

322

/**

323

* Check if command exists in PATH

324

* @param commandName - Command name

325

* @returns True if command exists

326

*/

327

function commandExists(commandName: string): Promise<boolean>;

328

329

/**

330

* Quote shell arguments safely

331

* @param args - Arguments to quote

332

* @returns Quoted arguments array

333

*/

334

function quoteShellArgs(args: string[]): string[];

335

336

/**

337

* Parse shell command line

338

* @param commandLine - Command line string

339

* @returns Parsed arguments array

340

*/

341

function parseShellCommand(commandLine: string): string[];

342

343

/**

344

* Get system environment variables

345

* @returns Environment variables object

346

*/

347

function getSystemEnvironment(): Record<string, string>;

348

349

/**

350

* Set environment variable for process

351

* @param key - Environment variable key

352

* @param value - Environment variable value

353

*/

354

function setEnvironmentVariable(key: string, value: string): void;

355

```

356

357

### Text Processing Utilities

358

359

Text manipulation, formatting, and processing utilities.

360

361

```typescript { .api }

362

/**

363

* Truncate text to maximum length

364

* @param text - Text to truncate

365

* @param maxLength - Maximum length

366

* @param ellipsis - Ellipsis string (default: '...')

367

* @returns Truncated text

368

*/

369

function truncateText(text: string, maxLength: number, ellipsis?: string): string;

370

371

/**

372

* Word wrap text to specified width

373

* @param text - Text to wrap

374

* @param width - Line width

375

* @returns Wrapped text

376

*/

377

function wordWrap(text: string, width: number): string;

378

379

/**

380

* Strip ANSI color codes from text

381

* @param text - Text with ANSI codes

382

* @returns Plain text

383

*/

384

function stripAnsiCodes(text: string): string;

385

386

/**

387

* Convert text to title case

388

* @param text - Text to convert

389

* @returns Title case text

390

*/

391

function toTitleCase(text: string): string;

392

393

/**

394

* Convert text to camelCase

395

* @param text - Text to convert

396

* @returns camelCase text

397

*/

398

function toCamelCase(text: string): string;

399

400

/**

401

* Convert text to kebab-case

402

* @param text - Text to convert

403

* @returns kebab-case text

404

*/

405

function toKebabCase(text: string): string;

406

407

/**

408

* Extract words from text

409

* @param text - Text to process

410

* @returns Array of words

411

*/

412

function extractWords(text: string): string[];

413

414

/**

415

* Calculate text similarity

416

* @param text1 - First text

417

* @param text2 - Second text

418

* @returns Similarity score (0-1)

419

*/

420

function calculateTextSimilarity(text1: string, text2: string): number;

421

422

/**

423

* Detect text encoding

424

* @param buffer - Text buffer

425

* @returns Detected encoding

426

*/

427

function detectTextEncoding(buffer: Buffer): string;

428

```

429

430

### Formatting Utilities

431

432

Formatting utilities for content display and processing.

433

434

```typescript { .api }

435

/**

436

* Format file size in human-readable format

437

* @param bytes - Size in bytes

438

* @returns Formatted size string

439

*/

440

function formatFileSize(bytes: number): string;

441

442

/**

443

* Format duration in human-readable format

444

* @param milliseconds - Duration in milliseconds

445

* @returns Formatted duration string

446

*/

447

function formatDuration(milliseconds: number): string;

448

449

/**

450

* Format date in relative format

451

* @param date - Date to format

452

* @returns Relative date string (e.g., '2 hours ago')

453

*/

454

function formatRelativeDate(date: Date): string;

455

456

/**

457

* Format JSON with syntax highlighting

458

* @param obj - Object to format

459

* @param options - Formatting options

460

* @returns Formatted JSON string

461

*/

462

function formatJson(

463

obj: any,

464

options?: {

465

indent?: number;

466

colors?: boolean;

467

maxDepth?: number;

468

}

469

): string;

470

471

/**

472

* Format code with syntax highlighting

473

* @param code - Code to format

474

* @param language - Programming language

475

* @returns Formatted code string

476

*/

477

function formatCode(code: string, language: string): string;

478

479

/**

480

* Format table data

481

* @param data - Table data

482

* @param options - Table options

483

* @returns Formatted table string

484

*/

485

function formatTable(

486

data: any[][],

487

options?: {

488

headers?: string[];

489

borders?: boolean;

490

alignment?: ('left' | 'center' | 'right')[];

491

}

492

): string;

493

```

494

495

### Retry and Resilience Utilities

496

497

Retry mechanisms and resilience patterns.

498

499

```typescript { .api }

500

/**

501

* Retry options configuration

502

*/

503

interface RetryOptions {

504

maxAttempts: number;

505

baseDelayMs: number;

506

maxDelayMs: number;

507

backoffMultiplier: number;

508

retryCondition?: (error: unknown) => boolean;

509

}

510

511

/**

512

* Retry function with exponential backoff

513

* @param fn - Function to retry

514

* @param options - Retry options

515

* @returns Function result or throws last error

516

*/

517

function withRetry<T>(

518

fn: () => Promise<T>,

519

options: RetryOptions

520

): Promise<T>;

521

522

/**

523

* Circuit breaker for preventing cascading failures

524

*/

525

class CircuitBreaker<T> {

526

constructor(

527

fn: (...args: any[]) => Promise<T>,

528

options: {

529

failureThreshold: number;

530

resetTimeoutMs: number;

531

monitoringPeriodMs: number;

532

}

533

);

534

535

execute(...args: any[]): Promise<T>;

536

getState(): 'closed' | 'open' | 'half-open';

537

}

538

539

/**

540

* Rate limiter for controlling request frequency

541

*/

542

class RateLimiter {

543

constructor(

544

maxRequests: number,

545

windowMs: number

546

);

547

548

async acquirePermit(): Promise<void>;

549

getRemainingPermits(): number;

550

}

551

```

552

553

### Validation and Schema Utilities

554

555

JSON schema validation and data validation utilities.

556

557

```typescript { .api }

558

/**

559

* JSON schema validator

560

*/

561

class SchemaValidator {

562

constructor();

563

564

/**

565

* Validate data against JSON schema

566

* @param data - Data to validate

567

* @param schema - JSON schema

568

* @returns Validation result

569

*/

570

validate(data: any, schema: object): {

571

valid: boolean;

572

errors: string[];

573

};

574

575

/**

576

* Add custom format validator

577

* @param name - Format name

578

* @param validator - Validation function

579

*/

580

addFormat(name: string, validator: (value: string) => boolean): void;

581

}

582

583

/**

584

* Data validation utilities

585

*/

586

namespace Validators {

587

function isEmail(value: string): boolean;

588

function isUrl(value: string): boolean;

589

function isUuid(value: string): boolean;

590

function isIpAddress(value: string): boolean;

591

function isPhoneNumber(value: string): boolean;

592

function isValidJson(value: string): boolean;

593

function isValidRegex(pattern: string): boolean;

594

}

595

```

596

597

**Usage Examples:**

598

599

```typescript

600

import {

601

FatalConfigError,

602

getErrorMessage,

603

readFileWithEncoding,

604

executeShellCommand,

605

withRetry,

606

SchemaValidator,

607

formatFileSize,

608

calculateTextSimilarity

609

} from '@google/gemini-cli-core';

610

611

// Error handling

612

try {

613

// Some operation that might fail

614

throw new Error('Something went wrong');

615

} catch (error) {

616

if (error instanceof FatalConfigError) {

617

console.error('Fatal config error:', error.message);

618

process.exit(1);

619

} else {

620

console.error('Error:', getErrorMessage(error));

621

}

622

}

623

624

// File operations with error handling

625

try {

626

const content = await readFileWithEncoding('/path/to/file.txt');

627

console.log('File content:', content);

628

} catch (error) {

629

console.error('Failed to read file:', getErrorMessage(error));

630

}

631

632

// Shell command execution

633

const result = await executeShellCommand('git status --porcelain', {

634

cwd: '/project/root',

635

timeout: 10000

636

});

637

638

if (result.exitCode === 0) {

639

console.log('Git status output:', result.stdout);

640

} else {

641

console.error('Git command failed:', result.stderr);

642

}

643

644

// Retry with exponential backoff

645

const data = await withRetry(

646

async () => {

647

const response = await fetch('https://api.example.com/data');

648

if (!response.ok) {

649

throw new Error(`HTTP ${response.status}`);

650

}

651

return response.json();

652

},

653

{

654

maxAttempts: 3,

655

baseDelayMs: 1000,

656

maxDelayMs: 10000,

657

backoffMultiplier: 2,

658

retryCondition: (error) => {

659

return error instanceof Error && error.message.includes('HTTP 5');

660

}

661

}

662

);

663

664

// Schema validation

665

const validator = new SchemaValidator();

666

const userSchema = {

667

type: 'object',

668

properties: {

669

name: { type: 'string', minLength: 1 },

670

email: { type: 'string', format: 'email' },

671

age: { type: 'number', minimum: 0 }

672

},

673

required: ['name', 'email']

674

};

675

676

const userData = { name: 'John', email: 'john@example.com', age: 30 };

677

const validation = validator.validate(userData, userSchema);

678

679

if (validation.valid) {

680

console.log('User data is valid');

681

} else {

682

console.error('Validation errors:', validation.errors);

683

}

684

685

// Text processing

686

const similarity = calculateTextSimilarity(

687

'Hello, world!',

688

'Hello, universe!'

689

);

690

console.log(`Text similarity: ${(similarity * 100).toFixed(1)}%`);

691

692

// Formatting utilities

693

console.log('File size:', formatFileSize(1048576)); // "1.0 MB"

694

console.log('Duration:', formatDuration(125000)); // "2m 5s"

695

```