cloving 0.3.17 → 0.3.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/.DS_Store +0 -0
  2. package/.aider.chat.history.md +16978 -0
  3. package/.aider.input.history +15 -0
  4. package/.aider.tags.cache.v3/cache.db +0 -0
  5. package/.aider.tags.cache.v3/cache.db-shm +0 -0
  6. package/.aider.tags.cache.v3/cache.db-wal +0 -0
  7. package/.cursorrules +77 -0
  8. package/.github/workflows/auto-release.yml +83 -0
  9. package/.github/workflows/ci.yml +32 -0
  10. package/.github/workflows/npm-publish.yml +34 -0
  11. package/.gitignore +67 -0
  12. package/.husky/_/.gitignore +1 -0
  13. package/.husky/_/applypatch-msg +2 -0
  14. package/.husky/_/commit-msg +2 -0
  15. package/.husky/_/h +22 -0
  16. package/.husky/_/husky.sh +9 -0
  17. package/.husky/_/post-applypatch +2 -0
  18. package/.husky/_/post-checkout +2 -0
  19. package/.husky/_/post-commit +2 -0
  20. package/.husky/_/post-merge +2 -0
  21. package/.husky/_/post-rewrite +2 -0
  22. package/.husky/_/pre-applypatch +2 -0
  23. package/.husky/_/pre-auto-gc +2 -0
  24. package/.husky/_/pre-commit +2 -0
  25. package/.husky/_/pre-merge-commit +2 -0
  26. package/.husky/_/pre-push +2 -0
  27. package/.husky/_/pre-rebase +2 -0
  28. package/.husky/_/prepare-commit-msg +2 -0
  29. package/.husky/pre-commit +1 -0
  30. package/.husky/pre-push +1 -0
  31. package/.prettierrc.json +7 -0
  32. package/.tool-versions +2 -0
  33. package/SECURITY.md +15 -0
  34. package/cloving.json +67 -0
  35. package/dist/cloving_gpt/adapters/openai.js +2 -0
  36. package/dist/commands/generate/context.js +1 -1
  37. package/dist/commands/tokens.js +1 -1
  38. package/dist/managers/CommitManager.js +8 -2
  39. package/dist/managers/ProxyManager.js +9 -2
  40. package/dist/managers/StreamManager.js +1 -1
  41. package/dist/package.json +26 -26
  42. package/dist/utils/config_utils.js +21 -4
  43. package/dist/utils/git_utils.js +109 -7
  44. package/dist/utils/prompt_utils.js +3 -3
  45. package/jest.config.js +11 -0
  46. package/package.json +23 -23
  47. package/src/cloving_gpt/adapters/azureopenai.ts +83 -0
  48. package/src/cloving_gpt/adapters/claude.ts +140 -0
  49. package/src/cloving_gpt/adapters/gemini.ts +146 -0
  50. package/src/cloving_gpt/adapters/index.ts +43 -0
  51. package/src/cloving_gpt/adapters/mistral.ts +142 -0
  52. package/src/cloving_gpt/adapters/ollama.ts +136 -0
  53. package/src/cloving_gpt/adapters/openai.ts +113 -0
  54. package/src/cloving_gpt/index.ts +229 -0
  55. package/src/commands/chat.ts +12 -0
  56. package/src/commands/config.ts +192 -0
  57. package/src/commands/generate/code.ts +18 -0
  58. package/src/commands/generate/commit.ts +9 -0
  59. package/src/commands/generate/context.ts +93 -0
  60. package/src/commands/generate/docs.ts +9 -0
  61. package/src/commands/generate/review.ts +9 -0
  62. package/src/commands/generate/shell.ts +9 -0
  63. package/src/commands/generate/unit_tests.ts +9 -0
  64. package/src/commands/init.ts +9 -0
  65. package/src/commands/models.ts +21 -0
  66. package/src/commands/proxy.ts +9 -0
  67. package/src/commands/tokens.ts +82 -0
  68. package/src/index.ts +197 -0
  69. package/src/managers/BlockManager.ts +126 -0
  70. package/src/managers/ChatManager.ts +755 -0
  71. package/src/managers/ChunkManager.ts +31 -0
  72. package/src/managers/CodeManager.ts +226 -0
  73. package/src/managers/CommitManager.ts +71 -0
  74. package/src/managers/DocsManager.ts +101 -0
  75. package/src/managers/InitManager.ts +263 -0
  76. package/src/managers/ProxyManager.ts +240 -0
  77. package/src/managers/ReviewManager.ts +154 -0
  78. package/src/managers/ShellManager.ts +172 -0
  79. package/src/managers/StreamManager.ts +353 -0
  80. package/src/managers/UnitTestManager.ts +293 -0
  81. package/src/utils/config_utils.ts +271 -0
  82. package/src/utils/git_utils.ts +230 -0
  83. package/src/utils/model_utils.ts +3 -0
  84. package/src/utils/prompt_utils.ts +375 -0
  85. package/src/utils/prompts/CODEGEN_COULDNT_APPLY.md +5 -0
  86. package/src/utils/prompts/CODEGEN_EXAMPLES.md +82 -0
  87. package/src/utils/prompts/CODEGEN_INSTRUCTIONS.md +43 -0
  88. package/src/utils/prompts/DOCS_INSTRUCTIONS.md +9 -0
  89. package/src/utils/prompts/INIT_INSTRUCTIONS.md +132 -0
  90. package/src/utils/prompts/REVIEW_INSTRUCTIONS.md +49 -0
  91. package/src/utils/prompts/SHELL_INSTRUCTIONS.md +15 -0
  92. package/src/utils/prompts/SPECIAL_FILES.md +66 -0
  93. package/src/utils/prompts/index.ts +37 -0
  94. package/src/utils/string_utils.ts +552 -0
  95. package/src/utils/types.ts +127 -0
  96. package/tests/commands/generate/unit_tests.test.ts +27 -0
  97. package/tests/utils/git_utils.test.ts +116 -0
  98. package/tests/utils/model_utils.test.ts +27 -0
  99. package/tests/utils/prompt_utils.test.ts +33 -0
  100. package/tests/utils/string_utils.test.ts +560 -0
  101. package/tsconfig.json +14 -0
  102. package/yarn.lock +5823 -0
