-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepomix-output.xml
More file actions
3147 lines (2552 loc) · 100 KB
/
repomix-output.xml
File metadata and controls
3147 lines (2552 loc) · 100 KB
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
.cursor/rules/rulefy-generated-rules.mdc
.eslintrc.json
.github/workflows/ci.yml
.gitignore
.npmignore
bin/rulefy.cjs
CHANGELOG.md
CONTRIBUTING.md
cursorrules-guidelines.md
LICENSE
package.json
README.md
src/index.ts
src/llm-generator-v2.ts
src/llmGenerator.ts
src/prompts/cursor_mdc.md
src/providers/anthropic-provider.ts
src/providers/base-provider.ts
src/providers/local-provider.ts
src/providers/openai-provider.ts
src/providers/provider-registry.ts
src/rulesGenerate.ts
src/types/llm-provider.ts
test-output-dir.js
test-repomix.txt
tsconfig.json
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path=".cursor/rules/rulefy-generated-rules.mdc">
---
description: "These rules apply when developing, extending, or contributing to the Rulefy project - a tool for generating Cursor AI rules from GitHub repositories. Follow these guidelines to ensure consistent code quality, proper error handling, and adherence to the project's architectural patterns."
globs:
alwaysApply: false
---
# Rulefy Development Guidelines
## Critical Rules
- Use TypeScript with strict typing and proper return type annotations for all functions
- Follow ESM module syntax with `.js` extensions in import paths despite TypeScript usage
- Handle errors properly with try/catch blocks and appropriate error messages
- Use color formatting with picocolors for console output to maintain consistent UX
- Validate all external inputs and environment variables before use
- Implement proper chunking for large repository content to avoid token limit issues
- Follow the established architecture separating CLI, rule generation, and LLM integration
- Maintain backward compatibility for CLI options and programmatic API
- Document public functions and interfaces with JSDoc comments
- Handle rate limits and API errors gracefully when interacting with external services
- Structure code to be testable, even though tests aren't implemented yet
## Examples
<example>
// VALID: Proper error handling with try/catch and color formatting
import pc from 'picocolors';
async function processRepository(repoPath: string): Promise<void> {
try {
// Validate inputs
if (!repoPath) {
throw new Error('Repository path is required');
}
// Process with proper error handling
console.log(pc.cyan('Processing repository...'));
const result = await someAsyncOperation(repoPath);
console.log(pc.green('✓ Successfully processed repository'));
return result;
} catch (error) {
if (error instanceof Error) {
console.error(pc.red(`Error: ${error.message}`));
} else {
console.error(pc.red('Unknown error occurred'));
}
process.exit(1);
}
}
</example>
<example type="invalid">
// INVALID: Missing error handling and type annotations
function processRepo(repo) {
// No input validation
// No try/catch block
const data = someAsyncOperation(repo);
// No proper console formatting
console.log("Done processing");
// Missing return type
return data;
}
</example>
<example>
// VALID: Proper module imports with ESM syntax
import fs from 'node:fs/promises';
import path from 'node:path';
import { generateRules } from './rulesGenerator.js';
export async function processFiles(directory: string): Promise<string[]> {
const files = await fs.readdir(directory);
return files.filter(file => path.extname(file) === '.ts');
}
</example>
<example type="invalid">
// INVALID: Incorrect import syntax for ESM
const fs = require('fs');
import { generateRules } from './rulesGenerator'; // Missing .js extension
function processFiles(directory) {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) reject(err);
resolve(files.filter(file => file.endsWith('.ts')));
});
});
}
</example>
## Key Files Reference
- [src/index.ts](mdc:src/index.ts) - Entry point with CLI handling
- [src/rulesGenerate.ts](mdc:src/rulesGenerate.ts) - Core rule generation logic
- [src/llmGenerator.ts](mdc:src/llmGenerator.ts) - Integration with Claude AI
- [src/prompts/cursor_mdc.md](mdc:src/prompts/cursor_mdc.md) - Rule format guidelines
</file>
<file path="src/llm-generator-v2.ts">
import { getEncoding } from 'js-tiktoken';
import fs from 'node:fs/promises';
import path from 'node:path';
import pc from 'picocolors';
import readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import { LLMProviderRegistry } from './providers/provider-registry.js';
import { LLMProviderConfig, LLMMessage, ChunkProcessingOptions } from './types/llm-provider.js';
// Environment variables for chunk configuration, with defaults
const CHUNK_SIZE = Number(process.env.CHUNK_SIZE || '100000');
const costPerToken = 3e-6; // 3$ per million tokens
export interface LLMGeneratorOptions {
provider: string;
model?: string;
apiKey?: string;
baseURL?: string;
maxTokens?: number;
temperature?: number;
chunkSize?: number;
}
export async function generateWithLLM(
repoContent: string,
guidelines: string,
outputDir: string = '.',
description?: string,
ruleType?: string,
options: LLMGeneratorOptions = { provider: 'anthropic' }
): Promise<string> {
// If this is a test run with dummy API key, just return a mock response
if (options.apiKey === 'dummy-key') {
console.log(pc.yellow('Using mock response for testing'));
return generateMockResponse(repoContent);
}
return await generateWithProvider(repoContent, guidelines, outputDir, description, ruleType, options);
}
/**
* Creates a visual progress bar
*/
function progressBar(current: number, total: number, length = 30): string {
const percentage = current / total;
const filledLength = Math.round(length * percentage);
const emptyLength = length - filledLength;
const filled = '█'.repeat(filledLength);
const empty = '░'.repeat(emptyLength);
const percentageText = Math.round(percentage * 100).toString().padStart(3);
return `${filled}${empty} ${percentageText}%`;
}
function formatTokenCount(count: number): string {
const formatted = count.toLocaleString();
if (count < 50000) return pc.green(formatted);
if (count < 100000) return pc.yellow(formatted);
return pc.red(formatted);
}
/**
* Calculate the number of chunks needed for processing
*/
function calculateChunkCount(totalTokens: number, chunkSize: number): number {
if (totalTokens <= chunkSize) return 1;
return Math.ceil(totalTokens / chunkSize);
}
/**
* Iterator that yields one chunk at a time to save memory
*/
async function* chunkIterator(text: string, chunkSize?: number): AsyncGenerator<{
chunk: string;
index: number;
tokenCount: number;
totalChunks: number;
}, void, unknown> {
console.log(pc.cyan('\n┌─────────────────────────────────────────┐'));
console.log(pc.cyan('│ CONTENT CHUNKING │'));
console.log(pc.cyan('└─────────────────────────────────────────┘\n'));
// Get tokenizer for the model
const encoding = getEncoding('cl100k_base');
const tokens = encoding.encode(text);
const totalTokens = tokens.length;
const cSize = chunkSize || CHUNK_SIZE;
console.log(`● Document size: ${formatTokenCount(totalTokens)} tokens`);
console.log(`● Chunk size: ${formatTokenCount(cSize)} tokens`);
// Calculate and display the estimated cost
const estimatedCost = (totalTokens * costPerToken).toFixed(4);
console.log(pc.yellow(`● Estimated input processing cost: $${estimatedCost} (${formatTokenCount(totalTokens)} tokens × $${costPerToken} per token)`));
// Create a user dialog to confirm proceeding
const rl = readline.createInterface({ input, output });
try {
const answer = await rl.question(pc.yellow('\nProceed with processing? (y/n): '));
const proceed = answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';
if (!proceed) {
console.log(pc.red('\nOperation cancelled by user.'));
process.exit(0);
}
} finally {
rl.close();
}
// Calculate the total number of chunks for progress reporting
const totalChunks = calculateChunkCount(totalTokens, chunkSize || CHUNK_SIZE);
console.log(pc.green(`✓ Will process ${totalChunks} chunks\n`));
// Yield chunks one at a time
let i = 0;
let chunkIndex = 0;
while (i < tokens.length) {
// Get the current chunk of tokens
const chunkTokens = tokens.slice(i, Math.min(i + cSize, tokens.length));
const chunk = encoding.decode(chunkTokens);
// Yield the current chunk along with its metadata
yield {
chunk,
index: chunkIndex,
tokenCount: chunkTokens.length,
totalChunks
};
// Move forward to the next chunk (no overlap)
i += cSize;
chunkIndex++;
}
process.stdout.write('\n\n');
}
async function generateWithProvider(
repoContent: string,
guidelines: string,
outputDir: string = '.',
description?: string,
ruleType?: string,
options: LLMGeneratorOptions = { provider: 'anthropic' }
): Promise<string> {
const registry = new LLMProviderRegistry();
// Determine provider type
const providerType = options.provider as any;
const provider = registry.getProvider(providerType);
// Get default configuration for the provider
const defaultConfig = registry.getDefaultConfig(providerType);
// Merge with provided options
const config: LLMProviderConfig = {
...defaultConfig,
...options,
model: options.model || defaultConfig.model
};
// Validate configuration
provider.validateConfig(config);
// Process text chunk by chunk using the iterator
let currentSummary = ''; // This will store our progressively built summary
// Helper function to extract content between <cursorrules> tags
function extractCursorrules(text: string): string {
const regex = /<cursorrules>([\s\S]*?)<\/cursorrules>/;
const match = text.match(regex);
if (!match) {
throw new Error('Response does not contain <cursorrules> tags. Make sure the model includes the required tags in its response.');
}
return match[1].trim();
}
// Create a chunk iterator to process one chunk at a time
const chunkGen = chunkIterator(repoContent, options.chunkSize);
for await (const { chunk, index, tokenCount, totalChunks } of chunkGen) {
const chunkDisplay = `[${index+1}/${totalChunks}]`;
console.log(`${pc.yellow('⟳')} Processing chunk ${pc.yellow(chunkDisplay)} ${progressBar(index+1, totalChunks)}`);
// Display chunk information
console.log(pc.cyan(`┌${'─'.repeat(58)}┐`));
console.log(pc.cyan(`│ Chunk: ${String(index+1).padEnd(10)} Token Count: ${formatTokenCount(tokenCount).padEnd(12)} │`));
console.log(pc.cyan(`└${'─'.repeat(58)}┘\n`));
const isFirstChunk = index === 0;
const systemPrompt = 'You are an expert AI system designed to analyze code repositories and generate Cursor AI rules. Your task is to create a .cursorrules file based on the provided repository content and guidelines.';
let userPrompt: string;
if (isFirstChunk) {
// For the first chunk, start creating the rules
userPrompt = `I need your help to create a Cursor rule (.cursorrules) file for my project. Please follow this process:
1. First, carefully read and understand this codebase chunk:
<repository_chunk>
${chunk}
</repository_chunk>
2. Now, review these guidelines for creating effective Cursor rules:
<guidelines>
${guidelines}
</guidelines>
${description ? `3. I specifically want to create rules for: "${description}"` : ''}
${ruleType ? `4. The rule type should be: "${ruleType}"` : ''}
${description || ruleType ? '5' : '3'}. Analyze the repository content and structure, considering:
- Main technologies, frameworks, and languages used
- Coding patterns, naming conventions, and architectural decisions
- Overall codebase structure including key directories and file types
- Project-specific practices and testing guidelines
- Guidelines and standards documented in comments or markdown files by developers
Present your analysis inside <repository_analysis> tags.
${description || ruleType ? '6' : '4'}. Create a complete .cursorrules file that:
- Is specific to this repository's structure and technologies
- Includes best practices and guidelines from code, comments, and documentation
- Organizes rules to match the codebase structure
- Is concise and actionable
- Includes testing best practices and guidelines
- Uses valid Markdown format${ruleType ? `
- Follows the rule type: "${ruleType}"` : ''}${description ? `
- Addresses the specific request: "${description}"` : ''}
Include your final .cursorrules content inside <cursorrules> tags.
Be concise - the final cursorrules file text must be not more than one page long.
Example structure:
<cursorrules>
...markdown content of the .cursorrules file, following the guidelines and analysis...
</cursorrules>`;
} else {
// For subsequent chunks, enhance the existing summary
userPrompt = `I need your help to update a Cursor rule (.cursorrules) file based on a new chunk of my project:
1. Here is the current .cursorrules file content:
<current_rules>
${currentSummary}
</current_rules>
2. Now, carefully review this new repository chunk:
<repository_chunk>
${chunk}
</repository_chunk>
3. Review these guidelines for creating effective Cursor rules:
<guidelines>
${guidelines}
</guidelines>
${description ? `4. Remember, I specifically want to create rules for: "${description}"` : ''}
${ruleType ? `${description ? '5' : '4'}. The rule type should be: "${ruleType}"` : ''}
${description || ruleType ? (description && ruleType ? '6' : '5') : '4'}. Analyze this new chunk for:
- New technologies, frameworks, or languages not previously covered
- Additional coding patterns, naming conventions, or architectural decisions
- Further insights into codebase structure
- Project-specific practices and testing guidelines
- Guidelines and standards documented in comments or markdown files by developers
Present your analysis inside <new_insights> tags.
${description || ruleType ? (description && ruleType ? '7' : '6') : '5'}. Update the existing rules by:
- Preserving all valuable information from existing rules
- Maintaining the same structure and organization
- Adding new information only for patterns not already covered
- Being specific about code structure and patterns
- Including testing-related insights and best practices
- Being concise but comprehensive${ruleType ? `
- Following the rule type: "${ruleType}"` : ''}${description ? `
- Addressing the specific request: "${description}"` : ''}
Include your final updated .cursorrules content inside <cursorrules> tags.
Be concise - the final cursorrules file text must be not more than one page long.`;
}
const messages: LLMMessage[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
];
process.stdout.write(`${pc.blue('🔄')} Sending to ${provider.displayName} ${config.model}... `);
try {
const startTime = Date.now();
const response = await provider.generateResponse(messages, config);
currentSummary = response.content;
const endTime = Date.now();
const processingTime = ((endTime - startTime) / 1000).toFixed(2);
process.stdout.write(pc.green('✓\n'));
// Save intermediate output to file in the specified directory
const intermediateFileName = path.join(outputDir, `cursorrules_chunk_${index+1}_of_${totalChunks}.md`);
await fs.writeFile(intermediateFileName, currentSummary);
console.log(`${pc.green('✓')} Saved intermediate output to ${pc.blue(intermediateFileName)} ${pc.gray(`(${processingTime}s)`)}\n`);
} catch (error) {
process.stdout.write(pc.red('✗\n'));
if (error instanceof Error) {
throw new Error(`${pc.red('Error generating with')} ${provider.displayName} ${pc.red('on chunk')} ${index+1}: ${error.message}`);
}
throw new Error(`${pc.red('Unknown error occurred while generating with')} ${provider.displayName} ${pc.red('on chunk')} ${index+1}`);
}
}
console.log(pc.green('\n┌─────────────────────────────────────────┐'));
console.log(pc.green('│ PROCESSING COMPLETE │'));
console.log(pc.green('└─────────────────────────────────────────┘\n'));
// Only extract the cursorrules content at the very end
return extractCursorrules(currentSummary);
}
function generateMockResponse(repoContent: string): string {
// Extract some information from the repo content for the mock response
const repoLines = repoContent.split('\n');
const repoName = repoLines.find(line => line.includes('# Project:'))?.replace('# Project:', '').trim() || 'Repository';
return `# .cursorrules for ${repoName}
## Project Overview
This project appears to be a TypeScript/Node.js application that processes GitHub repositories.
## Coding Standards
- Follow TypeScript best practices with strict typing
- Use async/await for asynchronous operations
- Prefer functional programming patterns where appropriate
- Use descriptive variable and function names
## File Structure Guidelines
- Place core logic in the \`src/\` directory
- Organize code by feature or functionality
- Keep related functionality together
- Use index.ts files for clean exports
## Style Conventions
- Use camelCase for variables and functions
- Use PascalCase for classes and interfaces
- Use 2-space indentation
- End files with a newline
## Testing Standards
- Write unit tests for all functionality
- Use descriptive test names
- Follow AAA (Arrange-Act-Assert) pattern
- Mock external dependencies
## Error Handling
- Use try/catch blocks for error handling
- Provide descriptive error messages
- Handle edge cases appropriately
- Log errors with appropriate severity levels
## Comments and Documentation
- Document public APIs
- Add comments for complex logic
- Use JSDoc for function documentation
- Keep comments up-to-date with code changes
## Performance Considerations
- Optimize for speed and efficiency
- Use appropriate data structures
- Minimize unnecessary computations
- Consider memory usage for large operations
## Security Best Practices
- Validate all inputs
- Avoid hardcoded credentials
- Use proper error handling
- Follow secure coding practices`;
}
</file>
<file path="src/providers/anthropic-provider.ts">
import Anthropic from '@anthropic-ai/sdk';
import pc from 'picocolors';
import { BaseLLMProvider } from './base-provider.js';
import { LLMProviderConfig, LLMMessage, LLMResponse } from '../types/llm-provider.js';
/**
* Anthropic Claude provider implementation
*/
export class AnthropicProvider extends BaseLLMProvider {
readonly name = 'anthropic';
readonly displayName = 'Anthropic Claude';
readonly requiresApiKey = true;
readonly defaultModel = 'claude-3-5-sonnet-20241022';
private client: Anthropic | null = null;
constructor() {
super();
}
/**
* Initialize the Anthropic client
*/
private initializeClient(apiKey: string): Anthropic {
if (!this.client) {
this.client = new Anthropic({ apiKey });
}
return this.client;
}
/**
* Generate a response using Anthropic Claude
*/
async generateResponse(
messages: LLMMessage[],
config: LLMProviderConfig
): Promise<LLMResponse> {
try {
this.validateConfig(config);
const client = this.initializeClient(config.apiKey!);
// Convert messages to Anthropic format
const systemMessage = messages.find(msg => msg.role === 'system');
const userMessages = messages.filter(msg => msg.role === 'user' || msg.role === 'assistant');
// Anthropic expects the last message to be from user
const lastMessage = userMessages[userMessages.length - 1];
const conversationMessages = userMessages.slice(0, -1).map(msg => ({
role: msg.role === 'assistant' ? 'assistant' as const : 'user' as const,
content: msg.content
}));
const response = await client.messages.create({
model: config.model,
max_tokens: config.maxTokens || 8000,
system: systemMessage?.content,
messages: [
...conversationMessages,
{
role: 'user',
content: lastMessage.content
}
]
});
const content = this.extractContent(response);
const usage = this.extractUsage(response);
return {
content,
usage,
model: config.model,
provider: this.name
};
} catch (error) {
this.handleApiError(error, 'Anthropic API error');
}
}
/**
* Get available Anthropic models
*/
getAvailableModels(): string[] {
return [
'claude-3-5-sonnet-20241022',
'claude-3-5-haiku-20241022',
'claude-3-opus-20240229',
'claude-3-sonnet-20240229',
'claude-3-haiku-20240307'
];
}
/**
* Extract content from Anthropic response
*/
protected extractContent(response: any): string {
if (response.content && Array.isArray(response.content) && response.content.length > 0) {
return response.content[0].text || '';
}
return '';
}
/**
* Extract usage information from Anthropic response
*/
protected extractUsage(response: any): LLMResponse['usage'] {
if (response.usage) {
return {
promptTokens: response.usage.input_tokens || 0,
completionTokens: response.usage.output_tokens || 0,
totalTokens: response.usage.input_tokens + response.usage.output_tokens || 0
};
}
return undefined;
}
}
</file>
<file path="src/providers/base-provider.ts">
import pc from 'picocolors';
import { LLMProvider, LLMProviderConfig, LLMMessage, LLMResponse } from '../types/llm-provider.js';
/**
* Base class for LLM providers
* Provides common functionality and error handling
*/
export abstract class BaseLLMProvider implements LLMProvider {
abstract readonly name: string;
abstract readonly displayName: string;
abstract readonly requiresApiKey: boolean;
abstract readonly defaultModel: string;
/**
* Generate a response using the LLM
*/
abstract generateResponse(
messages: LLMMessage[],
config: LLMProviderConfig
): Promise<LLMResponse>;
/**
* Validate the provider configuration
*/
validateConfig(config: LLMProviderConfig): void {
if (this.requiresApiKey && !config.apiKey) {
throw new Error(`${this.displayName} requires an API key. Please set the appropriate environment variable.`);
}
if (!config.model) {
throw new Error('Model is required for LLM generation');
}
if (config.maxTokens && config.maxTokens <= 0) {
throw new Error('maxTokens must be a positive number');
}
if (config.temperature && (config.temperature < 0 || config.temperature > 2)) {
throw new Error('temperature must be between 0 and 2');
}
}
/**
* Get available models for this provider
*/
abstract getAvailableModels(): string[];
/**
* Handle API errors with proper formatting
*/
protected handleApiError(error: unknown, context: string): never {
if (error instanceof Error) {
// Check for common API error patterns
if (error.message.includes('API key')) {
throw new Error(pc.red(`Authentication failed: ${error.message}`));
}
if (error.message.includes('rate limit') || error.message.includes('quota')) {
throw new Error(pc.yellow(`Rate limit exceeded: ${error.message}`));
}
if (error.message.includes('timeout')) {
throw new Error(pc.yellow(`Request timeout: ${error.message}`));
}
if (error.message.includes('network') || error.message.includes('connection')) {
throw new Error(pc.red(`Network error: ${error.message}`));
}
throw new Error(pc.red(`${context}: ${error.message}`));
}
throw new Error(pc.red(`${context}: Unknown error occurred`));
}
/**
* Format messages for the provider
*/
protected formatMessages(messages: LLMMessage[]): LLMMessage[] {
return messages.map(msg => ({
...msg,
content: msg.content.trim()
}));
}
/**
* Extract content from provider-specific response format
*/
protected extractContent(response: any): string {
// This should be overridden by each provider
return response.content || response.text || '';
}
/**
* Extract usage information from provider-specific response format
*/
protected extractUsage(response: any): LLMResponse['usage'] {
// This should be overridden by each provider
return undefined;
}
}
</file>
<file path="src/providers/local-provider.ts">
import pc from 'picocolors';
import { BaseLLMProvider } from './base-provider.js';
import { LLMProviderConfig, LLMMessage, LLMResponse } from '../types/llm-provider.js';
/**
* Local OpenAI-compatible provider implementation
* Supports Ollama, LM Studio, and other OpenAI-compatible local APIs
*/
export class LocalProvider extends BaseLLMProvider {
readonly name = 'local';
readonly displayName = 'Local (OpenAI-compatible)';
readonly requiresApiKey = false;
readonly defaultModel = 'llama3.1';
/**
* Generate a response using a local OpenAI-compatible API
*/
async generateResponse(
messages: LLMMessage[],
config: LLMProviderConfig
): Promise<LLMResponse> {
try {
this.validateConfig(config);
const baseURL = config.baseURL || 'http://localhost:11434/v1'; // Default Ollama URL
// Convert messages to OpenAI format
const openaiMessages = this.formatMessages(messages).map(msg => ({
role: msg.role as 'system' | 'user' | 'assistant',
content: msg.content
}));
const response = await fetch(`${baseURL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(config.apiKey && { 'Authorization': `Bearer ${config.apiKey}` })
},
body: JSON.stringify({
model: config.model,
messages: openaiMessages,
max_tokens: config.maxTokens || 8000,
temperature: config.temperature || 0.7,
stream: false
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
const content = this.extractContent(data);
const usage = this.extractUsage(data);
return {
content,
usage,
model: config.model,
provider: this.name
};
} catch (error) {
this.handleApiError(error, 'Local API error');
}
}
/**
* Get available local models
* Note: This is a static list as we can't query the local API without knowing the endpoint
*/
getAvailableModels(): string[] {
return [
'llama3.1',
'llama3.1:8b',
'llama3.1:70b',
'llama3.2',
'llama3.2:3b',
'llama3.2:1b',
'codellama',
'codellama:7b',
'codellama:13b',
'codellama:34b',
'mistral',
'mistral:7b',
'mixtral',
'mixtral:8x7b',
'phi3',
'phi3:mini',
'gemma',
'gemma:2b',
'gemma:7b',
'qwen',
'qwen2',
'qwen2.5',
'deepseek-coder',
'starcoder2',
'wizardcoder',
'magicoder'
];
}
/**
* Extract content from OpenAI-compatible response
*/
protected extractContent(response: any): string {
if (response.choices && response.choices.length > 0) {
return response.choices[0].message?.content || '';
}
return '';
}
/**
* Extract usage information from OpenAI-compatible response
*/
protected extractUsage(response: any): LLMResponse['usage'] {
if (response.usage) {
return {
promptTokens: response.usage.prompt_tokens || 0,
completionTokens: response.usage.completion_tokens || 0,
totalTokens: response.usage.total_tokens || 0
};
}
return undefined;
}
/**
* Validate local provider configuration
*/
validateConfig(config: LLMProviderConfig): void {
super.validateConfig(config);
if (config.baseURL && !this.isValidUrl(config.baseURL)) {
throw new Error('baseURL must be a valid URL');
}
}
/**
* Check if a string is a valid URL
*/
private isValidUrl(urlString: string): boolean {
try {
new URL(urlString);
return true;
} catch {
return false;
}
}
}
</file>
<file path="src/providers/openai-provider.ts">
import OpenAI from 'openai';
import pc from 'picocolors';
import { BaseLLMProvider } from './base-provider.js';
import { LLMProviderConfig, LLMMessage, LLMResponse } from '../types/llm-provider.js';
/**
* OpenAI provider implementation
*/
export class OpenAIProvider extends BaseLLMProvider {
readonly name = 'openai';
readonly displayName = 'OpenAI';
readonly requiresApiKey = true;
readonly defaultModel = 'gpt-4o';
private client: OpenAI | null = null;
constructor() {
super();
}
/**
* Initialize the OpenAI client
*/
private initializeClient(apiKey: string, baseURL?: string): OpenAI {
if (!this.client) {
this.client = new OpenAI({
apiKey,
baseURL,
timeout: 60000 // 60 seconds timeout
});
}
return this.client;
}
/**
* Generate a response using OpenAI
*/
async generateResponse(
messages: LLMMessage[],
config: LLMProviderConfig
): Promise<LLMResponse> {
try {
this.validateConfig(config);
const client = this.initializeClient(config.apiKey!, config.baseURL);
// Convert messages to OpenAI format
const openaiMessages = this.formatMessages(messages).map(msg => ({