@@ -0,0 +1,755 @@
1
+ import ncp from 'copy-paste'
2
+ import colors from 'colors'
3
+ import highlight from 'cli-highlight'
4
+ import readline from 'readline'
5
+ import { execSync } from 'child_process'
6
+ import type { AxiosError } from 'axios'
7
+
8
+ import CommitManager from './CommitManager'
9
+ import ReviewManager from './ReviewManager'
10
+ import {
11
+ extractCurrentNewBlocks,
12
+ applyAndSaveCurrentNewBlocks,
13
+ checkBlocksApplicability,
14
+ } from '../utils/string_utils'
15
+ import { getConfig } from '../utils/config_utils'
16
+ import { addFileOrDirectoryToContext } from '../utils/prompt_utils'
17
+ import { CODEGEN_COULDNT_APPLY } from '../utils/prompts'
18
+ import type { ClovingGPTOptions } from '../utils/types'
19
+ import StreamManager from './StreamManager'
20
+
21
+ const specialCommands = [
22
+ 'save',
23
+ 'commit',
24
+ 'copy',
25
+ 'review',
26
+ 'add <file-path>',
27
+ 'find <file-name>',
28
+ 'rm <pattern>',
29
+ 'ls <pattern>',
30
+ 'git <command>',
31
+ 'help',
32
+ 'exit',
33
+ ]
34
+
35
+ class ChatManager extends StreamManager {
36
+ private commandHistory: string[] = []
37
+ private historyIndex: number = -1
38
+ private multilineInput: string = ''
39
+ private isMultilineMode: boolean = false
40
+ private isSilent = false
41
+ private rl: readline.Interface
42
+
43
+ /**
44
+ * Creates an instance of ChatManager.
45
+ * @param {ClovingGPTOptions} options - Configuration options for the ChatManager.
46
+ */
47
+ constructor(options: ClovingGPTOptions) {
48
+ super(options)
49
+ this.isSilent = options.silent || getConfig(options).globalSilent || false
50
+ options.stream = true
51
+ options.silent = true
52
+ this.rl = readline.createInterface({
53
+ input: process.stdin,
54
+ output: process.stdout,
55
+ prompt: colors.green.bold('cloving> '),
56
+ historySize: 1000,
57
+ })
58
+ }
59
+
60
+ /**
61
+ * Initializes the ChatManager by loading context files, displaying a welcome message,
62
+ * and setting up event listeners.
63
+ * @returns {Promise<void>}
64
+ */
65
+ async initialize(): Promise<void> {
66
+ await this.checkForLatestVersion()
67
+ await this.loadContextFiles()
68
+ console.log(`\n🍀 🍀 🍀 ${colors.bold('Welcome to Cloving REPL')} 🍀 🍀 🍀\n`)
69
+ this.displayAvailableCommands()
70
+ console.log('\nWhat would you like to do?')
71
+ this.setupReadline()
72
+ }
73
+
74
+ private displayAvailableCommands(): void {
75
+ console.log(
76
+ `Type a freeform request or question to interact with your Cloving AI pair programmer.\n`,
77
+ )
78
+ console.log('Available special commands:')
79
+ console.log(
80
+ ` - ${colors.yellow(colors.bold('save'))} Save all the changes from the last response to files`,
81
+ )
82
+ console.log(
83
+ ` - ${colors.yellow(colors.bold('commit'))} Commit the changes to git with an AI-generated message that you can edit`,
84
+ )
85
+ console.log(
86
+ ` - ${colors.yellow(colors.bold('copy'))} Copy the last response to clipboard`,
87
+ )
88
+ console.log(` - ${colors.yellow(colors.bold('review'))} Start a code review`)
89
+ console.log(
90
+ ` - ${colors.yellow(colors.bold('find <file-name>'))} Find and add files matching the name to the chat context (supports * for glob matching)`,
91
+ )
92
+ console.log(
93
+ ` - ${colors.yellow(colors.bold('add <file-path>'))} Add a file to the chat context (supports * for glob matching)`,
94
+ )
95
+ console.log(
96
+ ` - ${colors.yellow(colors.bold('rm <pattern>'))} Remove files from the chat context (supports * for glob matching)`,
97
+ )
98
+ console.log(
99
+ ` - ${colors.yellow(colors.bold('ls <pattern>'))} List files in the chat context (supports * for glob matching)`,
100
+ )
101
+ console.log(` - ${colors.yellow(colors.bold('git <command>'))} Run a git command`)
102
+ console.log(` - ${colors.yellow(colors.bold('help'))} Display this help message`)
103
+ console.log(` - ${colors.yellow(colors.bold('exit'))} Quit this session`)
104
+ }
105
+
106
+ /**
107
+ * Sets up readline and event listeners for the readline interface and process input.
108
+ * @private
109
+ */
110
+ private setupReadline(): void {
111
+ this.rl.prompt()
112
+ this.rl.on('line', this.handleLine.bind(this))
113
+ this.rl.on('close', this.handleClose.bind(this))
114
+ process.stdin.on('keypress', this.handleKeypress.bind(this))
115
+ }
116
+
117
+ /**
118
+ * Handles each line of input from the user.
119
+ * @private
120
+ * @param {string} line - The input line from the user.
121
+ * @returns {Promise<void>}
122
+ */
123
+ private async handleLine(line: string): Promise<void> {
124
+ if (this.isProcessing) {
125
+ return
126
+ }
127
+
128
+ const trimmedLine = line.trim()
129
+
130
+ if (this.isPastedCode(trimmedLine)) {
131
+ this.multilineInput = trimmedLine
132
+ this.isMultilineMode = true
133
+ await this.handleCommand(this.multilineInput)
134
+ this.multilineInput = ''
135
+ this.isMultilineMode = false
136
+ return
137
+ }
138
+
139
+ if (this.handleMultilineInput(trimmedLine)) {
140
+ return
141
+ }
142
+
143
+ if (trimmedLine === '') {
144
+ this.displayPrompt()
145
+ return
146
+ }
147
+
148
+ this.updateCommandHistory(trimmedLine)
149
+
150
+ if (this.handleExitCommand(trimmedLine)) {
151
+ return
152
+ }
153
+
154
+ await this.handleCommand(trimmedLine)
155
+ }
156
+
157
+ private handleMultilineInput(line: string): boolean {
158
+ if (this.isMultilineMode) {
159
+ if (line === '```') {
160
+ this.isMultilineMode = false
161
+ this.handleCommand(this.multilineInput)
162
+ this.multilineInput = ''
163
+ } else {
164
+ this.multilineInput += line + '\n'
165
+ this.rl.prompt()
166
+ }
167
+ return true
168
+ } else if (line === '```') {
169
+ this.isMultilineMode = true
170
+ this.multilineInput = ''
171
+ console.log('Entering multiline mode. Type ``` on a new line to end.\n')
172
+ this.rl.prompt()
173
+ return true
174
+ }
175
+ return false
176
+ }
177
+
178
+ private isPastedCode(line: string): boolean {
179
+ // Check if the line contains multiple lines (indicating a paste)
180
+ return line.includes('\n') || line.length > 100
181
+ }
182
+
183
+ private handleExitCommand(command: string): boolean {
184
+ if (command.toLowerCase() === 'exit') {
185
+ this.rl.close()
186
+ return true
187
+ }
188
+ return false
189
+ }
190
+
191
+ private updateCommandHistory(command: string) {
192
+ if (this.commandHistory[0] !== command) {
193
+ this.commandHistory.unshift(command)
194
+ if (this.commandHistory.length > 1000) {
195
+ this.commandHistory.pop()
196
+ }
197
+ }
198
+ this.historyIndex = -1
199
+ }
200
+
201
+ /**
202
+ * Handles various commands entered by the user.
203
+ * This function acts as a command router, delegating to specific handlers based on the input.
204
+ *
205
+ * @private
206
+ * @param {string} command - The command entered by the user.
207
+ * @returns {Promise<void>}
208
+ *
209
+ * @description
210
+ * Supported commands:
211
+ * - 'copy': Copies the last response to clipboard.
212
+ * - 'save': Saves changes to files.
213
+ * - 'commit': Commits changes to git with an AI-generated message.
214
+ * - 'ls': Lists files in the context (equivalent to 'ls *').
215
+ * - 'rm': Removes all files from the context (equivalent to 'rm *').
216
+ * - 'review': Starts a code review.
217
+ * - 'add <file-path>': Adds a file to the context.
218
+ * - 'rm <pattern>': Removes files matching the pattern from the context.
219
+ * - 'ls <pattern>': Lists files in the context matching the pattern.
220
+ * - 'git <command>': Executes a git command.
221
+ * - Any other input is processed as a user query to the AI.
222
+ */
223
+ private async handleCommand(command: string): Promise<void> {
224
+ // Check if the command is a single character and map it to the first matching special command
225
+ if (command.length === 1) {
226
+ const matchingCommand = specialCommands.find((cmd) => cmd.startsWith(command))
227
+ if (matchingCommand) {
228
+ command = matchingCommand.split(' ')[0] // Use only the command part without arguments
229
+ } else {
230
+ console.log(`No matching command found for '${command}'. Processing as user input.`)
231
+ await this.processUserInput(command)
232
+ return
233
+ }
234
+ }
235
+
236
+ switch (command) {
237
+ case 'help':
238
+ this.displayHelp()
239
+ break
240
+ case 'copy':
241
+ await this.handleCopy()
242
+ break
243
+ case 'save':
244
+ await this.handleSave()
245
+ break
246
+ case 'commit':
247
+ await this.handleCommit()
248
+ break
249
+ case 'ls':
250
+ this.handleList('ls *')
251
+ break
252
+ case 'rm':
253
+ await this.handleRemove('rm *')
254
+ break
255
+ case 'review':
256
+ await this.handleReview()
257
+ break
258
+ default:
259
+ if (this.isAddCommand(command)) {
260
+ await this.handleAdd(command)
261
+ } else if (this.isFindCommand(command)) {
262
+ await this.handleFind(command)
263
+ } else if (this.isRemoveCommand(command)) {
264
+ await this.handleRemove(command)
265
+ } else if (this.isListCommand(command)) {
266
+ this.handleList(command)
267
+ } else if (this.isGitCommand(command)) {
268
+ this.executeGitCommand(command)
269
+ } else {
270
+ await this.processUserInput(command)
271
+ }
272
+ }
273
+ }
274
+
275
+ private isFindCommand(command: string): boolean {
276
+ const parts = command.trim().split(/\s+/)
277
+ return parts.length === 2 && parts[0] === 'find'
278
+ }
279
+
280
+ private async handleFind(command: string) {
281
+ const fileName = command.slice(5).trim()
282
+
283
+ if (fileName) {
284
+ try {
285
+ const foundFiles = await this.findFiles(fileName)
286
+ if (foundFiles.length === 0) {
287
+ console.log(`No files found matching ${colors.bold(colors.red(fileName))}.`)
288
+ } else {
289
+ for (const filePath of foundFiles) {
290
+ this.contextFiles = await addFileOrDirectoryToContext(
291
+ filePath,
292
+ this.contextFiles,
293
+ this.options,
294
+ )
295
+ const content = this.contextFiles[filePath]
296
+ const tokenEstimate = this.estimateTokens(content)
297
+ console.log(
298
+ `\nAdded ${colors.bold(colors.green(filePath))} to this chat session's context (${colors.yellow(`~${tokenEstimate.toLocaleString()} tokens`)})`,
299
+ )
300
+ }
301
+ const totalTokens = this.calculateTotalTokens()
302
+ console.log(
303
+ colors.yellow(`\n📊 Total tokens in context now: ${totalTokens.toLocaleString()}\n`),
304
+ )
305
+ }
306
+ } catch (error) {
307
+ console.error(
308
+ `Failed to find and add files matching ${colors.bold(colors.red(fileName))}:`,
309
+ error,
310
+ )
311
+ }
312
+ } else {
313
+ console.log('No file name provided.')
314
+ }
315
+
316
+ this.rl.prompt()
317
+ }
318
+
319
+ private async findFiles(fileName: string): Promise<string[]> {
320
+ const { exec } = require('child_process')
321
+ return new Promise((resolve, reject) => {
322
+ exec(`find . -name "${fileName}"`, (error: Error | null, stdout: string) => {
323
+ if (error) {
324
+ return reject(error)
325
+ }
326
+ const files = stdout
327
+ .split('\n')
328
+ .filter((filePath) => filePath.trim() !== '')
329
+ .map((filePath) => (filePath.startsWith('./') ? filePath.slice(2) : filePath))
330
+ resolve(files)
331
+ })
332
+ })
333
+ }
334
+
335
+ private displayHelp(): void {
336
+ console.log('')
337
+ this.displayAvailableCommands()
338
+ console.log('\nFor any other input, I will process it as a request or question.\n')
339
+ this.rl.prompt()
340
+ }
341
+
342
+ private isAddCommand(command: string): boolean {
343
+ const parts = command.trim().split(/\s+/)
344
+ return parts.length === 2 && parts[0] === 'add'
345
+ }
346
+
347
+ private async handleAdd(command: string) {
348
+ const filePath = command.slice(4).trim()
349
+
350
+ if (filePath) {
351
+ try {
352
+ this.contextFiles = await addFileOrDirectoryToContext(
353
+ filePath,
354
+ this.contextFiles,
355
+ this.options,
356
+ )
357
+ console.log(`\nAdded ${colors.bold(colors.green(filePath))} to this chat session's context`)
358
+ this.refreshContext()
359
+ } catch (error) {
360
+ console.error(
361
+ `Failed to add ${colors.bold(colors.red(filePath))} to this chat session's context:`,
362
+ error,
363
+ )
364
+ }
365
+ } else {
366
+ console.log('No file path provided.')
367
+ }
368
+
369
+ this.rl.prompt()
370
+ }
371
+
372
+ private isRemoveCommand(command: string): boolean {
373
+ return command.startsWith('rm ')
374
+ }
375
+
376
+ // Function to convert glob-like pattern to a regular expression
377
+ private globToRegExp(glob: string): RegExp {
378
+ const escapedGlob = glob.replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&')
379
+ const regexString = escapedGlob.replace(/\*/g, '.*')
380
+ return new RegExp(`^${regexString}$`)
381
+ }
382
+
383
+ // Function to filter paths using the pattern
384
+ private filterPaths(paths: string[], pattern: string): string[] {
385
+ const regex = this.globToRegExp(pattern)
386
+ return paths.filter((path) => regex.test(path))
387
+ }
388
+
389
+ private async handleRemove(command: string) {
390
+ const pattern = command.slice(3).trim()
391
+
392
+ if (pattern) {
393
+ const matchedFiles = this.filterPaths(Object.keys(this.contextFiles), pattern)
394
+
395
+ if (matchedFiles.length > 0) {
396
+ matchedFiles.forEach((filePath) => {
397
+ delete this.contextFiles[filePath]
398
+ console.log(
399
+ `Removed ${colors.bold(colors.green(filePath))} from this chat session's context files`,
400
+ )
401
+ })
402
+ } else {
403
+ console.log(
404
+ `No files matching pattern "${colors.bold(pattern)}" found in this chat session's context files, try running ${colors.yellow('ls')} to see the list of files.`,
405
+ )
406
+ }
407
+ } else {
408
+ console.log('No pattern provided.')
409
+ }
410
+
411
+ this.rl.prompt()
412
+ }
413
+
414
+ private isListCommand(command: string): boolean {
415
+ return command.startsWith('ls ')
416
+ }
417
+
418
+ private estimateTokens(text: string): number {
419
+ // A simple estimation: 1 token ≈ 4 characters
420
+ return Math.ceil(text.length / 4)
421
+ }
422
+
423
+ private handleList(command: string) {
424
+ const pattern = command.slice(3).trim()
425
+ const fileNames = Object.keys(this.contextFiles)
426
+
427
+ const matchedFiles = pattern ? this.filterPaths(fileNames, pattern) : fileNames
428
+
429
+ if (matchedFiles.length > 0) {
430
+ console.log(`\nFiles in the current chat session context:`)
431
+ let totalTokens = 0
432
+ matchedFiles.forEach((fileName) => {
433
+ const content = this.contextFiles[fileName]
434
+ const tokenEstimate = this.estimateTokens(content)
435
+ totalTokens += tokenEstimate
436
+ console.log(
437
+ ` - ${colors.bold(colors.green(fileName))} (${colors.yellow(`~${tokenEstimate.toLocaleString()} tokens`)})`,
438
+ )
439
+ })
440
+ console.log(`\nTotal files: ${matchedFiles.length}`)
441
+ console.log(`Total estimated tokens: ${colors.yellow(totalTokens.toLocaleString())}\n`)
442
+ } else {
443
+ console.log('No files currently in context.')
444
+ }
445
+ this.rl.prompt()
446
+ }
447
+
448
+ private async handleCopy() {
449
+ const lastResponse = this.chatHistory.filter((msg) => msg.role === 'assistant').pop()
450
+ if (lastResponse) {
451
+ ncp.copy(lastResponse.content, () => {
452
+ console.info('Last response copied to clipboard.')
453
+ this.rl.prompt()
454
+ })
455
+ } else {
456
+ console.error('No response to copy.')
457
+ }
458
+ }
459
+
460
+ private async handleReview() {
461
+ this.options.stream = false
462
+ const reviewManager = new ReviewManager(this.options)
463
+ await reviewManager.generateReview()
464
+ this.options.stream = true
465
+ this.rl.prompt()
466
+ }
467
+
468
+ private async handleCommit() {
469
+ this.options.stream = false
470
+ const commitManager = new CommitManager(this.options)
471
+ await commitManager.generateCommit()
472
+ this.options.stream = true
473
+ this.rl.prompt()
474
+ }
475
+
476
+ private async handleSave() {
477
+ const lastResponse = this.chatHistory
478
+ .slice()
479
+ .reverse()
480
+ .find((msg) => msg.role === 'assistant')
481
+
482
+ if (lastResponse) {
483
+ const currentNewBlocks = extractCurrentNewBlocks(lastResponse.content)
484
+ if (Object.keys(currentNewBlocks).length > 0) {
485
+ await applyAndSaveCurrentNewBlocks(currentNewBlocks)
486
+ console.info(`\n${colors.bold('save')} has finished\n`)
487
+ this.rl.prompt()
488
+ } else {
489
+ console.info('No changes found to save in the last response.')
490
+ this.rl.prompt()
491
+ }
492
+ } else {
493
+ console.error('No response to save files from.')
494
+ this.rl.prompt()
495
+ }
496
+ }
497
+
498
+ private isGitCommand(command: string): boolean {
499
+ return command.split(' ').length <= 3 && command.startsWith('git ')
500
+ }
501
+
502
+ private executeGitCommand(command: string) {
503
+ try {
504
+ execSync(command, { stdio: 'inherit' })
505
+ } catch (error) {
506
+ console.error('Error running command:', error)
507
+ }
508
+ this.rl.prompt()
509
+ }
510
+
511
+ /**
512
+ * Processes user input by sending it to the AI model and handling the response.
513
+ *
514
+ * This method manages the interaction with the AI model by:
515
+ * 1. Checking if a request is already being processed.
516
+ * 2. Initializing the chat history and generating a prompt.
517
+ * 3. Streaming the response from the AI model.
518
+ * 4. Handling the response stream and updating the chat history.
519
+ *
520
+ * @param {string} input - The user's input or request to be processed.
521
+ * @returns {Promise<void>} - A promise that resolves when the processing is complete.
522
+ */
523
+ private async processUserInput(input: string): Promise<void> {
524
+ if (this.isProcessing) {
525
+ console.log('Please wait for the current request to complete.')
526
+ return
527
+ }
528
+
529
+ this.isProcessing = true
530
+
531
+ try {
532
+ await this.refreshContext()
533
+ this.addUserPrompt(this.generatePrompt(input))
534
+
535
+ if (!this.gpt.silent) {
536
+ const fullPrompt = this.chatHistory
537
+ .map((m) => {
538
+ const content = m.content
539
+ .split('\n')
540
+ .map((line) => {
541
+ if (line.startsWith('###')) {
542
+ return colors.red.bold(line)
543
+ } else if (line.startsWith('##')) {
544
+ return colors.yellow.bold(line)
545
+ }
546
+ return line
547
+ })
548
+ .join('\n')
549
+ return m.role === 'user'
550
+ ? `${colors.yellow.bold('## User Prompt')}\n\n${content}`
551
+ : `${colors.green.bold("## 🍀 Cloving's Response 🍀")}\n\n${content}`
552
+ })
553
+ .join('\n\n')
554
+
555
+ // Review the prompt using the REPL
556
+ const tokenCount = Math.ceil(fullPrompt.length / 4).toLocaleString()
557
+ console.log(
558
+ `${colors.yellow.bold('INFORMATION')} The generated prompt is approximately ${tokenCount} tokens long. Would you like to review the prompt before sending it? ${colors.gray('(Y/n)')}`,
559
+ )
560
+
561
+ const reviewPrompt = await this.askQuestion('cloving> ')
562
+
563
+ if (reviewPrompt.startsWith('y') || reviewPrompt === '') {
564
+ this.reviewPrompt(fullPrompt)
565
+ console.log(`Do you want to proceed with this prompt? ${colors.gray('(Y/n)')}`)
566
+
567
+ const confirmPrompt = await this.askQuestion('cloving> ')
568
+
569
+ if (!confirmPrompt.startsWith('y') && confirmPrompt !== '') {
570
+ console.log('Operation cancelled by user.')
571
+ this.isProcessing = false
572
+ this.rl.prompt()
573
+ return
574
+ }
575
+ }
576
+ }
577
+
578
+ const responseStream = await this.gpt.streamText({
579
+ prompt: this.prompt,
580
+ messages: this.chatHistory,
581
+ })
582
+
583
+ this.handleResponseStream(responseStream)
584
+ } catch (err) {
585
+ this.handleError(err as AxiosError)
586
+ }
587
+ }
588
+
589
+ private askQuestion(prompt: string): Promise<string> {
590
+ return new Promise<string>((resolve) => {
591
+ this.rl.question(colors.green.bold(prompt), (answer) => {
592
+ resolve(answer.trim().toLowerCase())
593
+ })
594
+ })
595
+ }
596
+
597
+ private reviewPrompt(fullPrompt: string) {
598
+ console.log(colors.gray.bold('\n---------------------- PROMPT START ----------------------\n'))
599
+ const promptParts = fullPrompt.split('\n```')
600
+ const highlightedPrompt = promptParts
601
+ .map((part, index) => (index % 2 === 1 ? highlight(part, { language: 'typescript' }) : part))
602
+ .join('\n```')
603
+ console.log(highlightedPrompt)
604
+ console.log(colors.gray.bold('\n---------------------- PROMPT END ----------------------\n'))
605
+ }
606
+
607
+ protected async finalizeResponse(): Promise<void> {
608
+ this.addAssistantResponse(this.responseString)
609
+ this.isProcessing = false
610
+ process.stdout.write('\b'.repeat(100))
611
+
612
+ if (this.responseString !== '') {
613
+ const currentNewBlocks = extractCurrentNewBlocks(this.responseString)
614
+ const [canApply, summary] = await checkBlocksApplicability(currentNewBlocks)
615
+ if (!canApply) {
616
+ if (this.retryCount < this.maxRetries) {
617
+ console.log(
618
+ `\n\n${summary}\n\n${colors.yellow.bold('WARNING')} Some of the provided code blocks could not be automatically applied. Retrying (Attempt ${this.retryCount + 1}/${this.maxRetries})...\n`,
619
+ )
620
+
621
+ this.retryCount++
622
+ this.processUserInput(`${CODEGEN_COULDNT_APPLY}\n\n${summary}`)
623
+
624
+ return
625
+ } else {
626
+ console.log(
627
+ `\n\n${colors.red.bold('ERROR')} Failed to generate a diff that could be cleanly applied after ${this.maxRetries} attempts. Please review the changes manually and try again.\n`,
628
+ )
629
+ this.retryCount = 0 // Reset the retry count for future attempts
630
+ }
631
+ } else {
632
+ this.retryCount = 0 // Reset the retry count on successful application
633
+ }
634
+ }
635
+
636
+ process.stdout.write(`
637
+
638
+ You can follow up with another request or:
639
+ - type ${colors.yellow(colors.bold('"save"'))} to save all the changes to files
640
+ - type ${colors.yellow(colors.bold('"commit"'))} to commit the changes to git with a AI - generated message
641
+ - type ${colors.yellow(colors.bold('"copy"'))} to copy the last response to clipboard
642
+ - type ${colors.yellow(colors.bold('"review"'))} to start a code review
643
+ - type ${colors.yellow(colors.bold('"add <file-path>"'))} to add a file to the chat context
644
+ - type ${colors.yellow(colors.bold('"rm <pattern>"'))} to remove files from the chat context
645
+ - type ${colors.yellow(colors.bold('"ls <pattern>"'))} to list files in the chat context
646
+ - type ${colors.yellow(colors.bold('"git <command>"'))} to run a git command
647
+ - type ${colors.yellow(colors.bold('"exit"'))} to quit this session
648
+ `)
649
+ this.rl.prompt()
650
+ }
651
+
652
+ private handleError(error: AxiosError) {
653
+ let errorMessage = error.message || 'An error occurred.'
654
+ const errorNumber = error.response?.status || 'unknown'
655
+
656
+ switch (errorNumber) {
657
+ case 400:
658
+ errorMessage = 'Invalid model or prompt size too large. Try specifying fewer files.'
659
+ break
660
+ case 403:
661
+ errorMessage = 'Inactive subscription or usage limit reached'
662
+ break
663
+ case 429:
664
+ errorMessage = 'Rate limit error'
665
+ break
666
+ case 500:
667
+ errorMessage = 'Internal server error'
668
+ break
669
+ }
670
+
671
+ const statusMessage = (error.response?.data as any)?.statusMessage
672
+ console.error(
673
+ colors.red(
674
+ `\nError (${errorNumber}) while submitting the prompt to the AI API\n\n${statusMessage}\n`,
675
+ ),
676
+ )
677
+ this.isProcessing = false
678
+ this.rl.prompt()
679
+ }
680
+
681
+ /**
682
+ * Generates a comprehensive prompt for the AI model.
683
+ *
684
+ * This function constructs a detailed prompt that includes:
685
+ * 1. The user's current request
686
+ * 2. Contents of all context files
687
+ * 3. Full chat history (excluding the current request)
688
+ * 4. The current request repeated at the end
689
+ *
690
+ * @private
691
+ * @param {string} prompt - The user's current request or input.
692
+ * @returns {string} A formatted string containing the complete prompt for the AI.
693
+ *
694
+ * @description
695
+ * The generated prompt follows this structure:
696
+ * 1. "### Request" section with the current prompt
697
+ * 2. Contents of all context files, each prefixed with its file name
698
+ * 3. "### Full Chat History Context" section with all previous messages
699
+ * 4. "### Current Request" section repeating the current prompt
700
+ *
701
+ * This structure provides the AI with comprehensive context for generating
702
+ * accurate and relevant responses.
703
+ */
704
+ private generatePrompt(prompt: string): string {
705
+ return `### Request
706
+
707
+ ${prompt}
708
+
709
+ ### Note
710
+
711
+ Whenever possible, break up the changes into pieces and make sure every change is in its own *CURRENT/NEW* Blocks.
712
+ Do not allow empty CURRENT blocks in *CURRENT/NEW* Blocks and if you add content to the CURRENT block, you also have to add the same content to the NEW block.`
713
+ }
714
+
715
+ private handleClose() {
716
+ console.log('Goodbye!')
717
+ process.exit(0)
718
+ }
719
+
720
+ /**
721
+ * Displays the prompt in green and bold.
722
+ * This method should be used instead of directly calling this.rl.prompt().
723
+ * @private
724
+ */
725
+ private displayPrompt() {
726
+ this.rl.setPrompt(colors.green.bold('cloving> '))
727
+ this.rl.prompt()
728
+ }
729
+
730
+ private handleKeypress(_: any, key: { name: string }) {
731
+ if (key && (key.name === 'up' || key.name === 'down')) {
732
+ if (key.name === 'up' && this.historyIndex < this.commandHistory.length - 1) {
733
+ this.historyIndex++
734
+ } else if (key.name === 'down' && this.historyIndex > -1) {
735
+ this.historyIndex--
736
+ }
737
+
738
+ if (this.historyIndex >= 0) {
739
+ this.rl.write(null, { ctrl: true, name: 'u' })
740
+ this.rl.write(this.commandHistory[this.historyIndex])
741
+ } else if (this.historyIndex === -1) {
742
+ this.rl.write(null, { ctrl: true, name: 'u' })
743
+ }
744
+ } else if (key && key.name === 'tab') {
745
+ const line = this.rl.line.trim()
746
+ const hits = specialCommands.filter((command) => command.startsWith(line))
747
+ if (hits.length > 0) {
748
+ this.rl.write(null, { ctrl: true, name: 'u' })
749
+ this.rl.write(hits[0])
750
+ }
751
+ }
752
+ }
753
+ }
754
+
755
+ export default ChatManager